_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2900
|
PJsonArray.getString
|
train
|
@Override
public final String getString(final int i) {
String val = this.array.optString(i, null);
if (val == null) {
throw new ObjectMissingException(this, "[" + i + "]");
}
return val;
}
|
java
|
{
"resource": ""
}
|
q2901
|
PJsonArray.getBool
|
train
|
@Override
public final boolean getBool(final int i) {
try {
return this.array.getBoolean(i);
} catch (JSONException e) {
throw new ObjectMissingException(this, "[" + i + "]");
}
}
|
java
|
{
"resource": ""
}
|
q2902
|
PAbstractObject.getString
|
train
|
@Override
public final String getString(final String key) {
String result = optString(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q2903
|
PAbstractObject.optString
|
train
|
@Override
public final String optString(final String key, final String defaultValue) {
String result = optString(key);
return result == null ? defaultValue : result;
}
|
java
|
{
"resource": ""
}
|
q2904
|
PAbstractObject.getInt
|
train
|
@Override
public final int getInt(final String key) {
Integer result = optInt(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q2905
|
PAbstractObject.optInt
|
train
|
@Override
public final Integer optInt(final String key, final Integer defaultValue) {
Integer result = optInt(key);
return result == null ? defaultValue : result;
}
|
java
|
{
"resource": ""
}
|
q2906
|
PAbstractObject.getLong
|
train
|
@Override
public final long getLong(final String key) {
Long result = optLong(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q2907
|
PAbstractObject.optLong
|
train
|
@Override
public final long optLong(final String key, final long defaultValue) {
Long result = optLong(key);
return result == null ? defaultValue : result;
}
|
java
|
{
"resource": ""
}
|
q2908
|
PAbstractObject.getDouble
|
train
|
@Override
public final double getDouble(final String key) {
Double result = optDouble(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q2909
|
PAbstractObject.optDouble
|
train
|
@Override
public final Double optDouble(final String key, final Double defaultValue) {
Double result = optDouble(key);
return result == null ? defaultValue : result;
}
|
java
|
{
"resource": ""
}
|
q2910
|
PAbstractObject.getFloat
|
train
|
@Override
public final float getFloat(final String key) {
Float result = optFloat(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q2911
|
PAbstractObject.optFloat
|
train
|
@Override
public final Float optFloat(final String key, final Float defaultValue) {
Float result = optFloat(key);
return result == null ? defaultValue : result;
}
|
java
|
{
"resource": ""
}
|
q2912
|
PAbstractObject.getBool
|
train
|
@Override
public final boolean getBool(final String key) {
Boolean result = optBool(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q2913
|
PAbstractObject.optBool
|
train
|
@Override
public final Boolean optBool(final String key, final Boolean defaultValue) {
Boolean result = optBool(key);
return result == null ? defaultValue : result;
}
|
java
|
{
"resource": ""
}
|
q2914
|
PAbstractObject.getObject
|
train
|
@Override
public final PObject getObject(final String key) {
PObject result = optObject(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q2915
|
PAbstractObject.getArray
|
train
|
@Override
public final PArray getArray(final String key) {
PArray result = optArray(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q2916
|
AccessAssertionPersister.unmarshal
|
train
|
public AccessAssertion unmarshal(final JSONObject encodedAssertion) {
final String className;
try {
className = encodedAssertion.getString(JSON_CLASS_NAME);
final Class<?> assertionClass =
Thread.currentThread().getContextClassLoader().loadClass(className);
final AccessAssertion assertion =
(AccessAssertion) this.applicationContext.getBean(assertionClass);
assertion.unmarshal(encodedAssertion);
return assertion;
} catch (JSONException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q2917
|
AccessAssertionPersister.marshal
|
train
|
public JSONObject marshal(final AccessAssertion assertion) {
final JSONObject jsonObject = assertion.marshal();
if (jsonObject.has(JSON_CLASS_NAME)) {
throw new AssertionError("The toJson method in AccessAssertion: '" + assertion.getClass() +
"' defined a JSON field " + JSON_CLASS_NAME +
" which is a reserved keyword and is not permitted to be used " +
"in toJSON method");
}
try {
jsonObject.put(JSON_CLASS_NAME, assertion.getClass().getName());
} catch (JSONException e) {
throw new RuntimeException(e);
}
return jsonObject;
}
|
java
|
{
"resource": ""
}
|
q2918
|
AddHeadersProcessor.createFactoryWrapper
|
train
|
public static MfClientHttpRequestFactory createFactoryWrapper(
final MfClientHttpRequestFactory requestFactory,
final UriMatchers matchers, final Map<String, List<String>> headers) {
return new AbstractMfClientHttpRequestFactoryWrapper(requestFactory, matchers, false) {
@Override
protected ClientHttpRequest createRequest(
final URI uri,
final HttpMethod httpMethod,
final MfClientHttpRequestFactory requestFactory) throws IOException {
final ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);
request.getHeaders().putAll(headers);
return request;
}
};
}
|
java
|
{
"resource": ""
}
|
q2919
|
AddHeadersProcessor.setHeaders
|
train
|
@SuppressWarnings("unchecked")
public void setHeaders(final Map<String, Object> headers) {
this.headers.clear();
for (Map.Entry<String, Object> entry: headers.entrySet()) {
if (entry.getValue() instanceof List) {
List value = (List) entry.getValue();
// verify they are all strings
for (Object o: value) {
Assert.isTrue(o instanceof String, o + " is not a string it is a: '" +
o.getClass() + "'");
}
this.headers.put(entry.getKey(), (List<String>) entry.getValue());
} else if (entry.getValue() instanceof String) {
final List<String> value = Collections.singletonList((String) entry.getValue());
this.headers.put(entry.getKey(), value);
} else {
throw new IllegalArgumentException("Only strings and list of strings may be headers");
}
}
}
|
java
|
{
"resource": ""
}
|
q2920
|
ProcessorUtils.writeProcessorOutputToValues
|
train
|
public static void writeProcessorOutputToValues(
final Object output,
final Processor<?, ?> processor,
final Values values) {
Map<String, String> mapper = processor.getOutputMapperBiMap();
if (mapper == null) {
mapper = Collections.emptyMap();
}
final Collection<Field> fields = getAllAttributes(output.getClass());
for (Field field: fields) {
String name = getOutputValueName(processor.getOutputPrefix(), mapper, field);
try {
final Object value = field.get(output);
if (value != null) {
values.put(name, value);
} else {
values.remove(name);
}
} catch (IllegalAccessException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
}
|
java
|
{
"resource": ""
}
|
q2921
|
ProcessorUtils.getInputValueName
|
train
|
public static String getInputValueName(
@Nullable final String inputPrefix,
@Nonnull final BiMap<String, String> inputMapper,
@Nonnull final String field) {
String name = inputMapper == null ? null : inputMapper.inverse().get(field);
if (name == null) {
if (inputMapper != null && inputMapper.containsKey(field)) {
throw new RuntimeException("field in keys");
}
final String[] defaultValues = {
Values.TASK_DIRECTORY_KEY, Values.CLIENT_HTTP_REQUEST_FACTORY_KEY,
Values.TEMPLATE_KEY, Values.PDF_CONFIG_KEY, Values.SUBREPORT_DIR_KEY,
Values.OUTPUT_FORMAT_KEY, Values.JOB_ID_KEY
};
if (inputPrefix == null || Arrays.asList(defaultValues).contains(field)) {
name = field;
} else {
name = inputPrefix.trim() +
Character.toUpperCase(field.charAt(0)) +
field.substring(1);
}
}
return name;
}
|
java
|
{
"resource": ""
}
|
q2922
|
ProcessorUtils.getOutputValueName
|
train
|
public static String getOutputValueName(
@Nullable final String outputPrefix,
@Nonnull final Map<String, String> outputMapper,
@Nonnull final Field field) {
String name = outputMapper.get(field.getName());
if (name == null) {
name = field.getName();
if (!StringUtils.isEmpty(outputPrefix) && !outputPrefix.trim().isEmpty()) {
name = outputPrefix.trim() + Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
}
return name;
}
|
java
|
{
"resource": ""
}
|
q2923
|
MapfishMapContext.rectangleDoubleToDimension
|
train
|
public static Dimension rectangleDoubleToDimension(final Rectangle2D.Double rectangle) {
return new Dimension(
(int) Math.round(rectangle.width),
(int) Math.round(rectangle.height));
}
|
java
|
{
"resource": ""
}
|
q2924
|
MapfishMapContext.getRotatedBounds
|
train
|
public MapBounds getRotatedBounds(final Rectangle2D.Double paintAreaPrecise, final Rectangle paintArea) {
final MapBounds rotatedBounds = this.getRotatedBounds();
if (rotatedBounds instanceof CenterScaleMapBounds) {
return rotatedBounds;
}
final ReferencedEnvelope envelope = ((BBoxMapBounds) rotatedBounds).toReferencedEnvelope(null);
// the paint area size and the map bounds are rotated independently. because
// the paint area size is rounded to integers, the map bounds have to be adjusted
// to these rounding changes.
final double widthRatio = paintArea.getWidth() / paintAreaPrecise.getWidth();
final double heightRatio = paintArea.getHeight() / paintAreaPrecise.getHeight();
final double adaptedWidth = envelope.getWidth() * widthRatio;
final double adaptedHeight = envelope.getHeight() * heightRatio;
final double widthDiff = adaptedWidth - envelope.getWidth();
final double heigthDiff = adaptedHeight - envelope.getHeight();
envelope.expandBy(widthDiff / 2.0, heigthDiff / 2.0);
return new BBoxMapBounds(envelope);
}
|
java
|
{
"resource": ""
}
|
q2925
|
MapfishMapContext.getRotatedBoundsAdjustedForPreciseRotatedMapSize
|
train
|
public MapBounds getRotatedBoundsAdjustedForPreciseRotatedMapSize() {
Rectangle2D.Double paintAreaPrecise = getRotatedMapSizePrecise();
Rectangle paintArea = new Rectangle(MapfishMapContext.rectangleDoubleToDimension(paintAreaPrecise));
return getRotatedBounds(paintAreaPrecise, paintArea);
}
|
java
|
{
"resource": ""
}
|
q2926
|
Main.runMain
|
train
|
@VisibleForTesting
public static void runMain(final String[] args) throws Exception {
final CliHelpDefinition helpCli = new CliHelpDefinition();
try {
Args.parse(helpCli, args);
if (helpCli.help) {
printUsage(0);
return;
}
} catch (IllegalArgumentException invalidOption) {
// Ignore because it is probably one of the non-help options.
}
final CliDefinition cli = new CliDefinition();
try {
List<String> unusedArguments = Args.parse(cli, args);
if (!unusedArguments.isEmpty()) {
System.out.println("\n\nThe following arguments are not recognized: " + unusedArguments);
printUsage(1);
return;
}
} catch (IllegalArgumentException invalidOption) {
System.out.println("\n\n" + invalidOption.getMessage());
printUsage(1);
return;
}
configureLogs(cli.verbose);
AbstractXmlApplicationContext context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT);
if (cli.springConfig != null) {
context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT, cli.springConfig);
}
try {
context.getBean(Main.class).run(cli);
} finally {
context.close();
}
}
|
java
|
{
"resource": ""
}
|
q2927
|
CoverageTask.call
|
train
|
public GridCoverage2D call() {
try {
BufferedImage coverageImage = this.tiledLayer.createBufferedImage(
this.tilePreparationInfo.getImageWidth(),
this.tilePreparationInfo.getImageHeight());
Graphics2D graphics = coverageImage.createGraphics();
try {
for (SingleTilePreparationInfo tileInfo: this.tilePreparationInfo.getSingleTiles()) {
final TileTask task;
if (tileInfo.getTileRequest() != null) {
task = new SingleTileLoaderTask(
tileInfo.getTileRequest(), this.errorImage, tileInfo.getTileIndexX(),
tileInfo.getTileIndexY(), this.failOnError, this.registry, this.context);
} else {
task = new PlaceHolderImageTask(this.tiledLayer.getMissingTileImage(),
tileInfo.getTileIndexX(), tileInfo.getTileIndexY());
}
Tile tile = task.call();
if (tile.getImage() != null) {
graphics.drawImage(tile.getImage(),
tile.getxIndex() * this.tiledLayer.getTileSize().width,
tile.getyIndex() * this.tiledLayer.getTileSize().height, null);
}
}
} finally {
graphics.dispose();
}
GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);
GeneralEnvelope gridEnvelope = new GeneralEnvelope(this.tilePreparationInfo.getMapProjection());
gridEnvelope.setEnvelope(this.tilePreparationInfo.getGridCoverageOrigin().x,
this.tilePreparationInfo.getGridCoverageOrigin().y,
this.tilePreparationInfo.getGridCoverageMaxX(),
this.tilePreparationInfo.getGridCoverageMaxY());
return factory.create(this.tiledLayer.createCommonUrl(), coverageImage, gridEnvelope,
null, null, null);
} catch (Exception e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q2928
|
ThreadPoolJobManager.shutdown
|
train
|
@PreDestroy
public final void shutdown() {
this.timer.shutdownNow();
this.executor.shutdownNow();
if (this.cleanUpTimer != null) {
this.cleanUpTimer.shutdownNow();
}
}
|
java
|
{
"resource": ""
}
|
q2929
|
ThreadPoolJobManager.isAbandoned
|
train
|
private boolean isAbandoned(final SubmittedPrintJob printJob) {
final long duration = ThreadPoolJobManager.this.jobQueue.timeSinceLastStatusCheck(
printJob.getEntry().getReferenceId());
final boolean abandoned =
duration > TimeUnit.SECONDS.toMillis(ThreadPoolJobManager.this.abandonedTimeout);
if (abandoned) {
LOGGER.info("Job {} is abandoned (no status check within the last {} seconds)",
printJob.getEntry().getReferenceId(), ThreadPoolJobManager.this.abandonedTimeout);
}
return abandoned;
}
|
java
|
{
"resource": ""
}
|
q2930
|
ThreadPoolJobManager.isAcceptingNewJobs
|
train
|
private boolean isAcceptingNewJobs() {
if (this.requestedToStop) {
return false;
} else if (new File(this.workingDirectories.getWorking(), "stop").exists()) {
LOGGER.info("The print has been requested to stop");
this.requestedToStop = true;
notifyIfStopped();
return false;
} else {
return true;
}
}
|
java
|
{
"resource": ""
}
|
q2931
|
ThreadPoolJobManager.notifyIfStopped
|
train
|
private void notifyIfStopped() {
if (isAcceptingNewJobs() || !this.runningTasksFutures.isEmpty()) {
return;
}
final File stoppedFile = new File(this.workingDirectories.getWorking(), "stopped");
try {
LOGGER.info("The print has finished processing jobs and can now stop");
stoppedFile.createNewFile();
} catch (IOException e) {
LOGGER.warn("Cannot create the {} file", stoppedFile, e);
}
}
|
java
|
{
"resource": ""
}
|
q2932
|
AreaOfInterest.postConstruct
|
train
|
public void postConstruct() {
parseGeometry();
Assert.isTrue(this.polygon != null, "Polygon is null. 'area' string is: '" + this.area + "'");
Assert.isTrue(this.display != null, "'display' is null");
Assert.isTrue(this.style == null || this.display == AoiDisplay.RENDER,
"'style' does not make sense unless 'display' == RENDER. In this case 'display' == " +
this.display);
}
|
java
|
{
"resource": ""
}
|
q2933
|
AreaOfInterest.areaToFeatureCollection
|
train
|
public SimpleFeatureCollection areaToFeatureCollection(
@Nonnull final MapAttribute.MapAttributeValues mapAttributes) {
Assert.isTrue(mapAttributes.areaOfInterest == this,
"map attributes passed in does not contain this area of interest object");
final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
typeBuilder.setName("aoi");
CoordinateReferenceSystem crs = mapAttributes.getMapBounds().getProjection();
typeBuilder.add("geom", this.polygon.getClass(), crs);
final SimpleFeature feature =
SimpleFeatureBuilder.build(typeBuilder.buildFeatureType(), new Object[]{this.polygon}, "aoi");
final DefaultFeatureCollection features = new DefaultFeatureCollection();
features.add(feature);
return features;
}
|
java
|
{
"resource": ""
}
|
q2934
|
AreaOfInterest.copy
|
train
|
public AreaOfInterest copy() {
AreaOfInterest aoi = new AreaOfInterest();
aoi.display = this.display;
aoi.area = this.area;
aoi.polygon = this.polygon;
aoi.style = this.style;
aoi.renderAsSvg = this.renderAsSvg;
return aoi;
}
|
java
|
{
"resource": ""
}
|
q2935
|
ProcessorDependencyGraphFactory.fillProcessorAttributes
|
train
|
public static void fillProcessorAttributes(
final List<Processor> processors,
final Map<String, Attribute> initialAttributes) {
Map<String, Attribute> currentAttributes = new HashMap<>(initialAttributes);
for (Processor processor: processors) {
if (processor instanceof RequireAttributes) {
for (ProcessorDependencyGraphFactory.InputValue inputValue:
ProcessorDependencyGraphFactory.getInputs(processor)) {
if (inputValue.type == Values.class) {
if (processor instanceof CustomDependencies) {
for (String attributeName: ((CustomDependencies) processor).getDependencies()) {
Attribute attribute = currentAttributes.get(attributeName);
if (attribute != null) {
((RequireAttributes) processor).setAttribute(
attributeName, currentAttributes.get(attributeName));
}
}
} else {
for (Map.Entry<String, Attribute> attribute: currentAttributes.entrySet()) {
((RequireAttributes) processor).setAttribute(
attribute.getKey(), attribute.getValue());
}
}
} else {
try {
((RequireAttributes) processor).setAttribute(
inputValue.internalName,
currentAttributes.get(inputValue.name));
} catch (ClassCastException e) {
throw new IllegalArgumentException(String.format("The processor '%s' requires " +
"the attribute '%s' " +
"(%s) but he has the " +
"wrong type:\n%s",
processor, inputValue.name,
inputValue.internalName,
e.getMessage()), e);
}
}
}
}
if (processor instanceof ProvideAttributes) {
Map<String, Attribute> newAttributes = ((ProvideAttributes) processor).getAttributes();
for (ProcessorDependencyGraphFactory.OutputValue ouputValue:
ProcessorDependencyGraphFactory.getOutputValues(processor)) {
currentAttributes.put(
ouputValue.name, newAttributes.get(ouputValue.internalName));
}
}
}
}
|
java
|
{
"resource": ""
}
|
q2936
|
OneOfTracker.checkAllGroupsSatisfied
|
train
|
public void checkAllGroupsSatisfied(final String currentPath) {
StringBuilder errors = new StringBuilder();
for (OneOfGroup group: this.mapping.values()) {
if (group.satisfiedBy.isEmpty()) {
errors.append("\n");
errors.append("\t* The OneOf choice: ").append(group.name)
.append(" was not satisfied. One (and only one) of the ");
errors.append("following fields is required in the request data: ")
.append(toNames(group.choices));
}
Collection<OneOfSatisfier> oneOfSatisfiers =
Collections2.filter(group.satisfiedBy, input -> !input.isCanSatisfy);
if (oneOfSatisfiers.size() > 1) {
errors.append("\n");
errors.append("\t* The OneOf choice: ").append(group.name)
.append(" was satisfied by too many fields. Only one choice ");
errors.append("may be in the request data. The fields found were: ")
.append(toNames(toFields(group.satisfiedBy)));
}
}
Assert.equals(0, errors.length(),
"\nErrors were detected when analysing the @OneOf dependencies of '" + currentPath +
"': \n" + errors);
}
|
java
|
{
"resource": ""
}
|
q2937
|
LoggingMetricsConfigurator.addMetricsAppenderToLogback
|
train
|
@PostConstruct
public final void addMetricsAppenderToLogback() {
final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
final Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);
final InstrumentedAppender metrics = new InstrumentedAppender(this.metricRegistry);
metrics.setContext(root.getLoggerContext());
metrics.start();
root.addAppender(metrics);
}
|
java
|
{
"resource": ""
}
|
q2938
|
RequiresTracker.checkAllRequirementsSatisfied
|
train
|
public void checkAllRequirementsSatisfied(final String currentPath) {
StringBuilder errors = new StringBuilder();
for (Field field: this.dependantsInJson) {
final Collection<String> requirements = this.dependantToRequirementsMap.get(field);
if (!requirements.isEmpty()) {
errors.append("\n");
String type = field.getType().getName();
if (field.getType().isArray()) {
type = field.getType().getComponentType().getName() + "[]";
}
errors.append("\t* ").append(type).append(' ').append(field.getName()).append(" depends on ")
.append(requirements);
}
}
Assert.equals(0, errors.length(),
"\nErrors were detected when analysing the @Requires dependencies of '" +
currentPath + "': " + errors);
}
|
java
|
{
"resource": ""
}
|
q2939
|
Configuration.printClientConfig
|
train
|
public final void printClientConfig(final JSONWriter json) throws JSONException {
json.key("layouts");
json.array();
final Map<String, Template> accessibleTemplates = getTemplates();
accessibleTemplates.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
.forEach(entry -> {
json.object();
json.key("name").value(entry.getKey());
entry.getValue().printClientConfig(json);
json.endObject();
});
json.endArray();
json.key("smtp").object();
json.key("enabled").value(smtp != null);
if (smtp != null) {
json.key("storage").object();
json.key("enabled").value(smtp.getStorage() != null);
json.endObject();
}
json.endObject();
}
|
java
|
{
"resource": ""
}
|
q2940
|
Configuration.getTemplate
|
train
|
public final Template getTemplate(final String name) {
final Template template = this.templates.get(name);
if (template != null) {
this.accessAssertion.assertAccess("Configuration", this);
template.assertAccessible(name);
} else {
throw new IllegalArgumentException(String.format("Template '%s' does not exist. Options are: " +
"%s", name, this.templates.keySet()));
}
return template;
}
|
java
|
{
"resource": ""
}
|
q2941
|
Configuration.getDefaultStyle
|
train
|
@Nonnull
public final Style getDefaultStyle(@Nonnull final String geometryType) {
String normalizedGeomName = GEOMETRY_NAME_ALIASES.get(geometryType.toLowerCase());
if (normalizedGeomName == null) {
normalizedGeomName = geometryType.toLowerCase();
}
Style style = this.defaultStyle.get(normalizedGeomName.toLowerCase());
if (style == null) {
style = this.namedStyles.get(normalizedGeomName.toLowerCase());
}
if (style == null) {
StyleBuilder builder = new StyleBuilder();
final Symbolizer symbolizer;
if (isPointType(normalizedGeomName)) {
symbolizer = builder.createPointSymbolizer();
} else if (isLineType(normalizedGeomName)) {
symbolizer = builder.createLineSymbolizer(Color.black, 2);
} else if (isPolygonType(normalizedGeomName)) {
symbolizer = builder.createPolygonSymbolizer(Color.lightGray, Color.black, 2);
} else if (normalizedGeomName.equalsIgnoreCase(Constants.Style.Raster.NAME)) {
symbolizer = builder.createRasterSymbolizer();
} else if (normalizedGeomName.startsWith(Constants.Style.OverviewMap.NAME)) {
symbolizer = createMapOverviewStyle(normalizedGeomName, builder);
} else {
final Style geomStyle = this.defaultStyle.get(Geometry.class.getSimpleName().toLowerCase());
if (geomStyle != null) {
return geomStyle;
} else {
symbolizer = builder.createPointSymbolizer();
}
}
style = builder.createStyle(symbolizer);
}
return style;
}
|
java
|
{
"resource": ""
}
|
q2942
|
Configuration.setDefaultStyle
|
train
|
public final void setDefaultStyle(final Map<String, Style> defaultStyle) {
this.defaultStyle = new HashMap<>(defaultStyle.size());
for (Map.Entry<String, Style> entry: defaultStyle.entrySet()) {
String normalizedName = GEOMETRY_NAME_ALIASES.get(entry.getKey().toLowerCase());
if (normalizedName == null) {
normalizedName = entry.getKey().toLowerCase();
}
this.defaultStyle.put(normalizedName, entry.getValue());
}
}
|
java
|
{
"resource": ""
}
|
q2943
|
Configuration.validate
|
train
|
public final List<Throwable> validate() {
List<Throwable> validationErrors = new ArrayList<>();
this.accessAssertion.validate(validationErrors, this);
for (String jdbcDriver: this.jdbcDrivers) {
try {
Class.forName(jdbcDriver);
} catch (ClassNotFoundException e) {
try {
Configuration.class.getClassLoader().loadClass(jdbcDriver);
} catch (ClassNotFoundException e1) {
validationErrors.add(new ConfigurationException(String.format(
"Unable to load JDBC driver: %s ensure that the web application has the jar " +
"on its classpath", jdbcDriver)));
}
}
}
if (this.configurationFile == null) {
validationErrors.add(new ConfigurationException("Configuration file is field on configuration " +
"object is null"));
}
if (this.templates.isEmpty()) {
validationErrors.add(new ConfigurationException("There are not templates defined."));
}
for (Template template: this.templates.values()) {
template.validate(validationErrors, this);
}
for (HttpProxy proxy: this.proxies) {
proxy.validate(validationErrors, this);
}
try {
ColorParser.toColor(this.opaqueTileErrorColor);
} catch (RuntimeException ex) {
validationErrors.add(new ConfigurationException("Cannot parse opaqueTileErrorColor", ex));
}
try {
ColorParser.toColor(this.transparentTileErrorColor);
} catch (RuntimeException ex) {
validationErrors.add(new ConfigurationException("Cannot parse transparentTileErrorColor", ex));
}
if (smtp != null) {
smtp.validate(validationErrors, this);
}
return validationErrors;
}
|
java
|
{
"resource": ""
}
|
q2944
|
ProcessorGraphNode.addDependency
|
train
|
public void addDependency(final ProcessorGraphNode node) {
Assert.isTrue(node != this, "A processor can't depends on himself");
this.dependencies.add(node);
node.addRequirement(this);
}
|
java
|
{
"resource": ""
}
|
q2945
|
ProcessorGraphNode.getOutputMapper
|
train
|
@Nonnull
public BiMap<String, String> getOutputMapper() {
final BiMap<String, String> outputMapper = this.processor.getOutputMapperBiMap();
if (outputMapper == null) {
return HashBiMap.create();
}
return outputMapper;
}
|
java
|
{
"resource": ""
}
|
q2946
|
ProcessorGraphNode.getInputMapper
|
train
|
@Nonnull
public BiMap<String, String> getInputMapper() {
final BiMap<String, String> inputMapper = this.processor.getInputMapperBiMap();
if (inputMapper == null) {
return HashBiMap.create();
}
return inputMapper;
}
|
java
|
{
"resource": ""
}
|
q2947
|
ProcessorGraphNode.getAllProcessors
|
train
|
public Set<? extends Processor<?, ?>> getAllProcessors() {
IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();
all.put(this.getProcessor(), null);
for (ProcessorGraphNode<?, ?> dependency: this.dependencies) {
for (Processor<?, ?> p: dependency.getAllProcessors()) {
all.put(p, null);
}
}
return all.keySet();
}
|
java
|
{
"resource": ""
}
|
q2948
|
BaseMapServlet.findReplacement
|
train
|
public static String findReplacement(final String variableName, final Date date) {
if (variableName.equalsIgnoreCase("date")) {
return cleanUpName(DateFormat.getDateInstance().format(date));
} else if (variableName.equalsIgnoreCase("datetime")) {
return cleanUpName(DateFormat.getDateTimeInstance().format(date));
} else if (variableName.equalsIgnoreCase("time")) {
return cleanUpName(DateFormat.getTimeInstance().format(date));
} else {
try {
return new SimpleDateFormat(variableName).format(date);
} catch (Exception e) {
LOGGER.error("Unable to format timestamp according to pattern: {}", variableName, e);
return "${" + variableName + "}";
}
}
}
|
java
|
{
"resource": ""
}
|
q2949
|
BaseMapServlet.error
|
train
|
protected static void error(
final HttpServletResponse httpServletResponse, final String message, final HttpStatus code) {
try {
httpServletResponse.setContentType("text/plain");
httpServletResponse.setStatus(code.value());
setNoCache(httpServletResponse);
try (PrintWriter out = httpServletResponse.getWriter()) {
out.println("Error while processing request:");
out.println(message);
}
LOGGER.error("Error while processing request: {}", message);
} catch (IOException ex) {
throw ExceptionUtils.getRuntimeException(ex);
}
}
|
java
|
{
"resource": ""
}
|
q2950
|
BaseMapServlet.error
|
train
|
protected final void error(final HttpServletResponse httpServletResponse, final Throwable e) {
httpServletResponse.setContentType("text/plain");
httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
try (PrintWriter out = httpServletResponse.getWriter()) {
out.println("Error while processing request:");
LOGGER.error("Error while processing request", e);
} catch (IOException ex) {
throw ExceptionUtils.getRuntimeException(ex);
}
}
|
java
|
{
"resource": ""
}
|
q2951
|
BaseMapServlet.getBaseUrl
|
train
|
protected final StringBuilder getBaseUrl(final HttpServletRequest httpServletRequest) {
StringBuilder baseURL = new StringBuilder();
if (httpServletRequest.getContextPath() != null && !httpServletRequest.getContextPath().isEmpty()) {
baseURL.append(httpServletRequest.getContextPath());
}
if (httpServletRequest.getServletPath() != null && !httpServletRequest.getServletPath().isEmpty()) {
baseURL.append(httpServletRequest.getServletPath());
}
return baseURL;
}
|
java
|
{
"resource": ""
}
|
q2952
|
ScalebarGraphic.getSize
|
train
|
@VisibleForTesting
protected static Dimension getSize(
final ScalebarAttributeValues scalebarParams,
final ScaleBarRenderSettings settings, final Dimension maxLabelSize) {
final float width;
final float height;
if (scalebarParams.getOrientation().isHorizontal()) {
width = 2 * settings.getPadding()
+ settings.getIntervalLengthInPixels() * scalebarParams.intervals
+ settings.getLeftLabelMargin() + settings.getRightLabelMargin();
height = 2 * settings.getPadding()
+ settings.getBarSize() + settings.getLabelDistance()
+ Label.getRotatedHeight(maxLabelSize, scalebarParams.getLabelRotation());
} else {
width = 2 * settings.getPadding()
+ settings.getLabelDistance() + settings.getBarSize()
+ Label.getRotatedWidth(maxLabelSize, scalebarParams.getLabelRotation());
height = 2 * settings.getPadding()
+ settings.getTopLabelMargin()
+ settings.getIntervalLengthInPixels() * scalebarParams.intervals
+ settings.getBottomLabelMargin();
}
return new Dimension((int) Math.ceil(width), (int) Math.ceil(height));
}
|
java
|
{
"resource": ""
}
|
q2953
|
ScalebarGraphic.getMaxLabelSize
|
train
|
@VisibleForTesting
protected static Dimension getMaxLabelSize(final ScaleBarRenderSettings settings) {
float maxLabelHeight = 0.0f;
float maxLabelWidth = 0.0f;
for (final Label label: settings.getLabels()) {
maxLabelHeight = Math.max(maxLabelHeight, label.getHeight());
maxLabelWidth = Math.max(maxLabelWidth, label.getWidth());
}
return new Dimension((int) Math.ceil(maxLabelWidth), (int) Math.ceil(maxLabelHeight));
}
|
java
|
{
"resource": ""
}
|
q2954
|
ScalebarGraphic.createLabelText
|
train
|
@VisibleForTesting
protected static String createLabelText(
final DistanceUnit scaleUnit, final double value, final DistanceUnit intervalUnit) {
double scaledValue = scaleUnit.convertTo(value, intervalUnit);
// assume that there is no interval smaller then 0.0001
scaledValue = Math.round(scaledValue * 10000) / 10000;
String decimals = Double.toString(scaledValue).split("\\.")[1];
if (Double.valueOf(decimals) == 0) {
return Long.toString(Math.round(scaledValue));
} else {
return Double.toString(scaledValue);
}
}
|
java
|
{
"resource": ""
}
|
q2955
|
ScalebarGraphic.getNearestNiceValue
|
train
|
@VisibleForTesting
protected static double getNearestNiceValue(
final double value, final DistanceUnit scaleUnit, final boolean lockUnits) {
DistanceUnit bestUnit = bestUnit(scaleUnit, value, lockUnits);
double factor = scaleUnit.convertTo(1.0, bestUnit);
// nearest power of 10 lower than value
int digits = (int) Math.floor((Math.log(value * factor) / Math.log(10)));
double pow10 = Math.pow(10, digits);
// ok, find first character
double firstChar = value * factor / pow10;
// right, put it into the correct bracket
int barLen;
if (firstChar >= 10.0) {
barLen = 10;
} else if (firstChar >= 5.0) {
barLen = 5;
} else if (firstChar >= 2.0) {
barLen = 2;
} else {
barLen = 1;
}
// scale it up the correct power of 10
return barLen * pow10 / factor;
}
|
java
|
{
"resource": ""
}
|
q2956
|
ScalebarGraphic.getBarSize
|
train
|
@VisibleForTesting
protected static int getBarSize(final ScaleBarRenderSettings settings) {
if (settings.getParams().barSize != null) {
return settings.getParams().barSize;
} else {
if (settings.getParams().getOrientation().isHorizontal()) {
return settings.getMaxSize().height / 4;
} else {
return settings.getMaxSize().width / 4;
}
}
}
|
java
|
{
"resource": ""
}
|
q2957
|
ScalebarGraphic.getLabelDistance
|
train
|
@VisibleForTesting
protected static int getLabelDistance(final ScaleBarRenderSettings settings) {
if (settings.getParams().labelDistance != null) {
return settings.getParams().labelDistance;
} else {
if (settings.getParams().getOrientation().isHorizontal()) {
return settings.getMaxSize().width / 40;
} else {
return settings.getMaxSize().height / 40;
}
}
}
|
java
|
{
"resource": ""
}
|
q2958
|
ScalebarGraphic.render
|
train
|
public final URI render(
final MapfishMapContext mapContext,
final ScalebarAttributeValues scalebarParams,
final File tempFolder,
final Template template)
throws IOException, ParserConfigurationException {
final double dpi = mapContext.getDPI();
// get the map bounds
final Rectangle paintArea = new Rectangle(mapContext.getMapSize());
MapBounds bounds = mapContext.getBounds();
final DistanceUnit mapUnit = getUnit(bounds);
final Scale scale = bounds.getScale(paintArea, PDF_DPI);
final double scaleDenominator = scale.getDenominator(scalebarParams.geodetic,
bounds.getProjection(), dpi, bounds.getCenter());
DistanceUnit scaleUnit = scalebarParams.getUnit();
if (scaleUnit == null) {
scaleUnit = mapUnit;
}
// adjust scalebar width and height to the DPI value
final double maxLengthInPixel = (scalebarParams.getOrientation().isHorizontal()) ?
scalebarParams.getSize().width : scalebarParams.getSize().height;
final double maxIntervalLengthInWorldUnits = DistanceUnit.PX.convertTo(maxLengthInPixel, scaleUnit)
* scaleDenominator / scalebarParams.intervals;
final double niceIntervalLengthInWorldUnits =
getNearestNiceValue(maxIntervalLengthInWorldUnits, scaleUnit, scalebarParams.lockUnits);
final ScaleBarRenderSettings settings = new ScaleBarRenderSettings();
settings.setParams(scalebarParams);
settings.setMaxSize(scalebarParams.getSize());
settings.setPadding(getPadding(settings));
// start the rendering
File path = null;
if (template.getConfiguration().renderAsSvg(scalebarParams.renderAsSvg)) {
// render scalebar as SVG
final SVGGraphics2D graphics2D = CreateMapProcessor.createSvgGraphics(scalebarParams.getSize());
try {
tryLayout(
graphics2D, scaleUnit, scaleDenominator,
niceIntervalLengthInWorldUnits, settings, 0);
path = File.createTempFile("scalebar-graphic-", ".svg", tempFolder);
CreateMapProcessor.saveSvgFile(graphics2D, path);
} finally {
graphics2D.dispose();
}
} else {
// render scalebar as raster graphic
double dpiRatio = mapContext.getDPI() / PDF_DPI;
final BufferedImage bufferedImage = new BufferedImage(
(int) Math.round(scalebarParams.getSize().width * dpiRatio),
(int) Math.round(scalebarParams.getSize().height * dpiRatio),
TYPE_4BYTE_ABGR);
final Graphics2D graphics2D = bufferedImage.createGraphics();
try {
AffineTransform saveAF = new AffineTransform(graphics2D.getTransform());
graphics2D.scale(dpiRatio, dpiRatio);
tryLayout(
graphics2D, scaleUnit, scaleDenominator,
niceIntervalLengthInWorldUnits, settings, 0);
graphics2D.setTransform(saveAF);
path = File.createTempFile("scalebar-graphic-", ".png", tempFolder);
ImageUtils.writeImage(bufferedImage, "png", path);
} finally {
graphics2D.dispose();
}
}
return path.toURI();
}
|
java
|
{
"resource": ""
}
|
q2959
|
MapPrinter.parseSpec
|
train
|
public static PJsonObject parseSpec(final String spec) {
final JSONObject jsonSpec;
try {
jsonSpec = new JSONObject(spec);
} catch (JSONException e) {
throw new RuntimeException("Cannot parse the spec file: " + spec, e);
}
return new PJsonObject(jsonSpec, "spec");
}
|
java
|
{
"resource": ""
}
|
q2960
|
MapPrinter.getOutputFormat
|
train
|
public final OutputFormat getOutputFormat(final PJsonObject specJson) {
final String format = specJson.getString(MapPrinterServlet.JSON_OUTPUT_FORMAT);
final boolean mapExport =
this.configuration.getTemplate(specJson.getString(Constants.JSON_LAYOUT_KEY)).isMapExport();
final String beanName =
format + (mapExport ? MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING : OUTPUT_FORMAT_BEAN_NAME_ENDING);
if (!this.outputFormat.containsKey(beanName)) {
throw new RuntimeException("Format '" + format + "' with mapExport '" + mapExport
+ "' is not supported.");
}
return this.outputFormat.get(beanName);
}
|
java
|
{
"resource": ""
}
|
q2961
|
MapPrinter.print
|
train
|
public final Processor.ExecutionContext print(
final String jobId, final PJsonObject specJson, final OutputStream out)
throws Exception {
final OutputFormat format = getOutputFormat(specJson);
final File taskDirectory = this.workingDirectories.getTaskDirectory();
try {
return format.print(jobId, specJson, getConfiguration(), this.configFile.getParentFile(),
taskDirectory, out);
} finally {
this.workingDirectories.removeDirectory(taskDirectory);
}
}
|
java
|
{
"resource": ""
}
|
q2962
|
MapPrinter.getOutputFormatsNames
|
train
|
public final Set<String> getOutputFormatsNames() {
SortedSet<String> formats = new TreeSet<>();
for (String formatBeanName: this.outputFormat.keySet()) {
int endingIndex = formatBeanName.indexOf(MAP_OUTPUT_FORMAT_BEAN_NAME_ENDING);
if (endingIndex < 0) {
endingIndex = formatBeanName.indexOf(OUTPUT_FORMAT_BEAN_NAME_ENDING);
}
formats.add(formatBeanName.substring(0, endingIndex));
}
return formats;
}
|
java
|
{
"resource": ""
}
|
q2963
|
MapBounds.getNearestScale
|
train
|
public Scale getNearestScale(
final ZoomLevels zoomLevels,
final double tolerance,
final ZoomLevelSnapStrategy zoomLevelSnapStrategy,
final boolean geodetic,
final Rectangle paintArea,
final double dpi) {
final Scale scale = getScale(paintArea, dpi);
final Scale correctedScale;
final double scaleRatio;
if (geodetic) {
final double currentScaleDenominator = scale.getGeodeticDenominator(
getProjection(), dpi, getCenter());
scaleRatio = scale.getDenominator(dpi) / currentScaleDenominator;
correctedScale = scale.toResolution(scale.getResolution() / scaleRatio);
} else {
scaleRatio = 1;
correctedScale = scale;
}
DistanceUnit unit = DistanceUnit.fromProjection(getProjection());
final ZoomLevelSnapStrategy.SearchResult result = zoomLevelSnapStrategy.search(
correctedScale, tolerance, zoomLevels);
final Scale newScale;
if (geodetic) {
newScale = new Scale(
result.getScale(unit).getDenominator(PDF_DPI) * scaleRatio,
getProjection(), dpi);
} else {
newScale = result.getScale(unit);
}
return newScale;
}
|
java
|
{
"resource": ""
}
|
q2964
|
HibernateJobQueue.init
|
train
|
@PostConstruct
public final void init() {
this.cleanUpTimer = Executors.newScheduledThreadPool(1, timerTask -> {
final Thread thread = new Thread(timerTask, "Clean up old job records");
thread.setDaemon(true);
return thread;
});
this.cleanUpTimer.scheduleAtFixedRate(this::cleanup, this.cleanupInterval, this.cleanupInterval,
TimeUnit.SECONDS);
}
|
java
|
{
"resource": ""
}
|
q2965
|
ParserUtils.getAllAttributes
|
train
|
public static Collection<Field> getAllAttributes(final Class<?> classToInspect) {
Set<Field> allFields = new HashSet<>();
getAllAttributes(classToInspect, allFields, Function.identity(), field -> true);
return allFields;
}
|
java
|
{
"resource": ""
}
|
q2966
|
ParserUtils.getAttributes
|
train
|
public static Collection<Field> getAttributes(
final Class<?> classToInspect, final Predicate<Field> filter) {
Set<Field> allFields = new HashSet<>();
getAllAttributes(classToInspect, allFields, Function.identity(), filter);
return allFields;
}
|
java
|
{
"resource": ""
}
|
q2967
|
NorthArrowGraphic.createRaster
|
train
|
private static URI createRaster(
final Dimension targetSize, final RasterReference rasterReference,
final Double rotation, final Color backgroundColor,
final File workingDir) throws IOException {
final File path = File.createTempFile("north-arrow-", ".png", workingDir);
final BufferedImage newImage =
new BufferedImage(targetSize.width, targetSize.height, BufferedImage.TYPE_4BYTE_ABGR);
final Graphics2D graphics2d = newImage.createGraphics();
try {
final BufferedImage originalImage = ImageIO.read(rasterReference.inputStream);
if (originalImage == null) {
LOGGER.warn("Unable to load NorthArrow graphic: {}, it is not an image format that can be " +
"decoded",
rasterReference.uri);
throw new IllegalArgumentException();
}
// set background color
graphics2d.setColor(backgroundColor);
graphics2d.fillRect(0, 0, targetSize.width, targetSize.height);
// scale the original image to fit the new size
int newWidth;
int newHeight;
if (originalImage.getWidth() > originalImage.getHeight()) {
newWidth = targetSize.width;
newHeight = Math.min(
targetSize.height,
(int) Math.ceil(newWidth / (originalImage.getWidth() /
(double) originalImage.getHeight())));
} else {
newHeight = targetSize.height;
newWidth = Math.min(
targetSize.width,
(int) Math.ceil(newHeight / (originalImage.getHeight() /
(double) originalImage.getWidth())));
}
// position the original image in the center of the new
int deltaX = (int) Math.floor((targetSize.width - newWidth) / 2.0);
int deltaY = (int) Math.floor((targetSize.height - newHeight) / 2.0);
if (!FloatingPointUtil.equals(rotation, 0.0)) {
final AffineTransform rotate = AffineTransform.getRotateInstance(
rotation, targetSize.width / 2.0, targetSize.height / 2.0);
graphics2d.setTransform(rotate);
}
graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics2d.drawImage(originalImage, deltaX, deltaY, newWidth, newHeight, null);
ImageUtils.writeImage(newImage, "png", path);
} finally {
graphics2d.dispose();
}
return path.toURI();
}
|
java
|
{
"resource": ""
}
|
q2968
|
NorthArrowGraphic.createSvg
|
train
|
private static URI createSvg(
final Dimension targetSize,
final RasterReference rasterReference, final Double rotation,
final Color backgroundColor, final File workingDir)
throws IOException {
// load SVG graphic
final SVGElement svgRoot = parseSvg(rasterReference.inputStream);
// create a new SVG graphic in which the existing graphic is embedded (scaled and rotated)
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
Document newDocument = impl.createDocument(SVG_NS, "svg", null);
SVGElement newSvgRoot = (SVGElement) newDocument.getDocumentElement();
newSvgRoot.setAttributeNS(null, "width", Integer.toString(targetSize.width));
newSvgRoot.setAttributeNS(null, "height", Integer.toString(targetSize.height));
setSvgBackground(backgroundColor, targetSize, newDocument, newSvgRoot);
embedSvgGraphic(svgRoot, newSvgRoot, newDocument, targetSize, rotation);
File path = writeSvgToFile(newDocument, workingDir);
return path.toURI();
}
|
java
|
{
"resource": ""
}
|
q2969
|
NorthArrowGraphic.embedSvgGraphic
|
train
|
private static void embedSvgGraphic(
final SVGElement svgRoot,
final SVGElement newSvgRoot, final Document newDocument,
final Dimension targetSize, final Double rotation) {
final String originalWidth = svgRoot.getAttributeNS(null, "width");
final String originalHeight = svgRoot.getAttributeNS(null, "height");
/*
* To scale the SVG graphic and to apply the rotation, we distinguish two
* cases: width and height is set on the original SVG or not.
*
* Case 1: Width and height is set
* If width and height is set, we wrap the original SVG into 2 new SVG elements
* and a container element.
*
* Example:
* Original SVG:
* <svg width="100" height="100"></svg>
*
* New SVG (scaled to 300x300 and rotated by 90 degree):
* <svg width="300" height="300">
* <g transform="rotate(90.0 150 150)">
* <svg width="100%" height="100%" viewBox="0 0 100 100">
* <svg width="100" height="100"></svg>
* </svg>
* </g>
* </svg>
*
* The requested size is set on the outermost <svg>. Then, the rotation is applied to the
* <g> container and the scaling is achieved with the viewBox parameter on the 2nd <svg>.
*
*
* Case 2: Width and height is not set
* In this case the original SVG is wrapped into just one container and one new SVG element.
* The rotation is set on the container, and the scaling happens automatically.
*
* Example:
* Original SVG:
* <svg viewBox="0 0 61.06 91.83"></svg>
*
* New SVG (scaled to 300x300 and rotated by 90 degree):
* <svg width="300" height="300">
* <g transform="rotate(90.0 150 150)">
* <svg viewBox="0 0 61.06 91.83"></svg>
* </g>
* </svg>
*/
if (!StringUtils.isEmpty(originalWidth) && !StringUtils.isEmpty(originalHeight)) {
Element wrapperContainer = newDocument.createElementNS(SVG_NS, "g");
wrapperContainer.setAttributeNS(
null,
SVGConstants.SVG_TRANSFORM_ATTRIBUTE,
getRotateTransformation(targetSize, rotation));
newSvgRoot.appendChild(wrapperContainer);
Element wrapperSvg = newDocument.createElementNS(SVG_NS, "svg");
wrapperSvg.setAttributeNS(null, "width", "100%");
wrapperSvg.setAttributeNS(null, "height", "100%");
wrapperSvg.setAttributeNS(null, "viewBox", "0 0 " + originalWidth
+ " " + originalHeight);
wrapperContainer.appendChild(wrapperSvg);
Node svgRootImported = newDocument.importNode(svgRoot, true);
wrapperSvg.appendChild(svgRootImported);
} else if (StringUtils.isEmpty(originalWidth) && StringUtils.isEmpty(originalHeight)) {
Element wrapperContainer = newDocument.createElementNS(SVG_NS, "g");
wrapperContainer.setAttributeNS(
null,
SVGConstants.SVG_TRANSFORM_ATTRIBUTE,
getRotateTransformation(targetSize, rotation));
newSvgRoot.appendChild(wrapperContainer);
Node svgRootImported = newDocument.importNode(svgRoot, true);
wrapperContainer.appendChild(svgRootImported);
} else {
throw new IllegalArgumentException(
"Unsupported or invalid north-arrow SVG graphic: The same unit (px, em, %, ...) must be" +
" " +
"used for `width` and `height`.");
}
}
|
java
|
{
"resource": ""
}
|
q2970
|
JasperReportBuilder.setDirectory
|
train
|
public void setDirectory(final String directory) {
this.directory = new File(this.configuration.getDirectory(), directory);
if (!this.directory.exists()) {
throw new IllegalArgumentException(String.format(
"Directory does not exist: %s.\n" +
"Configuration contained value %s which is supposed to be relative to " +
"configuration directory.",
this.directory, directory));
}
if (!this.directory.getAbsolutePath()
.startsWith(this.configuration.getDirectory().getAbsolutePath())) {
throw new IllegalArgumentException(String.format(
"All files and directories must be contained in the configuration directory the " +
"directory provided in the configuration breaks that contract: %s in config " +
"file resolved to %s.",
directory, this.directory));
}
}
|
java
|
{
"resource": ""
}
|
q2971
|
CreateMapPagesProcessor.setAttribute
|
train
|
public void setAttribute(final String name, final Attribute attribute) {
if (name.equals(MAP_KEY)) {
this.mapAttribute = (MapAttribute) attribute;
}
}
|
java
|
{
"resource": ""
}
|
q2972
|
CreateMapPagesProcessor.getAttributes
|
train
|
public Map<String, Attribute> getAttributes() {
Map<String, Attribute> result = new HashMap<>();
DataSourceAttribute datasourceAttribute = new DataSourceAttribute();
Map<String, Attribute> dsResult = new HashMap<>();
dsResult.put(MAP_KEY, this.mapAttribute);
datasourceAttribute.setAttributes(dsResult);
result.put("datasource", datasourceAttribute);
return result;
}
|
java
|
{
"resource": ""
}
|
q2973
|
Template.printClientConfig
|
train
|
public final void printClientConfig(final JSONWriter json) throws JSONException {
json.key("attributes");
json.array();
for (Map.Entry<String, Attribute> entry: this.attributes.entrySet()) {
Attribute attribute = entry.getValue();
if (attribute.getClass().getAnnotation(InternalAttribute.class) == null) {
json.object();
attribute.printClientConfig(json, this);
json.endObject();
}
}
json.endArray();
}
|
java
|
{
"resource": ""
}
|
q2974
|
Template.setAttributes
|
train
|
public final void setAttributes(final Map<String, Attribute> attributes) {
for (Map.Entry<String, Attribute> entry: attributes.entrySet()) {
Object attribute = entry.getValue();
if (!(attribute instanceof Attribute)) {
final String msg =
"Attribute: '" + entry.getKey() + "' is not an attribute. It is a: " + attribute;
LOGGER.error("Error setting the Attributes: {}", msg);
throw new IllegalArgumentException(msg);
} else {
((Attribute) attribute).setConfigName(entry.getKey());
}
}
this.attributes = attributes;
}
|
java
|
{
"resource": ""
}
|
q2975
|
Template.getProcessorGraph
|
train
|
public final ProcessorDependencyGraph getProcessorGraph() {
if (this.processorGraph == null) {
synchronized (this) {
if (this.processorGraph == null) {
final Map<String, Class<?>> attcls = new HashMap<>();
for (Map.Entry<String, Attribute> attribute: this.attributes.entrySet()) {
attcls.put(attribute.getKey(), attribute.getValue().getValueType());
}
this.processorGraph = this.processorGraphFactory.build(this.processors, attcls);
}
}
}
return this.processorGraph;
}
|
java
|
{
"resource": ""
}
|
q2976
|
Template.getStyle
|
train
|
@SuppressWarnings("unchecked")
@Nonnull
public final java.util.Optional<Style> getStyle(final String styleName) {
final String styleRef = this.styles.get(styleName);
Optional<Style> style;
if (styleRef != null) {
style = (Optional<Style>) this.styleParser
.loadStyle(getConfiguration(), this.httpRequestFactory, styleRef);
} else {
style = Optional.empty();
}
return or(style, this.configuration.getStyle(styleName));
}
|
java
|
{
"resource": ""
}
|
q2977
|
JvmMetricsConfigurator.init
|
train
|
@PostConstruct
public void init() {
this.metricRegistry.register(name("gc"), new GarbageCollectorMetricSet());
this.metricRegistry.register(name("memory"), new MemoryUsageGaugeSet());
this.metricRegistry.register(name("thread-states"), new ThreadStatesGaugeSet());
this.metricRegistry.register(name("fd-usage"), new FileDescriptorRatioGauge());
}
|
java
|
{
"resource": ""
}
|
q2978
|
WmsLayerParam.postConstruct
|
train
|
public void postConstruct() throws URISyntaxException {
WmsVersion.lookup(this.version);
Assert.isTrue(validateBaseUrl(), "invalid baseURL");
Assert.isTrue(this.layers.length > 0, "There must be at least one layer defined for a WMS request" +
" to make sense");
// OpenLayers 2 compatibility. It will post a single empty style no matter how many layers there are
if (this.styles != null && this.styles.length != this.layers.length && this.styles.length == 1 &&
this.styles[0].trim().isEmpty()) {
this.styles = null;
} else {
Assert.isTrue(this.styles == null || this.layers.length == this.styles.length,
String.format(
"If styles are defined then there must be one for each layer. Number of" +
" layers: %s\nStyles: %s", this.layers.length,
Arrays.toString(this.styles)));
}
if (this.imageFormat.indexOf('/') < 0) {
LOGGER.warn("The format {} should be a mime type", this.imageFormat);
this.imageFormat = "image/" + this.imageFormat;
}
Assert.isTrue(this.method == HttpMethod.GET || this.method == HttpMethod.POST,
String.format("Unsupported method %s for WMS layer", this.method.toString()));
}
|
java
|
{
"resource": ""
}
|
q2979
|
TileCacheInformation.createBufferedImage
|
train
|
@Nonnull
public BufferedImage createBufferedImage(final int imageWidth, final int imageHeight) {
return new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
}
|
java
|
{
"resource": ""
}
|
q2980
|
PDFConfig.setKeywords
|
train
|
public void setKeywords(final List<String> keywords) {
StringBuilder builder = new StringBuilder();
for (String keyword: keywords) {
if (builder.length() > 0) {
builder.append(',');
}
builder.append(keyword.trim());
}
this.keywords = Optional.of(builder.toString());
}
|
java
|
{
"resource": ""
}
|
q2981
|
S3ReportStorage.getKey
|
train
|
protected String getKey(final String ref, final String filename, final String extension) {
return prefix + ref + "/" + filename + "." + extension;
}
|
java
|
{
"resource": ""
}
|
q2982
|
TableProcessor.tryConvert
|
train
|
private Object tryConvert(
final MfClientHttpRequestFactory clientHttpRequestFactory,
final Object rowValue) throws URISyntaxException, IOException {
if (this.converters.isEmpty()) {
return rowValue;
}
String value = String.valueOf(rowValue);
for (TableColumnConverter<?> converter: this.converters) {
if (converter.canConvert(value)) {
return converter.resolve(clientHttpRequestFactory, value);
}
}
return rowValue;
}
|
java
|
{
"resource": ""
}
|
q2983
|
PJsonObject.optInt
|
train
|
@Override
public final Integer optInt(final String key) {
final int result = this.obj.optInt(key, Integer.MIN_VALUE);
return result == Integer.MIN_VALUE ? null : result;
}
|
java
|
{
"resource": ""
}
|
q2984
|
PJsonObject.optDouble
|
train
|
@Override
public final Double optDouble(final String key) {
double result = this.obj.optDouble(key, Double.NaN);
if (Double.isNaN(result)) {
return null;
}
return result;
}
|
java
|
{
"resource": ""
}
|
q2985
|
PJsonObject.optBool
|
train
|
@Override
public final Boolean optBool(final String key) {
if (this.obj.optString(key, null) == null) {
return null;
} else {
return this.obj.optBoolean(key);
}
}
|
java
|
{
"resource": ""
}
|
q2986
|
PJsonObject.optJSONObject
|
train
|
public final PJsonObject optJSONObject(final String key) {
final JSONObject val = this.obj.optJSONObject(key);
return val != null ? new PJsonObject(this, val, key) : null;
}
|
java
|
{
"resource": ""
}
|
q2987
|
PJsonObject.getJSONArray
|
train
|
public final PJsonArray getJSONArray(final String key) {
final JSONArray val = this.obj.optJSONArray(key);
if (val == null) {
throw new ObjectMissingException(this, key);
}
return new PJsonArray(this, val, key);
}
|
java
|
{
"resource": ""
}
|
q2988
|
PJsonObject.optJSONArray
|
train
|
public final PJsonArray optJSONArray(final String key, final PJsonArray defaultValue) {
PJsonArray result = optJSONArray(key);
return result != null ? result : defaultValue;
}
|
java
|
{
"resource": ""
}
|
q2989
|
PJsonObject.has
|
train
|
@Override
public final boolean has(final String key) {
String result = this.obj.optString(key, null);
return result != null;
}
|
java
|
{
"resource": ""
}
|
q2990
|
DataSourceProcessor.setAttributes
|
train
|
public void setAttributes(final Map<String, Attribute> attributes) {
this.internalAttributes = attributes;
this.allAttributes.putAll(attributes);
}
|
java
|
{
"resource": ""
}
|
q2991
|
DataSourceProcessor.setAttribute
|
train
|
public void setAttribute(final String name, final Attribute attribute) {
if (name.equals("datasource")) {
this.allAttributes.putAll(((DataSourceAttribute) attribute).getAttributes());
} else if (this.copyAttributes.contains(name)) {
this.allAttributes.put(name, attribute);
}
}
|
java
|
{
"resource": ""
}
|
q2992
|
SmtpConfig.getBody
|
train
|
@Nonnull
public String getBody() {
if (body == null) {
return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE;
} else {
return body;
}
}
|
java
|
{
"resource": ""
}
|
q2993
|
TilePreparationTask.isTileVisible
|
train
|
private boolean isTileVisible(final ReferencedEnvelope tileBounds) {
if (FloatingPointUtil.equals(this.transformer.getRotation(), 0.0)) {
return true;
}
final GeometryFactory gfac = new GeometryFactory();
final Optional<Geometry> rotatedMapBounds = getRotatedMapBounds(gfac);
if (rotatedMapBounds.isPresent()) {
return rotatedMapBounds.get().intersects(gfac.toGeometry(tileBounds));
} else {
// in case of an error, we simply load the tile
return true;
}
}
|
java
|
{
"resource": ""
}
|
q2994
|
MapfishJsonStyleVersion1.getStyleRules
|
train
|
private List<Rule> getStyleRules(final String styleProperty) {
final List<Rule> styleRules = new ArrayList<>(this.json.size());
for (Iterator<String> iterator = this.json.keys(); iterator.hasNext(); ) {
String styleKey = iterator.next();
if (styleKey.equals(JSON_STYLE_PROPERTY) ||
styleKey.equals(MapfishStyleParserPlugin.JSON_VERSION)) {
continue;
}
PJsonObject styleJson = this.json.getJSONObject(styleKey);
final List<Rule> currentRules = createStyleRule(styleKey, styleJson, styleProperty);
for (Rule currentRule: currentRules) {
if (currentRule != null) {
styleRules.add(currentRule);
}
}
}
return styleRules;
}
|
java
|
{
"resource": ""
}
|
q2995
|
ForwardHeadersProcessor.setHeaders
|
train
|
public void setHeaders(final Set<String> names) {
// transform to lower-case because header names should be case-insensitive
Set<String> lowerCaseNames = new HashSet<>();
for (String name: names) {
lowerCaseNames.add(name.toLowerCase());
}
this.headerNames = lowerCaseNames;
}
|
java
|
{
"resource": ""
}
|
q2996
|
OsmLayerParam.convertToMultiMap
|
train
|
public static Multimap<String, String> convertToMultiMap(final PObject objectParams) {
Multimap<String, String> params = HashMultimap.create();
if (objectParams != null) {
Iterator<String> customParamsIter = objectParams.keys();
while (customParamsIter.hasNext()) {
String key = customParamsIter.next();
if (objectParams.isArray(key)) {
final PArray array = objectParams.optArray(key);
for (int i = 0; i < array.size(); i++) {
params.put(key, array.getString(i));
}
} else {
params.put(key, objectParams.optString(key, ""));
}
}
}
return params;
}
|
java
|
{
"resource": ""
}
|
q2997
|
OsmLayerParam.getMaxExtent
|
train
|
public Envelope getMaxExtent() {
final int minX = 0;
final int maxX = 1;
final int minY = 2;
final int maxY = 3;
return new Envelope(this.maxExtent[minX], this.maxExtent[minY], this.maxExtent[maxX],
this.maxExtent[maxY]);
}
|
java
|
{
"resource": ""
}
|
q2998
|
ServletMapPrinterFactory.setConfigurationFiles
|
train
|
public final void setConfigurationFiles(final Map<String, String> configurationFiles)
throws URISyntaxException {
this.configurationFiles.clear();
this.configurationFileLastModifiedTimes.clear();
for (Map.Entry<String, String> entry: configurationFiles.entrySet()) {
if (!entry.getValue().contains(":/")) {
// assume is a file
this.configurationFiles.put(entry.getKey(), new File(entry.getValue()).toURI());
} else {
this.configurationFiles.put(entry.getKey(), new URI(entry.getValue()));
}
}
if (this.configFileLoader != null) {
this.validateConfigurationFiles();
}
}
|
java
|
{
"resource": ""
}
|
q2999
|
ZoomToFeatures.copy
|
train
|
public final ZoomToFeatures copy() {
ZoomToFeatures obj = new ZoomToFeatures();
obj.zoomType = this.zoomType;
obj.minScale = this.minScale;
obj.minMargin = this.minMargin;
return obj;
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.