_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3000
|
DataUrlConnection.getFullContentType
|
train
|
public String getFullContentType() {
final String url = this.url.toExternalForm().substring("data:".length());
final int endIndex = url.indexOf(',');
if (endIndex >= 0) {
final String contentType = url.substring(0, endIndex);
if (!contentType.isEmpty()) {
return contentType;
}
}
return "text/plain;charset=US-ASCII";
}
|
java
|
{
"resource": ""
}
|
q3001
|
DnsHostMatcher.tryOverrideValidation
|
train
|
@Override
public final Optional<Boolean> tryOverrideValidation(final MatchInfo matchInfo) throws SocketException,
UnknownHostException, MalformedURLException {
for (AddressHostMatcher addressHostMatcher: this.matchersForHost) {
if (addressHostMatcher.matches(matchInfo)) {
return Optional.empty();
}
}
return Optional.of(false);
}
|
java
|
{
"resource": ""
}
|
q3002
|
DnsHostMatcher.setHost
|
train
|
public final void setHost(final String host) throws UnknownHostException {
this.host = host;
final InetAddress[] inetAddresses = InetAddress.getAllByName(host);
for (InetAddress address: inetAddresses) {
final AddressHostMatcher matcher = new AddressHostMatcher();
matcher.setIp(address.getHostAddress());
this.matchersForHost.add(matcher);
}
}
|
java
|
{
"resource": ""
}
|
q3003
|
ProcessorDependencyGraph.getAllRequiredAttributes
|
train
|
@SuppressWarnings("unchecked")
public Multimap<String, Processor> getAllRequiredAttributes() {
Multimap<String, Processor> requiredInputs = HashMultimap.create();
for (ProcessorGraphNode root: this.roots) {
final BiMap<String, String> inputMapper = root.getInputMapper();
for (String attr: inputMapper.keySet()) {
requiredInputs.put(attr, root.getProcessor());
}
final Object inputParameter = root.getProcessor().createInputParameter();
if (inputParameter instanceof Values) {
continue;
} else if (inputParameter != null) {
final Class<?> inputParameterClass = inputParameter.getClass();
final Set<String> requiredAttributesDefinedInInputParameter =
getAttributeNames(inputParameterClass,
FILTER_ONLY_REQUIRED_ATTRIBUTES);
for (String attName: requiredAttributesDefinedInInputParameter) {
try {
if (inputParameterClass.getField(attName).getType() == Values.class) {
continue;
}
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
String mappedName = ProcessorUtils.getInputValueName(
root.getProcessor().getInputPrefix(),
inputMapper, attName);
requiredInputs.put(mappedName, root.getProcessor());
}
}
}
return requiredInputs;
}
|
java
|
{
"resource": ""
}
|
q3004
|
ProcessorDependencyGraph.getAllProcessors
|
train
|
public Set<Processor<?, ?>> getAllProcessors() {
IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();
for (ProcessorGraphNode<?, ?> root: this.roots) {
for (Processor p: root.getAllProcessors()) {
all.put(p, null);
}
}
return all.keySet();
}
|
java
|
{
"resource": ""
}
|
q3005
|
UriMatchers.validate
|
train
|
public void validate(final List<Throwable> validationErrors) {
if (this.matchers == null) {
validationErrors.add(new IllegalArgumentException(
"Matchers cannot be null. There should be at least a !acceptAll matcher"));
}
if (this.matchers != null && this.matchers.isEmpty()) {
validationErrors.add(new IllegalArgumentException(
"There are no url matchers defined. There should be at least a " +
"!acceptAll matcher"));
}
}
|
java
|
{
"resource": ""
}
|
q3006
|
StatsDReporterInit.init
|
train
|
@PostConstruct
public final void init() throws URISyntaxException {
final String address = getConfig(ADDRESS, null);
if (address != null) {
final URI uri = new URI("udp://" + address);
final String prefix = getConfig(PREFIX, "mapfish-print").replace("%h", getHostname());
final int period = Integer.parseInt(getConfig(PERIOD, "10"));
LOGGER.info("Starting a StatsD reporter targeting {} with prefix {} and period {}s",
uri, prefix, period);
this.reporter = StatsDReporter.forRegistry(this.metricRegistry)
.prefixedWith(prefix)
.build(uri.getHost(), uri.getPort());
this.reporter.start(period, TimeUnit.SECONDS);
}
}
|
java
|
{
"resource": ""
}
|
q3007
|
CreateMapProcessor.adjustBoundsToScaleAndMapSize
|
train
|
public static MapBounds adjustBoundsToScaleAndMapSize(
final GenericMapAttributeValues mapValues,
final Rectangle paintArea,
final MapBounds bounds,
final double dpi) {
MapBounds newBounds = bounds;
if (mapValues.isUseNearestScale()) {
newBounds = newBounds.adjustBoundsToNearestScale(
mapValues.getZoomLevels(),
mapValues.getZoomSnapTolerance(),
mapValues.getZoomLevelSnapStrategy(),
mapValues.getZoomSnapGeodetic(),
paintArea, dpi);
}
newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));
if (mapValues.isUseAdjustBounds()) {
newBounds = newBounds.adjustedEnvelope(paintArea);
}
return newBounds;
}
|
java
|
{
"resource": ""
}
|
q3008
|
CreateMapProcessor.createSvgGraphics
|
train
|
public static SVGGraphics2D createSvgGraphics(final Dimension size)
throws ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.getDOMImplementation().createDocument(null, "svg", null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
ctx.setStyleHandler(new OpacityAdjustingStyleHandler());
ctx.setComment("Generated by GeoTools2 with Batik SVG Generator");
SVGGraphics2D g2d = new SVGGraphics2D(ctx, true);
g2d.setSVGCanvasSize(size);
return g2d;
}
|
java
|
{
"resource": ""
}
|
q3009
|
CreateMapProcessor.saveSvgFile
|
train
|
public static void saveSvgFile(final SVGGraphics2D graphics2d, final File path) throws IOException {
try (FileOutputStream fs = new FileOutputStream(path);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fs, StandardCharsets.UTF_8);
Writer osw = new BufferedWriter(outputStreamWriter)
) {
graphics2d.stream(osw, true);
}
}
|
java
|
{
"resource": ""
}
|
q3010
|
CreateMapProcessor.getFeatureBounds
|
train
|
@Nonnull
private ReferencedEnvelope getFeatureBounds(
final MfClientHttpRequestFactory clientHttpRequestFactory,
final MapAttributeValues mapValues, final ExecutionContext context) {
final MapfishMapContext mapContext = createMapContext(mapValues);
String layerName = mapValues.zoomToFeatures.layer;
ReferencedEnvelope bounds = new ReferencedEnvelope();
for (MapLayer layer: mapValues.getLayers()) {
context.stopIfCanceled();
if ((!StringUtils.isEmpty(layerName) && layerName.equals(layer.getName())) ||
(StringUtils.isEmpty(layerName) && layer instanceof AbstractFeatureSourceLayer)) {
AbstractFeatureSourceLayer featureLayer = (AbstractFeatureSourceLayer) layer;
FeatureSource<?, ?> featureSource =
featureLayer.getFeatureSource(clientHttpRequestFactory, mapContext);
FeatureCollection<?, ?> features;
try {
features = featureSource.getFeatures();
} catch (IOException e) {
throw ExceptionUtils.getRuntimeException(e);
}
if (!features.isEmpty()) {
final ReferencedEnvelope curBounds = features.getBounds();
bounds.expandToInclude(curBounds);
}
}
}
return bounds;
}
|
java
|
{
"resource": ""
}
|
q3011
|
WorkingDirectories.getJasperCompilation
|
train
|
public final File getJasperCompilation(final Configuration configuration) {
File jasperCompilation = new File(getWorking(configuration), "jasper-bin");
createIfMissing(jasperCompilation, "Jasper Compilation");
return jasperCompilation;
}
|
java
|
{
"resource": ""
}
|
q3012
|
WorkingDirectories.getTaskDirectory
|
train
|
public final File getTaskDirectory() {
createIfMissing(this.working, "Working");
try {
return Files.createTempDirectory(this.working.toPath(), TASK_DIR_PREFIX).toFile();
} catch (IOException e) {
throw new AssertionError("Unable to create temporary directory in '" + this.working + "'");
}
}
|
java
|
{
"resource": ""
}
|
q3013
|
WorkingDirectories.removeDirectory
|
train
|
public final void removeDirectory(final File directory) {
try {
FileUtils.deleteDirectory(directory);
} catch (IOException e) {
LOGGER.error("Unable to delete directory '{}'", directory);
}
}
|
java
|
{
"resource": ""
}
|
q3014
|
WorkingDirectories.getBuildFileFor
|
train
|
public final File getBuildFileFor(
final Configuration configuration, final File jasperFileXml,
final String extension, final Logger logger) {
final String configurationAbsolutePath = configuration.getDirectory().getPath();
final int prefixToConfiguration = configurationAbsolutePath.length() + 1;
final String parentDir = jasperFileXml.getAbsoluteFile().getParent();
final String relativePathToFile;
if (configurationAbsolutePath.equals(parentDir)) {
relativePathToFile = FilenameUtils.getBaseName(jasperFileXml.getName());
} else {
final String relativePathToContainingDirectory = parentDir.substring(prefixToConfiguration);
relativePathToFile = relativePathToContainingDirectory + File.separator +
FilenameUtils.getBaseName(jasperFileXml.getName());
}
final File buildFile = new File(getJasperCompilation(configuration), relativePathToFile + extension);
if (!buildFile.getParentFile().exists() && !buildFile.getParentFile().mkdirs()) {
logger.error("Unable to create directory for containing compiled jasper report templates: {}",
buildFile.getParentFile());
}
return buildFile;
}
|
java
|
{
"resource": ""
}
|
q3015
|
WMTSLayer.createRestURI
|
train
|
public static URI createRestURI(
final String matrixId, final int row, final int col,
final WMTSLayerParam layerParam) throws URISyntaxException {
String path = layerParam.baseURL;
if (layerParam.dimensions != null) {
for (int i = 0; i < layerParam.dimensions.length; i++) {
String dimension = layerParam.dimensions[i];
String value = layerParam.dimensionParams.optString(dimension);
if (value == null) {
value = layerParam.dimensionParams.getString(dimension.toUpperCase());
}
path = path.replace("{" + dimension + "}", value);
}
}
path = path.replace("{TileMatrixSet}", layerParam.matrixSet);
path = path.replace("{TileMatrix}", matrixId);
path = path.replace("{TileRow}", String.valueOf(row));
path = path.replace("{TileCol}", String.valueOf(col));
path = path.replace("{style}", layerParam.style);
path = path.replace("{Layer}", layerParam.layer);
return new URI(path);
}
|
java
|
{
"resource": ""
}
|
q3016
|
PElement.getPath
|
train
|
public final String getPath(final String key) {
StringBuilder result = new StringBuilder();
addPathTo(result);
result.append(".");
result.append(getPathElement(key));
return result.toString();
}
|
java
|
{
"resource": ""
}
|
q3017
|
PElement.addPathTo
|
train
|
protected final void addPathTo(final StringBuilder result) {
if (this.parent != null) {
this.parent.addPathTo(result);
if (!(this.parent instanceof PJsonArray)) {
result.append(".");
}
}
result.append(getPathElement(this.contextName));
}
|
java
|
{
"resource": ""
}
|
q3018
|
WaitDB.main
|
train
|
public static void main(final String[] args) {
if (System.getProperty("db.name") == null) {
System.out.println("Not running in multi-instance mode: no DB to connect to");
System.exit(1);
}
while (true) {
try {
Class.forName("org.postgresql.Driver");
DriverManager.getConnection("jdbc:postgresql://" + System.getProperty("db.host") + ":5432/" +
System.getProperty("db.name"),
System.getProperty("db.username"),
System.getProperty("db.password"));
System.out.println("Opened database successfully. Running in multi-instance mode");
System.exit(0);
return;
} catch (Exception e) {
System.out.println("Failed to connect to the DB: " + e.toString());
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
//ignored
}
}
}
}
|
java
|
{
"resource": ""
}
|
q3019
|
ProcessorExecutionContext.started
|
train
|
private void started(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
try {
this.runningProcessors.put(processorGraphNode.getProcessor(), null);
} finally {
this.processorLock.unlock();
}
}
|
java
|
{
"resource": ""
}
|
q3020
|
ProcessorExecutionContext.isRunning
|
train
|
public boolean isRunning(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
try {
return this.runningProcessors.containsKey(processorGraphNode.getProcessor());
} finally {
this.processorLock.unlock();
}
}
|
java
|
{
"resource": ""
}
|
q3021
|
ProcessorExecutionContext.isFinished
|
train
|
public boolean isFinished(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
try {
return this.executedProcessors.containsKey(processorGraphNode.getProcessor());
} finally {
this.processorLock.unlock();
}
}
|
java
|
{
"resource": ""
}
|
q3022
|
ProcessorExecutionContext.finished
|
train
|
public void finished(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
try {
this.runningProcessors.remove(processorGraphNode.getProcessor());
this.executedProcessors.put(processorGraphNode.getProcessor(), null);
} finally {
this.processorLock.unlock();
}
}
|
java
|
{
"resource": ""
}
|
q3023
|
ScalebarDrawer.draw
|
train
|
public final void draw() {
AffineTransform transform = new AffineTransform(this.transform);
transform.concatenate(getAlignmentTransform());
// draw the background box
this.graphics2d.setTransform(transform);
this.graphics2d.setColor(this.params.getBackgroundColor());
this.graphics2d.fillRect(0, 0, this.settings.getSize().width, this.settings.getSize().height);
//draw the labels
this.graphics2d.setColor(this.params.getFontColor());
drawLabels(transform, this.params.getOrientation(), this.params.getLabelRotation());
//sets the transformation for drawing the bar and do it
final AffineTransform lineTransform = new AffineTransform(transform);
setLineTranslate(lineTransform);
if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT ||
this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) {
final AffineTransform rotate = AffineTransform.getQuadrantRotateInstance(1);
lineTransform.concatenate(rotate);
}
this.graphics2d.setTransform(lineTransform);
this.graphics2d.setStroke(new BasicStroke(this.settings.getLineWidth()));
this.graphics2d.setColor(this.params.getColor());
drawBar();
}
|
java
|
{
"resource": ""
}
|
q3024
|
ScalebarDrawer.getAlignmentTransform
|
train
|
private AffineTransform getAlignmentTransform() {
final int offsetX;
switch (this.settings.getParams().getAlign()) {
case LEFT:
offsetX = 0;
break;
case RIGHT:
offsetX = this.settings.getMaxSize().width - this.settings.getSize().width;
break;
case CENTER:
default:
offsetX = (int) Math
.floor(this.settings.getMaxSize().width / 2.0 - this.settings.getSize().width / 2.0);
break;
}
final int offsetY;
switch (this.settings.getParams().getVerticalAlign()) {
case TOP:
offsetY = 0;
break;
case BOTTOM:
offsetY = this.settings.getMaxSize().height - this.settings.getSize().height;
break;
case MIDDLE:
default:
offsetY = (int) Math.floor(this.settings.getMaxSize().height / 2.0 -
this.settings.getSize().height / 2.0);
break;
}
return AffineTransform.getTranslateInstance(Math.round(offsetX), Math.round(offsetY));
}
|
java
|
{
"resource": ""
}
|
q3025
|
AbstractGeotoolsLayer.getLayerTransformer
|
train
|
protected final MapfishMapContext getLayerTransformer(final MapfishMapContext transformer) {
MapfishMapContext layerTransformer = transformer;
if (!FloatingPointUtil.equals(transformer.getRotation(), 0.0) && !this.supportsNativeRotation()) {
// if a rotation is set and the rotation can not be handled natively
// by the layer, we have to adjust the bounds and map size
layerTransformer = new MapfishMapContext(
transformer,
transformer.getRotatedBoundsAdjustedForPreciseRotatedMapSize(),
transformer.getRotatedMapSize(),
0,
transformer.getDPI(),
transformer.isForceLongitudeFirst(),
transformer.isDpiSensitiveStyle());
}
return layerTransformer;
}
|
java
|
{
"resource": ""
}
|
q3026
|
ValuesLogger.log
|
train
|
public static void log(final String templateName, final Template template, final Values values) {
new ValuesLogger().doLog(templateName, template, values);
}
|
java
|
{
"resource": ""
}
|
q3027
|
PrintJob.getFileName
|
train
|
private static String getFileName(@Nullable final MapPrinter mapPrinter, final PJsonObject spec) {
String fileName = spec.optString(Constants.OUTPUT_FILENAME_KEY);
if (fileName != null) {
return fileName;
}
if (mapPrinter != null) {
final Configuration config = mapPrinter.getConfiguration();
final String templateName = spec.getString(Constants.JSON_LAYOUT_KEY);
final Template template = config.getTemplate(templateName);
if (template.getOutputFilename() != null) {
return template.getOutputFilename();
}
if (config.getOutputFilename() != null) {
return config.getOutputFilename();
}
}
return "mapfish-print-report";
}
|
java
|
{
"resource": ""
}
|
q3028
|
PrintJob.withOpenOutputStream
|
train
|
protected PrintResult withOpenOutputStream(final PrintAction function) throws Exception {
final File reportFile = getReportFile();
final Processor.ExecutionContext executionContext;
try (FileOutputStream out = new FileOutputStream(reportFile);
BufferedOutputStream bout = new BufferedOutputStream(out)) {
executionContext = function.run(bout);
}
return new PrintResult(reportFile.length(), executionContext);
}
|
java
|
{
"resource": ""
}
|
q3029
|
PointGridStyle.get
|
train
|
static Style get(final GridParam params) {
final StyleBuilder builder = new StyleBuilder();
final Symbolizer pointSymbolizer = crossSymbolizer("shape://plus", builder, CROSS_SIZE,
params.gridColor);
final Style style = builder.createStyle(pointSymbolizer);
final List<Symbolizer> symbolizers = style.featureTypeStyles().get(0).rules().get(0).symbolizers();
if (params.haloRadius > 0.0) {
Symbolizer halo = crossSymbolizer("cross", builder, CROSS_SIZE + params.haloRadius * 2.0,
params.haloColor);
symbolizers.add(0, halo);
}
return style;
}
|
java
|
{
"resource": ""
}
|
q3030
|
ZoomLevels.get
|
train
|
public Scale get(final int index, final DistanceUnit unit) {
return new Scale(this.scaleDenominators[index], unit, PDF_DPI);
}
|
java
|
{
"resource": ""
}
|
q3031
|
ZoomLevels.getScaleDenominators
|
train
|
public double[] getScaleDenominators() {
double[] dest = new double[this.scaleDenominators.length];
System.arraycopy(this.scaleDenominators, 0, dest, 0, this.scaleDenominators.length);
return dest;
}
|
java
|
{
"resource": ""
}
|
q3032
|
FeaturesParser.autoTreat
|
train
|
public final SimpleFeatureCollection autoTreat(final Template template, final String features)
throws IOException {
SimpleFeatureCollection featuresCollection = treatStringAsURL(template, features);
if (featuresCollection == null) {
featuresCollection = treatStringAsGeoJson(features);
}
return featuresCollection;
}
|
java
|
{
"resource": ""
}
|
q3033
|
FeaturesParser.treatStringAsURL
|
train
|
public final SimpleFeatureCollection treatStringAsURL(final Template template, final String geoJsonUrl)
throws IOException {
URL url;
try {
url = FileUtils.testForLegalFileUrl(template.getConfiguration(), new URL(geoJsonUrl));
} catch (MalformedURLException e) {
return null;
}
final String geojsonString;
if (url.getProtocol().equalsIgnoreCase("file")) {
geojsonString = IOUtils.toString(url, Constants.DEFAULT_CHARSET.name());
} else {
geojsonString = URIUtils.toString(this.httpRequestFactory, url);
}
return treatStringAsGeoJson(geojsonString);
}
|
java
|
{
"resource": ""
}
|
q3034
|
WmsLayer.supportsNativeRotation
|
train
|
@Override
public boolean supportsNativeRotation() {
return this.params.useNativeAngle &&
(this.params.serverType == WmsLayerParam.ServerType.MAPSERVER ||
this.params.serverType == WmsLayerParam.ServerType.GEOSERVER);
}
|
java
|
{
"resource": ""
}
|
q3035
|
AbstractFileConfigFileLoader.platformIndependentUriToFile
|
train
|
protected static File platformIndependentUriToFile(final URI fileURI) {
File file;
try {
file = new File(fileURI);
} catch (IllegalArgumentException e) {
if (fileURI.toString().startsWith("file://")) {
file = new File(fileURI.toString().substring("file://".length()));
} else {
throw e;
}
}
return file;
}
|
java
|
{
"resource": ""
}
|
q3036
|
PMultiObject.getContext
|
train
|
public static String getContext(final PObject[] objs) {
StringBuilder result = new StringBuilder("(");
boolean first = true;
for (PObject obj: objs) {
if (!first) {
result.append('|');
}
first = false;
result.append(obj.getCurrentPath());
}
result.append(')');
return result.toString();
}
|
java
|
{
"resource": ""
}
|
q3037
|
PrintJobDao.save
|
train
|
public final void save(final PrintJobStatusExtImpl entry) {
getSession().merge(entry);
getSession().flush();
getSession().evict(entry);
}
|
java
|
{
"resource": ""
}
|
q3038
|
PrintJobDao.getValue
|
train
|
public final Object getValue(final String id, final String property) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);
final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);
criteria.select(root.get(property));
criteria.where(builder.equal(root.get("referenceId"), id));
return getSession().createQuery(criteria).uniqueResult();
}
|
java
|
{
"resource": ""
}
|
q3039
|
PrintJobDao.cancelOld
|
train
|
public final void cancelOld(
final long starttimeThreshold, final long checkTimeThreshold, final String message) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaUpdate<PrintJobStatusExtImpl> update =
builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);
final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);
update.where(builder.and(
builder.equal(root.get("status"), PrintJobStatus.Status.WAITING),
builder.or(
builder.lessThan(root.get("entry").get("startTime"), starttimeThreshold),
builder.and(builder.isNotNull(root.get("lastCheckTime")),
builder.lessThan(root.get("lastCheckTime"), checkTimeThreshold))
)
));
update.set(root.get("status"), PrintJobStatus.Status.CANCELLED);
update.set(root.get("error"), message);
getSession().createQuery(update).executeUpdate();
}
|
java
|
{
"resource": ""
}
|
q3040
|
PrintJobDao.updateLastCheckTime
|
train
|
public final void updateLastCheckTime(final String id, final long lastCheckTime) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaUpdate<PrintJobStatusExtImpl> update =
builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);
final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);
update.where(builder.equal(root.get("referenceId"), id));
update.set(root.get("lastCheckTime"), lastCheckTime);
getSession().createQuery(update).executeUpdate();
}
|
java
|
{
"resource": ""
}
|
q3041
|
PrintJobDao.deleteOld
|
train
|
public final int deleteOld(final long checkTimeThreshold) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaDelete<PrintJobStatusExtImpl> delete =
builder.createCriteriaDelete(PrintJobStatusExtImpl.class);
final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);
delete.where(builder.and(builder.isNotNull(root.get("lastCheckTime")),
builder.lessThan(root.get("lastCheckTime"), checkTimeThreshold)));
return getSession().createQuery(delete).executeUpdate();
}
|
java
|
{
"resource": ""
}
|
q3042
|
PrintJobDao.poll
|
train
|
public final List<PrintJobStatusExtImpl> poll(final int size) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaQuery<PrintJobStatusExtImpl> criteria =
builder.createQuery(PrintJobStatusExtImpl.class);
final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);
root.alias("pj");
criteria.where(builder.equal(root.get("status"), PrintJobStatus.Status.WAITING));
criteria.orderBy(builder.asc(root.get("entry").get("startTime")));
final Query<PrintJobStatusExtImpl> query = getSession().createQuery(criteria);
query.setMaxResults(size);
// LOCK but don't wait for release (since this is run continuously
// anyway, no wait prevents deadlock)
query.setLockMode("pj", LockMode.UPGRADE_NOWAIT);
try {
return query.getResultList();
} catch (PessimisticLockException ex) {
// Another process was polling at the same time. We can ignore this error
return Collections.emptyList();
}
}
|
java
|
{
"resource": ""
}
|
q3043
|
PrintJobDao.getResult
|
train
|
public final PrintJobResultExtImpl getResult(final URI reportURI) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaQuery<PrintJobResultExtImpl> criteria =
builder.createQuery(PrintJobResultExtImpl.class);
final Root<PrintJobResultExtImpl> root = criteria.from(PrintJobResultExtImpl.class);
criteria.where(builder.equal(root.get("reportURI"), reportURI.toString()));
return getSession().createQuery(criteria).uniqueResult();
}
|
java
|
{
"resource": ""
}
|
q3044
|
PrintJobDao.delete
|
train
|
public void delete(final String referenceId) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaDelete<PrintJobStatusExtImpl> delete =
builder.createCriteriaDelete(PrintJobStatusExtImpl.class);
final Root<PrintJobStatusExtImpl> root = delete.from(PrintJobStatusExtImpl.class);
delete.where(builder.equal(root.get("referenceId"), referenceId));
getSession().createQuery(delete).executeUpdate();
}
|
java
|
{
"resource": ""
}
|
q3045
|
PrintJobEntryImpl.configureAccess
|
train
|
public final void configureAccess(final Template template, final ApplicationContext context) {
final Configuration configuration = template.getConfiguration();
AndAccessAssertion accessAssertion = context.getBean(AndAccessAssertion.class);
accessAssertion.setPredicates(configuration.getAccessAssertion(), template.getAccessAssertion());
this.access = accessAssertion;
}
|
java
|
{
"resource": ""
}
|
q3046
|
AbstractGridCoverageLayerPlugin.createStyleSupplier
|
train
|
protected final <T> StyleSupplier<T> createStyleSupplier(
final Template template,
final String styleRef) {
return new StyleSupplier<T>() {
@Override
public Style load(
final MfClientHttpRequestFactory requestFactory,
final T featureSource) {
final StyleParser parser = AbstractGridCoverageLayerPlugin.this.styleParser;
return OptionalUtils.or(
() -> template.getStyle(styleRef),
() -> parser.loadStyle(template.getConfiguration(), requestFactory, styleRef))
.orElse(template.getConfiguration().getDefaultStyle(NAME));
}
};
}
|
java
|
{
"resource": ""
}
|
q3047
|
RegistryJobQueue.store
|
train
|
private void store(final PrintJobStatus printJobStatus) throws JSONException {
JSONObject metadata = new JSONObject();
metadata.put(JSON_REQUEST_DATA, printJobStatus.getEntry().getRequestData().getInternalObj());
metadata.put(JSON_STATUS, printJobStatus.getStatus().toString());
metadata.put(JSON_START_DATE, printJobStatus.getStartTime());
metadata.put(JSON_REQUEST_COUNT, printJobStatus.getRequestCount());
if (printJobStatus.getCompletionDate() != null) {
metadata.put(JSON_COMPLETION_DATE, printJobStatus.getCompletionTime());
}
metadata.put(JSON_ACCESS_ASSERTION, this.assertionPersister.marshal(printJobStatus.getAccess()));
if (printJobStatus.getError() != null) {
metadata.put(JSON_ERROR, printJobStatus.getError());
}
if (printJobStatus.getResult() != null) {
metadata.put(JSON_REPORT_URI, printJobStatus.getResult().getReportURIString());
metadata.put(JSON_FILENAME, printJobStatus.getResult().getFileName());
metadata.put(JSON_FILE_EXT, printJobStatus.getResult().getFileExtension());
metadata.put(JSON_MIME_TYPE, printJobStatus.getResult().getMimeType());
}
this.registry.put(RESULT_METADATA + printJobStatus.getReferenceId(), metadata);
}
|
java
|
{
"resource": ""
}
|
q3048
|
ColorParser.canParseColor
|
train
|
public static boolean canParseColor(final String colorString) {
try {
return ColorParser.toColor(colorString) != null;
} catch (Exception exc) {
return false;
}
}
|
java
|
{
"resource": ""
}
|
q3049
|
SetTiledWmsProcessor.adaptTileDimensions
|
train
|
private static Dimension adaptTileDimensions(
final Dimension pixels, final int maxWidth, final int maxHeight) {
return new Dimension(adaptTileDimension(pixels.width, maxWidth),
adaptTileDimension(pixels.height, maxHeight));
}
|
java
|
{
"resource": ""
}
|
q3050
|
URIUtils.getParameters
|
train
|
public static Multimap<String, String> getParameters(final String rawQuery) {
Multimap<String, String> result = HashMultimap.create();
if (rawQuery == null) {
return result;
}
StringTokenizer tokens = new StringTokenizer(rawQuery, "&");
while (tokens.hasMoreTokens()) {
String pair = tokens.nextToken();
int pos = pair.indexOf('=');
String key;
String value;
if (pos == -1) {
key = pair;
value = "";
} else {
try {
key = URLDecoder.decode(pair.substring(0, pos), "UTF-8");
value = URLDecoder.decode(pair.substring(pos + 1), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
result.put(key, value);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q3051
|
URIUtils.setQueryParams
|
train
|
public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {
StringBuilder queryString = new StringBuilder();
for (Map.Entry<String, String> entry: queryParams.entries()) {
if (queryString.length() > 0) {
queryString.append("&");
}
queryString.append(entry.getKey()).append("=").append(entry.getValue());
}
try {
if (initialUri.getHost() == null && initialUri.getAuthority() != null) {
return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),
queryString.toString(),
initialUri.getFragment());
} else {
return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),
initialUri.getPort(),
initialUri.getPath(),
queryString.toString(), initialUri.getFragment());
}
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q3052
|
URIUtils.setPath
|
train
|
public static URI setPath(final URI initialUri, final String path) {
String finalPath = path;
if (!finalPath.startsWith("/")) {
finalPath = '/' + path;
}
try {
if (initialUri.getHost() == null && initialUri.getAuthority() != null) {
return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,
initialUri.getQuery(),
initialUri.getFragment());
} else {
return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),
initialUri.getPort(),
finalPath, initialUri.getQuery(), initialUri.getFragment());
}
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q3053
|
PYamlArray.toJSON
|
train
|
public final PJsonArray toJSON() {
JSONArray jsonArray = new JSONArray();
final int size = this.array.size();
for (int i = 0; i < size; i++) {
final Object o = get(i);
if (o instanceof PYamlObject) {
PYamlObject pYamlObject = (PYamlObject) o;
jsonArray.put(pYamlObject.toJSON().getInternalObj());
} else if (o instanceof PYamlArray) {
PYamlArray pYamlArray = (PYamlArray) o;
jsonArray.put(pYamlArray.toJSON().getInternalArray());
} else {
jsonArray.put(o);
}
}
return new PJsonArray(null, jsonArray, getContextName());
}
|
java
|
{
"resource": ""
}
|
q3054
|
ConfigFileLoaderManager.checkUniqueSchemes
|
train
|
@PostConstruct
public void checkUniqueSchemes() {
Multimap<String, ConfigFileLoaderPlugin> schemeToPluginMap = HashMultimap.create();
for (ConfigFileLoaderPlugin plugin: getLoaderPlugins()) {
schemeToPluginMap.put(plugin.getUriScheme(), plugin);
}
StringBuilder violations = new StringBuilder();
for (String scheme: schemeToPluginMap.keySet()) {
final Collection<ConfigFileLoaderPlugin> plugins = schemeToPluginMap.get(scheme);
if (plugins.size() > 1) {
violations.append("\n\n* ").append("There are has multiple ")
.append(ConfigFileLoaderPlugin.class.getSimpleName())
.append(" plugins that support the scheme: '").append(scheme).append('\'')
.append(":\n\t").append(plugins);
}
}
if (violations.length() > 0) {
throw new IllegalStateException(violations.toString());
}
}
|
java
|
{
"resource": ""
}
|
q3055
|
ConfigFileLoaderManager.getSupportedUriSchemes
|
train
|
public Set<String> getSupportedUriSchemes() {
Set<String> schemes = new HashSet<>();
for (ConfigFileLoaderPlugin loaderPlugin: this.getLoaderPlugins()) {
schemes.add(loaderPlugin.getUriScheme());
}
return schemes;
}
|
java
|
{
"resource": ""
}
|
q3056
|
GenericMapAttribute.parseProjection
|
train
|
public static CoordinateReferenceSystem parseProjection(
final String projection, final Boolean longitudeFirst) {
try {
if (longitudeFirst == null) {
return CRS.decode(projection);
} else {
return CRS.decode(projection, longitudeFirst);
}
} catch (NoSuchAuthorityCodeException e) {
throw new RuntimeException(projection + " was not recognized as a crs code", e);
} catch (FactoryException e) {
throw new RuntimeException("Error occurred while parsing: " + projection, e);
}
}
|
java
|
{
"resource": ""
}
|
q3057
|
GenericMapAttribute.getDpiSuggestions
|
train
|
public final double[] getDpiSuggestions() {
if (this.dpiSuggestions == null) {
List<Double> list = new ArrayList<>();
for (double suggestion: DEFAULT_DPI_VALUES) {
if (suggestion <= this.maxDpi) {
list.add(suggestion);
}
}
double[] suggestions = new double[list.size()];
for (int i = 0; i < suggestions.length; i++) {
suggestions[i] = list.get(i);
}
return suggestions;
}
return this.dpiSuggestions;
}
|
java
|
{
"resource": ""
}
|
q3058
|
AbstractSingleImageLayer.createErrorImage
|
train
|
protected BufferedImage createErrorImage(final Rectangle area) {
final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE);
final Graphics2D graphics = bufferedImage.createGraphics();
try {
graphics.setBackground(ColorParser.toColor(this.configuration.getTransparentTileErrorColor()));
graphics.clearRect(0, 0, area.width, area.height);
return bufferedImage;
} finally {
graphics.dispose();
}
}
|
java
|
{
"resource": ""
}
|
q3059
|
AbstractSingleImageLayer.fetchImage
|
train
|
protected BufferedImage fetchImage(
@Nonnull final ClientHttpRequest request, @Nonnull final MapfishMapContext transformer)
throws IOException {
final String baseMetricName = getClass().getName() + ".read." +
StatsUtils.quotePart(request.getURI().getHost());
final Timer.Context timerDownload = this.registry.timer(baseMetricName).time();
try (ClientHttpResponse httpResponse = request.execute()) {
if (httpResponse.getStatusCode() != HttpStatus.OK) {
final String message = String.format(
"Invalid status code for %s (%d!=%d). The response was: '%s'",
request.getURI(), httpResponse.getStatusCode().value(),
HttpStatus.OK.value(), httpResponse.getStatusText());
this.registry.counter(baseMetricName + ".error").inc();
if (getFailOnError()) {
throw new RuntimeException(message);
} else {
LOGGER.info(message);
return createErrorImage(transformer.getPaintArea());
}
}
final List<String> contentType = httpResponse.getHeaders().get("Content-Type");
if (contentType == null || contentType.size() != 1) {
LOGGER.debug("The image {} didn't return a valid content type header.",
request.getURI());
} else if (!contentType.get(0).startsWith("image/")) {
final byte[] data;
try (InputStream body = httpResponse.getBody()) {
data = IOUtils.toByteArray(body);
}
LOGGER.debug("We get a wrong image for {}, content type: {}\nresult:\n{}",
request.getURI(), contentType.get(0),
new String(data, StandardCharsets.UTF_8));
this.registry.counter(baseMetricName + ".error").inc();
return createErrorImage(transformer.getPaintArea());
}
final BufferedImage image = ImageIO.read(httpResponse.getBody());
if (image == null) {
LOGGER.warn("Cannot read image from %a", request.getURI());
this.registry.counter(baseMetricName + ".error").inc();
if (getFailOnError()) {
throw new RuntimeException("Cannot read image from " + request.getURI());
} else {
return createErrorImage(transformer.getPaintArea());
}
}
timerDownload.stop();
return image;
} catch (Throwable e) {
this.registry.counter(baseMetricName + ".error").inc();
throw e;
}
}
|
java
|
{
"resource": ""
}
|
q3060
|
SetsUtils.create
|
train
|
@SafeVarargs
public static <T> Set<T> create(final T... values) {
Set<T> result = new HashSet<>(values.length);
Collections.addAll(result, values);
return result;
}
|
java
|
{
"resource": ""
}
|
q3061
|
ShutdownHookCleanUp.removeShutdownHook
|
train
|
@SuppressWarnings({"deprecation", "WeakerAccess"})
protected void removeShutdownHook(ClassLoaderLeakPreventor preventor, Thread shutdownHook) {
final String displayString = "'" + shutdownHook + "' of type " + shutdownHook.getClass().getName();
preventor.error("Removing shutdown hook: " + displayString);
Runtime.getRuntime().removeShutdownHook(shutdownHook);
if(executeShutdownHooks) { // Shutdown hooks should be executed
preventor.info("Executing shutdown hook now: " + displayString);
// Make sure it's from protected ClassLoader
shutdownHook.start(); // Run cleanup immediately
if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish
try {
shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run
}
catch (InterruptedException e) {
// Do nothing
}
if(shutdownHook.isAlive()) {
preventor.warn(shutdownHook + "still running after " + shutdownHookWaitMs + " ms - Stopping!");
shutdownHook.stop();
}
}
}
}
|
java
|
{
"resource": ""
}
|
q3062
|
ClassLoaderLeakPreventorListener.getIntInitParameter
|
train
|
protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {
final String parameterString = servletContext.getInitParameter(parameterName);
if(parameterString != null && parameterString.trim().length() > 0) {
try {
return Integer.parseInt(parameterString);
}
catch (NumberFormatException e) {
// Do nothing, return default value
}
}
return defaultValue;
}
|
java
|
{
"resource": ""
}
|
q3063
|
RmiTargetsCleanUp.clearRmiTargetsMap
|
train
|
@SuppressWarnings("WeakerAccess")
protected void clearRmiTargetsMap(ClassLoaderLeakPreventor preventor, Map<?, ?> rmiTargetsMap) {
try {
final Field cclField = preventor.findFieldOfClass("sun.rmi.transport.Target", "ccl");
preventor.debug("Looping " + rmiTargetsMap.size() + " RMI Targets to find leaks");
for(Iterator<?> iter = rmiTargetsMap.values().iterator(); iter.hasNext(); ) {
Object target = iter.next(); // sun.rmi.transport.Target
ClassLoader ccl = (ClassLoader) cclField.get(target);
if(preventor.isClassLoaderOrChild(ccl)) {
preventor.warn("Removing RMI Target: " + target);
iter.remove();
}
}
}
catch (Exception ex) {
preventor.error(ex);
}
}
|
java
|
{
"resource": ""
}
|
q3064
|
MBeanCleanUp.isJettyWithJMX
|
train
|
@SuppressWarnings("WeakerAccess")
protected boolean isJettyWithJMX(ClassLoaderLeakPreventor preventor) {
final ClassLoader classLoader = preventor.getClassLoader();
try {
// If package org.eclipse.jetty is found, we may be running under jetty
if (classLoader.getResource("org/eclipse/jetty") == null) {
return false;
}
Class.forName("org.eclipse.jetty.jmx.MBeanContainer", false, classLoader.getParent()); // JMX enabled?
Class.forName("org.eclipse.jetty.webapp.WebAppContext", false, classLoader.getParent());
}
catch(Exception ex) { // For example ClassNotFoundException
return false;
}
// Seems we are running in Jetty with JMX enabled
return true;
}
|
java
|
{
"resource": ""
}
|
q3065
|
LongHashMap.keys
|
train
|
public long[] keys() {
long[] values = new long[size];
int idx = 0;
for (Entry entry : table) {
while (entry != null) {
values[idx++] = entry.key;
entry = entry.next;
}
}
return values;
}
|
java
|
{
"resource": ""
}
|
q3066
|
LongHashMap.entries
|
train
|
public Entry<T>[] entries() {
@SuppressWarnings("unchecked")
Entry<T>[] entries = new Entry[size];
int idx = 0;
for (Entry entry : table) {
while (entry != null) {
entries[idx++] = entry;
entry = entry.next;
}
}
return entries;
}
|
java
|
{
"resource": ""
}
|
q3067
|
LongHashSet.add
|
train
|
public boolean add(long key) {
final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
final Entry entryOriginal = table[index];
for (Entry entry = entryOriginal; entry != null; entry = entry.next) {
if (entry.key == key) {
return false;
}
}
table[index] = new Entry(key, entryOriginal);
size++;
if (size > threshold) {
setCapacity(2 * capacity);
}
return true;
}
|
java
|
{
"resource": ""
}
|
q3068
|
LongHashSet.remove
|
train
|
public boolean remove(long key) {
int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
Entry previous = null;
Entry entry = table[index];
while (entry != null) {
Entry next = entry.next;
if (entry.key == key) {
if (previous == null) {
table[index] = next;
} else {
previous.next = next;
}
size--;
return true;
}
previous = entry;
entry = next;
}
return false;
}
|
java
|
{
"resource": ""
}
|
q3069
|
ObjectCache.put
|
train
|
public VALUE put(KEY key, VALUE object) {
CacheEntry<VALUE> entry;
if (referenceType == ReferenceType.WEAK) {
entry = new CacheEntry<>(new WeakReference<>(object), null);
} else if (referenceType == ReferenceType.SOFT) {
entry = new CacheEntry<>(new SoftReference<>(object), null);
} else {
entry = new CacheEntry<>(null, object);
}
countPutCountSinceEviction++;
countPut++;
if (isExpiring && nextCleanUpTimestamp == 0) {
nextCleanUpTimestamp = System.currentTimeMillis() + expirationMillis + 1;
}
CacheEntry<VALUE> oldEntry;
synchronized (this) {
if (values.size() >= maxSize) {
evictToTargetSize(maxSize - 1);
}
oldEntry = values.put(key, entry);
}
return getValueForRemoved(oldEntry);
}
|
java
|
{
"resource": ""
}
|
q3070
|
ObjectCache.putAll
|
train
|
public void putAll(Map<KEY, VALUE> mapDataToPut) {
int targetSize = maxSize - mapDataToPut.size();
if (maxSize > 0 && values.size() > targetSize) {
evictToTargetSize(targetSize);
}
Set<Entry<KEY, VALUE>> entries = mapDataToPut.entrySet();
for (Entry<KEY, VALUE> entry : entries) {
put(entry.getKey(), entry.getValue());
}
}
|
java
|
{
"resource": ""
}
|
q3071
|
ObjectCache.get
|
train
|
public VALUE get(KEY key) {
CacheEntry<VALUE> entry;
synchronized (this) {
entry = values.get(key);
}
VALUE value;
if (entry != null) {
if (isExpiring) {
long age = System.currentTimeMillis() - entry.timeCreated;
if (age < expirationMillis) {
value = getValue(key, entry);
} else {
countExpired++;
synchronized (this) {
values.remove(key);
}
value = null;
}
} else {
value = getValue(key, entry);
}
} else {
value = null;
}
if (value != null) {
countHit++;
} else {
countMiss++;
}
return value;
}
|
java
|
{
"resource": ""
}
|
q3072
|
IoUtils.copyAllBytes
|
train
|
public static int copyAllBytes(InputStream in, OutputStream out) throws IOException {
int byteCount = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
int read = in.read(buffer);
if (read == -1) {
break;
}
out.write(buffer, 0, read);
byteCount += read;
}
return byteCount;
}
|
java
|
{
"resource": ""
}
|
q3073
|
CircularByteBuffer.get
|
train
|
public synchronized int get() {
if (available == 0) {
return -1;
}
byte value = buffer[idxGet];
idxGet = (idxGet + 1) % capacity;
available--;
return value;
}
|
java
|
{
"resource": ""
}
|
q3074
|
CircularByteBuffer.get
|
train
|
public synchronized int get(byte[] dst, int off, int len) {
if (available == 0) {
return 0;
}
// limit is last index to read + 1
int limit = idxGet < idxPut ? idxPut : capacity;
int count = Math.min(limit - idxGet, len);
System.arraycopy(buffer, idxGet, dst, off, count);
idxGet += count;
if (idxGet == capacity) {
// Array end reached, check if we have more
int count2 = Math.min(len - count, idxPut);
if (count2 > 0) {
System.arraycopy(buffer, 0, dst, off + count, count2);
idxGet = count2;
count += count2;
} else {
idxGet = 0;
}
}
available -= count;
return count;
}
|
java
|
{
"resource": ""
}
|
q3075
|
CircularByteBuffer.put
|
train
|
public synchronized boolean put(byte value) {
if (available == capacity) {
return false;
}
buffer[idxPut] = value;
idxPut = (idxPut + 1) % capacity;
available++;
return true;
}
|
java
|
{
"resource": ""
}
|
q3076
|
CircularByteBuffer.put
|
train
|
public synchronized int put(byte[] src, int off, int len) {
if (available == capacity) {
return 0;
}
// limit is last index to put + 1
int limit = idxPut < idxGet ? idxGet : capacity;
int count = Math.min(limit - idxPut, len);
System.arraycopy(src, off, buffer, idxPut, count);
idxPut += count;
if (idxPut == capacity) {
// Array end reached, check if we have more
int count2 = Math.min(len - count, idxGet);
if (count2 > 0) {
System.arraycopy(src, off + count, buffer, 0, count2);
idxPut = count2;
count += count2;
} else {
idxPut = 0;
}
}
available += count;
return count;
}
|
java
|
{
"resource": ""
}
|
q3077
|
CircularByteBuffer.skip
|
train
|
public synchronized int skip(int count) {
if (count > available) {
count = available;
}
idxGet = (idxGet + count) % capacity;
available -= count;
return count;
}
|
java
|
{
"resource": ""
}
|
q3078
|
FileUtils.readObject
|
train
|
public static Object readObject(File file) throws IOException,
ClassNotFoundException {
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(fileIn));
try {
return in.readObject();
} finally {
IoUtils.safeClose(in);
}
}
|
java
|
{
"resource": ""
}
|
q3079
|
FileUtils.writeObject
|
train
|
public static void writeObject(File file, Object object) throws IOException {
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));
try {
out.writeObject(object);
out.flush();
// Force sync
fileOut.getFD().sync();
} finally {
IoUtils.safeClose(out);
}
}
|
java
|
{
"resource": ""
}
|
q3080
|
DateUtils.setTime
|
train
|
public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
calendar.set(Calendar.MILLISECOND, millisecond);
}
|
java
|
{
"resource": ""
}
|
q3081
|
DateUtils.getDayAsReadableInt
|
train
|
public static int getDayAsReadableInt(long time) {
Calendar cal = calendarThreadLocal.get();
cal.setTimeInMillis(time);
return getDayAsReadableInt(cal);
}
|
java
|
{
"resource": ""
}
|
q3082
|
DateUtils.getDayAsReadableInt
|
train
|
public static int getDayAsReadableInt(Calendar calendar) {
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
return year * 10000 + month * 100 + day;
}
|
java
|
{
"resource": ""
}
|
q3083
|
StringUtils.encodeUrlIso
|
train
|
public static String encodeUrlIso(String stringToEncode) {
try {
return URLEncoder.encode(stringToEncode, "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
}
|
java
|
{
"resource": ""
}
|
q3084
|
StringUtils.decodeUrl
|
train
|
public static String decodeUrl(String stringToDecode) {
try {
return URLDecoder.decode(stringToDecode, "UTF-8");
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
}
|
java
|
{
"resource": ""
}
|
q3085
|
StringUtils.decodeUrlIso
|
train
|
public static String decodeUrlIso(String stringToDecode) {
try {
return URLDecoder.decode(stringToDecode, "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
}
|
java
|
{
"resource": ""
}
|
q3086
|
StringUtils.ellipsize
|
train
|
public static String ellipsize(String text, int maxLength, String end) {
if (text != null && text.length() > maxLength) {
return text.substring(0, maxLength - end.length()) + end;
}
return text;
}
|
java
|
{
"resource": ""
}
|
q3087
|
StringUtils.join
|
train
|
public static String join(Iterable<?> iterable, String separator) {
if (iterable != null) {
StringBuilder buf = new StringBuilder();
Iterator<?> it = iterable.iterator();
char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;
while (it.hasNext()) {
buf.append(it.next());
if (it.hasNext()) {
if (singleChar != 0) {
// More efficient
buf.append(singleChar);
} else {
buf.append(separator);
}
}
}
return buf.toString();
} else {
return "";
}
}
|
java
|
{
"resource": ""
}
|
q3088
|
StringUtils.join
|
train
|
public static String join(int[] array, String separator) {
if (array != null) {
StringBuilder buf = new StringBuilder(Math.max(16, (separator.length() + 1) * array.length));
char singleChar = separator.length() == 1 ? separator.charAt(0) : 0;
for (int i = 0; i < array.length; i++) {
if (i != 0) {
if (singleChar != 0) {
// More efficient
buf.append(singleChar);
} else {
buf.append(separator);
}
}
buf.append(array[i]);
}
return buf.toString();
} else {
return "";
}
}
|
java
|
{
"resource": ""
}
|
q3089
|
RequestForwarder.prepareForwardedResponseHeaders
|
train
|
protected void prepareForwardedResponseHeaders(ResponseData response) {
HttpHeaders headers = response.getHeaders();
headers.remove(TRANSFER_ENCODING);
headers.remove(CONNECTION);
headers.remove("Public-Key-Pins");
headers.remove(SERVER);
headers.remove("Strict-Transport-Security");
}
|
java
|
{
"resource": ""
}
|
q3090
|
RequestForwarder.prepareForwardedRequestHeaders
|
train
|
protected void prepareForwardedRequestHeaders(RequestData request, ForwardDestination destination) {
HttpHeaders headers = request.getHeaders();
headers.set(HOST, destination.getUri().getAuthority());
headers.remove(TE);
}
|
java
|
{
"resource": ""
}
|
q3091
|
MigrationRepository.normalizePath
|
train
|
private String normalizePath(String scriptPath) {
StringBuilder builder = new StringBuilder(scriptPath.length() + 1);
if (scriptPath.startsWith("/")) {
builder.append(scriptPath.substring(1));
} else {
builder.append(scriptPath);
}
if (!scriptPath.endsWith("/")) {
builder.append("/");
}
return builder.toString();
}
|
java
|
{
"resource": ""
}
|
q3092
|
MigrationRepository.getMigrationsSinceVersion
|
train
|
public List<DbMigration> getMigrationsSinceVersion(int version) {
List<DbMigration> dbMigrations = new ArrayList<>();
migrationScripts.stream().filter(script -> script.getVersion() > version).forEach(script -> {
String content = loadScriptContent(script);
dbMigrations.add(new DbMigration(script.getScriptName(), script.getVersion(), content));
});
return dbMigrations;
}
|
java
|
{
"resource": ""
}
|
q3093
|
Database.getVersion
|
train
|
public int getVersion() {
ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));
Row result = resultSet.one();
if (result == null) {
return 0;
}
return result.getInt(0);
}
|
java
|
{
"resource": ""
}
|
q3094
|
Database.logMigration
|
train
|
private void logMigration(DbMigration migration, boolean wasSuccessful) {
BoundStatement boundStatement = logMigrationStatement.bind(wasSuccessful, migration.getVersion(),
migration.getScriptName(), migration.getMigrationScript(), new Date());
session.execute(boundStatement);
}
|
java
|
{
"resource": ""
}
|
q3095
|
MigrationTask.migrate
|
train
|
public void migrate() {
if (databaseIsUpToDate()) {
LOGGER.info(format("Keyspace %s is already up to date at version %d", database.getKeyspaceName(),
database.getVersion()));
return;
}
List<DbMigration> migrations = repository.getMigrationsSinceVersion(database.getVersion());
migrations.forEach(database::execute);
LOGGER.info(format("Migrated keyspace %s to version %d", database.getKeyspaceName(), database.getVersion()));
database.close();
}
|
java
|
{
"resource": ""
}
|
q3096
|
FileSystemLocationScanner.findResourceNames
|
train
|
public Set<String> findResourceNames(String location, URI locationUri) throws IOException {
String filePath = toFilePath(locationUri);
File folder = new File(filePath);
if (!folder.isDirectory()) {
LOGGER.debug("Skipping path as it is not a directory: " + filePath);
return new TreeSet<>();
}
String classPathRootOnDisk = filePath.substring(0, filePath.length() - location.length());
if (!classPathRootOnDisk.endsWith(File.separator)) {
classPathRootOnDisk = classPathRootOnDisk + File.separator;
}
LOGGER.debug("Scanning starting at classpath root in filesystem: " + classPathRootOnDisk);
return findResourceNamesFromFileSystem(classPathRootOnDisk, location, folder);
}
|
java
|
{
"resource": ""
}
|
q3097
|
FileSystemLocationScanner.findResourceNamesFromFileSystem
|
train
|
private Set<String> findResourceNamesFromFileSystem(String classPathRootOnDisk, String scanRootLocation, File folder) {
LOGGER.debug("Scanning for resources in path: {} ({})", folder.getPath(), scanRootLocation);
File[] files = folder.listFiles();
if (files == null) {
return emptySet();
}
Set<String> resourceNames = new TreeSet<>();
for (File file : files) {
if (file.canRead()) {
if (file.isDirectory()) {
resourceNames.addAll(findResourceNamesFromFileSystem(classPathRootOnDisk, scanRootLocation, file));
} else {
resourceNames.add(toResourceNameOnClasspath(classPathRootOnDisk, file));
}
}
}
return resourceNames;
}
|
java
|
{
"resource": ""
}
|
q3098
|
FileSystemLocationScanner.toResourceNameOnClasspath
|
train
|
private String toResourceNameOnClasspath(String classPathRootOnDisk, File file) {
String fileName = file.getAbsolutePath().replace("\\", "/");
return fileName.substring(classPathRootOnDisk.length());
}
|
java
|
{
"resource": ""
}
|
q3099
|
Ensure.notNull
|
train
|
public static <T> T notNull(T argument, String argumentName) {
if (argument == null) {
throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
}
return argument;
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.