gt stringclasses 1 value | context stringlengths 2.05k 161k |
|---|---|
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leap.htpl.ast;
import java.io.IOException;
import java.util.Enumeration;
import leap.htpl.HtplCompiler;
import leap.htpl.HtplContext;
import leap.htpl.HtplDocument;
import leap.htpl.HtplEngine;
import leap.htpl.HtplRenderable;
import leap.htpl.HtplResource;
import leap.htpl.HtplTemplate;
import leap.htpl.HtplWriter;
import leap.htpl.exception.HtplCompileException;
import leap.htpl.exception.HtplParseException;
import leap.htpl.exception.HtplRenderException;
import leap.lang.Strings;
import leap.lang.expression.Expression;
import leap.lang.resource.Resource;
public class Include extends Node implements HtplRenderable {
private final String templateName;
private final String fragmentName;
private final boolean required;
private Expression expression;
private HtplTemplate template; //included template
private Fragment fragment;
private Resource resource; //included resource
public Include(String templateName) {
this(templateName,null,true);
}
public Include(String templateName,String fragmentName) {
this(templateName,fragmentName,true);
}
public Include(String templateName,String fragmentName, boolean required) {
this.templateName = templateName;
this.fragmentName = fragmentName;
this.required = required;
}
public String getTemplateName() {
return templateName;
}
public String getFragmentName() {
return fragmentName;
}
protected Expression tryParseTemplateExpression() {
return null;
}
@Override
protected Node doDeepClone(Node parent) {
Include clone = new Include(templateName,fragmentName,required);
clone.template = template;
clone.expression = expression;
clone.fragment = null == fragment ? null : fragment.deepClone(clone);
clone.resource = resource;
return clone;
}
@Override
protected void doWriteTemplate(Appendable out) throws IOException {
out.append("<!--#include \"").append(templateName).append("\"-->");
}
@Override
protected Node doProcess(HtplEngine engine,HtplDocument doc, ProcessCallback callback) {
expression = engine.getExpressionManager().tryParseCompositeExpression(engine, templateName);
if(null == expression){
template = engine.resolveTemplate(doc.getResource(), templateName, doc.getLocale());
if(null == template){
processTemplateNotFound(engine, doc);
return this;
}
if(!Strings.isEmpty(fragmentName)){
fragment = template.getDocument().getFragment(fragmentName);
if(null == fragment && required){
throw new HtplCompileException("No fragment named '" + fragmentName + "' in the included template '" + templateName + "'");
}
fragment = fragment.deepClone(this);
}
doc.addIncludedTemplate(templateName, template);
}
return this;
}
@Override
public void compile(HtplEngine engine, HtplDocument doc, HtplCompiler compiler) {
if(null != fragment){
fragment.compileSelf(engine, doc);
}
compiler.renderable(this);
}
@Override
public void render(HtplTemplate tpl, HtplContext context, HtplWriter writer) throws IOException {
if(null != expression) {
String result = context.evalString(expression);
if(Strings.isEmpty(result)) {
if(required) {
throw new HtplRenderException("The included template expression '" + this.templateName + "' returns empty string");
}
return;
}
String templateName = result;
String fragmentName = null;
int index = templateName.indexOf('#');
if(index > 0) {
fragmentName = result.substring(index+1);
templateName = result.substring(0, index);
}
HtplTemplate template = context.getEngine().resolveTemplate(tpl.getDocument().getResource(), templateName, context.getLocale());
if(null == template) {
if(required) {
throw new HtplRenderException("The included template '" + templateName + "' not found");
}
return;
}
Fragment fragment = null;
if(null != fragmentName) {
fragment = template.getDocument().getFragment(fragmentName);
if(null == fragment) {
if(required) {
throw new HtplRenderException("The included fragment '" + result + "' not found");
}
return;
}
}
if(context.isDebug()) {
writer.append("<!--#include \"" + result + "\"-->\n");
}
if(null == fragment){
template.render(tpl, context, writer);
}else{
fragment.render(tpl, context, writer);
}
if(context.isDebug()) {
writer.append("\n<!--#endinclude-->");
}
}else if(null != template) {
if(context.isDebug()) {
writer.append("<!--#include \"" + templateName + "\"-->\n");
}
if(null == fragment){
//render the include templte
template.render(tpl, context, writer);
}else{
//render the include fragment
fragment.render(tpl, context, writer);
}
if(context.isDebug()) {
writer.append("\n<!--#endinclude-->");
}
}else if(null != resource){
if(context.isDebug()) {
writer.append("<!--#include \"" + resource.getPath() + "\"-->\n");
}
includeServletResource(tpl, context, writer, resource);
if(context.isDebug()) {
writer.append("\n<!--#endinclude-->");
}
}
}
protected void processTemplateNotFound(HtplEngine engine, HtplDocument doc) {
if(doc.getResource().isServletResource()) {
if(processServletResourceInclude(engine,doc)){
return;
}
}
if(required){
throw new HtplParseException("The include template '" + templateName + "' can not be resolved");
}
}
protected boolean processServletResourceInclude(HtplEngine engine, HtplDocument doc) {
HtplResource jsp = doc.getResource().tryGetResource(templateName, doc.getLocale());
if(jsp == null){
return false;
}
this.resource = jsp.getResource();
return true;
}
protected void includeServletResource(HtplTemplate tpl, HtplContext context, HtplWriter writer, Resource sr) throws IOException {
leap.web.Request r;
if(context.getRequest() instanceof leap.web.Request) {
r = (leap.web.Request)context.getRequest();
}else{
r = leap.web.Request.current();
}
javax.servlet.http.HttpServletRequest req = r.getServletRequest();
javax.servlet.http.HttpServletResponse resp = r.response().getServletResponse();
try {
req.getRequestDispatcher(sr.getPath()).include(req, resp);
//TODO : optimize
Enumeration<String> vars = req.getAttributeNames();
while(vars.hasMoreElements()) {
String var = vars.nextElement();
context.setLocalVariable(var, req.getAttribute(var));
}
} catch (javax.servlet.ServletException e) {
throw new HtplRenderException("Error including resource '" + resource.getPath() + "', " + e.getMessage(), e);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.runtime.operators.window;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.table.runtime.generated.GeneratedNamespaceAggsHandleFunction;
import org.apache.flink.table.runtime.generated.GeneratedNamespaceTableAggsHandleFunction;
import org.apache.flink.table.runtime.generated.GeneratedRecordEqualiser;
import org.apache.flink.table.runtime.generated.NamespaceAggsHandleFunction;
import org.apache.flink.table.runtime.generated.NamespaceAggsHandleFunctionBase;
import org.apache.flink.table.runtime.generated.NamespaceTableAggsHandleFunction;
import org.apache.flink.table.runtime.generated.RecordEqualiser;
import org.apache.flink.table.runtime.operators.window.assigners.CountSlidingWindowAssigner;
import org.apache.flink.table.runtime.operators.window.assigners.CountTumblingWindowAssigner;
import org.apache.flink.table.runtime.operators.window.assigners.CumulativeWindowAssigner;
import org.apache.flink.table.runtime.operators.window.assigners.InternalTimeWindowAssigner;
import org.apache.flink.table.runtime.operators.window.assigners.SessionWindowAssigner;
import org.apache.flink.table.runtime.operators.window.assigners.SlidingWindowAssigner;
import org.apache.flink.table.runtime.operators.window.assigners.TumblingWindowAssigner;
import org.apache.flink.table.runtime.operators.window.assigners.WindowAssigner;
import org.apache.flink.table.runtime.operators.window.triggers.ElementTriggers;
import org.apache.flink.table.runtime.operators.window.triggers.EventTimeTriggers;
import org.apache.flink.table.runtime.operators.window.triggers.ProcessingTimeTriggers;
import org.apache.flink.table.runtime.operators.window.triggers.Trigger;
import org.apache.flink.table.types.logical.LogicalType;
import java.time.Duration;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* The {@link WindowOperatorBuilder} is used to build {@link WindowOperator} fluently.
*
* <p>Note: You have to call the aggregate method before the last build method.
*
* <pre>
* WindowOperatorBuilder
* .builder(KeyedStream)
* .tumble(Duration.ofMinutes(1)) // sliding(...), session(...)
* .withEventTime() // withProcessingTime()
* .withAllowedLateness(Duration.ZERO)
* .produceUpdates()
* .aggregate(AggregationsFunction, accTypes, windowTypes)
* .build();
* </pre>
*/
public class WindowOperatorBuilder {
protected LogicalType[] inputFieldTypes;
protected WindowAssigner<?> windowAssigner;
protected Trigger<?> trigger;
protected LogicalType[] accumulatorTypes;
protected LogicalType[] aggResultTypes;
protected LogicalType[] windowPropertyTypes;
protected long allowedLateness = 0L;
protected boolean produceUpdates = false;
protected int rowtimeIndex = -1;
public static WindowOperatorBuilder builder() {
return new WindowOperatorBuilder();
}
public WindowOperatorBuilder withInputFields(LogicalType[] inputFieldTypes) {
this.inputFieldTypes = inputFieldTypes;
return this;
}
public WindowOperatorBuilder tumble(Duration size) {
checkArgument(windowAssigner == null);
this.windowAssigner = TumblingWindowAssigner.of(size);
return this;
}
public WindowOperatorBuilder sliding(Duration size, Duration slide) {
checkArgument(windowAssigner == null);
this.windowAssigner = SlidingWindowAssigner.of(size, slide);
return this;
}
public WindowOperatorBuilder cumulative(Duration size, Duration step) {
checkArgument(windowAssigner == null);
this.windowAssigner = CumulativeWindowAssigner.of(size, step);
return this;
}
public WindowOperatorBuilder session(Duration sessionGap) {
checkArgument(windowAssigner == null);
this.windowAssigner = SessionWindowAssigner.withGap(sessionGap);
return this;
}
public WindowOperatorBuilder countWindow(long size) {
checkArgument(windowAssigner == null);
checkArgument(trigger == null);
this.windowAssigner = CountTumblingWindowAssigner.of(size);
this.trigger = ElementTriggers.count(size);
return this;
}
public WindowOperatorBuilder countWindow(long size, long slide) {
checkArgument(windowAssigner == null);
checkArgument(trigger == null);
this.windowAssigner = CountSlidingWindowAssigner.of(size, slide);
this.trigger = ElementTriggers.count(size);
return this;
}
public WindowOperatorBuilder assigner(WindowAssigner<?> windowAssigner) {
checkArgument(this.windowAssigner == null);
checkNotNull(windowAssigner);
this.windowAssigner = windowAssigner;
return this;
}
public WindowOperatorBuilder triggering(Trigger<?> trigger) {
checkNotNull(trigger);
this.trigger = trigger;
return this;
}
public WindowOperatorBuilder withEventTime(int rowtimeIndex) {
checkNotNull(windowAssigner);
checkArgument(windowAssigner instanceof InternalTimeWindowAssigner);
InternalTimeWindowAssigner timeWindowAssigner = (InternalTimeWindowAssigner) windowAssigner;
this.windowAssigner = (WindowAssigner<?>) timeWindowAssigner.withEventTime();
this.rowtimeIndex = rowtimeIndex;
if (trigger == null) {
this.trigger = EventTimeTriggers.afterEndOfWindow();
}
return this;
}
public WindowOperatorBuilder withProcessingTime() {
checkNotNull(windowAssigner);
checkArgument(windowAssigner instanceof InternalTimeWindowAssigner);
InternalTimeWindowAssigner timeWindowAssigner = (InternalTimeWindowAssigner) windowAssigner;
this.windowAssigner = (WindowAssigner<?>) timeWindowAssigner.withProcessingTime();
if (trigger == null) {
this.trigger = ProcessingTimeTriggers.afterEndOfWindow();
}
return this;
}
public WindowOperatorBuilder withAllowedLateness(Duration allowedLateness) {
checkArgument(!allowedLateness.isNegative());
if (allowedLateness.toMillis() > 0) {
this.allowedLateness = allowedLateness.toMillis();
}
return this;
}
public WindowOperatorBuilder produceUpdates() {
this.produceUpdates = true;
return this;
}
protected void aggregate(
LogicalType[] accumulatorTypes,
LogicalType[] aggResultTypes,
LogicalType[] windowPropertyTypes) {
this.accumulatorTypes = accumulatorTypes;
this.aggResultTypes = aggResultTypes;
this.windowPropertyTypes = windowPropertyTypes;
}
public AggregateWindowOperatorBuilder aggregate(
NamespaceAggsHandleFunction<?> aggregateFunction,
RecordEqualiser equaliser,
LogicalType[] accumulatorTypes,
LogicalType[] aggResultTypes,
LogicalType[] windowPropertyTypes) {
aggregate(accumulatorTypes, aggResultTypes, windowPropertyTypes);
return new AggregateWindowOperatorBuilder(aggregateFunction, equaliser, this);
}
public AggregateWindowOperatorBuilder aggregate(
GeneratedNamespaceAggsHandleFunction<?> generatedAggregateFunction,
GeneratedRecordEqualiser generatedEqualiser,
LogicalType[] accumulatorTypes,
LogicalType[] aggResultTypes,
LogicalType[] windowPropertyTypes) {
aggregate(accumulatorTypes, aggResultTypes, windowPropertyTypes);
return new AggregateWindowOperatorBuilder(
generatedAggregateFunction, generatedEqualiser, this);
}
public TableAggregateWindowOperatorBuilder aggregate(
NamespaceTableAggsHandleFunction<?> tableAggregateFunction,
LogicalType[] accumulatorTypes,
LogicalType[] aggResultTypes,
LogicalType[] windowPropertyTypes) {
aggregate(accumulatorTypes, aggResultTypes, windowPropertyTypes);
return new TableAggregateWindowOperatorBuilder(tableAggregateFunction, this);
}
public TableAggregateWindowOperatorBuilder aggregate(
GeneratedNamespaceTableAggsHandleFunction<?> generatedTableAggregateFunction,
LogicalType[] accumulatorTypes,
LogicalType[] aggResultTypes,
LogicalType[] windowPropertyTypes) {
aggregate(accumulatorTypes, aggResultTypes, windowPropertyTypes);
return new TableAggregateWindowOperatorBuilder(generatedTableAggregateFunction, this);
}
@VisibleForTesting
WindowOperator aggregateAndBuild(
NamespaceAggsHandleFunctionBase<?> aggregateFunction,
RecordEqualiser equaliser,
LogicalType[] accumulatorTypes,
LogicalType[] aggResultTypes,
LogicalType[] windowPropertyTypes) {
aggregate(accumulatorTypes, aggResultTypes, windowPropertyTypes);
if (aggregateFunction instanceof NamespaceAggsHandleFunction) {
return new AggregateWindowOperatorBuilder(
(NamespaceAggsHandleFunction) aggregateFunction, equaliser, this)
.build();
} else {
return new TableAggregateWindowOperatorBuilder(
(NamespaceTableAggsHandleFunction) aggregateFunction, this)
.build();
}
}
/** The builder which is used to build {@link TableAggregateWindowOperator} fluently. */
public static class TableAggregateWindowOperatorBuilder {
private NamespaceTableAggsHandleFunction<?> tableAggregateFunction;
private GeneratedNamespaceTableAggsHandleFunction<?> generatedTableAggregateFunction;
private WindowOperatorBuilder windowOperatorBuilder;
public TableAggregateWindowOperatorBuilder(
NamespaceTableAggsHandleFunction<?> tableAggregateFunction,
WindowOperatorBuilder windowOperatorBuilder) {
this.tableAggregateFunction = tableAggregateFunction;
this.windowOperatorBuilder = windowOperatorBuilder;
}
public TableAggregateWindowOperatorBuilder(
GeneratedNamespaceTableAggsHandleFunction<?> generatedTableAggregateFunction,
WindowOperatorBuilder windowOperatorBuilder) {
this.generatedTableAggregateFunction = generatedTableAggregateFunction;
this.windowOperatorBuilder = windowOperatorBuilder;
}
public WindowOperator build() {
checkNotNull(windowOperatorBuilder.trigger, "trigger is not set");
if (generatedTableAggregateFunction != null) {
//noinspection unchecked
return new TableAggregateWindowOperator(
generatedTableAggregateFunction,
windowOperatorBuilder.windowAssigner,
windowOperatorBuilder.trigger,
windowOperatorBuilder.windowAssigner.getWindowSerializer(
new ExecutionConfig()),
windowOperatorBuilder.inputFieldTypes,
windowOperatorBuilder.accumulatorTypes,
windowOperatorBuilder.aggResultTypes,
windowOperatorBuilder.windowPropertyTypes,
windowOperatorBuilder.rowtimeIndex,
windowOperatorBuilder.produceUpdates,
windowOperatorBuilder.allowedLateness);
} else {
//noinspection unchecked
return new TableAggregateWindowOperator(
tableAggregateFunction,
windowOperatorBuilder.windowAssigner,
windowOperatorBuilder.trigger,
windowOperatorBuilder.windowAssigner.getWindowSerializer(
new ExecutionConfig()),
windowOperatorBuilder.inputFieldTypes,
windowOperatorBuilder.accumulatorTypes,
windowOperatorBuilder.aggResultTypes,
windowOperatorBuilder.windowPropertyTypes,
windowOperatorBuilder.rowtimeIndex,
windowOperatorBuilder.produceUpdates,
windowOperatorBuilder.allowedLateness);
}
}
}
/** The builder which is used to build {@link AggregateWindowOperator} fluently. */
public static class AggregateWindowOperatorBuilder {
private NamespaceAggsHandleFunction<?> aggregateFunction;
private GeneratedNamespaceAggsHandleFunction<?> generatedAggregateFunction;
private RecordEqualiser equaliser;
private GeneratedRecordEqualiser generatedEqualiser;
private WindowOperatorBuilder windowOperatorBuilder;
public AggregateWindowOperatorBuilder(
GeneratedNamespaceAggsHandleFunction<?> generatedAggregateFunction,
GeneratedRecordEqualiser generatedEqualiser,
WindowOperatorBuilder windowOperatorBuilder) {
this.generatedAggregateFunction = generatedAggregateFunction;
this.generatedEqualiser = generatedEqualiser;
this.windowOperatorBuilder = windowOperatorBuilder;
}
public AggregateWindowOperatorBuilder(
NamespaceAggsHandleFunction<?> aggregateFunction,
RecordEqualiser equaliser,
WindowOperatorBuilder windowOperatorBuilder) {
this.aggregateFunction = aggregateFunction;
this.equaliser = equaliser;
this.windowOperatorBuilder = windowOperatorBuilder;
}
public AggregateWindowOperator build() {
checkNotNull(windowOperatorBuilder.trigger, "trigger is not set");
if (generatedAggregateFunction != null && generatedEqualiser != null) {
//noinspection unchecked
return new AggregateWindowOperator(
generatedAggregateFunction,
generatedEqualiser,
windowOperatorBuilder.windowAssigner,
windowOperatorBuilder.trigger,
windowOperatorBuilder.windowAssigner.getWindowSerializer(
new ExecutionConfig()),
windowOperatorBuilder.inputFieldTypes,
windowOperatorBuilder.accumulatorTypes,
windowOperatorBuilder.aggResultTypes,
windowOperatorBuilder.windowPropertyTypes,
windowOperatorBuilder.rowtimeIndex,
windowOperatorBuilder.produceUpdates,
windowOperatorBuilder.allowedLateness);
} else {
//noinspection unchecked
return new AggregateWindowOperator(
aggregateFunction,
equaliser,
windowOperatorBuilder.windowAssigner,
windowOperatorBuilder.trigger,
windowOperatorBuilder.windowAssigner.getWindowSerializer(
new ExecutionConfig()),
windowOperatorBuilder.inputFieldTypes,
windowOperatorBuilder.accumulatorTypes,
windowOperatorBuilder.aggResultTypes,
windowOperatorBuilder.windowPropertyTypes,
windowOperatorBuilder.rowtimeIndex,
windowOperatorBuilder.produceUpdates,
windowOperatorBuilder.allowedLateness);
}
}
}
}
| |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tests.gl_400;
import com.jogamp.opengl.GL;
import static com.jogamp.opengl.GL3ES3.*;
import com.jogamp.opengl.GL4;
import com.jogamp.opengl.util.GLBuffers;
import com.jogamp.opengl.util.glsl.ShaderCode;
import com.jogamp.opengl.util.glsl.ShaderProgram;
import glm.glm;
import glm.mat._4.Mat4;
import glm.vec._2.Vec2;
import dev.Vec4u8;
import framework.BufferUtils;
import framework.Profile;
import framework.Semantic;
import framework.Test;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
/**
*
* @author GBarbieri
*/
public class Gl_400_primitive_smooth_shading extends Test {
public static void main(String[] args) {
Gl_400_primitive_smooth_shading gl_400_primitive_smooth_shading = new Gl_400_primitive_smooth_shading();
}
public Gl_400_primitive_smooth_shading() {
super("gl-400-primitive-smooth-shading", Profile.CORE, 4, 0);
}
private final String SHADERS_SOURCE1 = "tess";
private final String SHADERS_SOURCE2 = "smooth-shading-geom";
private final String SHADERS_ROOT = "src/data/gl_400";
private int vertexCount = 4;
private int vertexSize = vertexCount * glf.Vertex_v2fc4ub.SIZE;
private glf.Vertex_v2fc4ub[] vertexData = {
new glf.Vertex_v2fc4ub(new Vec2(-1.0f, -1.0f), new Vec4u8(255, 0, 0, 255)),
new glf.Vertex_v2fc4ub(new Vec2(1.0f, -1.0f), new Vec4u8(255, 255, 255, 255)),
new glf.Vertex_v2fc4ub(new Vec2(1.0f, 1.0f), new Vec4u8(0, 255, 0, 255)),
new glf.Vertex_v2fc4ub(new Vec2(-1.0f, 1.0f), new Vec4u8(0, 0, 255, 255))};
private int elementCount = 6;
private int elementSize = elementCount * Short.BYTES;
private short[] elementData = {
0, 1, 2,
2, 3, 0};
private class Program {
public static final int TESS = 0;
public static final int SMOOTH = 1;
public static final int MAX = 2;
}
private class Buffer {
public static final int ARRAY = 0;
public static final int ELEMENT = 1;
public static final int MAX = 2;
}
private int[] programName = new int[Program.MAX], uniformMvp = new int[Program.MAX];
private IntBuffer bufferName = GLBuffers.newDirectIntBuffer(Buffer.MAX),
vertexArrayName = GLBuffers.newDirectIntBuffer(1);
@Override
protected boolean begin(GL gl) {
GL4 gl4 = (GL4) gl;
boolean validated = true;
if (validated) {
validated = initProgram(gl4);
}
if (validated) {
validated = initBuffer(gl4);
}
if (validated) {
validated = initVertexArray(gl4);
}
return validated && checkError(gl4, "begin");
}
private boolean initProgram(GL4 gl4) {
boolean validated = true;
if (validated) {
ShaderProgram shaderProgram = new ShaderProgram();
ShaderCode vertShaderCode = ShaderCode.create(gl4, GL_VERTEX_SHADER, this.getClass(), SHADERS_ROOT,
null, SHADERS_SOURCE1, "vert", null, true);
ShaderCode contShaderCode = ShaderCode.create(gl4, GL_TESS_CONTROL_SHADER, this.getClass(), SHADERS_ROOT,
null, SHADERS_SOURCE1, "cont", null, true);
ShaderCode evalShaderCode = ShaderCode.create(gl4, GL_TESS_EVALUATION_SHADER, this.getClass(), SHADERS_ROOT,
null, SHADERS_SOURCE1, "eval", null, true);
ShaderCode geomShaderCode = ShaderCode.create(gl4, GL_GEOMETRY_SHADER, this.getClass(), SHADERS_ROOT,
null, SHADERS_SOURCE1, "geom", null, true);
ShaderCode fragShaderCode = ShaderCode.create(gl4, GL_FRAGMENT_SHADER, this.getClass(), SHADERS_ROOT,
null, SHADERS_SOURCE1, "frag", null, true);
shaderProgram.init(gl4);
programName[Program.TESS] = shaderProgram.program();
shaderProgram.add(vertShaderCode);
shaderProgram.add(geomShaderCode);
shaderProgram.add(contShaderCode);
shaderProgram.add(evalShaderCode);
shaderProgram.add(fragShaderCode);
shaderProgram.link(gl4, System.out);
}
if (validated) {
ShaderProgram shaderProgram = new ShaderProgram();
ShaderCode vertShaderCode = ShaderCode.create(gl4, GL_VERTEX_SHADER, this.getClass(), SHADERS_ROOT, null,
SHADERS_SOURCE2, "vert", null, true);
ShaderCode geomShaderCode = ShaderCode.create(gl4, GL_GEOMETRY_SHADER, this.getClass(), SHADERS_ROOT, null,
SHADERS_SOURCE2, "geom", null, true);
ShaderCode fragShaderCode = ShaderCode.create(gl4, GL_FRAGMENT_SHADER, this.getClass(), SHADERS_ROOT, null,
SHADERS_SOURCE2, "frag", null, true);
shaderProgram.init(gl4);
programName[Program.SMOOTH] = shaderProgram.program();
shaderProgram.add(vertShaderCode);
shaderProgram.add(geomShaderCode);
shaderProgram.add(fragShaderCode);
shaderProgram.link(gl4, System.out);
}
// Get variables locations
if (validated) {
uniformMvp[Program.TESS] = gl4.glGetUniformLocation(programName[Program.TESS], "mvp");
uniformMvp[Program.SMOOTH] = gl4.glGetUniformLocation(programName[Program.SMOOTH], "mvp");
}
return validated & checkError(gl4, "initProgram");
}
private boolean initVertexArray(GL4 gl4) {
gl4.glGenVertexArrays(1, vertexArrayName);
gl4.glBindVertexArray(vertexArrayName.get(0));
{
gl4.glBindBuffer(GL_ARRAY_BUFFER, bufferName.get(Buffer.ARRAY));
gl4.glVertexAttribPointer(Semantic.Attr.POSITION, 2, GL_FLOAT, false, glf.Vertex_v2fc4ub.SIZE, 0);
gl4.glVertexAttribPointer(Semantic.Attr.COLOR, 4, GL_UNSIGNED_BYTE, true, glf.Vertex_v2fc4ub.SIZE, Vec2.SIZE);
gl4.glEnableVertexAttribArray(Semantic.Attr.POSITION);
gl4.glEnableVertexAttribArray(Semantic.Attr.COLOR);
gl4.glBindBuffer(GL_ARRAY_BUFFER, 0);
}
gl4.glBindVertexArray(0);
return checkError(gl4, "initVertexArray");
}
private boolean initBuffer(GL4 gl4) {
ShortBuffer elementBuffer = GLBuffers.newDirectShortBuffer(elementData);
ByteBuffer vertexBuffer = GLBuffers.newDirectByteBuffer(vertexSize);
gl4.glGenBuffers(Buffer.MAX, bufferName);
gl4.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferName.get(Buffer.ELEMENT));
gl4.glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementSize, elementBuffer, GL_STATIC_DRAW);
gl4.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
gl4.glBindBuffer(GL_ARRAY_BUFFER, bufferName.get(Buffer.ARRAY));
for (int i = 0; i < vertexCount; i++) {
vertexData[i].toBb(vertexBuffer, i);
}
vertexBuffer.rewind();
gl4.glBufferData(GL_ARRAY_BUFFER, vertexSize, vertexBuffer, GL_STATIC_DRAW);
gl4.glBindBuffer(GL_ARRAY_BUFFER, 0);
BufferUtils.destroyDirectBuffer(elementBuffer);
BufferUtils.destroyDirectBuffer(vertexBuffer);
return checkError(gl4, "initBuffer");
}
@Override
protected boolean render(GL gl) {
GL4 gl4 = (GL4) gl;
Mat4 projection = glm.perspective_((float) Math.PI * 0.25f, windowSize.x * 0.5f / windowSize.y, 0.1f, 100.0f);
Mat4 model = new Mat4(1.0f);
Mat4 mvp = projection.mul(viewMat4()).mul(model);
gl4.glViewport(0, 0, windowSize.x, windowSize.y);
gl4.glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0).put(1, 0).put(2, 0).put(3, 1));
gl4.glBindVertexArray(vertexArrayName.get(0));
gl4.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferName.get(Buffer.ELEMENT));
gl4.glViewport(0, 0, (int) (windowSize.x * 0.5f), windowSize.y);
gl4.glUseProgram(programName[Program.TESS]);
gl4.glUniformMatrix4fv(uniformMvp[Program.TESS], 1, false, mvp.toFa_(), 0);
gl4.glPatchParameteri(GL_PATCH_VERTICES, vertexCount);
gl4.glDrawArraysInstanced(GL_PATCHES, 0, vertexCount, 1);
gl4.glViewport((int) (windowSize.x * 0.5f), 0, (int) (windowSize.x * 0.5f), windowSize.y);
gl4.glUseProgram(programName[Program.SMOOTH]);
gl4.glUniformMatrix4fv(uniformMvp[Program.SMOOTH], 1, false, mvp.toFa_(), 0);
gl4.glDrawElementsInstancedBaseVertex(GL_TRIANGLES, elementCount, GL_UNSIGNED_SHORT, 0, 1, 0);
return true;
}
@Override
protected boolean end(GL gl) {
GL4 gl4 = (GL4) gl;
gl4.glDeleteVertexArrays(1, vertexArrayName);
gl4.glDeleteBuffers(Buffer.MAX, bufferName);
gl4.glDeleteProgram(programName[0]);
gl4.glDeleteProgram(programName[1]);
BufferUtils.destroyDirectBuffer(vertexArrayName);
BufferUtils.destroyDirectBuffer(bufferName);
return checkError(gl4, "end");
}
}
| |
/**
* Copyright (c) 2015 DataTorrent, Inc.
* All rights reserved.
*/
package com.datatorrent.demos.dimensions.telecom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import com.google.common.collect.Maps;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.DAG;
import com.datatorrent.api.DAG.Locality;
import com.datatorrent.api.LocalMode;
import com.datatorrent.contrib.hbase.HBaseFieldInfo;
import com.datatorrent.contrib.hbase.HBasePOJOInputOperator;
import com.datatorrent.contrib.hbase.HBaseStore;
import com.datatorrent.demos.dimensions.telecom.conf.CustomerServiceHBaseConf;
import com.datatorrent.demos.dimensions.telecom.conf.DataWarehouseConfig;
import com.datatorrent.demos.dimensions.telecom.conf.TelecomDemoConf;
import com.datatorrent.demos.dimensions.telecom.model.CustomerService;
import com.datatorrent.demos.dimensions.telecom.model.CustomerService.IssueType;
import com.datatorrent.demos.dimensions.telecom.operator.CustomerServiceGenerateOperator;
import com.datatorrent.demos.dimensions.telecom.operator.CustomerServiceHbaseOutputOperator;
import com.datatorrent.lib.testbench.ArrayListTestSink;
import com.datatorrent.lib.util.FieldInfo.SupportType;
import com.datatorrent.lib.util.TableInfo;
public class CustomerServiceHbaseOutputOperatorTester
{
private static final transient Logger logger = LoggerFactory.getLogger(CustomerServiceHbaseOutputOperatorTester.class);
protected DataWarehouseConfig hbaseConfig = CustomerServiceHBaseConf.instance();
protected long CAPACITY = 1000;
protected long timeOutTime = 100000;
protected transient TupleCacheOperator<CustomerService> cacheOperator;
protected List<CustomerService> generatedDataList;
protected transient TupleCacheOperator<Object> hbaseInputCacheOperator;
protected List<Object> readDataList;
protected SpecificCustomerServiceGenerateOperator customerServiceGenerator;
@SuppressWarnings("unchecked")
@Test
public void test() throws Exception
{
CustomerServiceHBaseConf.instance().setHost("localhost");
TelecomDemoConf.instance.setCdrDir("target/CDR");
{
LocalMode lma = LocalMode.newInstance();
DAG dag = lma.getDAG();
Configuration conf = new Configuration(false);
populateOutputDAG(dag, conf);
// Create local cluster
final LocalMode.Controller lc = lma.getController();
lc.runAsync();
waitMills(1000);
//main thread wait for signal
final int checkTimePeriod = 200;
for (int index = 0; index < timeOutTime / checkTimePeriod + timeOutTime % checkTimePeriod; ++index) {
if (customerServiceGenerator.isTerminated()) {
break;
}
waitMills(checkTimePeriod);
}
logger.info("Send Tuples done. going to terminate the application.");
//make sure this last tuple and end-window handled.
waitMills(1000);
generatedDataList = cacheOperator.getCacheData();
lc.shutdown();
}
//start input dag to read data from HBase
{
LocalMode lma = LocalMode.newInstance();
DAG dag = lma.getDAG();
Configuration conf = new Configuration(false);
populateInputDAG(dag, conf);
// Create local cluster
final LocalMode.Controller lc = lma.getController();
lc.runAsync();
waitMills(1000);
int readSize = 0;
final int checkTimePeriod = 1000;
for (int index = 0; index < timeOutTime / checkTimePeriod + timeOutTime % checkTimePeriod; ++index) {
waitMills(checkTimePeriod);
readDataList = hbaseInputCacheOperator.getCacheData();
//the startup probably take a while
if (readSize == readDataList.size() && readSize != 0) {
break;
}
readSize = readDataList.size();
}
lc.shutdown();
}
verify();
}
/**
* this is the DAG for write tuples into HBase
* @param dag
* @param conf
*/
protected void populateOutputDAG(DAG dag, Configuration conf)
{
customerServiceGenerator = new SpecificCustomerServiceGenerateOperator();
customerServiceGenerator.capacity = CAPACITY;
dag.addOperator("CustomerService-Generator", customerServiceGenerator);
cacheOperator = new TupleCacheOperator<>("cacheOperatorData");
dag.addOperator("Cache", cacheOperator);
dag.addStream("GenerateStream", customerServiceGenerator.outputPort, cacheOperator.inputPort).setLocality(Locality.CONTAINER_LOCAL);
{
CustomerServiceHbaseOutputOperator hbaseOutput = new CustomerServiceHbaseOutputOperator();
hbaseOutput.setStartOver(true); //remove old table and create new
dag.addOperator("CustomerService-Output", hbaseOutput);
dag.addStream("CustomerService", cacheOperator.outputPort, hbaseOutput.input).setLocality(Locality.CONTAINER_LOCAL);
}
}
/**
* this is the DAG to read tuples from HBase
* @param dag
* @param conf
*/
protected void populateInputDAG(DAG dag, Configuration conf)
{
HBasePOJOInputOperator pojoInput = new HBasePOJOInputOperator();
pojoInput.setStore(createHBaseStore());
pojoInput.setPojoTypeName(LoadedCustomerService.class.getName());
{
TableInfo<HBaseFieldInfo> tableInfo = new TableInfo<HBaseFieldInfo>();
tableInfo.setRowOrIdExpression("imsi");
final String familyName = "f1";
List<HBaseFieldInfo> fieldsInfo = new ArrayList<HBaseFieldInfo>();
fieldsInfo.add( new HBaseFieldInfo( "totalDuration", "totalDuration", SupportType.INTEGER, familyName) );
fieldsInfo.add( new HBaseFieldInfo( "wait", "wait", SupportType.INTEGER, familyName) );
fieldsInfo.add( new HBaseFieldInfo( "zipCode", "zipCode", SupportType.STRING, familyName) );
fieldsInfo.add( new HBaseFieldInfo( "issueType", "issueType", SupportType.STRING, familyName) );
fieldsInfo.add( new HBaseFieldInfo( "satisfied", "satisfied", SupportType.BOOLEAN, familyName) );
tableInfo.setFieldsInfo(fieldsInfo);
pojoInput.setTableInfo(tableInfo);
}
dag.addOperator("HbaseInput", pojoInput);
hbaseInputCacheOperator = new TupleCacheOperator<>("hbaseInputCacheOperatorData");
dag.addOperator("InputCache", hbaseInputCacheOperator);
hbaseInputCacheOperator.outputPort.setSink(new ArrayListTestSink());
dag.addStream("InputStream", pojoInput.outputPort, hbaseInputCacheOperator.inputPort).setLocality(Locality.CONTAINER_LOCAL);
}
protected HBaseStore createHBaseStore()
{
//store
HBaseStore store = new HBaseStore();
store.setTableName(hbaseConfig.getTableName());
store.setZookeeperQuorum(hbaseConfig.getHost());
store.setZookeeperClientPort(hbaseConfig.getPort());
return store;
}
protected void verify() throws Exception
{
Assert.assertFalse("No tuple found in cache tuple.", generatedDataList == null || generatedDataList.isEmpty() );
logger.info("data size from cache: {}", generatedDataList.size() );
//the data saved to the HBase is key value.
Map<String, CustomerService> imsiToCsMap = Maps.newHashMap();
for (CustomerService cs : generatedDataList) {
imsiToCsMap.put(cs.imsi, cs);
}
logger.info("expected dataSet size: {}", imsiToCsMap.size());
int fetchedCount = 0;
for (Object readData : readDataList) {
LoadedCustomerService lcs = (LoadedCustomerService)readData;
Assert.assertTrue("Don't have data: " + lcs, lcs.equals(imsiToCsMap.get(lcs.imsi)));
fetchedCount++;
}
Assert.assertTrue("The number of records read from HBase (" + fetchedCount + ") is not same as expected (" + imsiToCsMap.size() + ").", fetchedCount == imsiToCsMap.size());
}
public static void waitMills(int millSeconds)
{
if (millSeconds <= 0) {
return;
}
try {
Thread.sleep(millSeconds);
} catch (Exception e) {
//ignore
}
}
public static class SpecificCustomerServiceGenerateOperator extends CustomerServiceGenerateOperator
{
protected String dataId = "SpecificCustomerServiceGenerateOperator";
protected long capacity = 100;
protected AtomicBoolean terminateFlag;
protected DataWrapper<AtomicBoolean> dataWrapper = DataWrapper.getOrCreateInstanceOfId(dataId);
protected long size = 0;
protected final int batchSize = 1;
public SpecificCustomerServiceGenerateOperator()
{
this.setBatchSleepTime(0);
this.setBatchSize(batchSize);
}
@Override
public void setup(OperatorContext context)
{
terminateFlag = dataWrapper.getOrSetData(new AtomicBoolean(false));
dataWrapper.syncData();
}
@Override
public void emitTuples()
{
if (size >= capacity) {
terminateFlag.set(true);
waitMills(2);
return;
}
super.emitTuples();
size += batchSize;
}
public boolean isTerminated()
{
return dataWrapper.getData() != null && dataWrapper.getData().get();
}
}
/**
* Keep the information loaded from HBase.
* NOTES: not all field of CustomerService be kept in the HBase.
*
*
*/
public static class LoadedCustomerService
{
protected String imsi;
protected int totalDuration;
protected int wait;
protected String zipCode;
protected String issueType;
protected boolean satisfied;
public LoadedCustomerService(){}
public LoadedCustomerService(String imsi, int totalDuration, int wait, String zipCode, String issueType,
boolean satisfied)
{
this.imsi = imsi;
this.totalDuration = totalDuration;
this.wait = wait;
this.zipCode = zipCode;
this.issueType = issueType;
this.satisfied = satisfied;
}
public boolean equals(Object obj)
{
if (obj == null || !(obj instanceof CustomerService)) {
return false;
}
CustomerService cs = (CustomerService)obj;
return imsi.equals(cs.imsi) && totalDuration == cs.totalDuration && wait == cs.wait && zipCode.equals(zipCode) && IssueType.valueOf(issueType) == cs.issueType && satisfied == cs.satisfied;
}
public String getImsi()
{
return imsi;
}
public void setImsi(String imsi)
{
this.imsi = imsi;
}
public int getTotalDuration()
{
return totalDuration;
}
public void setTotalDuration(int totalDuration)
{
this.totalDuration = totalDuration;
}
public int getWait()
{
return wait;
}
public void setWait(int wait)
{
this.wait = wait;
}
public String getZipCode()
{
return zipCode;
}
public void setZipCode(String zipCode)
{
this.zipCode = zipCode;
}
public String getIssueType()
{
return issueType;
}
public void setIssueType(String issueType)
{
this.issueType = issueType;
}
public boolean isSatisfied()
{
return satisfied;
}
public void setSatisfied(boolean satisfied)
{
this.satisfied = satisfied;
}
}
}
| |
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.function;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.DelegatingServerHttpResponse;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.ModelAndView;
/**
* Implementation of {@link ServerResponse} for sending
* <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events</a>.
*
* @author Arjen Poutsma
* @since 5.3.2
*/
final class SseServerResponse extends AbstractServerResponse {
private final Consumer<SseBuilder> sseConsumer;
@Nullable
private final Duration timeout;
private SseServerResponse(Consumer<SseBuilder> sseConsumer, @Nullable Duration timeout) {
super(200, createHeaders(), emptyCookies());
this.sseConsumer = sseConsumer;
this.timeout = timeout;
}
private static HttpHeaders createHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_EVENT_STREAM);
headers.setCacheControl(CacheControl.noCache());
return headers;
}
private static MultiValueMap<String, Cookie> emptyCookies() {
return CollectionUtils.toMultiValueMap(Collections.emptyMap());
}
@Nullable
@Override
protected ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response,
Context context) throws ServletException, IOException {
DeferredResult<?> result;
if (this.timeout != null) {
result = new DeferredResult<>(this.timeout.toMillis());
}
else {
result = new DeferredResult<>();
}
DefaultAsyncServerResponse.writeAsync(request, response, result);
this.sseConsumer.accept(new DefaultSseBuilder(response, context, result));
return null;
}
public static ServerResponse create(Consumer<SseBuilder> sseConsumer, @Nullable Duration timeout) {
Assert.notNull(sseConsumer, "SseConsumer must not be null");
return new SseServerResponse(sseConsumer, timeout);
}
private static final class DefaultSseBuilder implements SseBuilder {
private static final byte[] NL_NL = new byte[]{'\n', '\n'};
private final ServerHttpResponse outputMessage;
private final DeferredResult<?> deferredResult;
private final List<HttpMessageConverter<?>> messageConverters;
private final StringBuilder builder = new StringBuilder();
private boolean sendFailed;
public DefaultSseBuilder(HttpServletResponse response, Context context, DeferredResult<?> deferredResult) {
this.outputMessage = new ServletServerHttpResponse(response);
this.deferredResult = deferredResult;
this.messageConverters = context.messageConverters();
}
@Override
public void send(Object object) throws IOException {
data(object);
}
@Override
public SseBuilder id(String id) {
Assert.hasLength(id, "Id must not be empty");
return field("id", id);
}
@Override
public SseBuilder event(String eventName) {
Assert.hasLength(eventName, "Name must not be empty");
return field("event", eventName);
}
@Override
public SseBuilder retry(Duration duration) {
Assert.notNull(duration, "Duration must not be null");
String millis = Long.toString(duration.toMillis());
return field("retry", millis);
}
@Override
public SseBuilder comment(String comment) {
Assert.hasLength(comment, "Comment must not be empty");
String[] lines = comment.split("\n");
for (String line : lines) {
field("", line);
}
return this;
}
private SseBuilder field(String name, String value) {
this.builder.append(name).append(':').append(value).append('\n');
return this;
}
@Override
public void data(Object object) throws IOException {
Assert.notNull(object, "Object must not be null");
if (object instanceof String) {
writeString((String) object);
}
else {
writeObject(object);
}
}
private void writeString(String string) throws IOException {
String[] lines = string.split("\n");
for (String line : lines) {
field("data", line);
}
this.builder.append('\n');
try {
OutputStream body = this.outputMessage.getBody();
body.write(builderBytes());
body.flush();
}
catch (IOException ex) {
this.sendFailed = true;
throw ex;
}
finally {
this.builder.setLength(0);
}
}
@SuppressWarnings("unchecked")
private void writeObject(Object data) throws IOException {
this.builder.append("data:");
try {
this.outputMessage.getBody().write(builderBytes());
Class<?> dataClass = data.getClass();
for (HttpMessageConverter<?> converter : this.messageConverters) {
if (converter.canWrite(dataClass, MediaType.APPLICATION_JSON)) {
HttpMessageConverter<Object> objectConverter = (HttpMessageConverter<Object>) converter;
ServerHttpResponse response = new MutableHeadersServerHttpResponse(this.outputMessage);
objectConverter.write(data, MediaType.APPLICATION_JSON, response);
this.outputMessage.getBody().write(NL_NL);
this.outputMessage.flush();
return;
}
}
}
catch (IOException ex) {
this.sendFailed = true;
throw ex;
}
finally {
this.builder.setLength(0);
}
}
private byte[] builderBytes() {
return this.builder.toString().getBytes(StandardCharsets.UTF_8);
}
@Override
public void error(Throwable t) {
if (this.sendFailed) {
return;
}
this.deferredResult.setErrorResult(t);
}
@Override
public void complete() {
if (this.sendFailed) {
return;
}
try {
this.outputMessage.flush();
this.deferredResult.setResult(null);
}
catch (IOException ex) {
this.deferredResult.setErrorResult(ex);
}
}
@Override
public SseBuilder onTimeout(Runnable onTimeout) {
this.deferredResult.onTimeout(onTimeout);
return this;
}
@Override
public SseBuilder onError(Consumer<Throwable> onError) {
this.deferredResult.onError(onError);
return this;
}
@Override
public SseBuilder onComplete(Runnable onCompletion) {
this.deferredResult.onCompletion(onCompletion);
return this;
}
/**
* Wrap to silently ignore header changes HttpMessageConverter's that would
* otherwise cause HttpHeaders to raise exceptions.
*/
private static final class MutableHeadersServerHttpResponse extends DelegatingServerHttpResponse {
private final HttpHeaders mutableHeaders = new HttpHeaders();
public MutableHeadersServerHttpResponse(ServerHttpResponse delegate) {
super(delegate);
this.mutableHeaders.putAll(delegate.getHeaders());
}
@Override
public HttpHeaders getHeaders() {
return this.mutableHeaders;
}
}
}
}
| |
/*
* Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ensembl.healthcheck;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import org.ensembl.healthcheck.testcase.EnsTestCase;
import org.ensembl.healthcheck.util.Utils;
/**
* Subclass of TestRunner that produces a web page containing descriptions of available tests.
*/
public class BuildTestLibrary extends TestRunner {
private String template = "";
// -------------------------------------------------------------------------
/**
* Command-line run method.
*
* @param args
* The command-line arguments.
*/
public static void main(final String[] args) {
BuildTestLibrary btl = new BuildTestLibrary();
logger.setLevel(Level.OFF);
btl.parseCommandLine(args);
Utils.readPropertiesFileIntoSystem(getPropertiesFile(), false);
btl.buildList();
} // main
// -------------------------------------------------------------------------
private void parseCommandLine(final String[] args) {
if (args.length == 0) {
printUsage();
System.exit(1);
}
if (args[0].equals("-h") || args.length == 0) {
printUsage();
System.exit(0);
} else {
template = args[0];
}
} // parseCommandLine
// -------------------------------------------------------------------------
private void printUsage() {
System.out.println("\nUsage: BuildTestLibrary <template>\n");
System.out.println("Options:");
System.out.println(" None.");
System.out.println("");
System.out.println("Expects template file to exist and contain #TEST_TABLE# and #TIMESTAMP# placeholders.");
System.out.println("Writes to test_list.html in same directory as template.");
} // printUsage
// -------------------------------------------------------------------------
private void buildList() {
try {
// get the directory
String dir = template.substring(0, template.lastIndexOf(File.separator));
String outputFile = dir + File.separator + "test_list.html";
PrintWriter out = new PrintWriter(new FileWriter(outputFile));
// parse the template until we find the #TEST_TABLE# placeholder
BufferedReader in = new BufferedReader(new FileReader(template));
String line = in.readLine();
while (line != null) {
if (line.indexOf("#TEST_TABLE#") > -1) {
out.println(listAllTestsAsHTMLTable());
} else if (line.indexOf("#TESTS_BY_GROUP#") > -1) {
out.println(listTestsByGroup());
} else if (line.indexOf("#TIMESTAMP#") > -1) {
out.println(new Date());
} else {
out.println(line);
}
line = in.readLine();
}
System.out.println("Wrote output to " + outputFile);
in.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// -------------------------------------------------------------------------
private String listAllTestsAsHTMLTable() {
StringBuffer buf = new StringBuffer();
List tests = new DiscoveryBasedTestRegistry().findAllTests();
Iterator it = tests.iterator();
while (it.hasNext()) {
// test name
EnsTestCase test = (EnsTestCase) it.next();
buf.append("<tr>");
buf.append("<td class=\"lfooter\"><strong>" + test.getShortTestName() + "</strong></td>");
// group(s)
List groups = test.getGroups();
Iterator gIt = groups.iterator();
buf.append("<td>");
while (gIt.hasNext()) {
String group = (String) gIt.next();
if (!group.equals(test.getShortTestName()) && !group.equals("all")) {
buf.append(group + "<br>");
}
}
buf.append("</td>");
// description
buf.append("<td><font size=-1>" + test.getDescription() + "</font></td>");
buf.append("</tr>\n");
} // while tests
return buf.toString();
} // listAllTestsAsHTMLTable
// -------------------------------------------------------------------------
private String listTestsByGroup() {
StringBuffer buf = new StringBuffer();
List allTests = new DiscoveryBasedTestRegistry().findAllTests();
String[] groups = listAllGroups(allTests);
for (int i = 0; i < groups.length; i++) {
String group = groups[i];
if (!group.equalsIgnoreCase("all") && group.indexOf("TestCase") < 0) {
buf.append("<p><strong>" + group + "</strong></p>");
String[] tests = listTestsInGroup(allTests, group);
for (int j = 0; j < tests.length; j++) {
buf.append(tests[j] + "<br>");
} // tests
}
} // groups
return buf.toString();
}
// -------------------------------------------------------------------------
} // BuildTestLibrary
| |
package org.jivesoftware.openfire.plugin.ofmeet;
import org.dom4j.Element;
import org.jitsi.videobridge.Videobridge;
import org.jitsi.videobridge.Conference;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.group.Group;
import org.jivesoftware.openfire.group.GroupManager;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.roster.RosterManager;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* custom IQ handler for user and group properties JSON request/response.
*/
public class OfMeetIQHandler extends IQHandler
{
private final static Logger Log = LoggerFactory.getLogger( OfMeetIQHandler.class );
private final Videobridge videobridge;
public OfMeetIQHandler( Videobridge videobridge )
{
super("Openfire Meetings IQ Handler");
this.videobridge = videobridge;
}
@Override
public IQ handleIQ(IQ iq)
{
IQ reply = IQ.createResultIQ(iq);
try {
Log.info("Openfire Meetings handleIQ \n" + iq.toString());
final Element element = iq.getChildElement();
JSONObject requestJSON = new JSONObject( element.getText());
String action = requestJSON.getString("action");
if ("get_user_properties".equals(action)) getUserProperties(iq.getFrom().getNode(), reply, requestJSON);
if ("set_user_properties".equals(action)) setUserProperties(iq.getFrom().getNode(), reply, requestJSON);
if ("get_user_groups".equals(action)) getUserGroups(iq.getFrom().getNode(), reply, requestJSON);
if ("get_group".equals(action)) getGroup(iq.getFrom().getNode(), reply, requestJSON);
if ("get_conference_id".equals(action)) getConferenceId(iq.getFrom().getNode(), reply, requestJSON);
return reply;
} catch(Exception e) {
Log.error("Openfire Meetings handleIQ", e);
reply.setError(new PacketError(PacketError.Condition.internal_server_error, PacketError.Type.modify, e.toString()));
return reply;
}
}
@Override
public IQHandlerInfo getInfo()
{
return new IQHandlerInfo("request", "http://igniterealtime.org/protocol/ofmeet");
}
private void getConferenceId(String defaultUsername, IQ reply, JSONObject requestJSON)
{
Element childElement = reply.setChildElement("response", "http://igniterealtime.org/protocol/ofmeet");
try {
String roomName = requestJSON.getString("room");
for (Conference conference : videobridge.getConferences())
{
String room = conference.getName();
if (room != null && !"".equals(room) && roomName.equals(room))
{
JSONObject userJSON = new JSONObject();
userJSON.put("room", roomName);
userJSON.put("id", conference.getID());
userJSON.put("lastActivityTime", String.valueOf(conference.getLastActivityTime()));
userJSON.put("focus", conference.getFocus());
userJSON.put("expired", conference.isExpired() ? "yes" : "no");
childElement.setText(userJSON.toString());
break;
}
}
} catch (Exception e1) {
reply.setError(new PacketError(PacketError.Condition.not_allowed, PacketError.Type.modify, requestJSON.toString() + " " + e1));
return;
}
}
private void setUserProperties(String username, IQ reply, JSONObject requestJSON)
{
Element childElement = reply.setChildElement("response", "http://igniterealtime.org/protocol/ofmeet");
try {
UserManager userManager = XMPPServer.getInstance().getUserManager();
User user = userManager.getUser(username);
if (requestJSON != null)
{
Iterator<?> keys = requestJSON.keys();
while( keys.hasNext() )
{
String key = (String)keys.next();
String value = requestJSON.getString(key);
user.getProperties().put(key, value);
}
}
} catch (Exception e) {
reply.setError(new PacketError(PacketError.Condition.not_allowed, PacketError.Type.modify, "User " + username + " " + requestJSON.toString() + " " + e));
return;
}
}
private void getUserProperties(String defaultUsername, IQ reply, JSONObject requestJSON)
{
Element childElement = reply.setChildElement("response", "http://igniterealtime.org/protocol/ofmeet");
try {
String username = requestJSON.getString("username");
if (username == null) username = defaultUsername;
UserManager userManager = XMPPServer.getInstance().getUserManager();
User user = userManager.getUser(username);
JSONObject userJSON = new JSONObject();
userJSON.put("username", JID.unescapeNode(user.getUsername()));
userJSON.put("name", user.isNameVisible() ? removeNull(user.getName()) : "");
userJSON.put("email", user.isEmailVisible() ? removeNull(user.getEmail()) : "");
for(Map.Entry<String, String> props : user.getProperties().entrySet())
{
userJSON.put(props.getKey(), props.getValue());
}
childElement.setText(userJSON.toString());
} catch (UserNotFoundException e) {
reply.setError(new PacketError(PacketError.Condition.not_allowed, PacketError.Type.modify, "User not found"));
return;
} catch (Exception e1) {
reply.setError(new PacketError(PacketError.Condition.not_allowed, PacketError.Type.modify, requestJSON.toString() + " " + e1));
return;
}
}
private void getUserGroups(String defaultUsername, IQ reply, JSONObject requestJSON)
{
Element childElement = reply.setChildElement("response", "http://igniterealtime.org/protocol/ofmeet");
try {
String username = requestJSON.getString("username");
if (username == null) username = defaultUsername;
UserManager userManager = XMPPServer.getInstance().getUserManager();
User user = userManager.getUser(username);
Collection<Group> groups = GroupManager.getInstance().getGroups(user);
JSONArray groupsJSON = new JSONArray();
int index = 0;
for (Group group : groups)
{
groupsJSON.put(index++, getJsonFromGroupXml(group.getName()));
}
childElement.setText(groupsJSON.toString());
} catch (UserNotFoundException e) {
reply.setError(new PacketError(PacketError.Condition.not_allowed, PacketError.Type.modify, "User not found"));
return;
} catch (Exception e1) {
reply.setError(new PacketError(PacketError.Condition.not_allowed, PacketError.Type.modify, requestJSON.toString() + " " + e1));
return;
}
}
private void getGroup(String defaultUsername, IQ reply, JSONObject requestJSON)
{
Element childElement = reply.setChildElement("response", "http://igniterealtime.org/protocol/ofmeet");
try {
JSONObject groupJSON = getJsonFromGroupXml(requestJSON.getString("groupname"));
childElement.setText(groupJSON.toString());
} catch (Exception e1) {
reply.setError(new PacketError(PacketError.Condition.not_allowed, PacketError.Type.modify, requestJSON.toString() + " " + e1));
return;
}
}
private JSONObject getJsonFromGroupXml(String groupname)
{
JSONObject groupJSON = new JSONObject();
try {
Group group = GroupManager.getInstance().getGroup(groupname);
boolean isSharedGroup = RosterManager.isSharedGroup(group);
Map<String, String> properties = group.getProperties();
String showInRoster = (isSharedGroup ? properties.get("sharedRoster.showInRoster") : "");
groupJSON.put("name", group.getName());
groupJSON.put("desc", group.getDescription());
groupJSON.put("count", group.getMembers().size() + group.getAdmins().size());
groupJSON.put("shared", String.valueOf(isSharedGroup));
groupJSON.put("display", (isSharedGroup ? properties.get("sharedRoster.displayName") : ""));
groupJSON.put("specified_groups", String.valueOf("onlyGroup".equals(showInRoster) && properties.get("sharedRoster.groupList").trim().length() > 0));
groupJSON.put("visibility", showInRoster);
groupJSON.put("groups", (isSharedGroup ? properties.get("sharedRoster.groupList") : ""));
for(Map.Entry<String, String> props : properties.entrySet())
{
groupJSON.put(props.getKey(), props.getValue());
}
JSONArray membersJSON = new JSONArray();
JSONArray adminsJSON = new JSONArray();
int i = 0;
for (JID memberJID : group.getMembers())
{
JSONObject memberJSON = new JSONObject();
memberJSON.put("jid", memberJID.toString());
memberJSON.put("name", memberJID.getNode());
membersJSON.put(i++, memberJSON);
}
groupJSON.put("members", membersJSON);
i = 0;
for (JID memberJID : group.getAdmins())
{
JSONObject adminJSON = new JSONObject();
adminJSON.put("jid", memberJID.toString());
adminJSON.put("name", memberJID.getNode());
adminsJSON.put(i++, adminJSON);
}
groupJSON.put("admins", adminsJSON);
} catch (Exception e) {
Log.error("getJsonFromGroupXml", e);
}
return groupJSON;
}
private String removeNull(String s)
{
if (s == null)
{
return "";
}
return s.trim();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.test.func.api.javax.management;
import java.util.ArrayList;
import javax.management.JMRuntimeException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import org.apache.harmony.test.func.api.javax.management.share.SimpleMBeanServerBuilder;
import org.apache.harmony.test.func.api.javax.management.share.SimpleMBeanServerImpl;
import org.apache.harmony.test.func.api.javax.management.share.framework.Test;
import org.apache.harmony.test.func.api.javax.management.share.framework.TestRunner;
/**
* Test for the class javax.management.MBeanServerFactory
*
*/
public class MBeanServerFactoryTest extends Test {
/**
* Test for the method createMBeanServer()
*
* @see javax.management.MBeanServerFactory#createMBeanServer()
*/
public final void testCreateMBeanServer() {
MBeanServer srv = MBeanServerFactory.createMBeanServer();
assertEquals("DefaultDomain", srv.getDefaultDomain());
MBeanServerFactory.releaseMBeanServer(srv);
// Check reaction on the javax.management.builder.initial system
// property.
System.setProperty("javax.management.builder.initial",
SimpleMBeanServerBuilder.class.getName());
srv = MBeanServerFactory.createMBeanServer();
assertEquals(SimpleMBeanServerImpl.class, srv.getClass());
assertEquals("DefaultDomain", srv.getDefaultDomain());
MBeanServerFactory.releaseMBeanServer(srv);
SimpleMBeanServerBuilder.returnNull = true;
try {
srv = MBeanServerFactory.createMBeanServer();
fail("JMRuntimeException wasn't thrown.");
} catch (JMRuntimeException ex) {
}
System.setProperty("javax.management.builder.initial", "builder");
SimpleMBeanServerBuilder.returnNull = true;
try {
srv = MBeanServerFactory.createMBeanServer();
fail("JMRuntimeException wasn't thrown.");
} catch (JMRuntimeException ex) {
}
System.setProperty("javax.management.builder.initial", String.class
.getName());
try {
srv = MBeanServerFactory.createMBeanServer();
fail("ClassCastException wasn't thrown.");
} catch (ClassCastException ex) {
}
}
/**
* Test for the method createMBeanServer(java.lang.String)
*
* @see javax.management.MBeanServerFactory#createMBeanServer(java.lang.String)
*/
public final void testCreateMBeanServerString() {
MBeanServer srv = MBeanServerFactory
.createMBeanServer("Default Domain");
assertEquals("Default Domain", srv.getDefaultDomain());
MBeanServerFactory.releaseMBeanServer(srv);
// Check reaction on the javax.management.builder.initial system
// property.
System.setProperty("javax.management.builder.initial",
SimpleMBeanServerBuilder.class.getName());
srv = MBeanServerFactory.createMBeanServer("Default Domain");
assertEquals(SimpleMBeanServerImpl.class, srv.getClass());
assertEquals("Default Domain", srv.getDefaultDomain());
MBeanServerFactory.releaseMBeanServer(srv);
SimpleMBeanServerBuilder.returnNull = true;
try {
srv = MBeanServerFactory.createMBeanServer("Default Domain");
fail("JMRuntimeException wasn't thrown.");
} catch (JMRuntimeException ex) {
}
System.setProperty("javax.management.builder.initial", "builder");
SimpleMBeanServerBuilder.returnNull = false;
try {
srv = MBeanServerFactory.createMBeanServer("Default Domain");
fail("JMRuntimeException wasn't thrown.");
} catch (JMRuntimeException ex) {
}
System.setProperty("javax.management.builder.initial", String.class
.getName());
try {
srv = MBeanServerFactory.createMBeanServer("Default Domain");
fail("ClassCastException wasn't thrown.");
} catch (ClassCastException ex) {
}
}
/**
* Test for the method findMBeanServer(java.lang.String)
*
* @see javax.management.MBeanServerFactory#findMBeanServer(java.lang.String)
*/
public final void testFindMBeanServer() {
MBeanServer srv = MBeanServerFactory.createMBeanServer();
MBeanServer srv1 = MBeanServerFactory.createMBeanServer("Server1");
MBeanServer srv2 = MBeanServerFactory.createMBeanServer("Server2");
ArrayList l = MBeanServerFactory.findMBeanServer(null);
assertTrue(l.contains(srv));
assertTrue(l.contains(srv1));
assertTrue(l.contains(srv2));
try {
l = MBeanServerFactory.findMBeanServer((String) srv2.getAttribute(
new ObjectName("JMImplementation:type=MBeanServerDelegate"),
"MBeanServerId"));
if (l.size() == 1) {
assertEquals(srv2, l.get(0));
} else {
fail("The ArrayList object should contain the only one "
+ "MBeanServer object - srv2. Actual: " + l);
}
} catch (Exception ex) {
fail(ex);
}
MBeanServerFactory.releaseMBeanServer(srv);
MBeanServerFactory.releaseMBeanServer(srv1);
MBeanServerFactory.releaseMBeanServer(srv2);
}
/**
* Test for the method
* getClassLoaderRepository(javax.management.MBeanServer)
*
* @see javax.management.MBeanServerFactory#getClassLoaderRepository(javax.management.MBeanServer)
*/
public final void testGetClassLoaderRepository() {
MBeanServer srv = MBeanServerFactory.createMBeanServer("Server1");
assertEquals(srv.getClassLoaderRepository(), MBeanServerFactory
.getClassLoaderRepository(srv));
try {
MBeanServerFactory.getClassLoaderRepository(null);
fail("NullPointerException wasn't thrown.");
} catch (NullPointerException ex) {
}
MBeanServerFactory.releaseMBeanServer(srv);
}
/**
* Test for the method newMBeanServer()
*
* @see javax.management.MBeanServerFactory#newMBeanServer()
*/
public final void testNewMBeanServer() {
MBeanServer srv = MBeanServerFactory.newMBeanServer();
assertEquals("DefaultDomain", srv.getDefaultDomain());
try {
ArrayList l = MBeanServerFactory.findMBeanServer((String) srv
.getAttribute(new ObjectName(
"JMImplementation:type=MBeanServerDelegate"),
"MBeanServerId"));
if (l.size() != 0) {
fail("The ArrayList object should be empty. Actual: " + l);
}
} catch (Exception ex) {
fail(ex);
}
// Check reaction on the javax.management.builder.initial system
// property.
System.setProperty("javax.management.builder.initial",
SimpleMBeanServerBuilder.class.getName());
srv = MBeanServerFactory.newMBeanServer();
assertEquals(SimpleMBeanServerImpl.class, srv.getClass());
assertEquals("DefaultDomain", srv.getDefaultDomain());
SimpleMBeanServerBuilder.returnNull = true;
try {
srv = MBeanServerFactory.newMBeanServer();
fail("JMRuntimeException wasn't thrown.");
} catch (JMRuntimeException ex) {
}
System.setProperty("javax.management.builder.initial", "builder");
SimpleMBeanServerBuilder.returnNull = true;
try {
srv = MBeanServerFactory.newMBeanServer();
fail("JMRuntimeException wasn't thrown.");
} catch (JMRuntimeException ex) {
}
System.setProperty("javax.management.builder.initial", String.class
.getName());
try {
srv = MBeanServerFactory.newMBeanServer();
fail("ClassCastException wasn't thrown.");
} catch (ClassCastException ex) {
}
}
/**
* Test for the method newMBeanServer(java.lang.String)
*
* @see javax.management.MBeanServerFactory#newMBeanServer(java.lang.String)
*/
public final void testNewMBeanServerString() {
MBeanServer srv = MBeanServerFactory.newMBeanServer("Default Domain");
assertEquals("Default Domain", srv.getDefaultDomain());
try {
ArrayList l = MBeanServerFactory.findMBeanServer((String) srv
.getAttribute(new ObjectName(
"JMImplementation:type=MBeanServerDelegate"),
"MBeanServerId"));
if (l.size() != 0) {
fail("The ArrayList object should be empty. Actual: " + l);
}
} catch (Exception ex) {
fail(ex);
}
// Check reaction on the javax.management.builder.initial system
// property.
System.setProperty("javax.management.builder.initial",
SimpleMBeanServerBuilder.class.getName());
srv = MBeanServerFactory.newMBeanServer("Default Domain");
assertEquals(SimpleMBeanServerImpl.class, srv.getClass());
assertEquals("Default Domain", srv.getDefaultDomain());
SimpleMBeanServerBuilder.returnNull = true;
try {
srv = MBeanServerFactory.newMBeanServer("Default Domain");
fail("JMRuntimeException wasn't thrown.");
} catch (JMRuntimeException ex) {
}
System.setProperty("javax.management.builder.initial", "builder");
SimpleMBeanServerBuilder.returnNull = true;
try {
srv = MBeanServerFactory.newMBeanServer("Default Domain");
fail("JMRuntimeException wasn't thrown.");
} catch (JMRuntimeException ex) {
}
System.setProperty("javax.management.builder.initial", String.class
.getName());
try {
srv = MBeanServerFactory.newMBeanServer("Default Domain");
fail("ClassCastException wasn't thrown.");
} catch (ClassCastException ex) {
}
}
/**
* Test for the method releaseMBeanServer(javax.management.MBeanServer)
*
* @see javax.management.MBeanServerFactory#releaseMBeanServer(javax.management.MBeanServer)
*/
public final void testReleaseMBeanServer() {
MBeanServer srv = MBeanServerFactory.createMBeanServer();
MBeanServerFactory.releaseMBeanServer(srv);
try {
ArrayList l = MBeanServerFactory.findMBeanServer((String) srv
.getAttribute(new ObjectName(
"JMImplementation:type=MBeanServerDelegate"),
"MBeanServerId"));
if (l.size() != 0) {
fail("The ArrayList object should be empty. Actual: " + l);
}
} catch (Exception ex) {
fail(ex);
}
try {
MBeanServerFactory.releaseMBeanServer(srv);
fail("IllegalArgumentException wasn't thrown.");
} catch (IllegalArgumentException ex) {
}
try {
MBeanServerFactory.releaseMBeanServer(MBeanServerFactory
.newMBeanServer());
fail("IllegalArgumentException wasn't thrown.");
} catch (IllegalArgumentException ex) {
}
}
/**
* Remove the system property javax.management.builder.initial.
*/
public void tearDown() {
SimpleMBeanServerBuilder.returnNull = false;
System.getProperties().remove("javax.management.builder.initial");
}
/**
* Release all MBean servers.
*/
public void release() {
ArrayList list = MBeanServerFactory.findMBeanServer(null);
int size = list.size();
for (int i = 0; i < size; i++) {
MBeanServerFactory.releaseMBeanServer((MBeanServer) list.get(i));
}
}
/**
* Run the test.
*
* @param args command line arguments.
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.exit(TestRunner.run(MBeanServerFactoryTest.class, args));
}
}
| |
/*
* Copyright (c) 2010-2020. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.axonserver.connector.event.axon;
import com.google.protobuf.ByteString;
import io.axoniq.axonserver.connector.event.EventChannel;
import io.axoniq.axonserver.grpc.InstructionAck;
import io.axoniq.axonserver.grpc.event.Event;
import org.axonframework.axonserver.connector.AxonServerConnectionManager;
import org.axonframework.axonserver.connector.ErrorCode;
import org.axonframework.axonserver.connector.event.util.GrpcExceptionParser;
import org.axonframework.axonserver.connector.util.GrpcMetaDataConverter;
import org.axonframework.common.Assert;
import org.axonframework.common.AxonConfigurationException;
import org.axonframework.common.IdentifierFactory;
import org.axonframework.eventhandling.EventMessage;
import org.axonframework.eventhandling.scheduling.EventScheduler;
import org.axonframework.eventhandling.scheduling.ScheduleToken;
import org.axonframework.eventhandling.scheduling.java.SimpleScheduleToken;
import org.axonframework.lifecycle.Phase;
import org.axonframework.lifecycle.ShutdownHandler;
import org.axonframework.lifecycle.StartHandler;
import org.axonframework.messaging.MetaData;
import org.axonframework.serialization.SerializedObject;
import org.axonframework.serialization.Serializer;
import org.axonframework.serialization.xml.XStreamSerializer;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import static org.axonframework.common.BuilderUtils.assertNonNull;
import static org.axonframework.common.ObjectUtils.getOrDefault;
/**
* Implementation of the {@link EventScheduler} that uses Axon Server to schedule the events.
*
* @author Marc Gathier
* @since 4.4
*/
public class AxonServerEventScheduler implements EventScheduler {
private final long requestTimeout;
private final Serializer serializer;
private final AxonServerConnectionManager axonServerConnectionManager;
private final GrpcMetaDataConverter converter;
private final AtomicBoolean started = new AtomicBoolean();
/**
* Instantiate a Builder to be able to create a {@link AxonServerEventScheduler}.
* <p>
* The {@code requestTimeout} is defaulted to {@code 15000} millis and the {@link Serializer} to a {@link
* XStreamSerializer}. The {@link AxonServerConnectionManager} is a <b>hard requirement</b> and as such should be
* provided.
*
* @return a Builder to be able to create a {@link AxonServerEventScheduler}
*/
public static Builder builder() {
return new Builder();
}
/**
* Instantiates an {@link AxonServerEventScheduler} using the given {@link Builder}.
* <p>
* Will assert that the {@link AxonServerConnectionManager} is not {@code null} and will throw an {@link
* AxonConfigurationException} if this is the case.
*
* @param builder the {@link Builder} used.
*/
protected AxonServerEventScheduler(Builder builder) {
builder.validate();
this.requestTimeout = builder.requestTimeout;
this.serializer = builder.eventSerializer.get();
this.axonServerConnectionManager = builder.axonServerConnectionManager;
this.converter = new GrpcMetaDataConverter(serializer);
}
/**
* Start the Axon Server {@link EventScheduler} implementation.
*/
@StartHandler(phase = Phase.OUTBOUND_EVENT_CONNECTORS)
public void start() {
started.set(true);
}
/**
* Shuts down the Axon Server {@link EventScheduler} implementation.
*/
@ShutdownHandler(phase = Phase.OUTBOUND_EVENT_CONNECTORS)
public void shutdownDispatching() {
started.set(false);
}
/**
* Schedules an event to be published at a given moment. The event is published in the application's default
* context.
*
* @param triggerDateTime The moment to trigger publication of the event
* @param event The event to publish
* @return a token used to manage the schedule later
*/
@Override
public ScheduleToken schedule(Instant triggerDateTime, Object event) {
Assert.isTrue(started.get(), () -> "Cannot dispatch new events as this scheduler is being shutdown");
try {
String response = eventChannel().scheduleEvent(triggerDateTime, toEvent(event))
.get(requestTimeout, TimeUnit.MILLISECONDS);
return new SimpleScheduleToken(response);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw GrpcExceptionParser.parse(e);
} catch (ExecutionException e) {
throw GrpcExceptionParser.parse(e.getCause());
} catch (TimeoutException e) {
throw GrpcExceptionParser.parse(e);
}
}
/**
* Schedules an event to be published after a specified amount of time.
*
* @param triggerDuration the amount of time to wait before publishing the event
* @param event the event to publish
* @return a token used to manage the schedule later
*/
@Override
public ScheduleToken schedule(Duration triggerDuration, Object event) {
return schedule(Instant.now().plus(triggerDuration), event);
}
/**
* Cancel a scheduled event.
*
* @param scheduleToken the token returned when the event was scheduled
*/
@Override
public void cancelSchedule(ScheduleToken scheduleToken) {
Assert.isTrue(started.get(), () -> "Scheduler is being shutdown");
Assert.isTrue(scheduleToken instanceof SimpleScheduleToken,
() -> "Invalid tracking token type. Must be SimpleScheduleToken.");
String token = ((SimpleScheduleToken) scheduleToken).getTokenId();
try {
InstructionAck instructionAck = eventChannel().cancelSchedule(token)
.get(requestTimeout, TimeUnit.MILLISECONDS);
if (!instructionAck.getSuccess()) {
throw ErrorCode.getFromCode(instructionAck.getError().getErrorCode())
.convert(instructionAck.getError());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw GrpcExceptionParser.parse(e);
} catch (ExecutionException e) {
throw GrpcExceptionParser.parse(e.getCause());
} catch (TimeoutException e) {
throw GrpcExceptionParser.parse(e);
}
}
/**
* Changes the trigger time for a scheduled event.
*
* @param scheduleToken the token returned when the event was scheduled, might be null
* @param triggerDuration the amount of time to wait before publishing the event
* @param event the event to publish
* @return a token used to manage the schedule later
*/
@Override
public ScheduleToken reschedule(ScheduleToken scheduleToken, Duration triggerDuration, Object event) {
Assert.isTrue(started.get(), () -> "Cannot dispatch new events as this scheduler is being shutdown");
Assert.isTrue(scheduleToken == null || scheduleToken instanceof SimpleScheduleToken,
() -> "Invalid tracking token type. Must be SimpleScheduleToken.");
String token = scheduleToken == null ? "" : ((SimpleScheduleToken) scheduleToken).getTokenId();
try {
String updatedScheduleToken = eventChannel().reschedule(token,
Instant.now().plus(triggerDuration),
toEvent(event))
.get(requestTimeout, TimeUnit.MILLISECONDS);
return new SimpleScheduleToken(updatedScheduleToken);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw GrpcExceptionParser.parse(e);
} catch (ExecutionException e) {
throw GrpcExceptionParser.parse(e.getCause());
} catch (TimeoutException e) {
throw GrpcExceptionParser.parse(e);
}
}
private EventChannel eventChannel() {
return axonServerConnectionManager.getConnection().eventChannel();
}
private Event toEvent(Object event) {
SerializedObject<byte[]> serializedPayload;
MetaData metadata;
String requestId = null;
if (event instanceof EventMessage<?>) {
serializedPayload = ((EventMessage<?>) event)
.serializePayload(serializer, byte[].class);
metadata = ((EventMessage<?>) event).getMetaData();
requestId = ((EventMessage<?>) event).getIdentifier();
} else {
metadata = MetaData.emptyInstance();
serializedPayload = serializer.serialize(event, byte[].class);
}
if (requestId == null) {
requestId = IdentifierFactory.getInstance().generateIdentifier();
}
Event.Builder builder = Event.newBuilder()
.setMessageIdentifier(requestId);
builder.setPayload(
io.axoniq.axonserver.grpc.SerializedObject.newBuilder()
.setType(serializedPayload.getType().getName())
.setRevision(getOrDefault(
serializedPayload.getType().getRevision(),
""
))
.setData(ByteString.copyFrom(serializedPayload.getData())));
metadata.forEach((k, v) -> builder.putMetaData(k, converter.convertToMetaDataValue(v)));
return builder.build();
}
/**
* Builder class to instantiate an {@link AxonServerEventScheduler}.
* <p>
* The {@code requestTimeout} is defaulted to {@code 15000} millis and the {@link Serializer} to a {@link
* XStreamSerializer}. The {@link AxonServerConnectionManager} is a <b>hard requirement</b> and as such should be
* provided.
*/
public static class Builder {
private long requestTimeout = 15000;
private Supplier<Serializer> eventSerializer = XStreamSerializer::defaultSerializer;
private AxonServerConnectionManager axonServerConnectionManager;
/**
* Sets the timeout in which a confirmation of the scheduling interaction is expected. Defaults to 15 seconds.
*
* @param timeout the time to wait at most for a confirmation
* @param unit the unit in which the timeout is expressed
* @return the current Builder instance, for fluent interfacing
*/
public Builder requestTimeout(long timeout, TimeUnit unit) {
this.requestTimeout = unit.toMillis(timeout);
return this;
}
/**
* Sets the {@link Serializer} used to de-/serialize events.
*
* @param eventSerializer a {@link Serializer} used to de-/serialize events
* @return the current Builder instance, for fluent interfacing
*/
public Builder eventSerializer(Serializer eventSerializer) {
this.eventSerializer = () -> eventSerializer;
return this;
}
/**
* Sets the {@link AxonServerConnectionManager} used to create connections between this application and an Axon
* Server instance.
*
* @param axonServerConnectionManager an {@link AxonServerConnectionManager} used to create connections between
* this application and an Axon Server instance
* @return the current Builder instance, for fluent interfacing
*/
public Builder connectionManager(AxonServerConnectionManager axonServerConnectionManager) {
assertNonNull(axonServerConnectionManager, "AxonServerConnectionManager may not be null");
this.axonServerConnectionManager = axonServerConnectionManager;
return this;
}
/**
* Initializes a {@link AxonServerEventScheduler} as specified through this Builder.
*
* @return a {@link AxonServerEventScheduler} as specified through this Builder
*/
public AxonServerEventScheduler build() {
return new AxonServerEventScheduler(this);
}
protected void validate() throws AxonConfigurationException {
assertNonNull(axonServerConnectionManager,
"The AxonServerConnectionManager is a hard requirement and should be provided");
}
}
}
| |
package com.cloud.api.response;
import com.cloud.acl.RoleType;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseResponse;
import com.cloud.api.EntityReference;
import com.cloud.legacymodel.network.Network;
import com.cloud.projects.ProjectAccount;
import com.cloud.serializer.Param;
import java.util.List;
import java.util.Set;
import com.google.gson.annotations.SerializedName;
@EntityReference(value = {Network.class, ProjectAccount.class})
public class NetworkResponse extends BaseResponse implements ControlledEntityResponse {
@SerializedName(ApiConstants.ID)
@Param(description = "the id of the network")
private String id;
@SerializedName(ApiConstants.NAME)
@Param(description = "the name of the network")
private String name;
@SerializedName(ApiConstants.DISPLAY_TEXT)
@Param(description = "the displaytext of the network")
private String displaytext;
@SerializedName("broadcastdomaintype")
@Param(description = "Broadcast domain type of the network")
private String broadcastDomainType;
@SerializedName(ApiConstants.TRAFFIC_TYPE)
@Param(description = "the traffic type of the network")
private String trafficType;
@SerializedName(ApiConstants.GATEWAY)
@Param(description = "the network's gateway")
private String gateway;
@SerializedName(ApiConstants.NETMASK)
@Param(description = "the network's netmask")
private String netmask;
@SerializedName(ApiConstants.CIDR)
@Param(description = "Cloudstack managed address space, all CloudStack managed VMs get IP address from CIDR")
private String cidr;
@SerializedName(ApiConstants.NETWORK_CIDR)
@Param(description = "the network CIDR of the guest network configured with IP reservation. It is the summation of CIDR and RESERVED_IP_RANGE")
private String networkCidr;
@SerializedName(ApiConstants.RESERVED_IP_RANGE)
@Param(description = "the network's IP range not to be used by CloudStack guest VMs and can be used for non CloudStack purposes")
private String reservedIpRange;
@SerializedName(ApiConstants.ZONE_ID)
@Param(description = "zone id of the network")
private String zoneId;
@SerializedName(ApiConstants.ZONE_NAME)
@Param(description = "the name of the zone the network belongs to")
private String zoneName;
@SerializedName("networkofferingid")
@Param(description = "network offering id the network is created from")
private String networkOfferingId;
@SerializedName("networkofferingname")
@Param(description = "name of the network offering the network is created from")
private String networkOfferingName;
@SerializedName("networkofferingdisplaytext")
@Param(description = "display text of the network offering the network is created from")
private String networkOfferingDisplayText;
@SerializedName("networkofferingconservemode")
@Param(description = "true if network offering is ip conserve mode enabled")
private Boolean networkOfferingConserveMode;
@SerializedName("networkofferingavailability")
@Param(description = "availability of the network offering the network is created from")
private String networkOfferingAvailability;
@SerializedName(ApiConstants.IS_SYSTEM)
@Param(description = "true if network is system, false otherwise")
private Boolean isSystem;
@SerializedName(ApiConstants.STATE)
@Param(description = "state of the network")
private String state;
@SerializedName("related")
@Param(description = "related to what other network configuration")
private String related;
@SerializedName("broadcasturi")
@Param(description = "broadcast uri of the network. This parameter is visible to ROOT admins only")
private String broadcastUri;
@SerializedName(ApiConstants.DNS1)
@Param(description = "the first DNS for the network")
private String dns1;
@SerializedName(ApiConstants.DNS2)
@Param(description = "the second DNS for the network")
private String dns2;
@SerializedName(ApiConstants.TYPE)
@Param(description = "the type of the network")
private String type;
@SerializedName(ApiConstants.VLAN)
@Param(description = "The vlan of the network. This parameter is visible to ROOT admins only")
private String vlan;
@SerializedName(ApiConstants.ACL_TYPE)
@Param(description = "acl type - access type to the network")
private String aclType;
@SerializedName(ApiConstants.SUBDOMAIN_ACCESS)
@Param(description = "true if users from subdomains can access the domain level network")
private Boolean subdomainAccess;
@SerializedName(ApiConstants.ACCOUNT)
@Param(description = "the owner of the network")
private String accountName;
@SerializedName(ApiConstants.PROJECT_ID)
@Param(description = "the project id of the ipaddress")
private String projectId;
@SerializedName(ApiConstants.PROJECT)
@Param(description = "the project name of the address")
private String projectName;
@SerializedName(ApiConstants.DOMAIN_ID)
@Param(description = "the domain id of the network owner")
private String domainId;
@SerializedName(ApiConstants.DOMAIN)
@Param(description = "the domain name of the network owner")
private String domain;
@SerializedName("isdefault")
@Param(description = "true if network is default, false otherwise")
private Boolean isDefault;
@SerializedName("service")
@Param(description = "the list of services", responseObject = ServiceResponse.class)
private List<ServiceResponse> services;
@SerializedName(ApiConstants.NETWORK_DOMAIN)
@Param(description = "the network domain")
private String networkDomain;
@SerializedName(ApiConstants.PHYSICAL_NETWORK_ID)
@Param(description = "the physical network id")
private String physicalNetworkId;
@SerializedName(ApiConstants.RESTART_REQUIRED)
@Param(description = "true network requires restart")
private Boolean restartRequired;
@SerializedName(ApiConstants.SPECIFY_IP_RANGES)
@Param(description = "true if network supports specifying ip ranges, false otherwise")
private Boolean specifyIpRanges;
@SerializedName(ApiConstants.VPC_ID)
@Param(description = "VPC the network belongs to")
private String vpcId;
@SerializedName(ApiConstants.VPC_NAME)
@Param(description = "VPC the network belongs to")
private String vpcName;
@SerializedName(ApiConstants.CAN_USE_FOR_DEPLOY)
@Param(description = "list networks available for vm deployment")
private Boolean canUseForDeploy;
@SerializedName(ApiConstants.IS_PERSISTENT)
@Param(description = "list networks that are persistent")
private Boolean isPersistent;
@SerializedName(ApiConstants.TAGS)
@Param(description = "the list of resource tags associated with network", responseObject = ResourceTagResponse.class)
private List<ResourceTagResponse> tags;
@SerializedName(ApiConstants.IP6_GATEWAY)
@Param(description = "the gateway of IPv6 network")
private String ip6Gateway;
@SerializedName(ApiConstants.IP6_CIDR)
@Param(description = "the cidr of IPv6 network")
private String ip6Cidr;
@SerializedName(ApiConstants.IP_EXCLUSION_LIST)
@Param(description = "list of ip addresses and/or ranges of addresses to be excluded from the network for assignment")
private String ipExclusionList;
@SerializedName(ApiConstants.DISPLAY_NETWORK)
@Param(description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin})
private Boolean displayNetwork;
@SerializedName(ApiConstants.ACL_ID)
@Param(description = "ACL Id associated with the VPC network")
private String aclId;
@SerializedName(ApiConstants.ACL_NAME)
@Param(description = "the name of the ACL applied to this IP")
private String aclName;
@SerializedName(ApiConstants.STRECHED_L2_SUBNET)
@Param(description = "true if network can span multiple zones", since = "4.4")
private Boolean strechedL2Subnet;
@SerializedName(ApiConstants.NETWORK_SPANNED_ZONES)
@Param(description = "If a network is enabled for 'streched l2 subnet' then represents zones on which network currently spans", since = "4.4")
private Set<String> networkSpannedZones;
@SerializedName(ApiConstants.DHCP_TFTP_SERVER)
@Param(description = "DHCP option 66: tftp-server")
private String dhcpTftpServer;
@SerializedName(ApiConstants.DHCP_BOOTFILE_NAME)
@Param(description = "DHCP option 67: bootfile-name")
private String dhcpBootfileName;
public Boolean getDisplayNetwork() {
return displayNetwork;
}
public void setDisplayNetwork(final Boolean displayNetwork) {
this.displayNetwork = displayNetwork;
}
public void setId(final String id) {
this.id = id;
}
public void setName(final String name) {
this.name = name;
}
public void setBroadcastDomainType(final String broadcastDomainType) {
this.broadcastDomainType = broadcastDomainType;
}
public void setTrafficType(final String trafficType) {
this.trafficType = trafficType;
}
public void setGateway(final String gateway) {
this.gateway = gateway;
}
public void setNetmask(final String netmask) {
this.netmask = netmask;
}
public void setZoneId(final String zoneId) {
this.zoneId = zoneId;
}
public void setNetworkOfferingId(final String networkOfferingId) {
this.networkOfferingId = networkOfferingId;
}
public void setState(final String state) {
this.state = state;
}
public void setRelated(final String related) {
this.related = related;
}
public void setBroadcastUri(final String broadcastUri) {
this.broadcastUri = broadcastUri;
}
public void setDns1(final String dns1) {
this.dns1 = dns1;
}
public void setDns2(final String dns2) {
this.dns2 = dns2;
}
public void setIpExclusionList(final String ipExclusionList) {
this.ipExclusionList = ipExclusionList;
}
public void setType(final String type) {
this.type = type;
}
@Override
public void setAccountName(final String accountName) {
this.accountName = accountName;
}
@Override
public void setProjectId(final String projectId) {
this.projectId = projectId;
}
@Override
public void setProjectName(final String projectName) {
this.projectName = projectName;
}
@Override
public void setDomainId(final String domainId) {
this.domainId = domainId;
}
@Override
public void setDomainName(final String domain) {
this.domain = domain;
}
public void setNetworkOfferingName(final String networkOfferingName) {
this.networkOfferingName = networkOfferingName;
}
public void setNetworkOfferingDisplayText(final String networkOfferingDisplayText) {
this.networkOfferingDisplayText = networkOfferingDisplayText;
}
public void setNetworkOfferingConserveMode(final Boolean networkOfferingConserveMode) {
this.networkOfferingConserveMode = networkOfferingConserveMode;
}
public void setDisplaytext(final String displaytext) {
this.displaytext = displaytext;
}
public void setVlan(final String vlan) {
this.vlan = vlan;
}
public void setIsSystem(final Boolean isSystem) {
this.isSystem = isSystem;
}
public void setNetworkOfferingAvailability(final String networkOfferingAvailability) {
this.networkOfferingAvailability = networkOfferingAvailability;
}
public void setServices(final List<ServiceResponse> services) {
this.services = services;
}
public void setIsDefault(final Boolean isDefault) {
this.isDefault = isDefault;
}
public void setNetworkDomain(final String networkDomain) {
this.networkDomain = networkDomain;
}
public void setPhysicalNetworkId(final String physicalNetworkId) {
this.physicalNetworkId = physicalNetworkId;
}
public void setAclType(final String aclType) {
this.aclType = aclType;
}
public void setSubdomainAccess(final Boolean subdomainAccess) {
this.subdomainAccess = subdomainAccess;
}
public void setZoneName(final String zoneName) {
this.zoneName = zoneName;
}
public void setCidr(final String cidr) {
this.cidr = cidr;
}
public void setNetworkCidr(final String networkCidr) {
this.networkCidr = networkCidr;
}
public void setReservedIpRange(final String reservedIpRange) {
this.reservedIpRange = reservedIpRange;
}
public void setRestartRequired(final Boolean restartRequired) {
this.restartRequired = restartRequired;
}
public void setSpecifyIpRanges(final Boolean specifyIpRanges) {
this.specifyIpRanges = specifyIpRanges;
}
public void setVpcId(final String vpcId) {
this.vpcId = vpcId;
}
public void setVpcName(final String vpcName) {
this.vpcName = vpcName;
}
public void setCanUseForDeploy(final Boolean canUseForDeploy) {
this.canUseForDeploy = canUseForDeploy;
}
public void setIsPersistent(final Boolean isPersistent) {
this.isPersistent = isPersistent;
}
public void setTags(final List<ResourceTagResponse> tags) {
this.tags = tags;
}
public void setIp6Gateway(final String ip6Gateway) {
this.ip6Gateway = ip6Gateway;
}
public void setIp6Cidr(final String ip6Cidr) {
this.ip6Cidr = ip6Cidr;
}
public String getAclId() {
return aclId;
}
public void setAclId(final String aclId) {
this.aclId = aclId;
}
public void setStrechedL2Subnet(final Boolean strechedL2Subnet) {
this.strechedL2Subnet = strechedL2Subnet;
}
public void setNetworkSpannedZones(final Set<String> networkSpannedZones) {
this.networkSpannedZones = networkSpannedZones;
}
public void setAclName(final String aclName) {
this.aclName = aclName;
}
public void setDhcpTftpServer(final String dhcpTftpServer) {
this.dhcpTftpServer = dhcpTftpServer;
}
public void setDhcpBootfileName(final String dhcpBootfileName) {
this.dhcpBootfileName = dhcpBootfileName;
}
}
| |
/*=========================================================================
* Copyright (c) 2010-2014 Pivotal Software, Inc. All Rights Reserved.
* This product is protected by U.S. and international copyright
* and intellectual property laws. Pivotal products are covered by
* one or more patents listed at http://www.pivotal.io/patents.
*=========================================================================
*/
package com.gemstone.gemfire.internal.cache;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
import java.util.UUID;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import com.gemstone.gemfire.internal.cache.lru.EnableLRU;
import com.gemstone.gemfire.internal.cache.persistence.DiskRecoveryStore;
import com.gemstone.gemfire.internal.cache.lru.LRUClockNode;
import com.gemstone.gemfire.internal.cache.lru.NewLRUClockHand;
import com.gemstone.gemfire.internal.offheap.OffHeapRegionEntryHelper;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.offheap.annotations.Retained;
import com.gemstone.gemfire.internal.offheap.annotations.Unretained;
import com.gemstone.gemfire.internal.util.concurrent.CustomEntryConcurrentHashMap.HashEntry;
// macros whose definition changes this class:
// disk: DISK
// lru: LRU
// stats: STATS
// versioned: VERSIONED
// offheap: OFFHEAP
// One of the following key macros must be defined:
// key object: KEY_OBJECT
// key int: KEY_INT
// key long: KEY_LONG
// key uuid: KEY_UUID
// key string1: KEY_STRING1
// key string2: KEY_STRING2
/**
* Do not modify this class. It was generated.
* Instead modify LeafRegionEntry.cpp and then run
* bin/generateRegionEntryClasses.sh from the directory
* that contains your build.xml.
*/
public class VMThinDiskLRURegionEntryOffHeapUUIDKey extends VMThinDiskLRURegionEntryOffHeap {
public VMThinDiskLRURegionEntryOffHeapUUIDKey (RegionEntryContext context, UUID key,
@Retained
Object value
) {
super(context,
(value instanceof RecoveredEntry ? null : value)
);
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
initialize(context, value);
this.keyMostSigBits = key.getMostSignificantBits();
this.keyLeastSigBits = key.getLeastSignificantBits();
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// common code
protected int hash;
private HashEntry<Object, Object> next;
@SuppressWarnings("unused")
private volatile long lastModified;
private static final AtomicLongFieldUpdater<VMThinDiskLRURegionEntryOffHeapUUIDKey> lastModifiedUpdater
= AtomicLongFieldUpdater.newUpdater(VMThinDiskLRURegionEntryOffHeapUUIDKey.class, "lastModified");
/**
* All access done using ohAddrUpdater so it is used even though the compiler can not tell it is.
*/
@SuppressWarnings("unused")
@Retained @Released private volatile long ohAddress;
/**
* I needed to add this because I wanted clear to call setValue which normally can only be called while the re is synced.
* But if I sync in that code it causes a lock ordering deadlock with the disk regions because they also get a rw lock in clear.
* Some hardware platforms do not support CAS on a long. If gemfire is run on one of those the AtomicLongFieldUpdater does a sync
* on the re and we will once again be deadlocked.
* I don't know if we support any of the hardware platforms that do not have a 64bit CAS. If we do then we can expect deadlocks
* on disk regions.
*/
private final static AtomicLongFieldUpdater<VMThinDiskLRURegionEntryOffHeapUUIDKey> ohAddrUpdater = AtomicLongFieldUpdater.newUpdater(VMThinDiskLRURegionEntryOffHeapUUIDKey.class, "ohAddress");
@Override
public Token getValueAsToken() {
return OffHeapRegionEntryHelper.getValueAsToken(this);
}
@Override
protected Object getValueField() {
return OffHeapRegionEntryHelper._getValue(this);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
@Override
@Unretained
protected void setValueField(@Unretained Object v) {
OffHeapRegionEntryHelper.setValue(this, v);
}
@Override
@Retained
public Object _getValueRetain(RegionEntryContext context, boolean decompress) {
return OffHeapRegionEntryHelper._getValueRetain(this, decompress, context);
}
@Override
public long getAddress() {
return ohAddrUpdater.get(this);
}
@Override
public boolean setAddress(long expectedAddr, long newAddr) {
return ohAddrUpdater.compareAndSet(this, expectedAddr, newAddr);
}
@Override
@Released
public void release() {
OffHeapRegionEntryHelper.releaseEntry(this);
}
@Override
public void returnToPool() {
// Deadcoded for now; never was working
// if (this instanceof VMThinRegionEntryLongKey) {
// factory.returnToPool((VMThinRegionEntryLongKey)this);
// }
}
protected long getlastModifiedField() {
return lastModifiedUpdater.get(this);
}
protected boolean compareAndSetLastModifiedField(long expectedValue, long newValue) {
return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
}
/**
* @see HashEntry#getEntryHash()
*/
public final int getEntryHash() {
return this.hash;
}
protected void setEntryHash(int v) {
this.hash = v;
}
/**
* @see HashEntry#getNextEntry()
*/
public final HashEntry<Object, Object> getNextEntry() {
return this.next;
}
/**
* @see HashEntry#setNextEntry
*/
public final void setNextEntry(final HashEntry<Object, Object> n) {
this.next = n;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// disk code
protected void initialize(RegionEntryContext drs, Object value) {
boolean isBackup;
if (drs instanceof LocalRegion) {
isBackup = ((LocalRegion)drs).getDiskRegion().isBackup();
} else if (drs instanceof PlaceHolderDiskRegion) {
isBackup = true;
} else {
throw new IllegalArgumentException("expected a LocalRegion or PlaceHolderDiskRegion");
}
// Delay the initialization of DiskID if overflow only
if (isBackup) {
diskInitialize(drs, value);
}
}
@Override
public final synchronized int updateAsyncEntrySize(EnableLRU capacityController) {
int oldSize = getEntrySize();
int newSize = capacityController.entrySize( getKeyForSizing(), null);
setEntrySize(newSize);
int delta = newSize - oldSize;
return delta;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
private void diskInitialize(RegionEntryContext context, Object value) {
DiskRecoveryStore drs = (DiskRecoveryStore)context;
DiskStoreImpl ds = drs.getDiskStore();
long maxOplogSize = ds.getMaxOplogSize();
//get appropriate instance of DiskId implementation based on maxOplogSize
this.id = DiskId.createDiskId(maxOplogSize, true/* is persistence */, ds.needsLinkedList());
Helper.initialize(this, drs, value);
}
/**
* DiskId
*
* @since 5.1
*/
protected DiskId id;//= new DiskId();
public DiskId getDiskId() {
return this.id;
}
@Override
void setDiskId(RegionEntry old) {
this.id = ((AbstractDiskRegionEntry)old).getDiskId();
}
// // inlining DiskId
// // always have these fields
// /**
// * id consists of
// * most significant
// * 1 byte = users bits
// * 2-8 bytes = oplog id
// * least significant.
// *
// * The highest bit in the oplog id part is set to 1 if the oplog id
// * is negative.
// * @todo this field could be an int for an overflow only region
// */
// private long id;
// /**
// * Length of the bytes on disk.
// * This is always set. If the value is invalid then it will be set to 0.
// * The most significant bit is used by overflow to mark it as needing to be written.
// */
// protected int valueLength = 0;
// // have intOffset or longOffset
// // intOffset
// /**
// * The position in the oplog (the oplog offset) where this entry's value is
// * stored
// */
// private volatile int offsetInOplog;
// // longOffset
// /**
// * The position in the oplog (the oplog offset) where this entry's value is
// * stored
// */
// private volatile long offsetInOplog;
// // have overflowOnly or persistence
// // overflowOnly
// // no fields
// // persistent
// /** unique entry identifier * */
// private long keyId;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// lru code
@Override
public void setDelayedDiskId(LocalRegion r) {
DiskStoreImpl ds = r.getDiskStore();
long maxOplogSize = ds.getMaxOplogSize();
this.id = DiskId.createDiskId(maxOplogSize, false /* over flow only */, ds.needsLinkedList());
}
public final synchronized int updateEntrySize(EnableLRU capacityController) {
return updateEntrySize(capacityController, _getValue()); // OFHEAP: _getValue ok w/o incing refcount because we are synced and only getting the size
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
public final synchronized int updateEntrySize(EnableLRU capacityController,
Object value) {
int oldSize = getEntrySize();
int newSize = capacityController.entrySize( getKeyForSizing(), value);
setEntrySize(newSize);
int delta = newSize - oldSize;
// if ( debug ) log( "updateEntrySize key=" + getKey()
// + (_getValue() == Token.INVALID ? " invalid" :
// (_getValue() == Token.LOCAL_INVALID ? "local_invalid" :
// (_getValue()==null ? " evicted" : " valid")))
// + " oldSize=" + oldSize
// + " newSize=" + this.size );
return delta;
}
public final boolean testRecentlyUsed() {
return areAnyBitsSet(RECENTLY_USED);
}
@Override
public final void setRecentlyUsed() {
setBits(RECENTLY_USED);
}
public final void unsetRecentlyUsed() {
clearBits(~RECENTLY_USED);
}
public final boolean testEvicted() {
return areAnyBitsSet(EVICTED);
}
public final void setEvicted() {
setBits(EVICTED);
}
public final void unsetEvicted() {
clearBits(~EVICTED);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
private LRUClockNode nextLRU;
private LRUClockNode prevLRU;
private int size;
public final void setNextLRUNode( LRUClockNode next ) {
this.nextLRU = next;
}
public final LRUClockNode nextLRUNode() {
return this.nextLRU;
}
public final void setPrevLRUNode( LRUClockNode prev ) {
this.prevLRU = prev;
}
public final LRUClockNode prevLRUNode() {
return this.prevLRU;
}
public final int getEntrySize() {
return this.size;
}
protected final void setEntrySize(int size) {
this.size = size;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
//@Override
//public StringBuilder appendFieldsToString(final StringBuilder sb) {
// StringBuilder result = super.appendFieldsToString(sb);
// result.append("; prev=").append(this.prevLRU==null?"null":"not null");
// result.append("; next=").append(this.nextLRU==null?"null":"not null");
// return result;
//}
@Override
public Object getKeyForSizing() {
// inline keys always report null for sizing since the size comes from the entry size
return null;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// key code
private final long keyMostSigBits;
private final long keyLeastSigBits;
@Override
public final Object getKey() {
return new UUID(this.keyMostSigBits, this.keyLeastSigBits);
}
@Override
public boolean isKeyEqual(Object k) {
if (k instanceof UUID) {
UUID uuid = (UUID)k;
return uuid.getLeastSignificantBits() == this.keyLeastSigBits && uuid.getMostSignificantBits() == this.keyMostSigBits;
}
return false;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.editor.colors.impl;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.*;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.testFramework.LightPlatformCodeInsightTestCase;
import org.jdom.Element;
import org.jdom.input.DOMBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jetbrains.annotations.NotNull;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections;
import static com.intellij.openapi.editor.colors.FontPreferencesTest.*;
import static java.util.Collections.singletonList;
public class EditorColorsSchemeImplTest extends LightPlatformCodeInsightTestCase {
EditorColorsSchemeImpl myScheme = new EditorColorsSchemeImpl(null);
public void testDefaults() {
checkState(myScheme.getFontPreferences(),
Collections.<String>emptyList(),
Collections.<String>emptyList(),
FontPreferences.DEFAULT_FONT_NAME,
FontPreferences.DEFAULT_FONT_NAME, null);
assertEquals(FontPreferences.DEFAULT_FONT_NAME, myScheme.getEditorFontName());
assertEquals(FontPreferences.DEFAULT_FONT_SIZE, myScheme.getEditorFontSize());
checkState(myScheme.getConsoleFontPreferences(),
Collections.<String>emptyList(),
Collections.<String>emptyList(),
FontPreferences.DEFAULT_FONT_NAME,
FontPreferences.DEFAULT_FONT_NAME, null);
assertEquals(FontPreferences.DEFAULT_FONT_NAME, myScheme.getConsoleFontName());
assertEquals(FontPreferences.DEFAULT_FONT_SIZE, myScheme.getConsoleFontSize());
}
public void testSetPreferences() throws Exception {
String fontName1 = getExistingNonDefaultFontName();
String fontName2 = getAnotherExistingNonDefaultFontName();
myScheme.getFontPreferences().register(fontName1, 25);
myScheme.getFontPreferences().register(fontName2, 13);
myScheme.getConsoleFontPreferences().register(fontName1, 21);
myScheme.getConsoleFontPreferences().register(fontName2, 15);
checkState(myScheme.getFontPreferences(),
Arrays.asList(fontName1, fontName2),
Arrays.asList(fontName1, fontName2),
fontName1,
fontName1, 25,
fontName2, 13);
assertEquals(fontName1, myScheme.getEditorFontName());
assertEquals(25, myScheme.getEditorFontSize());
checkState(myScheme.getConsoleFontPreferences(),
Arrays.asList(fontName1, fontName2),
Arrays.asList(fontName1, fontName2),
fontName1,
fontName1, 21,
fontName2, 15);
assertEquals(fontName1, myScheme.getConsoleFontName());
assertEquals(21, myScheme.getConsoleFontSize());
}
public void testSetName() throws Exception {
String fontName1 = getExistingNonDefaultFontName();
String fontName2 = getAnotherExistingNonDefaultFontName();
myScheme.setEditorFontName(fontName1);
myScheme.setConsoleFontName(fontName2);
checkState(myScheme.getFontPreferences(),
singletonList(fontName1),
singletonList(fontName1),
fontName1,
fontName1, FontPreferences.DEFAULT_FONT_SIZE);
assertEquals(fontName1, myScheme.getEditorFontName());
assertEquals(FontPreferences.DEFAULT_FONT_SIZE, myScheme.getEditorFontSize());
checkState(myScheme.getConsoleFontPreferences(),
singletonList(fontName2),
singletonList(fontName2),
fontName2,
fontName2, FontPreferences.DEFAULT_FONT_SIZE);
assertEquals(fontName2, myScheme.getConsoleFontName());
assertEquals(FontPreferences.DEFAULT_FONT_SIZE, myScheme.getConsoleFontSize());
}
public void testSetSize() throws Exception {
myScheme.setEditorFontSize(25);
myScheme.setConsoleFontSize(21);
checkState(myScheme.getFontPreferences(),
singletonList(FontPreferences.DEFAULT_FONT_NAME),
singletonList(FontPreferences.DEFAULT_FONT_NAME),
FontPreferences.DEFAULT_FONT_NAME,
FontPreferences.DEFAULT_FONT_NAME, 25);
assertEquals(FontPreferences.DEFAULT_FONT_NAME, myScheme.getEditorFontName());
assertEquals(25, myScheme.getEditorFontSize());
checkState(myScheme.getConsoleFontPreferences(),
singletonList(FontPreferences.DEFAULT_FONT_NAME),
singletonList(FontPreferences.DEFAULT_FONT_NAME),
FontPreferences.DEFAULT_FONT_NAME,
FontPreferences.DEFAULT_FONT_NAME, 21);
assertEquals(FontPreferences.DEFAULT_FONT_NAME, myScheme.getConsoleFontName());
assertEquals(21, myScheme.getConsoleFontSize());
}
public void testSetNameAndSize() throws Exception {
String fontName1 = getExistingNonDefaultFontName();
String fontName2 = getAnotherExistingNonDefaultFontName();
myScheme.setEditorFontName(fontName1);
myScheme.setEditorFontSize(25);
myScheme.setConsoleFontName(fontName2);
myScheme.setConsoleFontSize(21);
checkState(myScheme.getFontPreferences(),
singletonList(fontName1),
singletonList(fontName1),
fontName1,
fontName1, 25);
assertEquals(fontName1, myScheme.getEditorFontName());
assertEquals(25, myScheme.getEditorFontSize());
checkState(myScheme.getConsoleFontPreferences(),
singletonList(fontName2),
singletonList(fontName2),
fontName2,
fontName2, 21);
assertEquals(fontName2, myScheme.getConsoleFontName());
assertEquals(21, myScheme.getConsoleFontSize());
}
public void testSetSizeAndName() throws Exception {
String fontName1 = getExistingNonDefaultFontName();
String fontName2 = getAnotherExistingNonDefaultFontName();
myScheme.setEditorFontSize(25);
myScheme.setEditorFontName(fontName1);
myScheme.setConsoleFontSize(21);
myScheme.setConsoleFontName(fontName2);
checkState(myScheme.getFontPreferences(),
singletonList(fontName1),
singletonList(fontName1),
fontName1,
fontName1, 25);
assertEquals(fontName1, myScheme.getEditorFontName());
assertEquals(25, myScheme.getEditorFontSize());
checkState(myScheme.getConsoleFontPreferences(),
singletonList(fontName2),
singletonList(fontName2),
fontName2,
fontName2, 21);
assertEquals(fontName2, myScheme.getConsoleFontName());
assertEquals(21, myScheme.getConsoleFontSize());
}
public void testWriteInheritedFromDefault() throws Exception {
EditorColorsScheme defaultScheme = EditorColorsManager.getInstance().getScheme(EditorColorsScheme.DEFAULT_SCHEME_NAME);
EditorColorsScheme editorColorsScheme = (EditorColorsScheme)defaultScheme.clone();
editorColorsScheme.setName("test");
Element root = new Element("scheme");
((AbstractColorsScheme)editorColorsScheme).writeExternal(root);
root.removeChildren("option"); // Remove font options
assertXmlOutputEquals("<scheme name=\"test\" version=\"142\" parent_scheme=\"Default\" />", root);
}
public void testWriteInheritedFromDarcula() throws Exception {
EditorColorsScheme darculaScheme = EditorColorsManager.getInstance().getScheme("Darcula");
EditorColorsScheme editorColorsScheme = (EditorColorsScheme)darculaScheme.clone();
editorColorsScheme.setName("test");
Element root = new Element("scheme");
((AbstractColorsScheme)editorColorsScheme).writeExternal(root);
root.removeChildren("option"); // Remove font options
assertXmlOutputEquals("<scheme name=\"test\" version=\"142\" parent_scheme=\"Darcula\" />", root);
}
public void testSaveInheritance() throws Exception {
Pair<EditorColorsScheme,TextAttributes> result = doTestWriteRead(DefaultLanguageHighlighterColors.STATIC_METHOD, new TextAttributes());
TextAttributes fallbackAttrs = result.first.getAttributes(DefaultLanguageHighlighterColors.STATIC_METHOD.getFallbackAttributeKey());
assertSame(result.second, fallbackAttrs);
}
public void testSaveNoInheritanceAndDefaults() throws Exception {
TextAttributes identifierAttrs = EditorColorsManager.getInstance().getScheme(EditorColorsScheme.DEFAULT_SCHEME_NAME)
.getAttributes(DefaultLanguageHighlighterColors.IDENTIFIER);
TextAttributes declarationAttrs = identifierAttrs.clone();
Pair<EditorColorsScheme, TextAttributes> result =
doTestWriteRead(DefaultLanguageHighlighterColors.FUNCTION_DECLARATION, declarationAttrs);
TextAttributes fallbackAttrs = result.first.getAttributes(
DefaultLanguageHighlighterColors.FUNCTION_DECLARATION.getFallbackAttributeKey()
);
assertEquals(result.second, fallbackAttrs);
assertNotSame(result.second, fallbackAttrs);
}
public void testSaveInheritanceForEmptyAttrs() throws Exception {
TextAttributes abstractMethodAttrs = new TextAttributes();
assertTrue(abstractMethodAttrs.isFallbackEnabled());
Pair<EditorColorsScheme, TextAttributes> result =
doTestWriteRead(CodeInsightColors.ABSTRACT_METHOD_ATTRIBUTES, abstractMethodAttrs);
TextAttributes fallbackAttrs = result.first.getAttributes(
CodeInsightColors.ABSTRACT_METHOD_ATTRIBUTES.getFallbackAttributeKey()
);
TextAttributes directlyDefined =
((AbstractColorsScheme)result.first).getDirectlyDefinedAttributes(CodeInsightColors.ABSTRACT_METHOD_ATTRIBUTES);
assertTrue(directlyDefined != null && directlyDefined.isFallbackEnabled());
assertSame(fallbackAttrs, result.second);
}
/**
* Check that the attributes missing in a custom scheme with a version prior to 142 are explicitly added with fallback enabled,
* not taken from parent scheme.
*
* @throws Exception
*/
public void testUpgradeFromVer141() throws Exception {
TextAttributesKey constKey = DefaultLanguageHighlighterColors.CONSTANT;
TextAttributesKey fallbackKey = constKey.getFallbackAttributeKey();
assertNotNull(fallbackKey);
EditorColorsScheme scheme = loadScheme(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<scheme name=\"Test\" version=\"141\" parent_scheme=\"Default\">\n" +
// Some 'attributes' section is required for the upgrade procedure to work.
"<attributes>" +
" <option name=\"TEXT\">\n" +
" <value>\n" +
" option name=\"FOREGROUND\" value=\"ffaaaa\" />\n" +
" </value>\n" +
" </option>" +
"</attributes>" +
"</scheme>\n"
);
TextAttributes constAttrs = scheme.getAttributes(constKey);
TextAttributes fallbackAttrs = scheme.getAttributes(fallbackKey);
assertSame(fallbackAttrs, constAttrs);
}
private static EditorColorsScheme loadScheme(@NotNull String docText) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(docText));
org.w3c.dom.Document doc = docBuilder.parse(inputSource);
Element root = new DOMBuilder().build(doc.getDocumentElement());
EditorColorsScheme defaultScheme = EditorColorsManager.getInstance().getScheme(EditorColorsScheme.DEFAULT_SCHEME_NAME);
EditorColorsScheme targetScheme = new EditorColorsSchemeImpl(defaultScheme);
targetScheme.readExternal(root);
return targetScheme;
}
@NotNull
public Pair<EditorColorsScheme,TextAttributes> doTestWriteRead(TextAttributesKey key, TextAttributes attributes)
throws WriteExternalException {
EditorColorsScheme defaultScheme = EditorColorsManager.getInstance().getScheme(EditorColorsScheme.DEFAULT_SCHEME_NAME);
EditorColorsScheme sourceScheme = (EditorColorsScheme)defaultScheme.clone();
sourceScheme.setName("test");
sourceScheme.setAttributes(key, attributes);
Element root = new Element("scheme");
((AbstractColorsScheme)sourceScheme).writeExternal(root);
EditorColorsScheme targetScheme = new EditorColorsSchemeImpl(defaultScheme);
targetScheme.readExternal(root);
assertEquals("test", targetScheme.getName());
TextAttributes targetAttrs = targetScheme.getAttributes(key);
return Pair.create(targetScheme,targetAttrs);
}
private static void assertXmlOutputEquals(String expected, Element root) throws IOException {
StringWriter writer = new StringWriter();
Format format = Format.getPrettyFormat();
format.setLineSeparator("\n");
new XMLOutputter(format).output(root, writer);
String actual = writer.toString();
assertEquals(expected, actual);
}
}
| |
package storm.trident.topology;
import backtype.storm.Config;
import backtype.storm.Constants;
import backtype.storm.coordination.BatchOutputCollector;
import backtype.storm.coordination.BatchOutputCollectorImpl;
import backtype.storm.generated.GlobalStreamId;
import backtype.storm.generated.Grouping;
import backtype.storm.task.IOutputCollector;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.FailedException;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.ReportedFailedException;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import backtype.storm.utils.RotatingMap;
import backtype.storm.utils.Utils;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.builder.ToStringBuilder;
import storm.trident.spout.IBatchID;
public class TridentBoltExecutor implements IRichBolt {
public static String COORD_STREAM_PREFIX = "$coord-";
public static String COORD_STREAM(String batch) {
return COORD_STREAM_PREFIX + batch;
}
public static class CoordType implements Serializable {
public boolean singleCount;
protected CoordType(boolean singleCount) {
this.singleCount = singleCount;
}
public static CoordType single() {
return new CoordType(true);
}
public static CoordType all() {
return new CoordType(false);
}
@Override
public boolean equals(Object o) {
return singleCount == ((CoordType) o).singleCount;
}
@Override
public String toString() {
return "<Single: " + singleCount + ">";
}
}
public static class CoordSpec implements Serializable {
public GlobalStreamId commitStream = null;
public Map<String, CoordType> coords = new HashMap<String, CoordType>();
public CoordSpec() {
}
}
public static class CoordCondition implements Serializable {
public GlobalStreamId commitStream;
public int expectedTaskReports;
Set<Integer> targetTasks;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
Map<GlobalStreamId, String> _batchGroupIds;
Map<String, CoordSpec> _coordSpecs;
Map<String, CoordCondition> _coordConditions;
ITridentBatchBolt _bolt;
long _messageTimeoutMs;
long _lastRotate;
RotatingMap _batches;
// map from batchgroupid to coordspec
public TridentBoltExecutor(ITridentBatchBolt bolt, Map<GlobalStreamId, String> batchGroupIds, Map<String, CoordSpec> coordinationSpecs) {
_batchGroupIds = batchGroupIds;
_coordSpecs = coordinationSpecs;
_bolt = bolt;
}
public static class TrackedBatch {
int attemptId;
BatchInfo info;
CoordCondition condition;
int reportedTasks = 0;
int expectedTupleCount = 0;
int receivedTuples = 0;
Map<Integer, Integer> taskEmittedTuples = new HashMap();
boolean failed = false;
boolean receivedCommit;
Tuple delayedAck = null;
public TrackedBatch(BatchInfo info, CoordCondition condition, int attemptId) {
this.info = info;
this.condition = condition;
this.attemptId = attemptId;
receivedCommit = condition.commitStream == null;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
public class CoordinatedOutputCollector implements IOutputCollector {
IOutputCollector _delegate;
TrackedBatch _currBatch = null;;
public void setCurrBatch(TrackedBatch batch) {
_currBatch = batch;
}
public CoordinatedOutputCollector(IOutputCollector delegate) {
_delegate = delegate;
}
public List<Integer> emit(String stream, Collection<Tuple> anchors, List<Object> tuple) {
List<Integer> tasks = _delegate.emit(stream, anchors, tuple);
updateTaskCounts(tasks);
return tasks;
}
public void emitDirect(int task, String stream, Collection<Tuple> anchors, List<Object> tuple) {
updateTaskCounts(Arrays.asList(task));
_delegate.emitDirect(task, stream, anchors, tuple);
}
public void ack(Tuple tuple) {
throw new IllegalStateException("Method should never be called");
}
public void fail(Tuple tuple) {
throw new IllegalStateException("Method should never be called");
}
public void reportError(Throwable error) {
_delegate.reportError(error);
}
private void updateTaskCounts(List<Integer> tasks) {
if(_currBatch!=null) {
Map<Integer, Integer> taskEmittedTuples = _currBatch.taskEmittedTuples;
for(Integer task: tasks) {
int newCount = Utils.get(taskEmittedTuples, task, 0) + 1;
taskEmittedTuples.put(task, newCount);
}
}
}
}
OutputCollector _collector;
CoordinatedOutputCollector _coordCollector;
BatchOutputCollector _coordOutputCollector;
TopologyContext _context;
@Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
_messageTimeoutMs = context.maxTopologyMessageTimeout() * 1000L;
_lastRotate = System.currentTimeMillis();
_batches = new RotatingMap(2);
_context = context;
_collector = collector;
_coordCollector = new CoordinatedOutputCollector(collector);
_coordOutputCollector = new BatchOutputCollectorImpl(new OutputCollector(_coordCollector));
_coordConditions = (Map) context.getExecutorData("__coordConditions");
if(_coordConditions==null) {
_coordConditions = new HashMap();
for(String batchGroup: _coordSpecs.keySet()) {
CoordSpec spec = _coordSpecs.get(batchGroup);
CoordCondition cond = new CoordCondition();
cond.commitStream = spec.commitStream;
cond.expectedTaskReports = 0;
for(String comp: spec.coords.keySet()) {
CoordType ct = spec.coords.get(comp);
if(ct.equals(CoordType.single())) {
cond.expectedTaskReports+=1;
} else {
cond.expectedTaskReports+=context.getComponentTasks(comp).size();
}
}
cond.targetTasks = new HashSet<Integer>();
for(String component: Utils.get(context.getThisTargets(),
COORD_STREAM(batchGroup),
new HashMap<String, Grouping>()).keySet()) {
cond.targetTasks.addAll(context.getComponentTasks(component));
}
_coordConditions.put(batchGroup, cond);
}
context.setExecutorData("_coordConditions", _coordConditions);
}
_bolt.prepare(conf, context, _coordOutputCollector);
}
private void failBatch(TrackedBatch tracked, FailedException e) {
if(e!=null && e instanceof ReportedFailedException) {
_collector.reportError(e);
}
tracked.failed = true;
if(tracked.delayedAck!=null) {
_collector.fail(tracked.delayedAck);
tracked.delayedAck = null;
}
}
private void failBatch(TrackedBatch tracked) {
failBatch(tracked, null);
}
private boolean finishBatch(TrackedBatch tracked, Tuple finishTuple) {
boolean success = true;
try {
_bolt.finishBatch(tracked.info);
String stream = COORD_STREAM(tracked.info.batchGroup);
for(Integer task: tracked.condition.targetTasks) {
_collector.emitDirect(task, stream, finishTuple, new Values(tracked.info.batchId, Utils.get(tracked.taskEmittedTuples, task, 0)));
}
if(tracked.delayedAck!=null) {
_collector.ack(tracked.delayedAck);
tracked.delayedAck = null;
}
} catch(FailedException e) {
failBatch(tracked, e);
success = false;
}
_batches.remove(tracked.info.batchId.getId());
return success;
}
private void checkFinish(TrackedBatch tracked, Tuple tuple, TupleType type) {
if(tracked.failed) {
failBatch(tracked);
_collector.fail(tuple);
return;
}
CoordCondition cond = tracked.condition;
boolean delayed = tracked.delayedAck==null &&
(cond.commitStream!=null && type==TupleType.COMMIT
|| cond.commitStream==null);
if(delayed) {
tracked.delayedAck = tuple;
}
boolean failed = false;
if(tracked.receivedCommit && tracked.reportedTasks == cond.expectedTaskReports) {
if(tracked.receivedTuples == tracked.expectedTupleCount) {
finishBatch(tracked, tuple);
} else {
//TODO: add logging that not all tuples were received
failBatch(tracked);
_collector.fail(tuple);
failed = true;
}
}
if(!delayed && !failed) {
_collector.ack(tuple);
}
}
@Override
public void execute(Tuple tuple) {
if(tuple.getSourceStreamId().equals(Constants.SYSTEM_TICK_STREAM_ID)) {
long now = System.currentTimeMillis();
if(now - _lastRotate > _messageTimeoutMs) {
_batches.rotate();
_lastRotate = now;
}
return;
}
String batchGroup = _batchGroupIds.get(tuple.getSourceGlobalStreamid());
if(batchGroup==null) {
// this is so we can do things like have simple DRPC that doesn't need to use batch processing
_coordCollector.setCurrBatch(null);
_bolt.execute(null, tuple);
_collector.ack(tuple);
return;
}
IBatchID id = (IBatchID) tuple.getValue(0);
//get transaction id
//if it already exissts and attempt id is greater than the attempt there
TrackedBatch tracked = (TrackedBatch) _batches.get(id.getId());
// if(_batches.size() > 10 && _context.getThisTaskIndex() == 0) {
// System.out.println("Received in " + _context.getThisComponentId() + " " + _context.getThisTaskIndex()
// + " (" + _batches.size() + ")" +
// "\ntuple: " + tuple +
// "\nwith tracked " + tracked +
// "\nwith id " + id +
// "\nwith group " + batchGroup
// + "\n");
//
// }
//System.out.println("Num tracked: " + _batches.size() + " " + _context.getThisComponentId() + " " + _context.getThisTaskIndex());
// this code here ensures that only one attempt is ever tracked for a batch, so when
// failures happen you don't get an explosion in memory usage in the tasks
if(tracked!=null) {
if(id.getAttemptId() > tracked.attemptId) {
_batches.remove(id.getId());
tracked = null;
} else if(id.getAttemptId() < tracked.attemptId) {
// no reason to try to execute a previous attempt than we've already seen
return;
}
}
if(tracked==null) {
tracked = new TrackedBatch(new BatchInfo(batchGroup, id, _bolt.initBatchState(batchGroup, id)), _coordConditions.get(batchGroup), id.getAttemptId());
_batches.put(id.getId(), tracked);
}
_coordCollector.setCurrBatch(tracked);
//System.out.println("TRACKED: " + tracked + " " + tuple);
TupleType t = getTupleType(tuple, tracked);
if(t==TupleType.COMMIT) {
tracked.receivedCommit = true;
checkFinish(tracked, tuple, t);
} else if(t==TupleType.COORD) {
int count = tuple.getInteger(1);
tracked.reportedTasks++;
tracked.expectedTupleCount+=count;
checkFinish(tracked, tuple, t);
} else {
tracked.receivedTuples++;
boolean success = true;
try {
_bolt.execute(tracked.info, tuple);
if(tracked.condition.expectedTaskReports==0) {
success = finishBatch(tracked, tuple);
}
} catch(FailedException e) {
failBatch(tracked, e);
}
if(success) {
_collector.ack(tuple);
} else {
_collector.fail(tuple);
}
}
_coordCollector.setCurrBatch(null);
}
@Override
public void cleanup() {
_bolt.cleanup();
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
_bolt.declareOutputFields(declarer);
for(String batchGroup: _coordSpecs.keySet()) {
declarer.declareStream(COORD_STREAM(batchGroup), true, new Fields("id", "count"));
}
}
@Override
public Map<String, Object> getComponentConfiguration() {
Map<String, Object> ret = _bolt.getComponentConfiguration();
if(ret==null) ret = new HashMap();
ret.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, 5);
// TODO: Need to be able to set the tick tuple time to the message timeout, ideally without parameterization
return ret;
}
private TupleType getTupleType(Tuple tuple, TrackedBatch batch) {
CoordCondition cond = batch.condition;
if(cond.commitStream!=null
&& tuple.getSourceGlobalStreamid().equals(cond.commitStream)) {
return TupleType.COMMIT;
} else if(cond.expectedTaskReports > 0
&& tuple.getSourceStreamId().startsWith(COORD_STREAM_PREFIX)) {
return TupleType.COORD;
} else {
return TupleType.REGULAR;
}
}
static enum TupleType {
REGULAR,
COMMIT,
COORD
}
}
| |
///******************************************************************************
//
//Copyright (c) 2010, Cormac Flanagan (University of California, Santa Cruz)
// and Stephen Freund (Williams College)
//
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are
//met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the names of the University of California, Santa Cruz
// and Williams College nor the names of its contributors may be
// used to endorse or promote products derived from this software
// without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
//A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
//HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
//THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//******************************************************************************/
//
//// based on ASM code
//
///***
// * ASM: a very small and fast Java bytecode manipulation framework
// * Copyright (c) 2000-2005 INRIA, France Telecom
// * All rights reserved.
// *
// * Redistribution and use in source and binary forms, with or without
// * modification, are permitted provided that the following conditions
// * are met:
// * 1. Redistributions of source code must retain the above copyright
// * notice, this list of conditions and the following disclaimer.
// * 2. Redistributions in binary form must reproduce the above copyright
// * notice, this list of conditions and the following disclaimer in the
// * documentation and/or other materials provided with the distribution.
// * 3. Neither the name of the copyright holders nor the names of its
// * contributors may be used to endorse or promote products derived from
// * this software without specific prior written permission.
// *
// * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// * THE POSSIBILITY OF SUCH DAMAGE.
// */
//package rr.instrument.tools;
//
//import java.util.HashMap;
//
//import rr.org.objectweb.asm.AnnotationVisitor;
//import rr.org.objectweb.asm.Attribute;
//import rr.org.objectweb.asm.Label;
//import rr.org.objectweb.asm.MethodVisitor;
//import rr.org.objectweb.asm.Opcodes;
//import rr.org.objectweb.asm.Type;
//import rr.org.objectweb.asm.signature.SignatureReader;
//import rr.org.objectweb.asm.util.AbstractVisitor;
//import rr.org.objectweb.asm.util.TraceAbstractVisitor;
//import rr.org.objectweb.asm.util.TraceAnnotationVisitor;
//import rr.org.objectweb.asm.util.TraceSignatureVisitor;
//import rr.org.objectweb.asm.util.Traceable;
//
//import acme.util.Util;
//
///**
// * A {@link MethodVisitor} that prints a disassembled view of the methods it
// * visits.
// *
// * @author Eric Bruneton
// */
//public class DumpingMethodVisitor extends TraceAbstractVisitor implements
// MethodVisitor
//{
//
// /**
// * The {@link MethodVisitor} to which this visitor delegates calls. May be
// * <tt>null</tt>.
// */
// protected MethodVisitor mv;
//
// /**
// * Tab for bytecode instructions.
// */
// protected String tab2 = " ";
//
// /**
// * Tab for table and lookup switch instructions.
// */
// protected String tab3 = " ";
//
// /**
// * Tab for labels.
// */
// protected String ltab = " ";
//
// /**
// * The label names. This map associate String values to Label keys.
// */
// protected final HashMap labelNames;
//
// /**
// * Constructs a new {@link DumpingMethodVisitor}.
// */
// public DumpingMethodVisitor() {
// this(null);
// }
//
// /**
// * Constructs a new {@link DumpingMethodVisitor}.
// *
// * @param mv the {@link MethodVisitor} to which this visitor delegates
// * calls. May be <tt>null</tt>.
// */
// public DumpingMethodVisitor(final MethodVisitor mv) {
// this.labelNames = new HashMap();
// this.mv = mv;
// }
//
// // ------------------------------------------------------------------------
// // Implementation of the MethodVisitor interface
// // ------------------------------------------------------------------------
//
// @Override
// public AnnotationVisitor visitAnnotation(
// final String desc,
// final boolean visible)
// {
// AnnotationVisitor av = super.visitAnnotation(desc, visible);
// if (mv != null) {
// ((TraceAnnotationVisitor) av).av = mv.visitAnnotation(desc, visible);
// }
// return av;
// }
//
// @Override
// public void visitAttribute(final Attribute attr) {
// buf.setLength(0);
// buf.append(tab).append("ATTRIBUTE ");
// appendDescriptor(-1, attr.type);
//
// if (attr instanceof Traceable) {
// ((Traceable) attr).trace(buf, labelNames);
// } else {
// buf.append(" : unknown\n");
// }
//
// dump();
// if (mv != null) {
// mv.visitAttribute(attr);
// }
// }
//
// public AnnotationVisitor visitAnnotationDefault() {
// text.add(tab2 + "default=");
// TraceAnnotationVisitor tav = createTraceAnnotationVisitor();
// text.add(tav.getText());
// text.add("\n");
// if (mv != null) {
// tav.av = mv.visitAnnotationDefault();
// }
// return tav;
// }
//
// public AnnotationVisitor visitParameterAnnotation(
// final int parameter,
// final String desc,
// final boolean visible)
// {
// buf.setLength(0);
// buf.append(tab2).append('@');
// appendDescriptor(FIELD_DESCRIPTOR, desc);
// buf.append('(');
// dump();
// TraceAnnotationVisitor tav = createTraceAnnotationVisitor();
// text.add(tav.getText());
// text.add(visible ? ") // parameter " : ") // invisible, parameter ");
// text.add(new Integer(parameter));
// text.add("\n");
// if (mv != null) {
// tav.av = mv.visitParameterAnnotation(parameter, desc, visible);
// }
// return tav;
// }
//
// public void visitCode() {
// if (mv != null) {
// mv.visitCode();
// }
// }
//
// public void visitFrame(
// final int type,
// final int nLocal,
// final Object[] local,
// final int nStack,
// final Object[] stack)
// {
// buf.setLength(0);
// buf.append(ltab);
// buf.append("FRAME ");
// switch (type) {
// case Opcodes.F_NEW:
// case Opcodes.F_FULL:
// buf.append("FULL [");
// appendFrameTypes(nLocal, local);
// buf.append("] [");
// appendFrameTypes(nStack, stack);
// buf.append("]");
// break;
// case Opcodes.F_APPEND:
// buf.append("APPEND [");
// appendFrameTypes(nLocal, local);
// buf.append("]");
// break;
// case Opcodes.F_CHOP:
// buf.append("CHOP ").append(nLocal);
// break;
// case Opcodes.F_SAME:
// buf.append("SAME");
// break;
// case Opcodes.F_SAME1:
// buf.append("SAME1 ");
// appendFrameTypes(1, stack);
// break;
// }
// buf.append("\n");
// dump();
//
// if (mv != null) {
// mv.visitFrame(type, nLocal, local, nStack, stack);
// }
// }
//
// public void visitInsn(final int opcode) {
// buf.setLength(0);
// buf.append(tab2).append(OPCODES[opcode]).append('\n');
// dump();
//
// if (mv != null) {
// mv.visitInsn(opcode);
// }
// }
//
// public void visitIntInsn(final int opcode, final int operand) {
// buf.setLength(0);
// buf.append(tab2)
// .append(OPCODES[opcode])
// .append(' ')
// .append(opcode == Opcodes.NEWARRAY
// ? TYPES[operand]
// : Integer.toString(operand))
// .append('\n');
// dump();
//
// if (mv != null) {
// mv.visitIntInsn(opcode, operand);
// }
// }
//
// public void visitVarInsn(final int opcode, final int var) {
// buf.setLength(0);
// buf.append(tab2)
// .append(OPCODES[opcode])
// .append(' ')
// .append(var)
// .append('\n');
// dump();
//
// if (mv != null) {
// mv.visitVarInsn(opcode, var);
// }
// }
//
// public void visitTypeInsn(final int opcode, final String desc) {
// buf.setLength(0);
// buf.append(tab2).append(OPCODES[opcode]).append(' ');
// if (desc.startsWith("[")) {
// appendDescriptor(FIELD_DESCRIPTOR, desc);
// } else {
// appendDescriptor(INTERNAL_NAME, desc);
// }
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitTypeInsn(opcode, desc);
// }
// }
//
// public void visitFieldInsn(
// final int opcode,
// final String owner,
// final String name,
// final String desc)
// {
// buf.setLength(0);
// buf.append(tab2).append(OPCODES[opcode]).append(' ');
// appendDescriptor(INTERNAL_NAME, owner);
// buf.append('.').append(name).append(" : ");
// appendDescriptor(FIELD_DESCRIPTOR, desc);
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitFieldInsn(opcode, owner, name, desc);
// }
// }
//
// public void visitMethodInsn(
// final int opcode,
// final String owner,
// final String name,
// final String desc)
// {
// buf.setLength(0);
// buf.append(tab2).append(OPCODES[opcode]).append(' ');
// appendDescriptor(INTERNAL_NAME, owner);
// buf.append('.').append(name).append(' ');
// appendDescriptor(METHOD_DESCRIPTOR, desc);
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitMethodInsn(opcode, owner, name, desc);
// }
// }
//
// public void visitJumpInsn(final int opcode, final Label label) {
// buf.setLength(0);
// buf.append(tab2).append(OPCODES[opcode]).append(' ');
// appendLabel(label);
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitJumpInsn(opcode, label);
// }
// }
//
// public void visitLabel(final Label label) {
// buf.setLength(0);
// buf.append(ltab);
// appendLabel(label);
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitLabel(label);
// }
// }
//
// public void visitLdcInsn(final Object cst) {
// buf.setLength(0);
// buf.append(tab2).append("LDC ");
// if (cst instanceof String) {
// AbstractVisitor.appendString(buf, (String) cst);
// } else if (cst instanceof Type) {
// buf.append(((Type) cst).getDescriptor() + ".class");
// } else {
// buf.append(cst);
// }
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitLdcInsn(cst);
// }
// }
//
// public void visitIincInsn(final int var, final int increment) {
// buf.setLength(0);
// buf.append(tab2)
// .append("IINC ")
// .append(var)
// .append(' ')
// .append(increment)
// .append('\n');
// dump();
//
// if (mv != null) {
// mv.visitIincInsn(var, increment);
// }
// }
//
// public void visitTableSwitchInsn(
// final int min,
// final int max,
// final Label dflt,
// final Label labels[])
// {
// buf.setLength(0);
// buf.append(tab2).append("TABLESWITCH\n");
// for (int i = 0; i < labels.length; ++i) {
// buf.append(tab3).append(min + i).append(": ");
// appendLabel(labels[i]);
// buf.append('\n');
// }
// buf.append(tab3).append("default: ");
// appendLabel(dflt);
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitTableSwitchInsn(min, max, dflt, labels);
// }
// }
//
// public void visitLookupSwitchInsn(
// final Label dflt,
// final int keys[],
// final Label labels[])
// {
// buf.setLength(0);
// buf.append(tab2).append("LOOKUPSWITCH\n");
// for (int i = 0; i < labels.length; ++i) {
// buf.append(tab3).append(keys[i]).append(": ");
// appendLabel(labels[i]);
// buf.append('\n');
// }
// buf.append(tab3).append("default: ");
// appendLabel(dflt);
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitLookupSwitchInsn(dflt, keys, labels);
// }
// }
//
// public void visitMultiANewArrayInsn(final String desc, final int dims) {
// buf.setLength(0);
// buf.append(tab2).append("MULTIANEWARRAY ");
// appendDescriptor(FIELD_DESCRIPTOR, desc);
// buf.append(' ').append(dims).append('\n');
// dump();
//
// if (mv != null) {
// mv.visitMultiANewArrayInsn(desc, dims);
// }
// }
//
// public void visitTryCatchBlock(
// final Label start,
// final Label end,
// final Label handler,
// final String type)
// {
// buf.setLength(0);
// buf.append(tab2).append("TRYCATCHBLOCK ");
// appendLabel(start);
// buf.append(' ');
// appendLabel(end);
// buf.append(' ');
// appendLabel(handler);
// buf.append(' ');
// appendDescriptor(INTERNAL_NAME, type);
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitTryCatchBlock(start, end, handler, type);
// }
// }
//
// public void visitLocalVariable(
// final String name,
// final String desc,
// final String signature,
// final Label start,
// final Label end,
// final int index)
// {
// buf.setLength(0);
// buf.append(tab2).append("LOCALVARIABLE ").append(name).append(' ');
// appendDescriptor(FIELD_DESCRIPTOR, desc);
// buf.append(' ');
// appendLabel(start);
// buf.append(' ');
// appendLabel(end);
// buf.append(' ').append(index).append('\n');
//
// if (signature != null) {
// buf.append(tab2);
// appendDescriptor(FIELD_SIGNATURE, signature);
//
// TraceSignatureVisitor sv = new TraceSignatureVisitor(0);
// SignatureReader r = new SignatureReader(signature);
// r.acceptType(sv);
// buf.append(tab2)
// .append("// declaration: ")
// .append(sv.getDeclaration())
// .append('\n');
// }
// dump();
//
// if (mv != null) {
// mv.visitLocalVariable(name, desc, signature, start, end, index);
// }
// }
//
// private void dump() {
// String s = buf.toString();
// s = s.substring(0, s.length() - 1);
// Util.log(s);
// }
//
// public void visitLineNumber(final int line, final Label start) {
// buf.setLength(0);
// buf.append(tab2).append("LINENUMBER ").append(line).append(' ');
// appendLabel(start);
// buf.append('\n');
// dump();
//
// if (mv != null) {
// mv.visitLineNumber(line, start);
// }
// }
//
// public void visitMaxs(final int maxStack, final int maxLocals) {
// buf.setLength(0);
// buf.append(tab2).append("MAXSTACK = ").append(maxStack).append('\n');
// dump();
//
// buf.setLength(0);
// buf.append(tab2).append("MAXLOCALS = ").append(maxLocals).append('\n');
// dump();
//
// if (mv != null) {
// mv.visitMaxs(maxStack, maxLocals);
// }
// }
//
// @Override
// public void visitEnd() {
//// super.visitEnd();
//
// if (mv != null) {
// mv.visitEnd();
// }
// }
//
// // ------------------------------------------------------------------------
// // Utility methods
// // ------------------------------------------------------------------------
//
// private void appendFrameTypes(final int n, final Object[] o) {
// for (int i = 0; i < n; ++i) {
// if (i > 0) {
// buf.append(' ');
// }
// if (o[i] instanceof String) {
// String desc = (String) o[i];
// if (desc.startsWith("[")) {
// appendDescriptor(FIELD_DESCRIPTOR, desc);
// } else {
// appendDescriptor(INTERNAL_NAME, desc);
// }
// } else if (o[i] instanceof Integer) {
// switch (((Integer) o[i]).intValue()) {
// case 0:
// appendDescriptor(FIELD_DESCRIPTOR, "T");
// break;
// case 1:
// appendDescriptor(FIELD_DESCRIPTOR, "I");
// break;
// case 2:
// appendDescriptor(FIELD_DESCRIPTOR, "F");
// break;
// case 3:
// appendDescriptor(FIELD_DESCRIPTOR, "D");
// break;
// case 4:
// appendDescriptor(FIELD_DESCRIPTOR, "J");
// break;
// case 5:
// appendDescriptor(FIELD_DESCRIPTOR, "N");
// break;
// case 6:
// appendDescriptor(FIELD_DESCRIPTOR, "U");
// break;
// }
// } else {
// appendLabel((Label) o[i]);
// }
// }
// }
//
// /**
// * Appends the name of the given label to {@link #buf buf}. Creates a new
// * label name if the given label does not yet have one.
// *
// * @param l a label.
// */
// protected void appendLabel(final Label l) {
// String name = (String) labelNames.get(l);
// if (name == null) {
// name = "L" + labelNames.size();
// labelNames.put(l, name);
// }
// buf.append(name);
// }
//}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.sql2rel;
import org.apache.calcite.linq4j.Ord;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.RelFieldCollation;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Aggregate;
import org.apache.calcite.rel.core.AggregateCall;
import org.apache.calcite.rel.core.CorrelationId;
import org.apache.calcite.rel.core.Filter;
import org.apache.calcite.rel.core.Join;
import org.apache.calcite.rel.core.Project;
import org.apache.calcite.rel.core.RelFactories;
import org.apache.calcite.rel.core.SemiJoin;
import org.apache.calcite.rel.core.SetOp;
import org.apache.calcite.rel.core.Sort;
import org.apache.calcite.rel.core.TableScan;
import org.apache.calcite.rel.logical.LogicalTableFunctionScan;
import org.apache.calcite.rel.logical.LogicalTableModify;
import org.apache.calcite.rel.logical.LogicalValues;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rel.type.RelDataTypeImpl;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexCorrelVariable;
import org.apache.calcite.rex.RexFieldAccess;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexPermuteInputsShuttle;
import org.apache.calcite.rex.RexUtil;
import org.apache.calcite.rex.RexVisitor;
import org.apache.calcite.sql.SqlExplainLevel;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.tools.RelBuilder;
import org.apache.calcite.util.Bug;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.calcite.util.Pair;
import org.apache.calcite.util.ReflectUtil;
import org.apache.calcite.util.ReflectiveVisitor;
import org.apache.calcite.util.Util;
import org.apache.calcite.util.mapping.IntPair;
import org.apache.calcite.util.mapping.Mapping;
import org.apache.calcite.util.mapping.MappingType;
import org.apache.calcite.util.mapping.Mappings;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Transformer that walks over a tree of relational expressions, replacing each
* {@link RelNode} with a 'slimmed down' relational expression that projects
* only the columns required by its consumer.
*
* <p>Uses multi-methods to fire the right rule for each type of relational
* expression. This allows the transformer to be extended without having to
* add a new method to RelNode, and without requiring a collection of rule
* classes scattered to the four winds.
*
* <p>REVIEW: jhyde, 2009/7/28: Is sql2rel the correct package for this class?
* Trimming fields is not an essential part of SQL-to-Rel translation, and
* arguably belongs in the optimization phase. But this transformer does not
* obey the usual pattern for planner rules; it is difficult to do so, because
* each {@link RelNode} needs to return a different set of fields after
* trimming.
*
* <p>TODO: Change 2nd arg of the {@link #trimFields} method from BitSet to
* Mapping. Sometimes it helps the consumer if you return the columns in a
* particular order. For instance, it may avoid a project at the top of the
* tree just for reordering. Could ease the transition by writing methods that
* convert BitSet to Mapping and vice versa.
*/
public class RelFieldTrimmer implements ReflectiveVisitor {
//~ Static fields/initializers ---------------------------------------------
//~ Instance fields --------------------------------------------------------
private final ReflectUtil.MethodDispatcher<TrimResult> trimFieldsDispatcher;
private final RelBuilder relBuilder;
//~ Constructors -----------------------------------------------------------
/**
* Creates a RelFieldTrimmer.
*
* @param validator Validator
*/
public RelFieldTrimmer(SqlValidator validator, RelBuilder relBuilder) {
Util.discard(validator); // may be useful one day
this.relBuilder = relBuilder;
this.trimFieldsDispatcher =
ReflectUtil.createMethodDispatcher(
TrimResult.class,
this,
"trimFields",
RelNode.class,
ImmutableBitSet.class,
Set.class);
}
@Deprecated // to be removed before 2.0
public RelFieldTrimmer(SqlValidator validator,
RelOptCluster cluster,
RelFactories.ProjectFactory projectFactory,
RelFactories.FilterFactory filterFactory,
RelFactories.JoinFactory joinFactory,
RelFactories.SemiJoinFactory semiJoinFactory,
RelFactories.SortFactory sortFactory,
RelFactories.AggregateFactory aggregateFactory,
RelFactories.SetOpFactory setOpFactory) {
this(validator,
RelBuilder.proto(projectFactory, filterFactory, joinFactory,
semiJoinFactory, sortFactory, aggregateFactory, setOpFactory)
.create(cluster, null));
}
//~ Methods ----------------------------------------------------------------
/**
* Trims unused fields from a relational expression.
*
* <p>We presume that all fields of the relational expression are wanted by
* its consumer, so only trim fields that are not used within the tree.
*
* @param root Root node of relational expression
* @return Trimmed relational expression
*/
public RelNode trim(RelNode root) {
final int fieldCount = root.getRowType().getFieldCount();
final ImmutableBitSet fieldsUsed = ImmutableBitSet.range(fieldCount);
final Set<RelDataTypeField> extraFields = Collections.emptySet();
final TrimResult trimResult =
dispatchTrimFields(root, fieldsUsed, extraFields);
if (!trimResult.right.isIdentity()) {
throw new IllegalArgumentException();
}
if (SqlToRelConverter.SQL2REL_LOGGER.isDebugEnabled()) {
SqlToRelConverter.SQL2REL_LOGGER.debug(
RelOptUtil.dumpPlan("Plan after trimming unused fields",
trimResult.left, false, SqlExplainLevel.EXPPLAN_ATTRIBUTES));
}
return trimResult.left;
}
/**
* Trims the fields of an input relational expression.
*
* @param rel Relational expression
* @param input Input relational expression, whose fields to trim
* @param fieldsUsed Bitmap of fields needed by the consumer
* @return New relational expression and its field mapping
*/
protected TrimResult trimChild(
RelNode rel,
RelNode input,
final ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final ImmutableBitSet.Builder fieldsUsedBuilder = fieldsUsed.rebuild();
// Fields that define the collation cannot be discarded.
final RelMetadataQuery mq = RelMetadataQuery.instance();
final ImmutableList<RelCollation> collations = mq.collations(input);
for (RelCollation collation : collations) {
for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
fieldsUsedBuilder.set(fieldCollation.getFieldIndex());
}
}
// Correlating variables are a means for other relational expressions to use
// fields.
for (final CorrelationId correlation : rel.getVariablesSet()) {
rel.accept(
new CorrelationReferenceFinder() {
protected RexNode handle(RexFieldAccess fieldAccess) {
final RexCorrelVariable v =
(RexCorrelVariable) fieldAccess.getReferenceExpr();
if (v.id.equals(correlation)) {
fieldsUsedBuilder.set(fieldAccess.getField().getIndex());
}
return fieldAccess;
}
});
}
return dispatchTrimFields(input, fieldsUsedBuilder.build(), extraFields);
}
/**
* Trims a child relational expression, then adds back a dummy project to
* restore the fields that were removed.
*
* <p>Sounds pointless? It causes unused fields to be removed
* further down the tree (towards the leaves), but it ensure that the
* consuming relational expression continues to see the same fields.
*
* @param rel Relational expression
* @param input Input relational expression, whose fields to trim
* @param fieldsUsed Bitmap of fields needed by the consumer
* @return New relational expression and its field mapping
*/
protected TrimResult trimChildRestore(
RelNode rel,
RelNode input,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
TrimResult trimResult = trimChild(rel, input, fieldsUsed, extraFields);
if (trimResult.right.isIdentity()) {
return trimResult;
}
final RelDataType rowType = input.getRowType();
List<RelDataTypeField> fieldList = rowType.getFieldList();
final List<RexNode> exprList = new ArrayList<>();
final List<String> nameList = rowType.getFieldNames();
RexBuilder rexBuilder = rel.getCluster().getRexBuilder();
assert trimResult.right.getSourceCount() == fieldList.size();
for (int i = 0; i < fieldList.size(); i++) {
int source = trimResult.right.getTargetOpt(i);
RelDataTypeField field = fieldList.get(i);
exprList.add(
source < 0
? rexBuilder.makeZeroLiteral(field.getType())
: rexBuilder.makeInputRef(field.getType(), source));
}
relBuilder.push(trimResult.left)
.project(exprList, nameList);
return result(relBuilder.build(),
Mappings.createIdentity(fieldList.size()));
}
/**
* Invokes {@link #trimFields}, or the appropriate method for the type
* of the rel parameter, using multi-method dispatch.
*
* @param rel Relational expression
* @param fieldsUsed Bitmap of fields needed by the consumer
* @return New relational expression and its field mapping
*/
protected final TrimResult dispatchTrimFields(
RelNode rel,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final TrimResult trimResult =
trimFieldsDispatcher.invoke(rel, fieldsUsed, extraFields);
final RelNode newRel = trimResult.left;
final Mapping mapping = trimResult.right;
final int fieldCount = rel.getRowType().getFieldCount();
assert mapping.getSourceCount() == fieldCount
: "source: " + mapping.getSourceCount() + " != " + fieldCount;
final int newFieldCount = newRel.getRowType().getFieldCount();
assert mapping.getTargetCount() + extraFields.size() == newFieldCount
|| Bug.TODO_FIXED
: "target: " + mapping.getTargetCount()
+ " + " + extraFields.size()
+ " != " + newFieldCount;
if (Bug.TODO_FIXED) {
assert newFieldCount > 0 : "rel has no fields after trim: " + rel;
}
if (newRel.equals(rel)) {
return result(rel, mapping);
}
return trimResult;
}
private TrimResult result(RelNode r, final Mapping mapping) {
final RexBuilder rexBuilder = relBuilder.getRexBuilder();
for (final CorrelationId correlation : r.getVariablesSet()) {
r = r.accept(
new CorrelationReferenceFinder() {
protected RexNode handle(RexFieldAccess fieldAccess) {
final RexCorrelVariable v =
(RexCorrelVariable) fieldAccess.getReferenceExpr();
if (v.id.equals(correlation)
&& v.getType().getFieldCount() == mapping.getSourceCount()) {
final int old = fieldAccess.getField().getIndex();
final int new_ = mapping.getTarget(old);
final RelDataTypeFactory.FieldInfoBuilder typeBuilder =
relBuilder.getTypeFactory().builder();
for (int target : Util.range(mapping.getTargetCount())) {
typeBuilder.add(
v.getType().getFieldList().get(mapping.getSource(target)));
}
final RexNode newV =
rexBuilder.makeCorrel(typeBuilder.build(), v.id);
if (old != new_) {
return rexBuilder.makeFieldAccess(newV, new_);
}
}
return fieldAccess;
}
});
}
return new TrimResult(r, mapping);
}
/**
* Visit method, per {@link org.apache.calcite.util.ReflectiveVisitor}.
*
* <p>This method is invoked reflectively, so there may not be any apparent
* calls to it. The class (or derived classes) may contain overloads of
* this method with more specific types for the {@code rel} parameter.
*
* <p>Returns a pair: the relational expression created, and the mapping
* between the original fields and the fields of the newly created
* relational expression.
*
* @param rel Relational expression
* @param fieldsUsed Fields needed by the consumer
* @return relational expression and mapping
*/
public TrimResult trimFields(
RelNode rel,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
// We don't know how to trim this kind of relational expression, so give
// it back intact.
Util.discard(fieldsUsed);
return result(rel,
Mappings.createIdentity(rel.getRowType().getFieldCount()));
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.logical.LogicalProject}.
*/
public TrimResult trimFields(
Project project,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final RelDataType rowType = project.getRowType();
final int fieldCount = rowType.getFieldCount();
final RelNode input = project.getInput();
// Which fields are required from the input?
final Set<RelDataTypeField> inputExtraFields =
new LinkedHashSet<>(extraFields);
RelOptUtil.InputFinder inputFinder =
new RelOptUtil.InputFinder(inputExtraFields);
for (Ord<RexNode> ord : Ord.zip(project.getProjects())) {
if (fieldsUsed.get(ord.i)) {
ord.e.accept(inputFinder);
}
}
ImmutableBitSet inputFieldsUsed = inputFinder.inputBitSet.build();
// Create input with trimmed columns.
TrimResult trimResult =
trimChild(project, input, inputFieldsUsed, inputExtraFields);
RelNode newInput = trimResult.left;
final Mapping inputMapping = trimResult.right;
// If the input is unchanged, and we need to project all columns,
// there's nothing we can do.
if (newInput == input
&& fieldsUsed.cardinality() == fieldCount) {
return result(project, Mappings.createIdentity(fieldCount));
}
// Some parts of the system can't handle rows with zero fields, so
// pretend that one field is used.
if (fieldsUsed.cardinality() == 0) {
return dummyProject(fieldCount, newInput);
}
// Build new project expressions, and populate the mapping.
final List<RexNode> newProjects = new ArrayList<>();
final RexVisitor<RexNode> shuttle =
new RexPermuteInputsShuttle(
inputMapping, newInput);
final Mapping mapping =
Mappings.create(
MappingType.INVERSE_SURJECTION,
fieldCount,
fieldsUsed.cardinality());
for (Ord<RexNode> ord : Ord.zip(project.getProjects())) {
if (fieldsUsed.get(ord.i)) {
mapping.set(ord.i, newProjects.size());
RexNode newProjectExpr = ord.e.accept(shuttle);
newProjects.add(newProjectExpr);
}
}
final RelDataType newRowType =
RelOptUtil.permute(project.getCluster().getTypeFactory(), rowType,
mapping);
relBuilder.push(newInput);
relBuilder.project(newProjects, newRowType.getFieldNames());
return result(relBuilder.build(), mapping);
}
/** Creates a project with a dummy column, to protect the parts of the system
* that cannot handle a relational expression with no columns.
*
* @param fieldCount Number of fields in the original relational expression
* @param input Trimmed input
* @return Dummy project, or null if no dummy is required
*/
private TrimResult dummyProject(int fieldCount, RelNode input) {
final RelOptCluster cluster = input.getCluster();
final Mapping mapping =
Mappings.create(MappingType.INVERSE_SURJECTION, fieldCount, 1);
if (input.getRowType().getFieldCount() == 1) {
// Input already has one field (and may in fact be a dummy project we
// created for the child). We can't do better.
return result(input, mapping);
}
final RexLiteral expr =
cluster.getRexBuilder().makeExactLiteral(BigDecimal.ZERO);
relBuilder.push(input);
relBuilder.project(ImmutableList.<RexNode>of(expr), ImmutableList.of("DUMMY"));
return result(relBuilder.build(), mapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.logical.LogicalFilter}.
*/
public TrimResult trimFields(
Filter filter,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final RelDataType rowType = filter.getRowType();
final int fieldCount = rowType.getFieldCount();
final RexNode conditionExpr = filter.getCondition();
final RelNode input = filter.getInput();
// We use the fields used by the consumer, plus any fields used in the
// filter.
final Set<RelDataTypeField> inputExtraFields =
new LinkedHashSet<>(extraFields);
RelOptUtil.InputFinder inputFinder =
new RelOptUtil.InputFinder(inputExtraFields);
inputFinder.inputBitSet.addAll(fieldsUsed);
conditionExpr.accept(inputFinder);
final ImmutableBitSet inputFieldsUsed = inputFinder.inputBitSet.build();
// Create input with trimmed columns.
TrimResult trimResult =
trimChild(filter, input, inputFieldsUsed, inputExtraFields);
RelNode newInput = trimResult.left;
final Mapping inputMapping = trimResult.right;
// If the input is unchanged, and we need to project all columns,
// there's nothing we can do.
if (newInput == input
&& fieldsUsed.cardinality() == fieldCount) {
return result(filter, Mappings.createIdentity(fieldCount));
}
// Build new project expressions, and populate the mapping.
final RexVisitor<RexNode> shuttle =
new RexPermuteInputsShuttle(inputMapping, newInput);
RexNode newConditionExpr =
conditionExpr.accept(shuttle);
// Use copy rather than relBuilder so that correlating variables get set.
relBuilder.push(
filter.copy(filter.getTraitSet(), newInput, newConditionExpr));
// The result has the same mapping as the input gave us. Sometimes we
// return fields that the consumer didn't ask for, because the filter
// needs them for its condition.
return result(relBuilder.build(), inputMapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.core.Sort}.
*/
public TrimResult trimFields(
Sort sort,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final RelDataType rowType = sort.getRowType();
final int fieldCount = rowType.getFieldCount();
final RelCollation collation = sort.getCollation();
final RelNode input = sort.getInput();
// We use the fields used by the consumer, plus any fields used as sort
// keys.
final ImmutableBitSet.Builder inputFieldsUsed =
ImmutableBitSet.builder(fieldsUsed);
for (RelFieldCollation field : collation.getFieldCollations()) {
inputFieldsUsed.set(field.getFieldIndex());
}
// Create input with trimmed columns.
final Set<RelDataTypeField> inputExtraFields = Collections.emptySet();
TrimResult trimResult =
trimChild(sort, input, inputFieldsUsed.build(), inputExtraFields);
RelNode newInput = trimResult.left;
final Mapping inputMapping = trimResult.right;
// If the input is unchanged, and we need to project all columns,
// there's nothing we can do.
if (newInput == input
&& inputMapping.isIdentity()
&& fieldsUsed.cardinality() == fieldCount) {
return result(sort, Mappings.createIdentity(fieldCount));
}
relBuilder.push(newInput);
final int offset =
sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
final int fetch =
sort.fetch == null ? -1 : RexLiteral.intValue(sort.fetch);
final ImmutableList<RexNode> fields =
relBuilder.fields(RexUtil.apply(inputMapping, collation));
relBuilder.sortLimit(offset, fetch, fields);
// The result has the same mapping as the input gave us. Sometimes we
// return fields that the consumer didn't ask for, because the filter
// needs them for its condition.
return result(relBuilder.build(), inputMapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.logical.LogicalJoin}.
*/
public TrimResult trimFields(
Join join,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final int fieldCount = join.getSystemFieldList().size()
+ join.getLeft().getRowType().getFieldCount()
+ join.getRight().getRowType().getFieldCount();
final RexNode conditionExpr = join.getCondition();
final int systemFieldCount = join.getSystemFieldList().size();
// Add in fields used in the condition.
final Set<RelDataTypeField> combinedInputExtraFields =
new LinkedHashSet<>(extraFields);
RelOptUtil.InputFinder inputFinder =
new RelOptUtil.InputFinder(combinedInputExtraFields);
inputFinder.inputBitSet.addAll(fieldsUsed);
conditionExpr.accept(inputFinder);
final ImmutableBitSet fieldsUsedPlus = inputFinder.inputBitSet.build();
// If no system fields are used, we can remove them.
int systemFieldUsedCount = 0;
for (int i = 0; i < systemFieldCount; ++i) {
if (fieldsUsed.get(i)) {
++systemFieldUsedCount;
}
}
final int newSystemFieldCount;
if (systemFieldUsedCount == 0) {
newSystemFieldCount = 0;
} else {
newSystemFieldCount = systemFieldCount;
}
int offset = systemFieldCount;
int changeCount = 0;
int newFieldCount = newSystemFieldCount;
final List<RelNode> newInputs = new ArrayList<>(2);
final List<Mapping> inputMappings = new ArrayList<>();
final List<Integer> inputExtraFieldCounts = new ArrayList<>();
for (RelNode input : join.getInputs()) {
final RelDataType inputRowType = input.getRowType();
final int inputFieldCount = inputRowType.getFieldCount();
// Compute required mapping.
ImmutableBitSet.Builder inputFieldsUsed = ImmutableBitSet.builder();
for (int bit : fieldsUsedPlus) {
if (bit >= offset && bit < offset + inputFieldCount) {
inputFieldsUsed.set(bit - offset);
}
}
// If there are system fields, we automatically use the
// corresponding field in each input.
inputFieldsUsed.set(0, newSystemFieldCount);
// FIXME: We ought to collect extra fields for each input
// individually. For now, we assume that just one input has
// on-demand fields.
Set<RelDataTypeField> inputExtraFields =
RelDataTypeImpl.extra(inputRowType) == null
? Collections.<RelDataTypeField>emptySet()
: combinedInputExtraFields;
inputExtraFieldCounts.add(inputExtraFields.size());
TrimResult trimResult =
trimChild(join, input, inputFieldsUsed.build(), inputExtraFields);
newInputs.add(trimResult.left);
if (trimResult.left != input) {
++changeCount;
}
final Mapping inputMapping = trimResult.right;
inputMappings.add(inputMapping);
// Move offset to point to start of next input.
offset += inputFieldCount;
newFieldCount +=
inputMapping.getTargetCount() + inputExtraFields.size();
}
Mapping mapping =
Mappings.create(
MappingType.INVERSE_SURJECTION,
fieldCount,
newFieldCount);
for (int i = 0; i < newSystemFieldCount; ++i) {
mapping.set(i, i);
}
offset = systemFieldCount;
int newOffset = newSystemFieldCount;
for (int i = 0; i < inputMappings.size(); i++) {
Mapping inputMapping = inputMappings.get(i);
for (IntPair pair : inputMapping) {
mapping.set(pair.source + offset, pair.target + newOffset);
}
offset += inputMapping.getSourceCount();
newOffset += inputMapping.getTargetCount()
+ inputExtraFieldCounts.get(i);
}
if (changeCount == 0
&& mapping.isIdentity()) {
return result(join, Mappings.createIdentity(fieldCount));
}
// Build new join.
final RexVisitor<RexNode> shuttle =
new RexPermuteInputsShuttle(
mapping, newInputs.get(0), newInputs.get(1));
RexNode newConditionExpr =
conditionExpr.accept(shuttle);
relBuilder.push(newInputs.get(0));
relBuilder.push(newInputs.get(1));
if (join instanceof SemiJoin) {
relBuilder.semiJoin(newConditionExpr);
// For SemiJoins only map fields from the left-side
Mapping inputMapping = inputMappings.get(0);
mapping = Mappings.create(MappingType.INVERSE_SURJECTION,
join.getRowType().getFieldCount(),
newSystemFieldCount + inputMapping.getTargetCount());
for (int i = 0; i < newSystemFieldCount; ++i) {
mapping.set(i, i);
}
offset = systemFieldCount;
newOffset = newSystemFieldCount;
for (IntPair pair : inputMapping) {
mapping.set(pair.source + offset, pair.target + newOffset);
}
} else {
relBuilder.join(join.getJoinType(), newConditionExpr);
}
return result(relBuilder.build(), mapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.core.SetOp} (including UNION and UNION ALL).
*/
public TrimResult trimFields(
SetOp setOp,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final RelDataType rowType = setOp.getRowType();
final int fieldCount = rowType.getFieldCount();
int changeCount = 0;
// Fennel abhors an empty row type, so pretend that the parent rel
// wants the last field. (The last field is the least likely to be a
// system field.)
if (fieldsUsed.isEmpty()) {
fieldsUsed = ImmutableBitSet.of(rowType.getFieldCount() - 1);
}
// Compute the desired field mapping. Give the consumer the fields they
// want, in the order that they appear in the bitset.
final Mapping mapping = createMapping(fieldsUsed, fieldCount);
// Create input with trimmed columns.
for (RelNode input : setOp.getInputs()) {
TrimResult trimResult =
trimChild(setOp, input, fieldsUsed, extraFields);
// We want "mapping", the input gave us "inputMapping", compute
// "remaining" mapping.
// | | |
// |---------------- mapping ---------->|
// |-- inputMapping -->| |
// | |-- remaining -->|
//
// For instance, suppose we have columns [a, b, c, d],
// the consumer asked for mapping = [b, d],
// and the transformed input has columns inputMapping = [d, a, b].
// remaining will permute [b, d] to [d, a, b].
Mapping remaining = Mappings.divide(mapping, trimResult.right);
// Create a projection; does nothing if remaining is identity.
relBuilder.push(trimResult.left);
relBuilder.permute(remaining);
if (input != relBuilder.peek()) {
++changeCount;
}
}
// If the input is unchanged, and we need to project all columns,
// there's to do.
if (changeCount == 0
&& mapping.isIdentity()) {
for (RelNode input : setOp.getInputs()) {
relBuilder.build();
}
return result(setOp, mapping);
}
switch (setOp.kind) {
case UNION:
relBuilder.union(setOp.all, setOp.getInputs().size());
break;
case INTERSECT:
relBuilder.intersect(setOp.all, setOp.getInputs().size());
break;
case EXCEPT:
assert setOp.getInputs().size() == 2;
relBuilder.minus(setOp.all);
break;
default:
throw new AssertionError("unknown setOp " + setOp);
}
return result(relBuilder.build(), mapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.logical.LogicalAggregate}.
*/
public TrimResult trimFields(
Aggregate aggregate,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
// Fields:
//
// | sys fields | group fields | indicator fields | agg functions |
//
// Two kinds of trimming:
//
// 1. If agg rel has system fields but none of these are used, create an
// agg rel with no system fields.
//
// 2. If aggregate functions are not used, remove them.
//
// But group and indicator fields stay, even if they are not used.
final RelDataType rowType = aggregate.getRowType();
// Compute which input fields are used.
// 1. group fields are always used
final ImmutableBitSet.Builder inputFieldsUsed =
ImmutableBitSet.builder(aggregate.getGroupSet());
// 2. agg functions
for (AggregateCall aggCall : aggregate.getAggCallList()) {
for (int i : aggCall.getArgList()) {
inputFieldsUsed.set(i);
}
if (aggCall.filterArg >= 0) {
inputFieldsUsed.set(aggCall.filterArg);
}
}
// Create input with trimmed columns.
final RelNode input = aggregate.getInput();
final Set<RelDataTypeField> inputExtraFields = Collections.emptySet();
final TrimResult trimResult =
trimChild(aggregate, input, inputFieldsUsed.build(), inputExtraFields);
final RelNode newInput = trimResult.left;
final Mapping inputMapping = trimResult.right;
// We have to return group keys and (if present) indicators.
// So, pretend that the consumer asked for them.
final int groupCount = aggregate.getGroupSet().cardinality();
final int indicatorCount = aggregate.getIndicatorCount();
fieldsUsed =
fieldsUsed.union(ImmutableBitSet.range(groupCount + indicatorCount));
// If the input is unchanged, and we need to project all columns,
// there's nothing to do.
if (input == newInput
&& fieldsUsed.equals(ImmutableBitSet.range(rowType.getFieldCount()))) {
return result(aggregate,
Mappings.createIdentity(rowType.getFieldCount()));
}
// Which agg calls are used by our consumer?
int j = groupCount + indicatorCount;
int usedAggCallCount = 0;
for (int i = 0; i < aggregate.getAggCallList().size(); i++) {
if (fieldsUsed.get(j++)) {
++usedAggCallCount;
}
}
// Offset due to the number of system fields having changed.
Mapping mapping =
Mappings.create(
MappingType.INVERSE_SURJECTION,
rowType.getFieldCount(),
groupCount + indicatorCount + usedAggCallCount);
final ImmutableBitSet newGroupSet =
Mappings.apply(inputMapping, aggregate.getGroupSet());
final ImmutableList<ImmutableBitSet> newGroupSets =
ImmutableList.copyOf(
Iterables.transform(aggregate.getGroupSets(),
new Function<ImmutableBitSet, ImmutableBitSet>() {
public ImmutableBitSet apply(ImmutableBitSet input) {
return Mappings.apply(inputMapping, input);
}
}));
// Populate mapping of where to find the fields. System, group key and
// indicator fields first.
for (j = 0; j < groupCount + indicatorCount; j++) {
mapping.set(j, j);
}
// Now create new agg calls, and populate mapping for them.
relBuilder.push(newInput);
final List<RelBuilder.AggCall> newAggCallList = new ArrayList<>();
j = groupCount + indicatorCount;
for (AggregateCall aggCall : aggregate.getAggCallList()) {
if (fieldsUsed.get(j)) {
final ImmutableList<RexNode> args =
relBuilder.fields(
Mappings.apply2(inputMapping, aggCall.getArgList()));
final RexNode filterArg = aggCall.filterArg < 0 ? null
: relBuilder.field(Mappings.apply(inputMapping, aggCall.filterArg));
RelBuilder.AggCall newAggCall =
relBuilder.aggregateCall(aggCall.getAggregation(),
aggCall.isDistinct(), filterArg, aggCall.name, args);
mapping.set(j, groupCount + indicatorCount + newAggCallList.size());
newAggCallList.add(newAggCall);
}
++j;
}
final RelBuilder.GroupKey groupKey = relBuilder.groupKey(newGroupSet,
aggregate.indicator, newGroupSets);
relBuilder.aggregate(groupKey, newAggCallList);
return result(relBuilder.build(), mapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.logical.LogicalTableModify}.
*/
public TrimResult trimFields(
LogicalTableModify modifier,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
// Ignore what consumer wants. We always project all columns.
Util.discard(fieldsUsed);
final RelDataType rowType = modifier.getRowType();
final int fieldCount = rowType.getFieldCount();
RelNode input = modifier.getInput();
// We want all fields from the child.
final int inputFieldCount = input.getRowType().getFieldCount();
final ImmutableBitSet inputFieldsUsed =
ImmutableBitSet.range(inputFieldCount);
// Create input with trimmed columns.
final Set<RelDataTypeField> inputExtraFields = Collections.emptySet();
TrimResult trimResult =
trimChild(modifier, input, inputFieldsUsed, inputExtraFields);
RelNode newInput = trimResult.left;
final Mapping inputMapping = trimResult.right;
if (!inputMapping.isIdentity()) {
// We asked for all fields. Can't believe that the child decided
// to permute them!
throw Util.newInternal(
"Expected identity mapping, got " + inputMapping);
}
LogicalTableModify newModifier = modifier;
if (newInput != input) {
newModifier =
modifier.copy(
modifier.getTraitSet(),
Collections.singletonList(newInput));
}
assert newModifier.getClass() == modifier.getClass();
// Always project all fields.
Mapping mapping = Mappings.createIdentity(fieldCount);
return result(newModifier, mapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.logical.LogicalTableFunctionScan}.
*/
public TrimResult trimFields(
LogicalTableFunctionScan tabFun,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final RelDataType rowType = tabFun.getRowType();
final int fieldCount = rowType.getFieldCount();
final List<RelNode> newInputs = new ArrayList<>();
for (RelNode input : tabFun.getInputs()) {
final int inputFieldCount = input.getRowType().getFieldCount();
ImmutableBitSet inputFieldsUsed = ImmutableBitSet.range(inputFieldCount);
// Create input with trimmed columns.
final Set<RelDataTypeField> inputExtraFields =
Collections.emptySet();
TrimResult trimResult =
trimChildRestore(
tabFun, input, inputFieldsUsed, inputExtraFields);
assert trimResult.right.isIdentity();
newInputs.add(trimResult.left);
}
LogicalTableFunctionScan newTabFun = tabFun;
if (!tabFun.getInputs().equals(newInputs)) {
newTabFun = tabFun.copy(tabFun.getTraitSet(), newInputs,
tabFun.getCall(), tabFun.getElementType(), tabFun.getRowType(),
tabFun.getColumnMappings());
}
assert newTabFun.getClass() == tabFun.getClass();
// Always project all fields.
Mapping mapping = Mappings.createIdentity(fieldCount);
return result(newTabFun, mapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.logical.LogicalValues}.
*/
public TrimResult trimFields(
LogicalValues values,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final RelDataType rowType = values.getRowType();
final int fieldCount = rowType.getFieldCount();
// If they are asking for no fields, we can't give them what they want,
// because zero-column records are illegal. Give them the last field,
// which is unlikely to be a system field.
if (fieldsUsed.isEmpty()) {
fieldsUsed = ImmutableBitSet.range(fieldCount - 1, fieldCount);
}
// If all fields are used, return unchanged.
if (fieldsUsed.equals(ImmutableBitSet.range(fieldCount))) {
Mapping mapping = Mappings.createIdentity(fieldCount);
return result(values, mapping);
}
final ImmutableList.Builder<ImmutableList<RexLiteral>> newTuples =
ImmutableList.builder();
for (ImmutableList<RexLiteral> tuple : values.getTuples()) {
ImmutableList.Builder<RexLiteral> newTuple = ImmutableList.builder();
for (int field : fieldsUsed) {
newTuple.add(tuple.get(field));
}
newTuples.add(newTuple.build());
}
final Mapping mapping = createMapping(fieldsUsed, fieldCount);
final RelDataType newRowType =
RelOptUtil.permute(values.getCluster().getTypeFactory(), rowType,
mapping);
final LogicalValues newValues =
LogicalValues.create(values.getCluster(), newRowType,
newTuples.build());
return result(newValues, mapping);
}
private Mapping createMapping(ImmutableBitSet fieldsUsed, int fieldCount) {
final Mapping mapping =
Mappings.create(
MappingType.INVERSE_SURJECTION,
fieldCount,
fieldsUsed.cardinality());
int i = 0;
for (int field : fieldsUsed) {
mapping.set(field, i++);
}
return mapping;
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.logical.LogicalTableScan}.
*/
public TrimResult trimFields(
final TableScan tableAccessRel,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final int fieldCount = tableAccessRel.getRowType().getFieldCount();
if (fieldsUsed.equals(ImmutableBitSet.range(fieldCount))
&& extraFields.isEmpty()) {
// if there is nothing to project or if we are projecting everything
// then no need to introduce another RelNode
return trimFields(
(RelNode) tableAccessRel, fieldsUsed, extraFields);
}
final RelNode newTableAccessRel =
tableAccessRel.project(fieldsUsed, extraFields, relBuilder);
// Some parts of the system can't handle rows with zero fields, so
// pretend that one field is used.
if (fieldsUsed.cardinality() == 0) {
RelNode input = newTableAccessRel;
if (input instanceof Project) {
// The table has implemented the project in the obvious way - by
// creating project with 0 fields. Strip it away, and create our own
// project with one field.
Project project = (Project) input;
if (project.getRowType().getFieldCount() == 0) {
input = project.getInput();
}
}
return dummyProject(fieldCount, input);
}
final Mapping mapping = createMapping(fieldsUsed, fieldCount);
return result(newTableAccessRel, mapping);
}
//~ Inner Classes ----------------------------------------------------------
/**
* Result of an attempt to trim columns from a relational expression.
*
* <p>The mapping describes where to find the columns wanted by the parent
* of the current relational expression.
*
* <p>The mapping is a
* {@link org.apache.calcite.util.mapping.Mappings.SourceMapping}, which means
* that no column can be used more than once, and some columns are not used.
* {@code columnsUsed.getSource(i)} returns the source of the i'th output
* field.
*
* <p>For example, consider the mapping for a relational expression that
* has 4 output columns but only two are being used. The mapping
* {2 → 1, 3 → 0} would give the following behavior:
*
* <ul>
* <li>columnsUsed.getSourceCount() returns 4
* <li>columnsUsed.getTargetCount() returns 2
* <li>columnsUsed.getSource(0) returns 3
* <li>columnsUsed.getSource(1) returns 2
* <li>columnsUsed.getSource(2) throws IndexOutOfBounds
* <li>columnsUsed.getTargetOpt(3) returns 0
* <li>columnsUsed.getTargetOpt(0) returns -1
* </ul>
*/
protected static class TrimResult extends Pair<RelNode, Mapping> {
/**
* Creates a TrimResult.
*
* @param left New relational expression
* @param right Mapping of fields onto original fields
*/
public TrimResult(RelNode left, Mapping right) {
super(left, right);
assert right.getTargetCount() == left.getRowType().getFieldCount()
: "rowType: " + left.getRowType() + ", mapping: " + right;
}
}
}
// End RelFieldTrimmer.java
| |
/**
* Copyright (C) 2009-2012 enStratus Networks Inc
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.dasein.cloud.rackspace.compute;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudErrorType;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.OperationNotSupportedException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.Tag;
import org.dasein.cloud.compute.Architecture;
import org.dasein.cloud.compute.ImageClass;
import org.dasein.cloud.compute.MachineImage;
import org.dasein.cloud.compute.Platform;
import org.dasein.cloud.compute.VMLaunchOptions;
import org.dasein.cloud.compute.VMScalingCapabilities;
import org.dasein.cloud.compute.VMScalingOptions;
import org.dasein.cloud.compute.VirtualMachine;
import org.dasein.cloud.compute.VirtualMachineProduct;
import org.dasein.cloud.compute.VirtualMachineSupport;
import org.dasein.cloud.compute.VmState;
import org.dasein.cloud.compute.VmStatistics;
import org.dasein.cloud.dc.DataCenter;
import org.dasein.cloud.identity.ServiceAction;
import org.dasein.cloud.rackspace.RackspaceCloud;
import org.dasein.cloud.rackspace.RackspaceException;
import org.dasein.cloud.rackspace.RackspaceMethod;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class CloudServers implements VirtualMachineSupport {
static private HashMap<String,Collection<VirtualMachineProduct>> cachedProducts = new HashMap<String,Collection<VirtualMachineProduct>>();
static public final int NAME_LIMIT = 30;
static public final int TAG_LIMIT = 4;
private RackspaceCloud provider;
CloudServers(@Nonnull RackspaceCloud provider) { this.provider = provider; }
@Override
public VirtualMachine alterVirtualMachine(@Nonnull String vmId, @Nonnull VMScalingOptions options) throws InternalException, CloudException {
throw new OperationNotSupportedException("Not supported");
}
@Override
public @Nonnull VirtualMachine clone(@Nonnull String vmId, @Nullable String intoDcId, @Nonnull String name, @Nonnull String description, boolean powerOn, @Nullable String... firewallIds) throws InternalException, CloudException {
throw new OperationNotSupportedException("Rackspace foes not support the cloning of servers.");
}
@Override
public VMScalingCapabilities describeVerticalScalingCapabilities() throws CloudException, InternalException {
return null;
}
@Override
public void disableAnalytics(@Nonnull String vmId) throws InternalException, CloudException {
// NO-OP
}
@Override
public void enableAnalytics(@Nonnull String vmId) throws InternalException, CloudException {
// NO-OP
}
@Override
public @Nonnull String getConsoleOutput(@Nonnull String vmId) throws InternalException, CloudException {
return "";
}
@Override
public int getCostFactor(@Nonnull VmState state) throws InternalException, CloudException {
return 100;
}
@Override
public int getMaximumVirtualMachineCount() throws CloudException, InternalException {
return -2;
}
@Override
public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException {
Logger std = RackspaceCloud.getLogger(CloudServers.class, "std");
if( std.isTraceEnabled() ) {
std.trace("enter - " + CloudServers.class.getName() + ".getProduct(" + productId + ")");
}
try {
if( !provider.isMyRegion() ) {
return null;
}
for( VirtualMachineProduct product : listProducts(Architecture.I64) ) {
if( product.getProviderProductId().equals(productId) ) {
return product;
}
}
return null;
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + CloudServers.class.getName() + ".getProduct()");
}
}
}
@Override
public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) {
return "server";
}
@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String vmId) throws InternalException, CloudException {
Logger std = RackspaceCloud.getLogger(CloudServers.class, "std");
if( std.isTraceEnabled() ) {
std.trace("enter - " + CloudServers.class.getName() + ".getVirtualMachine(" + vmId + ")");
}
try {
/*
if( !provider.isMyRegion() ) {
return null;
}
*/
RackspaceMethod method = new RackspaceMethod(provider);
JSONObject ob = method.getServers("/servers", vmId);
if( ob == null ) {
return null;
}
try {
if( ob.has("server") ) {
JSONObject server = ob.getJSONObject("server");
VirtualMachine vm = toVirtualMachine(server);
if( vm != null ) {
return vm;
}
}
}
catch( JSONException e ) {
std.error("getVirtualMachine(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers");
}
return null;
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + CloudServers.class.getName() + ".getVirtualMachine()");
}
}
}
@Override
public @Nullable VmStatistics getVMStatistics(@Nonnull String vmId, long from, long to) throws InternalException, CloudException {
return null;
}
@Override
public @Nonnull Iterable<VmStatistics> getVMStatisticsForPeriod(@Nonnull String vmId, long from, long to) throws InternalException, CloudException {
return Collections.emptyList();
}
@Nonnull
@Override
public Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException {
return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.NONE);
}
@Override
public @Nonnull Requirement identifyPasswordRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Nonnull
@Override
public Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyShellKeyRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Nonnull
@Override
public Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.NONE;
}
@Nonnull
@Override
public Requirement identifyStaticIPRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public boolean isAPITerminationPreventable() throws CloudException, InternalException {
return false;
}
@Override
public boolean isBasicAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
return (provider.isMyRegion() && provider.testContext() != null);
}
@Override
public boolean isUserDataSupported() throws CloudException, InternalException {
return false;
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException {
Logger logger = RackspaceCloud.getLogger(CloudServers.class, "std");
if( logger.isTraceEnabled() ) {
logger.trace("enter - " + CloudServers.class.getName() + ".launch(" + withLaunchOptions + ")");
}
try {
if( !provider.isMyRegion() ) {
throw new CloudException("Unable to launch any servers in " + provider.getContext().getRegionId());
}
String fromMachineImageId = withLaunchOptions.getMachineImageId();
String productId = withLaunchOptions.getStandardProductId();
Map<String,Object> meta = withLaunchOptions.getMetaData();
MachineImage targetImage = provider.getComputeServices().getImageSupport().getImage(fromMachineImageId);
HashMap<String,Object> wrapper = new HashMap<String,Object>();
HashMap<String,Object> json = new HashMap<String,Object>();
json.put("imageId", Long.parseLong(fromMachineImageId));
json.put("flavorId", Long.parseLong(productId));
HashMap<String,Object> metaData = new HashMap<String,Object>();
boolean safeName = false;
int tagCount = 0;
if( meta != null ) {
for( Map.Entry<String,Object> tag : meta.entrySet() ) {
if( tag.getKey() != null && tag.getValue() != null && tag.getKey().length() > 0 && tag.getValue().toString().length() > 0 ) {
metaData.put(tag.getKey(), tag.getValue());
tagCount++;
if( tagCount >= TAG_LIMIT ) {
break;
}
}
}
}
if( tagCount < TAG_LIMIT && !targetImage.getPlatform().equals(Platform.UNKNOWN) ) {
metaData.put("dsnPlatform", targetImage.getPlatform().name());
tagCount++;
}
if( tagCount < TAG_LIMIT ) {
metaData.put("dsnDescription", withLaunchOptions.getDescription());
tagCount++;
}
if( tagCount < TAG_LIMIT ) {
metaData.put("dsnName", withLaunchOptions.getFriendlyName());
safeName = true;
}
metaData.put("dsnTrueImage", targetImage.getProviderMachineImageId());
json.put("metadata", metaData);
json.put("name", validateName(withLaunchOptions.getHostName(), safeName));
wrapper.put("server", json);
RackspaceMethod method = new RackspaceMethod(provider);
JSONObject result = method.postServers("/servers", null, new JSONObject(wrapper));
if( result.has("server") ) {
try {
JSONObject server = result.getJSONObject("server");
VirtualMachine vm = toVirtualMachine(server);
if( vm != null ) {
return vm;
}
}
catch( JSONException e ) {
logger.error("launch(): Unable to understand launch response: " + e.getMessage());
if( logger.isTraceEnabled() ) {
e.printStackTrace();
}
throw new CloudException(e);
}
}
logger.error("launch(): No server was created by the launch attempt, and no error was returned");
throw new CloudException("No virtual machine was launched");
}
finally {
if( logger.isTraceEnabled() ) {
logger.trace("exit - " + CloudServers.class.getName() + ".launch()");
}
}
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull String fromMachineImageId, @Nonnull VirtualMachineProduct product, @Nullable String dataCenterId, @Nonnull String name, @Nonnull String description, @Nullable String withKeypairId, @Nullable String inVlanId, boolean withAnalytics, boolean asSandbox, @Nullable String... firewallIds) throws InternalException, CloudException {
return launch(fromMachineImageId, product, dataCenterId, name, description, withKeypairId, inVlanId, withAnalytics, asSandbox, firewallIds, new Tag[0]);
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull String fromMachineImageId, @Nonnull VirtualMachineProduct product, @Nullable String dataCenterId, @Nonnull String name, @Nonnull String description, @Nullable String withKeypairId, @Nullable String inVlanId, boolean withAnalytics, boolean asSandbox, @Nullable String[] firewallIds, @Nullable Tag... tags) throws InternalException, CloudException {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was provided for this request");
}
//noinspection ConstantConditions
if( description == null ) {
description = name;
}
if( dataCenterId == null ) {
for( DataCenter dc : provider.getDataCenterServices().listDataCenters(ctx.getRegionId()) ) {
if( dc != null ) {
dataCenterId = dc.getProviderDataCenterId();
break;
}
}
}
VMLaunchOptions options;
if( inVlanId == null ) {
//noinspection ConstantConditions
options = VMLaunchOptions.getInstance(product.getProviderProductId(), fromMachineImageId, name, description).inDataCenter(dataCenterId);
}
else {
//noinspection ConstantConditions
options = VMLaunchOptions.getInstance(product.getProviderProductId(), fromMachineImageId, name, description).inVlan(null, dataCenterId, inVlanId);
}
if( withKeypairId != null ) {
options = options.withBoostrapKey(withKeypairId);
}
if( tags != null ) {
for( Tag t : tags ) {
options = options.withMetaData(t.getKey(), t.getValue());
}
}
if( firewallIds != null ) {
options = options.behindFirewalls(firewallIds);
}
return launch(options);
}
@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException {
return Collections.emptyList();
}
@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException {
Logger std = RackspaceCloud.getLogger(CloudServers.class, "std");
if( std.isTraceEnabled() ) {
std.trace("enter - " + CloudServers.class.getName() + ".listProducts()");
}
try {
if( !provider.isMyRegion() ) {
return Collections.emptyList();
}
if( architecture.equals(Architecture.I32) ) {
return Collections.emptyList();
}
Collection<VirtualMachineProduct> products = cachedProducts.get(provider.getContext().getRegionId());
if( products == null ) {
if( std.isDebugEnabled() ) {
std.debug("listProducts(): Cache for " + provider.getContext().getRegionId() + " is empty, fetching values from cloud");
}
RackspaceMethod method = new RackspaceMethod(provider);
JSONObject ob = method.getServers("/flavors", null);
products = new ArrayList<VirtualMachineProduct>();
try {
if( ob.has("flavors") ) {
JSONArray list = ob.getJSONArray("flavors");
for( int i=0; i<list.length(); i++ ) {
JSONObject p = list.getJSONObject(i);
VirtualMachineProduct product = toProduct(p);
if( product != null ) {
products.add(product);
}
}
}
}
catch( JSONException e ) {
std.error("listProducts(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors: " + e.getMessage());
}
cachedProducts.put(provider.getContext().getRegionId(), Collections.unmodifiableCollection(products));
}
return products;
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + CloudServers.class.getName() + ".listProducts()");
}
}
}
private transient Collection<Architecture> architectures;
@Override
public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException {
if( architectures == null ) {
ArrayList<Architecture> tmp = new ArrayList<Architecture>();
tmp.add(Architecture.I32);
tmp.add(Architecture.I64);
architectures = Collections.unmodifiableList(tmp);
}
return architectures;
}
@Nonnull
@Override
public Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException {
ArrayList<ResourceStatus> status = new ArrayList<ResourceStatus>();
for( VirtualMachine vm : listVirtualMachines() ) {
status.add(new ResourceStatus(vm.getProviderVirtualMachineId(), vm.getCurrentState()));
}
return status;
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException {
Logger std = RackspaceCloud.getLogger(CloudServers.class, "std");
if( std.isTraceEnabled() ) {
std.trace("enter - " + CloudServers.class.getName() + ".listVirtualMachines()");
}
try {
if( !provider.isMyRegion() ) {
return Collections.emptyList();
}
RackspaceMethod method = new RackspaceMethod(provider);
JSONObject ob = method.getServers("/servers", null);
ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>();
try {
if( ob.has("servers") ) {
JSONArray list = ob.getJSONArray("servers");
for( int i=0; i<list.length(); i++ ) {
JSONObject server = list.getJSONObject(i);
VirtualMachine vm = toVirtualMachine(server);
if( vm != null ) {
servers.add(vm);
}
}
}
}
catch( JSONException e ) {
std.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers");
}
return servers;
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + CloudServers.class.getName() + ".listVirtualMachines()");
}
}
}
@Override
public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) {
return new String[0];
}
@Override
public void pause(@Nonnull String vmId) throws InternalException, CloudException {
throw new OperationNotSupportedException("Rackspace does not support pause/unpause.");
}
@Override
public void reboot(@Nonnull String vmId) throws CloudException, InternalException {
Logger logger = RackspaceCloud.getLogger(CloudServers.class, "std");
if( logger.isTraceEnabled() ) {
logger.trace("enter - " + CloudServers.class.getName() + ".reboot(" + vmId + ")");
}
try {
HashMap<String,Object> json = new HashMap<String,Object>();
HashMap<String,Object> action = new HashMap<String,Object>();
action.put("type", "HARD");
json.put("reboot", action);
RackspaceMethod method = new RackspaceMethod(provider);
method.postServers("/servers", vmId, new JSONObject(json));
}
finally {
if( logger.isTraceEnabled() ) {
logger.trace("exit - " + CloudServers.class.getName() + ".reboot()");
}
}
}
@Override
public void resume(@Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Rackspace does not support suspend/resume of servers.");
}
@Override
public void start(@Nonnull String vmId) throws InternalException, CloudException {
throw new OperationNotSupportedException("Rackspace does not support start/stop of servers.");
}
@Override
public void stop(@Nonnull String vmId) throws InternalException, CloudException {
stop(vmId, false);
}
@Override
public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException {
throw new OperationNotSupportedException("Rackspace does not support start/stop of servers");
}
@Override
public boolean supportsAnalytics() throws CloudException, InternalException {
return false;
}
@Override
public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public boolean supportsStartStop(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public void suspend(@Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Rackspace does not support suspend/resume of servers.");
}
@Override
public void terminate(@Nonnull String vmId) throws InternalException, CloudException {
Logger std = RackspaceCloud.getLogger(CloudServers.class, "std");
if( std.isTraceEnabled() ) {
std.trace("enter - " + CloudServers.class.getName() + ".terminate(" + vmId + ")");
}
try {
RackspaceMethod method = new RackspaceMethod(provider);
long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR;
do {
try {
method.deleteServers("/servers", vmId);
return;
}
catch( RackspaceException e ) {
if( e.getHttpCode() != HttpServletResponse.SC_CONFLICT ) {
throw e;
}
}
try { Thread.sleep(CalendarWrapper.MINUTE); }
catch( InterruptedException e ) { /* ignore */ }
} while( System.currentTimeMillis() < timeout );
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + CloudServers.class.getName() + ".terminate()");
}
}
}
@Override
public void unpause(@Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Rackspace does not support pause/unpause.");
}
@Override
public void updateTags(@Nonnull String vmId, @Nonnull Tag... tags) throws CloudException, InternalException {
// NO-OP
}
private @Nullable VirtualMachineProduct toProduct(@Nullable JSONObject json) throws JSONException, InternalException, CloudException {
Logger std = RackspaceCloud.getLogger(CloudServers.class, "std");
if( std.isTraceEnabled() ) {
std.trace("enter - " + CloudServers.class.getName() + ".toProduct(" + json + ")");
}
try {
if( json == null ) {
return null;
}
VirtualMachineProduct product = new VirtualMachineProduct();
if( json.has("id") ) {
product.setProviderProductId(json.getString("id"));
}
if( json.has("name") ) {
product.setName(json.getString("name"));
}
if( json.has("description") ) {
product.setDescription(json.getString("description"));
}
if( json.has("ram") ) {
product.setRamSize(new Storage<Megabyte>(json.getInt("ram"), Storage.MEGABYTE));
}
if( json.has("disk") ) {
product.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("disk"), Storage.GIGABYTE));
}
product.setCpuCount(1);
if( product.getProviderProductId() == null ) {
return null;
}
if( product.getName() == null ) {
product.setName(product.getProviderProductId());
}
if( product.getDescription() == null ) {
product.setDescription(product.getName());
}
return product;
}
finally {
if( std.isTraceEnabled() ) {
std.trace("enter - " + CloudServers.class.getName() + ".toProduct()");
}
}
}
private @Nullable VirtualMachine toVirtualMachine(@Nullable JSONObject server) throws JSONException, InternalException, CloudException {
Logger std = RackspaceCloud.getLogger(CloudServers.class, "std");
if( std.isTraceEnabled() ) {
std.trace("enter - " + CloudServers.class.getName() + ".toVirtualMachine(" + server + ")");
}
try {
if( server == null ) {
return null;
}
VirtualMachine vm = new VirtualMachine();
vm.setCurrentState(VmState.RUNNING);
vm.setArchitecture(Architecture.I64);
vm.setClonable(false);
vm.setCreationTimestamp(-1L);
vm.setImagable(false);
vm.setLastBootTimestamp(-1L);
vm.setLastPauseTimestamp(-1L);
vm.setPausable(false);
vm.setPersistent(true);
vm.setPlatform(Platform.UNKNOWN);
vm.setRebootable(true);
vm.setProviderOwnerId(provider.getContext().getAccountNumber());
if( server.has("id") ) {
vm.setProviderVirtualMachineId(String.valueOf(server.getLong("id")));
}
if( server.has("name") ) {
vm.setName(server.getString("name"));
}
if( server.has("description") ) {
vm.setDescription(server.getString("description"));
}
if( server.has("imageId") ) {
vm.setProviderMachineImageId(server.getString("imageId"));
}
if( vm.getDescription() == null ) {
HashMap<String,String> map = new HashMap<String,String>();
if( server.has("metadata") ) {
JSONObject md = server.getJSONObject("metadata");
if( md.has("dsnDescription") ) {
vm.setDescription(md.getString("dsnDescription"));
}
else if( md.has("dsnTrueImage") ) { // this will override the nonsense Rackspace is sending us
String imageId = md.getString("dsnTrueImage");
if( imageId != null && imageId.length() > 0 ) {
vm.setProviderMachineImageId(imageId);
}
}
else if( md.has("Server Label") ) {
vm.setDescription(md.getString("Server Label"));
}
if( md.has("dsnName") ) {
String str = md.getString("dsnName");
if( str != null && str.length() > 0 ) {
vm.setName(str);
}
}
if( md.has("dsnPlatform") ) {
try {
vm.setPlatform(Platform.valueOf(md.getString("dsnPlatform")));
}
catch( Throwable ignore ) {
// ignore
}
}
String[] keys = JSONObject.getNames(md);
if( keys != null ) {
for( String key : keys ) {
String value = md.getString(key);
if( value != null ) {
map.put(key, value);
}
}
}
}
if( vm.getDescription() == null ) {
if( vm.getName() == null ) {
vm.setName(vm.getProviderVirtualMachineId());
}
vm.setDescription(vm.getName());
}
if( server.has("hostId") ) {
map.put("host", server.getString("hostId"));
}
vm.setTags(map);
}
if( server.has("flavorId") ) {
vm.setProductId(server.getString("flavorId"));
}
if( server.has("adminPass") ) {
vm.setRootPassword(server.getString("adminPass"));
}
if( server.has("status") ) {
String s = server.getString("status").toLowerCase();
if( s.equals("active") ) {
vm.setCurrentState(VmState.RUNNING);
}
else if( s.equals("building") || s.equals("build") ) {
vm.setCurrentState(VmState.PENDING);
}
else if( s.equals("deleted") ) {
vm.setCurrentState(VmState.TERMINATED);
}
else if( s.equals("suspended") ) {
vm.setCurrentState(VmState.SUSPENDED);
}
else if( s.equals("error") ) {
return null;
}
else if( s.equals("reboot") || s.equals("hard_reboot") ) {
vm.setCurrentState(VmState.REBOOTING);
}
else {
std.warn("toVirtualMachine(): Unknown server state: " + s);
vm.setCurrentState(VmState.PENDING);
}
}
if( server.has("addresses") ) {
JSONObject addrs = server.getJSONObject("addresses");
if( addrs.has("public") ) {
JSONArray arr = addrs.getJSONArray("public");
String[] addresses = new String[arr.length()];
for( int i=0; i<arr.length(); i++ ) {
addresses[i] = arr.getString(i);
}
vm.setPublicIpAddresses(addresses);
}
else {
vm.setPublicIpAddresses(new String[0]);
}
if( addrs.has("private") ) {
JSONArray arr = addrs.getJSONArray("private");
String[] addresses = new String[arr.length()];
for( int i=0; i<arr.length(); i++ ) {
addresses[i] = arr.getString(i);
}
vm.setPrivateIpAddresses(addresses);
}
else {
vm.setPrivateIpAddresses(new String[0]);
}
}
vm.setProviderRegionId(provider.getContext().getRegionId());
vm.setProviderDataCenterId(vm.getProviderRegionId() + "1");
vm.setTerminationTimestamp(-1L);
if( vm.getProviderVirtualMachineId() == null ) {
return null;
}
vm.setImagable(vm.getCurrentState().equals(VmState.RUNNING));
vm.setRebootable(vm.getCurrentState().equals(VmState.RUNNING));
if( vm.getPlatform().equals(Platform.UNKNOWN) ) {
Platform p = Platform.guess(vm.getName() + " " + vm.getDescription());
if( p.equals(Platform.UNKNOWN) ) {
MachineImage img = provider.getComputeServices().getImageSupport().getMachineImage(vm.getProviderMachineImageId());
if( img != null ) {
p = img.getPlatform();
}
}
vm.setPlatform(p);
}
return vm;
}
finally {
if( std.isTraceEnabled() ) {
std.trace("exit - " + CloudServers.class.getName() + ".toVirtualMachine()");
}
}
}
private boolean serverExists(String name) throws InternalException, CloudException {
for( VirtualMachine vm : listVirtualMachines() ) {
if( vm.getName().equalsIgnoreCase(name) ) {
return true;
}
}
return false;
}
private String makeUpName(String name) throws InternalException, CloudException {
StringBuilder str = new StringBuilder();
char last = '\0';
for( int i=0; i<name.length(); i++ ) {
char c = name.charAt(i);
if( c >= 'a' && c <= 'z' ) {
if( last == '-' && !str.toString().endsWith("-") ) {
str.append('-');
}
str.append(c);
}
last = c;
}
if( name.length() < 1 ) {
name = "a";
}
String test = name;
int idx = 1;
while( serverExists(test) && idx<1000000 ) {
test = name + "-" + (idx++);
}
return test;
}
private String validateName(String name, boolean safeName) throws InternalException, CloudException {
if( safeName ) {
name = name.toLowerCase().replaceAll(" ", "-");
}
if( name.length() > NAME_LIMIT ) {
name = name.substring(0,NAME_LIMIT);
}
StringBuilder str = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char c = name.charAt(i);
if( !safeName ) {
if( Character.isLetterOrDigit(c) || c == '-' || c == ' ') {
if( str.length() > 0 || Character.isLetter(c) ) {
str.append(c);
}
}
}
else {
if( (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' ) {
if( str.length() > 0 || Character.isLetter(c) ) {
str.append(c);
}
}
}
}
if( str.length() < 1 ) {
return makeUpName(name);
}
name = str.toString();
while( !Character.isLetterOrDigit(name.charAt(name.length()-1)) ) {
if( name.length() < 2 ) {
return makeUpName(name);
}
name = name.substring(0, name.length()-1);
}
if( serverExists(name) ) {
return makeUpName(name);
}
return name;
}
}
| |
package co.touchlab.android.threading.tasks;
import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.PriorityQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import co.touchlab.android.threading.utils.UiThreadContext;
/**
* Created by kgalligan on 11/30/14.
*/
public abstract class BaseTaskQueue
{
protected final Application application;
protected final Handler handler;
protected final QueueWrapper<Task> tasks;
private Task currentTask;
protected final ExecutorService executorService = Executors
.newSingleThreadExecutor(new ThreadFactory()
{
@Override
public Thread newThread(Runnable r)
{
return new Thread(r);
}
});
private List<QueueListener> listeners = new ArrayList<QueueListener>();
private boolean startedCalled = false;
public BaseTaskQueue(Application application, QueueWrapper<Task> queueWrapper)
{
this.application = application;
tasks = queueWrapper;
handler = new QueueHandler(Looper.getMainLooper());
}
protected interface QueueWrapper <T>
{
T poll();
void offer(T task);
Collection<T> all();
void remove(T task);
}
public int countTasks()
{
return tasks.all().size() + (currentTask == null ? 0 : 1);
}
public void addListener(QueueListener listener)
{
listeners.add(listener);
}
public void clearListeners()
{
listeners.clear();
}
protected void insertTask(Task task)
{
UiThreadContext.assertUiThread();
tasks.offer(task);
resetPollRunnable();
}
public void remove(Task task)
{
tasks.remove(task);
}
protected void resetPollRunnable()
{
handler.removeMessages(QueueHandler.POLL_TASK);
handler.sendMessage(handler.obtainMessage(QueueHandler.POLL_TASK));
}
protected class QueueHandler extends Handler
{
static final int INSERT_TASK = 0;
static final int POLL_TASK = 1;
public static final int POST_EXE = 2;
static final int THROW = 3;
private QueueHandler(Looper looper)
{
super(looper);
}
@Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case INSERT_TASK:
insertTask((Task) msg.obj);
break;
case POLL_TASK:
if(currentTask != null)
{
return;
}
Task task = tasks.poll();
if(task != null)
{
currentTask = task;
if(! startedCalled)
{
startedCalled = true;
for(QueueListener listener : listeners)
{
listener.queueStarted(BaseTaskQueue.this);
}
}
for(QueueListener listener : listeners)
{
listener.taskStarted(BaseTaskQueue.this, task);
}
runTask(task);
}
else
{
callQueueFinished();
}
break;
case POST_EXE:
Task tempTask = currentTask;
currentTask = null;
finishTask(msg, tempTask);
for(QueueListener listener : listeners)
{
listener.taskFinished(BaseTaskQueue.this, tempTask);
}
break;
case THROW:
Throwable cause = (Throwable) msg.obj;
if(cause instanceof RuntimeException)
{
throw (RuntimeException) cause;
}
else if(cause instanceof Error)
{
throw (Error) cause;
}
else
{
throw new RuntimeException(cause);
}
default:
otherOperations(msg);
}
}
}
protected void callQueueFinished()
{
for(QueueListener listener : listeners)
{
listener.queueFinished(this);
}
startedCalled = false;
}
public TaskQueueState copyState()
{
UiThreadContext.assertUiThread();
PriorityQueue<Task> commands = new PriorityQueue<Task>(tasks.all());
List<Task> commandList = new ArrayList<Task>();
while(! commands.isEmpty())
{
commandList.add(commands.poll());
}
return new TaskQueueState(commandList, currentTask);
}
public static class TaskQueueState
{
List<Task> queued;
Task currentTask;
public TaskQueueState(List<Task> queued, Task currentTask)
{
this.queued = queued;
this.currentTask = currentTask;
}
public List<Task> getQueued()
{
return queued;
}
public Task getCurrentTask()
{
return currentTask;
}
}
protected abstract void runTask(Task task);
protected abstract void finishTask(Message msg, Task task);
protected void otherOperations(Message msg)
{
}
public interface QueueQuery
{
void query(BaseTaskQueue queue, Task task);
}
public interface QueueListener
{
void queueStarted(BaseTaskQueue queue);
void queueFinished(BaseTaskQueue queue);
void taskStarted(BaseTaskQueue queue, Task task);
void taskFinished(BaseTaskQueue queue, Task task);
}
/**
* Query existing tasks. Call on main thread only.
*
* @param queueQuery
*/
public void query(QueueQuery queueQuery)
{
UiThreadContext.assertUiThread();
for(Task task : tasks.all())
{
queueQuery.query(this, task);
}
if(currentTask != null)
{
queueQuery.query(this, currentTask);
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.timelineservice.collector;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.service.CompositeService;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.server.timelineservice.storage.TimelineWriter;
import org.apache.hadoop.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class that manages adding and removing collectors and their lifecycle. It
* provides thread safety access to the collectors inside.
*
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public class TimelineCollectorManager extends CompositeService {
private static final Logger LOG =
LoggerFactory.getLogger(TimelineCollectorManager.class);
private TimelineWriter writer;
private ScheduledExecutorService writerFlusher;
private int flushInterval;
private boolean writerFlusherRunning;
@Override
protected void serviceInit(Configuration conf) throws Exception {
writer = createTimelineWriter(conf);
writer.init(conf);
// create a single dedicated thread for flushing the writer on a periodic
// basis
writerFlusher = Executors.newSingleThreadScheduledExecutor();
flushInterval = conf.getInt(
YarnConfiguration.
TIMELINE_SERVICE_WRITER_FLUSH_INTERVAL_SECONDS,
YarnConfiguration.
DEFAULT_TIMELINE_SERVICE_WRITER_FLUSH_INTERVAL_SECONDS);
super.serviceInit(conf);
}
private TimelineWriter createTimelineWriter(final Configuration conf) {
String timelineWriterClassName = conf.get(
YarnConfiguration.TIMELINE_SERVICE_WRITER_CLASS,
YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WRITER_CLASS);
LOG.info("Using TimelineWriter: " + timelineWriterClassName);
try {
Class<?> timelineWriterClazz = Class.forName(timelineWriterClassName);
if (TimelineWriter.class.isAssignableFrom(timelineWriterClazz)) {
return (TimelineWriter) ReflectionUtils.newInstance(
timelineWriterClazz, conf);
} else {
throw new YarnRuntimeException("Class: " + timelineWriterClassName
+ " not instance of " + TimelineWriter.class.getCanonicalName());
}
} catch (ClassNotFoundException e) {
throw new YarnRuntimeException("Could not instantiate TimelineWriter: "
+ timelineWriterClassName, e);
}
}
@Override
protected void serviceStart() throws Exception {
super.serviceStart();
if (writer != null) {
writer.start();
}
// schedule the flush task
writerFlusher.scheduleAtFixedRate(new WriterFlushTask(writer),
flushInterval, flushInterval, TimeUnit.SECONDS);
writerFlusherRunning = true;
}
// access to this map is synchronized with the map itself
private final Map<ApplicationId, TimelineCollector> collectors =
Collections.synchronizedMap(
new HashMap<ApplicationId, TimelineCollector>());
public TimelineCollectorManager(String name) {
super(name);
}
protected TimelineWriter getWriter() {
return writer;
}
/**
* Put the collector into the collection if an collector mapped by id does
* not exist.
*
* @param appId Application Id for which collector needs to be put.
* @param collector timeline collector to be put.
* @throws YarnRuntimeException if there was any exception in initializing
* and starting the app level service
* @return the collector associated with id after the potential put.
*/
public TimelineCollector putIfAbsent(ApplicationId appId,
TimelineCollector collector) {
TimelineCollector collectorInTable = null;
synchronized (collectors) {
collectorInTable = collectors.get(appId);
if (collectorInTable == null) {
try {
// initialize, start, and add it to the collection so it can be
// cleaned up when the parent shuts down
collector.init(getConfig());
collector.setWriter(writer);
collector.start();
collectors.put(appId, collector);
LOG.info("the collector for " + appId + " was added");
collectorInTable = collector;
postPut(appId, collectorInTable);
} catch (Exception e) {
throw new YarnRuntimeException(e);
}
} else {
LOG.info("the collector for " + appId + " already exists!");
}
}
return collectorInTable;
}
/**
* Callback handler for the timeline collector manager when a collector has
* been added into the collector map.
* @param appId Application id of the collector.
* @param collector The actual timeline collector that has been added.
*/
public void postPut(ApplicationId appId, TimelineCollector collector) {
doPostPut(appId, collector);
collector.setReadyToAggregate();
}
/**
* A template method that will be called by
* {@link #postPut(ApplicationId, TimelineCollector)}.
* @param appId Application id of the collector.
* @param collector The actual timeline collector that has been added.
*/
protected void doPostPut(ApplicationId appId, TimelineCollector collector) {
}
/**
* Removes the collector for the specified id. The collector is also stopped
* as a result. If the collector does not exist, no change is made.
*
* @param appId Application Id to remove.
* @return whether it was removed successfully
*/
public boolean remove(ApplicationId appId) {
TimelineCollector collector = collectors.remove(appId);
if (collector == null) {
LOG.error("the collector for " + appId + " does not exist!");
} else {
synchronized (collector) {
postRemove(appId, collector);
// stop the service to do clean up
collector.stop();
}
LOG.info("The collector service for " + appId + " was removed");
}
return collector != null;
}
protected void postRemove(ApplicationId appId, TimelineCollector collector) {
}
/**
* Returns the collector for the specified id.
*
* @param appId Application Id for which we need to get the collector.
* @return the collector or null if it does not exist
*/
public TimelineCollector get(ApplicationId appId) {
return collectors.get(appId);
}
/**
* Returns whether the collector for the specified id exists in this
* collection.
* @param appId Application Id.
* @return true if collector for the app id is found, false otherwise.
*/
public boolean containsTimelineCollector(ApplicationId appId) {
return collectors.containsKey(appId);
}
@Override
protected void serviceStop() throws Exception {
if (collectors != null && collectors.size() > 0) {
synchronized (collectors) {
for (TimelineCollector c : collectors.values()) {
c.serviceStop();
}
}
}
// stop the flusher first
if (writerFlusher != null) {
writerFlusher.shutdown();
writerFlusherRunning = false;
if (!writerFlusher.awaitTermination(30, TimeUnit.SECONDS)) {
// in reality it should be ample time for the flusher task to finish
// even if it times out, writers may be able to handle closing in this
// situation fine
// proceed to close the writer
LOG.warn("failed to stop the flusher task in time. " +
"will still proceed to close the writer.");
}
}
if (writer != null) {
writer.close();
}
super.serviceStop();
}
@VisibleForTesting
boolean writerFlusherRunning() {
return writerFlusherRunning;
}
/**
* Task that invokes the flush operation on the timeline writer.
*/
private static class WriterFlushTask implements Runnable {
private final TimelineWriter writer;
public WriterFlushTask(TimelineWriter writer) {
this.writer = writer;
}
public void run() {
try {
// synchronize on the writer object to avoid flushing timeline
// entities placed on the buffer by synchronous putEntities
// requests.
synchronized (writer) {
writer.flush();
}
} catch (Throwable th) {
// we need to handle all exceptions or subsequent execution may be
// suppressed
LOG.error("exception during timeline writer flush!", th);
}
}
}
}
| |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.casemgmt.impl.model.instance;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import org.jbpm.casemgmt.api.model.instance.CaseFileInstance;
import org.jbpm.casemgmt.api.model.instance.CaseInstance;
import org.jbpm.casemgmt.api.model.instance.CaseMilestoneInstance;
import org.jbpm.casemgmt.api.model.instance.CaseRoleInstance;
import org.jbpm.casemgmt.api.model.instance.CaseStageInstance;
public class CaseInstanceImpl implements CaseInstance, Serializable {
private static final long serialVersionUID = 832035193857983082L;
private String caseId;
private String caseDescription;
private Collection<CaseStageInstance> caseStages;
private Collection<CaseMilestoneInstance> caseMilestones;
private Collection<CaseRoleInstance> caseRoles;
private CaseFileInstance caseFile;
private String caseDefinitionId;
private Integer status;
private String deploymentId;
private String owner;
private Date startedAt;
private Date completedAt;
private Long processInstanceId;
private String completionMessage;
private Date slaDueDate;
private Integer slaCompliance;
public CaseInstanceImpl() {
}
public CaseInstanceImpl(String caseId, String caseDescription, Collection<CaseStageInstance> caseStages, Collection<CaseMilestoneInstance> caseMilestones, Collection<CaseRoleInstance> caseRoles, CaseFileInstance caseFile) {
this.caseId = caseId;
this.caseDescription = caseDescription;
this.caseStages = caseStages;
this.caseMilestones = caseMilestones;
this.caseRoles = caseRoles;
this.caseFile = caseFile;
}
/**
* Constructor to be used mainly by persistence provider to create instances automatically
* @param caseId
* @param caseDescription
*/
public CaseInstanceImpl(String caseId, String caseDescription, String caseDefinitionId, Integer status, String deploymentId, String owner, Date startedAt, Date completedAt, Long processInstanceId, String completionMessage, Date slaDueDate, Integer slaCompliance) {
this.caseId = caseId;
this.caseDescription = caseDescription;
this.caseDefinitionId = caseDefinitionId;
this.status = status;
this.deploymentId = deploymentId;
this.owner = owner;
this.startedAt = startedAt;
this.completedAt = completedAt;
this.processInstanceId = processInstanceId;
this.completionMessage = completionMessage;
this.slaDueDate = slaDueDate;
this.slaCompliance = slaCompliance;
}
@Override
public String getCaseId() {
return caseId;
}
@Override
public String getCaseDescription() {
return caseDescription;
}
@Override
public Collection<CaseStageInstance> getCaseStages() {
return caseStages;
}
@Override
public Collection<CaseMilestoneInstance> getCaseMilestones() {
return caseMilestones;
}
@Override
public Collection<CaseRoleInstance> getCaseRoles() {
return caseRoles;
}
@Override
public CaseFileInstance getCaseFile() {
return caseFile;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Date getStartedAt() {
return startedAt;
}
public void setStartedAt(Date startedAt) {
this.startedAt = startedAt;
}
public Long getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(Long processInstanceId) {
this.processInstanceId = processInstanceId;
}
public void setCaseId(String caseId) {
this.caseId = caseId;
}
public void setCaseDescription(String caseDescription) {
this.caseDescription = caseDescription;
}
public void setCaseStages(Collection<CaseStageInstance> caseStages) {
this.caseStages = caseStages;
}
public void setCaseMilestones(Collection<CaseMilestoneInstance> caseMilestones) {
this.caseMilestones = caseMilestones;
}
public void setCaseRoles(Collection<CaseRoleInstance> caseRoles) {
this.caseRoles = caseRoles;
}
public void setCaseFile(CaseFileInstance caseFile) {
this.caseFile = caseFile;
}
public Date getCompletedAt() {
return completedAt;
}
public void setCompletedAt(Date completedAt) {
this.completedAt = completedAt;
}
public String getCompletionMessage() {
return completionMessage;
}
public void setCompletionMessage(String completionMessage) {
this.completionMessage = completionMessage;
}
public Date getSlaDueDate() {
return slaDueDate;
}
public void setSlaDueDate(Date slaDueDate) {
this.slaDueDate = slaDueDate;
}
public Integer getSlaCompliance() {
return slaCompliance;
}
public void setSlaCompliance(Integer slaCompliance) {
this.slaCompliance = slaCompliance;
}
@Override
public String toString() {
return "CaseInstanceImpl [caseId=" + caseId + ", status=" + status + ", deploymentId=" + deploymentId + ", owner=" + owner + ", processInstanceId=" + processInstanceId + "]";
}
}
| |
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.remote.worker;
import static com.google.devtools.build.lib.remote.util.Utils.getFromFuture;
import build.bazel.remote.execution.v2.Digest;
import build.bazel.remote.execution.v2.RequestMetadata;
import com.google.bytestream.ByteStreamGrpc.ByteStreamImplBase;
import com.google.bytestream.ByteStreamProto.ReadRequest;
import com.google.bytestream.ByteStreamProto.ReadResponse;
import com.google.bytestream.ByteStreamProto.WriteRequest;
import com.google.bytestream.ByteStreamProto.WriteResponse;
import com.google.common.flogger.GoogleLogger;
import com.google.devtools.build.lib.remote.Chunker;
import com.google.devtools.build.lib.remote.common.CacheNotFoundException;
import com.google.devtools.build.lib.remote.common.RemoteActionExecutionContext;
import com.google.devtools.build.lib.remote.util.DigestUtil;
import com.google.devtools.build.lib.remote.util.TracingMetadataUtils;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import io.grpc.Status;
import io.grpc.protobuf.StatusProto;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import javax.annotation.Nullable;
/** A basic implementation of a {@link ByteStreamImplBase} service. */
final class ByteStreamServer extends ByteStreamImplBase {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
private final OnDiskBlobStoreCache cache;
private final Path workPath;
private final DigestUtil digestUtil;
@Nullable
static Digest parseDigestFromResourceName(String resourceName) {
try {
String[] tokens = resourceName.split("/");
if (tokens.length < 2) {
return null;
}
String hash = tokens[tokens.length - 2];
long size = Long.parseLong(tokens[tokens.length - 1]);
return DigestUtil.buildDigest(hash, size);
} catch (NumberFormatException e) {
return null;
}
}
public ByteStreamServer(OnDiskBlobStoreCache cache, Path workPath, DigestUtil digestUtil) {
this.cache = cache;
this.workPath = workPath;
this.digestUtil = digestUtil;
}
@Override
public void read(ReadRequest request, StreamObserver<ReadResponse> responseObserver) {
RequestMetadata meta = TracingMetadataUtils.fromCurrentContext();
RemoteActionExecutionContext context = RemoteActionExecutionContext.create(meta);
Digest digest = parseDigestFromResourceName(request.getResourceName());
if (digest == null) {
responseObserver.onError(
StatusUtils.invalidArgumentError(
"resource_name",
"Failed parsing digest from resource_name:" + request.getResourceName()));
}
try {
// This still relies on the blob size to be small enough to fit in memory.
// TODO(olaola): refactor to fix this if the need arises.
Chunker c =
Chunker.builder().setInput(getFromFuture(cache.downloadBlob(context, digest))).build();
while (c.hasNext()) {
responseObserver.onNext(
ReadResponse.newBuilder().setData(c.next().getData()).build());
}
responseObserver.onCompleted();
} catch (CacheNotFoundException e) {
responseObserver.onError(StatusUtils.notFoundError(digest));
} catch (Exception e) {
logger.atWarning().withCause(e).log("Read request failed");
responseObserver.onError(StatusUtils.internalError(e));
}
}
@Override
public StreamObserver<WriteRequest> write(final StreamObserver<WriteResponse> responseObserver) {
RequestMetadata meta = TracingMetadataUtils.fromCurrentContext();
RemoteActionExecutionContext context = RemoteActionExecutionContext.create(meta);
Path temp = workPath.getRelative("upload").getRelative(UUID.randomUUID().toString());
try {
FileSystemUtils.createDirectoryAndParents(temp.getParentDirectory());
FileSystemUtils.createEmptyFile(temp);
} catch (IOException e) {
logger.atSevere().withCause(e).log("Failed to create temporary file for upload");
responseObserver.onError(StatusUtils.internalError(e));
// We need to make sure that subsequent onNext or onCompleted calls don't make any further
// calls on the responseObserver after the onError above, so we return a no-op observer.
return new NoOpStreamObserver<>();
}
return new StreamObserver<WriteRequest>() {
private Digest digest;
private long offset;
private String resourceName;
private boolean closed;
@Override
public void onNext(WriteRequest request) {
if (closed) {
return;
}
if (digest == null) {
resourceName = request.getResourceName();
digest = parseDigestFromResourceName(resourceName);
}
if (digest == null) {
responseObserver.onError(
StatusUtils.invalidArgumentError(
"resource_name",
"Failed parsing digest from resource_name: " + request.getResourceName()));
closed = true;
return;
}
if (offset == 0) {
if (cache.containsKey(digest)) {
responseObserver.onNext(
WriteResponse.newBuilder().setCommittedSize(digest.getSizeBytes()).build());
responseObserver.onCompleted();
closed = true;
return;
}
}
if (request.getWriteOffset() != offset) {
responseObserver.onError(
StatusUtils.invalidArgumentError(
"write_offset",
"Expected: " + offset + ", received: " + request.getWriteOffset()));
closed = true;
return;
}
if (!request.getResourceName().isEmpty()
&& !request.getResourceName().equals(resourceName)) {
responseObserver.onError(
StatusUtils.invalidArgumentError(
"resource_name",
"Expected: " + resourceName + ", received: " + request.getResourceName()));
closed = true;
return;
}
long size = request.getData().size();
if (size > 0) {
try (OutputStream out = temp.getOutputStream(true)) {
request.getData().writeTo(out);
} catch (IOException e) {
responseObserver.onError(StatusUtils.internalError(e));
closed = true;
return;
}
offset += size;
}
boolean shouldFinishWrite = offset == digest.getSizeBytes();
if (shouldFinishWrite != request.getFinishWrite()) {
responseObserver.onError(
StatusUtils.invalidArgumentError(
"finish_write",
"Expected:" + shouldFinishWrite + ", received: " + request.getFinishWrite()));
closed = true;
return;
}
}
@Override
public void onError(Throwable t) {
if (Status.fromThrowable(t).getCode() != Status.Code.CANCELLED) {
logger.atWarning().withCause(t).log("Write request failed remotely");
}
closed = true;
try {
temp.delete();
} catch (IOException e) {
logger.atWarning().withCause(e).log("Could not delete temp file");
}
}
@Override
public void onCompleted() {
if (closed) {
return;
}
if (digest == null || offset != digest.getSizeBytes()) {
responseObserver.onError(
StatusProto.toStatusRuntimeException(
com.google.rpc.Status.newBuilder()
.setCode(Status.Code.FAILED_PRECONDITION.value())
.setMessage("Request completed before all data was sent.")
.build()));
closed = true;
return;
}
try {
Digest d = digestUtil.compute(temp);
getFromFuture(cache.uploadFile(context, d, temp));
try {
temp.delete();
} catch (IOException e) {
logger.atWarning().withCause(e).log("Could not delete temp file");
}
if (!d.equals(digest)) {
responseObserver.onError(
StatusUtils.invalidArgumentError(
"resource_name",
"Received digest " + digest + " does not match computed digest " + d));
closed = true;
return;
}
responseObserver.onNext(WriteResponse.newBuilder().setCommittedSize(offset).build());
responseObserver.onCompleted();
} catch (Exception e) {
logger.atWarning().withCause(e).log("Write request failed");
responseObserver.onError(StatusUtils.internalError(e));
closed = true;
}
}
};
}
private static class NoOpStreamObserver<T> implements StreamObserver<T> {
@Override
public void onNext(T value) {
}
@Override
public void onError(Throwable t) {
}
@Override
public void onCompleted() {
}
}
}
| |
package org.apache.maven.artifact.versioning;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import java.util.NoSuchElementException;
/**
* Default implementation of artifact versioning.
*
* @author <a href="mailto:brett@apache.org">Brett Porter</a>
*/
public class DefaultArtifactVersion
implements ArtifactVersion
{
private Integer majorVersion;
private Integer minorVersion;
private Integer incrementalVersion;
private Integer buildNumber;
private String qualifier;
private ComparableVersion comparable;
public DefaultArtifactVersion( String version )
{
parseVersion( version );
}
@Override
public int hashCode()
{
return 11 + comparable.hashCode();
}
@Override
public boolean equals( Object other )
{
if ( this == other )
{
return true;
}
if ( !( other instanceof ArtifactVersion ) )
{
return false;
}
return compareTo( (ArtifactVersion) other ) == 0;
}
public int compareTo( ArtifactVersion otherVersion )
{
if ( otherVersion instanceof DefaultArtifactVersion )
{
return this.comparable.compareTo( ( (DefaultArtifactVersion) otherVersion ).comparable );
}
else
{
return compareTo( new DefaultArtifactVersion( otherVersion.toString() ) );
}
}
public int getMajorVersion()
{
return majorVersion != null ? majorVersion : 0;
}
public int getMinorVersion()
{
return minorVersion != null ? minorVersion : 0;
}
public int getIncrementalVersion()
{
return incrementalVersion != null ? incrementalVersion : 0;
}
public int getBuildNumber()
{
return buildNumber != null ? buildNumber : 0;
}
public String getQualifier()
{
return qualifier;
}
public final void parseVersion( String version )
{
comparable = new ComparableVersion( version );
int index = version.indexOf( '-' );
String part1;
String part2 = null;
if ( index < 0 )
{
part1 = version;
}
else
{
part1 = version.substring( 0, index );
part2 = version.substring( index + 1 );
}
if ( part2 != null )
{
try
{
if ( ( part2.length() == 1 ) || !part2.startsWith( "0" ) )
{
buildNumber = Integer.valueOf( part2 );
}
else
{
qualifier = part2;
}
}
catch ( NumberFormatException e )
{
qualifier = part2;
}
}
if ( ( !part1.contains( "." ) ) && !part1.startsWith( "0" ) )
{
try
{
majorVersion = Integer.valueOf( part1 );
}
catch ( NumberFormatException e )
{
// qualifier is the whole version, including "-"
qualifier = version;
buildNumber = null;
}
}
else
{
boolean fallback = false;
StringTokenizer tok = new StringTokenizer( part1, "." );
try
{
majorVersion = getNextIntegerToken( tok );
if ( tok.hasMoreTokens() )
{
minorVersion = getNextIntegerToken( tok );
}
if ( tok.hasMoreTokens() )
{
incrementalVersion = getNextIntegerToken( tok );
}
if ( tok.hasMoreTokens() )
{
qualifier = tok.nextToken();
fallback = Pattern.compile( "\\d+" ).matcher( qualifier ).matches();
}
// string tokenzier won't detect these and ignores them
if ( part1.contains( ".." ) || part1.startsWith( "." ) || part1.endsWith( "." ) )
{
fallback = true;
}
}
catch ( NumberFormatException e )
{
fallback = true;
}
if ( fallback )
{
// qualifier is the whole version, including "-"
qualifier = version;
majorVersion = null;
minorVersion = null;
incrementalVersion = null;
buildNumber = null;
}
}
}
private static Integer getNextIntegerToken( StringTokenizer tok )
{
try
{
String s = tok.nextToken();
if ( ( s.length() > 1 ) && s.startsWith( "0" ) )
{
throw new NumberFormatException( "Number part has a leading 0: '" + s + "'" );
}
return Integer.valueOf( s );
}
catch ( NoSuchElementException e )
{
throw new NumberFormatException( "Number is invalid" );
}
}
@Override
public String toString()
{
return comparable.toString();
}
}
| |
/*
* Copyright (C) 2012-2015 DataStax Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.driver.core;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.google.common.reflect.TypeToken;
import com.datastax.driver.core.exceptions.InvalidTypeException;
abstract class AbstractGettableByIndexData implements GettableByIndexData {
protected final ProtocolVersion protocolVersion;
protected AbstractGettableByIndexData(ProtocolVersion protocolVersion) {
this.protocolVersion = protocolVersion;
}
/**
* Returns the type for the value at index {@code i}.
*
* @param i the index of the type to fetch.
* @return the type of the value at index {@code i}.
*
* @throws IndexOutOfBoundsException if {@code i} is not a valid index.
*/
protected abstract DataType getType(int i);
/**
* Returns the name corresponding to the value at index {@code i}.
*
* @param i the index of the name to fetch.
* @return the name corresponding to the value at index {@code i}.
*
* @throws IndexOutOfBoundsException if {@code i} is not a valid index.
*/
protected abstract String getName(int i);
/**
* Returns the value at index {@code i}.
*
* @param i the index to fetch.
* @return the value at index {@code i}.
*
* @throws IndexOutOfBoundsException if {@code i} is not a valid index.
*/
protected abstract ByteBuffer getValue(int i);
// Note: we avoid having a vararg method to avoid the array allocation that comes with it.
protected void checkType(int i, DataType.Name name) {
DataType defined = getType(i);
if (name != defined.getName())
throw new InvalidTypeException(String.format("Value %s is of type %s", getName(i), defined));
}
protected DataType.Name checkType(int i, DataType.Name name1, DataType.Name name2) {
DataType defined = getType(i);
if (name1 != defined.getName() && name2 != defined.getName())
throw new InvalidTypeException(String.format("Value %s is of type %s", getName(i), defined));
return defined.getName();
}
protected DataType.Name checkType(int i, DataType.Name name1, DataType.Name name2, DataType.Name name3) {
DataType defined = getType(i);
if (name1 != defined.getName() && name2 != defined.getName() && name3 != defined.getName())
throw new InvalidTypeException(String.format("Value %s is of type %s", getName(i), defined));
return defined.getName();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isNull(int i) {
return getValue(i) == null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getBool(int i) {
checkType(i, DataType.Name.BOOLEAN);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return false;
return TypeCodec.BooleanCodec.instance.deserializeNoBoxing(value);
}
/**
* {@inheritDoc}
*/
@Override
public int getInt(int i) {
checkType(i, DataType.Name.INT);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return 0;
return TypeCodec.IntCodec.instance.deserializeNoBoxing(value);
}
/**
* {@inheritDoc}
*/
@Override
public long getLong(int i) {
checkType(i, DataType.Name.BIGINT, DataType.Name.COUNTER);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return 0L;
return TypeCodec.LongCodec.instance.deserializeNoBoxing(value);
}
/**
* {@inheritDoc}
*/
@Override
public Date getDate(int i) {
checkType(i, DataType.Name.TIMESTAMP);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return null;
return TypeCodec.DateCodec.instance.deserialize(value);
}
/**
* {@inheritDoc}
*/
@Override
public float getFloat(int i) {
checkType(i, DataType.Name.FLOAT);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return 0.0f;
return TypeCodec.FloatCodec.instance.deserializeNoBoxing(value);
}
/**
* {@inheritDoc}
*/
@Override
public double getDouble(int i) {
checkType(i, DataType.Name.DOUBLE);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return 0.0;
return TypeCodec.DoubleCodec.instance.deserializeNoBoxing(value);
}
/**
* {@inheritDoc}
*/
@Override
public ByteBuffer getBytesUnsafe(int i) {
ByteBuffer value = getValue(i);
if (value == null)
return null;
return value.duplicate();
}
/**
* {@inheritDoc}
*/
@Override
public ByteBuffer getBytes(int i) {
checkType(i, DataType.Name.BLOB);
return getBytesUnsafe(i);
}
/**
* {@inheritDoc}
*/
@Override
public String getString(int i) {
DataType.Name type = checkType(i, DataType.Name.VARCHAR,
DataType.Name.TEXT,
DataType.Name.ASCII);
ByteBuffer value = getValue(i);
if (value == null)
return null;
return type == DataType.Name.ASCII
? TypeCodec.StringCodec.asciiInstance.deserialize(value)
: TypeCodec.StringCodec.utf8Instance.deserialize(value);
}
/**
* {@inheritDoc}
*/
@Override
public BigInteger getVarint(int i) {
checkType(i, DataType.Name.VARINT);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return null;
return TypeCodec.BigIntegerCodec.instance.deserialize(value);
}
/**
* {@inheritDoc}
*/
@Override
public BigDecimal getDecimal(int i) {
checkType(i, DataType.Name.DECIMAL);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return null;
return TypeCodec.DecimalCodec.instance.deserialize(value);
}
/**
* {@inheritDoc}
*/
@Override
public UUID getUUID(int i) {
DataType.Name type = checkType(i, DataType.Name.UUID, DataType.Name.TIMEUUID);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return null;
return type == DataType.Name.UUID
? TypeCodec.UUIDCodec.instance.deserialize(value)
: TypeCodec.TimeUUIDCodec.instance.deserialize(value);
}
/**
* {@inheritDoc}
*/
@Override
public InetAddress getInet(int i) {
checkType(i, DataType.Name.INET);
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return null;
return TypeCodec.InetCodec.instance.deserialize(value);
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public <T> List<T> getList(int i, Class<T> elementsClass) {
DataType type = getType(i);
if (type.getName() != DataType.Name.LIST)
throw new InvalidTypeException(String.format("Column %s is not of list type", getName(i)));
Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
if (!elementsClass.isAssignableFrom(expectedClass))
throw new InvalidTypeException(String.format("Column %s is a list of %s (CQL type %s), cannot be retrieved as a list of %s", getName(i), expectedClass, type, elementsClass));
ByteBuffer value = getValue(i);
if (value == null)
return Collections.<T>emptyList();
return Collections.unmodifiableList((List<T>)type.codec(protocolVersion).deserialize(value));
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public <T> List<T> getList(int i, TypeToken<T> elementsType) {
DataType type = getType(i);
if (type.getName() != DataType.Name.LIST)
throw new InvalidTypeException(String.format("Column %s is not of list type", getName(i)));
DataType expectedType = type.getTypeArguments().get(0);
if (!expectedType.canBeDeserializedAs(elementsType))
throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a list of %s", getName(i), type, elementsType));
ByteBuffer value = getValue(i);
if (value == null)
return Collections.<T>emptyList();
return Collections.unmodifiableList((List<T>)type.codec(protocolVersion).deserialize(value));
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public <T> Set<T> getSet(int i, Class<T> elementsClass) {
DataType type = getType(i);
if (type.getName() != DataType.Name.SET)
throw new InvalidTypeException(String.format("Column %s is not of set type", getName(i)));
Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType;
if (!elementsClass.isAssignableFrom(expectedClass))
throw new InvalidTypeException(String.format("Column %s is a set of %s (CQL type %s), cannot be retrieved as a set of %s", getName(i), expectedClass, type, elementsClass));
ByteBuffer value = getValue(i);
if (value == null)
return Collections.<T>emptySet();
return Collections.unmodifiableSet((Set<T>)type.codec(protocolVersion).deserialize(value));
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public <T> Set<T> getSet(int i, TypeToken<T> elementsType) {
DataType type = getType(i);
if (type.getName() != DataType.Name.SET)
throw new InvalidTypeException(String.format("Column %s is not of set type", getName(i)));
DataType expectedType = type.getTypeArguments().get(0);
if (!expectedType.canBeDeserializedAs(elementsType))
throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a set of %s", getName(i), type, elementsType));
ByteBuffer value = getValue(i);
if (value == null)
return Collections.<T>emptySet();
return Collections.unmodifiableSet((Set<T>)type.codec(protocolVersion).deserialize(value));
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) {
DataType type = getType(i);
if (type.getName() != DataType.Name.MAP)
throw new InvalidTypeException(String.format("Column %s is not of map type", getName(i)));
Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType;
Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType;
if (!keysClass.isAssignableFrom(expectedKeysClass) || !valuesClass.isAssignableFrom(expectedValuesClass))
throw new InvalidTypeException(String.format("Column %s is a map of %s->%s (CQL type %s), cannot be retrieved as a map of %s->%s", getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass));
ByteBuffer value = getValue(i);
if (value == null)
return Collections.<K, V>emptyMap();
return Collections.unmodifiableMap((Map<K, V>)type.codec(protocolVersion).deserialize(value));
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) {
DataType type = getType(i);
if (type.getName() != DataType.Name.MAP)
throw new InvalidTypeException(String.format("Column %s is not of map type", getName(i)));
DataType expectedKeysType = type.getTypeArguments().get(0);
DataType expectedValuesType = type.getTypeArguments().get(1);
if (!expectedKeysType.canBeDeserializedAs(keysType) || !expectedValuesType.canBeDeserializedAs(valuesType))
throw new InvalidTypeException(String.format("Column %s has CQL type %s, cannot be retrieved as a map of %s->%s", getName(i), type, keysType, valuesType));
ByteBuffer value = getValue(i);
if (value == null)
return Collections.<K, V>emptyMap();
return Collections.unmodifiableMap((Map<K, V>)type.codec(protocolVersion).deserialize(value));
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public UDTValue getUDTValue(int i) {
DataType type = getType(i);
if (type.getName() != DataType.Name.UDT)
throw new InvalidTypeException(String.format("Column %s is not a UDT", getName(i)));
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return null;
// UDT always use the protocol V3 to encode values
return (UDTValue)type.codec(ProtocolVersion.V3).deserialize(value);
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public TupleValue getTupleValue(int i) {
DataType type = getType(i);
if (type.getName() != DataType.Name.TUPLE)
throw new InvalidTypeException(String.format("Column %s is not a tuple", getName(i)));
ByteBuffer value = getValue(i);
if (value == null || value.remaining() == 0)
return null;
// tuples always use the protocol V3 to encode values
return (TupleValue)type.codec(ProtocolVersion.V3).deserialize(value);
}
/**
* {@inheritDoc}
*/
@Override
public Object getObject(int i) {
ByteBuffer raw = getValue(i);
DataType type = getType(i);
if (raw == null)
switch (type.getName()) {
case LIST:
return Collections.emptyList();
case SET:
return Collections.emptySet();
case MAP:
return Collections.emptyMap();
default:
return null;
}
else
return type.deserialize(raw, protocolVersion);
}
}
| |
/*
* Copyright (C) 2004, 2005 Joe Walnes.
* Copyright (C) 2006, 2007, 2009, 2013 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 02. September 2004 by Joe Walnes
*/
package com.thoughtworks.xstream.io.path;
import com.thoughtworks.xstream.core.util.FastStack;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a path to a single node in the tree.
*
* <p>Two absolute paths can also be compared to calculate the relative path between them.
* A relative path can be applied to an absolute path to calculate another absolute path.</p>
*
* <p>Note that the paths are normally XPath compliant, so can be read by other XPath engines.
* However, {@link #toString()} will select a node list while {@link #explicit()} will always select
* an individual node. If the return type of the XPath evaluation is a node, the result will be the same,
* because XPath will then use the first element of the list. The following are examples of path
* expressions that the Path object supports:</p>
*
* <p>Note that the implementation does not take care if the paths are XPath compliant, it simply
* manages the values between the path separator. However, it normalizes the path if a path element
* ends with a selector for the first element (i.e. "[1]"). Those will be handled transparent i.e. two Paths
* are treated equal if one was created with path elements containing this selector and the other one
* without.</p>
*
* <p>The following are examples of path expressions that the Path object supports:</p>
* <ul>
* <li>/</li>
* <li>/some/node</li>
* <li>/a/b/c/b/a</li>
* <li>/a/b[1]/c[1]/b[1]/a[1]</li>
* <li>/some[3]/node[2]/a</li>
* <li>../../../another[3]/node</li>
* </ul>
*
* <h3>Example</h3>
*
* <pre>
* Path a = new Path("/html/body/div[1]/table[2]/tr[3]/td/div");
* Path b = new Path("/html/body/div/table[2]/tr[6]/td/form");
*
* Path relativePath = a.relativeTo(b); // produces: "../../../tr[6]/td/form"
* Path c = a.apply(relativePath); // same as Path b.
* </pre>
*
* @see PathTracker
*
* @author Joe Walnes
*/
public class Path {
private final String[] chunks;
private transient String pathAsString;
private transient String pathExplicit;
private static final Path DOT = new Path(new String[] {"."});
public Path(String pathAsString) {
// String.split() too slow. StringTokenizer too crappy.
List result = new ArrayList();
int currentIndex = 0;
int nextSeparator;
this.pathAsString = pathAsString;
while ((nextSeparator = pathAsString.indexOf('/', currentIndex)) != -1) {
// normalize explicit paths
result.add(normalize(pathAsString, currentIndex, nextSeparator));
currentIndex = nextSeparator + 1;
}
result.add(normalize(pathAsString,currentIndex,pathAsString.length()));
String[] arr = new String[result.size()];
result.toArray(arr);
chunks = arr;
}
private String normalize(String s, int start, int end) {
if (end - start > 3
&& s.charAt(end-3) == '['
&& s.charAt(end-2) == '1'
&& s.charAt(end-1) == ']') {
this.pathAsString = null;
return s.substring(start, end-3);
} else {
return s.substring(start, end);
}
}
public Path(String[] chunks) {
this.chunks = chunks;
}
public String toString() {
if (pathAsString == null) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < chunks.length; i++) {
if (i > 0) buffer.append('/');
buffer.append(chunks[i]);
}
pathAsString = buffer.toString();
}
return pathAsString;
}
public String explicit() {
if (pathExplicit == null) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < chunks.length; i++) {
if (i > 0) buffer.append('/');
String chunk = chunks[i];
buffer.append(chunk);
int length = chunk.length();
if (length > 0) {
char c = chunk.charAt(length-1);
if (c != ']' && c != '.') {
buffer.append("[1]");
}
}
}
pathExplicit = buffer.toString();
}
return pathExplicit;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Path)) return false;
final Path other = (Path) o;
if (chunks.length != other.chunks.length) return false;
for (int i = 0; i < chunks.length; i++) {
if (!chunks[i].equals(other.chunks[i])) return false;
}
return true;
}
public int hashCode() {
int result = 543645643;
for (int i = 0; i < chunks.length; i++) {
result = 29 * result + chunks[i].hashCode();
}
return result;
}
public Path relativeTo(Path that) {
int depthOfPathDivergence = depthOfPathDivergence(chunks, that.chunks);
String[] result = new String[chunks.length + that.chunks.length - 2 * depthOfPathDivergence];
int count = 0;
for (int i = depthOfPathDivergence; i < chunks.length; i++) {
result[count++] = "..";
}
for (int j = depthOfPathDivergence; j < that.chunks.length; j++) {
result[count++] = that.chunks[j];
}
if (count == 0) {
return DOT;
} else {
return new Path(result);
}
}
private int depthOfPathDivergence(String[] path1, String[] path2) {
int minLength = Math.min(path1.length, path2.length);
for (int i = 0; i < minLength; i++) {
if (!path1[i].equals(path2[i])) {
return i;
}
}
return minLength;
}
public Path apply(Path relativePath) {
FastStack absoluteStack = new FastStack(16);
for (int i = 0; i < chunks.length; i++) {
absoluteStack.push(chunks[i]);
}
for (int i = 0; i < relativePath.chunks.length; i++) {
String relativeChunk = relativePath.chunks[i];
if (relativeChunk.equals("..")) {
absoluteStack.pop();
} else if (!relativeChunk.equals(".")) {
absoluteStack.push(relativeChunk);
}
}
String[] result = new String[absoluteStack.size()];
for (int i = 0; i < result.length; i++) {
result[i] = (String) absoluteStack.get(i);
}
return new Path(result);
}
public boolean isAncestor(Path child) {
if (child == null || child.chunks.length < chunks.length) {
return false;
}
for (int i = 0; i < chunks.length; i++) {
if (!chunks[i].equals(child.chunks[i])) {
return false;
}
}
return true;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package javax.portlet.tck.portlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ResourceServingPortlet;
import javax.portlet.ResourceURL;
import javax.portlet.tck.beans.JSR286SpecTestCaseDetails;
import javax.portlet.tck.beans.TestLink;
import javax.portlet.tck.beans.TestResult;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHING2;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHING3;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL1;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL5;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL6;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL7;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL8;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL9;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET1;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET2;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET3;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET4;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET5;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET6;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET7;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET8;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET9;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE1;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE2;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE3;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE4;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE5;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE6;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE7;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE8;
import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE9;
import static javax.portlet.tck.constants.Constants.THREADID_ATTR;
import static javax.portlet.ResourceURL.PAGE;
import static javax.portlet.ResourceURL.PORTLET;
import static javax.portlet.ResourceURL.FULL;
/**
* This portlet implements several test cases for the JSR 362 TCK. The test case names are defined
* in the /src/main/resources/xml-resources/additionalTCs.xml file. The build process will integrate
* the test case names defined in the additionalTCs.xml file into the complete list of test case
* names for execution by the driver.
*
* This is the main portlet for the test cases. If the test cases call for events, this portlet will
* initiate the events, but not process them. The processing is done in the companion portlet
* AddlPortletTests_SPEC2_13_ResourceServingCache_event
*
* @author ahmed
*/
public class AddlPortletTests_SPEC2_13_ResourceServingCache
implements Portlet, ResourceServingPortlet {
@Override
public void init(PortletConfig config) throws PortletException {}
@Override
public void destroy() {}
@Override
public void processAction(ActionRequest portletReq, ActionResponse portletResp)
throws PortletException, IOException {
portletResp.setRenderParameters(portletReq.getParameterMap());
long tid = Thread.currentThread().getId();
portletReq.setAttribute(THREADID_ATTR, tid);
}
@Override
public void serveResource(ResourceRequest portletReq, ResourceResponse portletResp)
throws PortletException, IOException {
long tid = Thread.currentThread().getId();
portletReq.setAttribute(THREADID_ATTR, tid);
PrintWriter writer = portletResp.getWriter();
JSR286SpecTestCaseDetails tcd = new JSR286SpecTestCaseDetails();
String action = portletReq.getParameter("action");
if (action != null) {
if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_caching2")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_caching2 */
/* Details: "The portlet can use the setCacheability method to set */
/* the cache level for the ResourceURL" */
TestResult tr1 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHING2);
if (portletReq.getCacheability().equals(ResourceURL.FULL)) {
tr1.setTcSuccess(true);
}
tr1.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_caching3")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_caching3 */
/* Details: "If the cache level is not set, a generated resource URL */
/* has the cacheability of the request in which it was created" */
TestResult tr2 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHING3);
if (portletReq.getParameter("tr2") != null
&& portletReq.getParameter("tr2").equals(portletReq.getCacheability())) {
tr2.setTcSuccess(true);
}
tr2.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL1")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL1 */
/* Details: "If the cache level is set to FULL, the resource URL does */
/* not contain the current render parameters" */
TestResult tr3 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL1);
if (portletReq.getParameter("tr3") == null) {
tr3.setTcSuccess(true);
} else {
tr3.appendTcDetail(
"Failed because render parameter \"tr3\" is still present in FULL cacheability");
}
tr3.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL5")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL5 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, a resource URL with */
/* cacheability set to FULL may be generated" */
TestResult tr7 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL5);
try {
ResourceURL tr7_resourceURL = portletResp.createResourceURL();
tr7_resourceURL.setCacheability(FULL);
tr7.appendTcDetail("ResourceURL successfully created - " + tr7_resourceURL.toString());
tr7.setTcSuccess(true);
} catch (IllegalStateException e) {
tr7.setTcSuccess(false);
tr7.appendTcDetail(e.getMessage());
}
tr7.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL6")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL6 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, setting cacheability */
/* on a resource URL to PORTLET results in an an */
/* IllegalStateException" */
TestResult tr8 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL6);
try {
ResourceURL tr8_resourceURL = portletResp.createResourceURL();
tr8_resourceURL.setCacheability(PORTLET);
tr8.appendTcDetail("ResourceURL successfully created - " + tr8_resourceURL.toString());
} catch (IllegalStateException e) {
tr8.setTcSuccess(true);
tr8.appendTcDetail(e.getMessage());
}
tr8.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL7")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL7 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, setting cacheability */
/* on a resource URL to PAGE results in an an IllegalStateException" */
TestResult tr9 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL7);
try {
ResourceURL tr9_resourceURL = portletResp.createResourceURL();
tr9_resourceURL.setCacheability(PAGE);
tr9.appendTcDetail("ResourceURL successfully created - " + tr9_resourceURL.toString());
} catch (IllegalStateException e) {
tr9.setTcSuccess(true);
tr9.appendTcDetail(e.getMessage());
}
tr9.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL8")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL8 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, an attempt to create a */
/* render URL results in an an IllegalStateException" */
TestResult tr10 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL8);
try {
PortletURL tr10_renderURL = portletResp.createRenderURL();
tr10.appendTcDetail("RenderURL successfully created - " + tr10_renderURL.toString());
} catch (IllegalStateException e) {
tr10.setTcSuccess(true);
tr10.appendTcDetail(e.getMessage());
}
tr10.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL9")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL9 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, an attempt to create */
/* an action URL results in an an IllegalStateException" */
TestResult tr11 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL9);
try {
PortletURL tr11_actionURL = portletResp.createActionURL();
tr11.appendTcDetail("ActionURL successfully created - " + tr11_actionURL.toString());
} catch (IllegalStateException e) {
tr11.setTcSuccess(true);
tr11.appendTcDetail(e.getMessage());
}
tr11.writeTo(writer);
} else if (action
.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET1")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET1 */
/* Details: "If the cache level is set to PORTLET, the resource URL */
/* contains the current render parameters" */
TestResult tr12 = tcd
.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET1);
if (portletReq.getParameter("tr12") != null
&& portletReq.getParameter("tr12").equals("true")) {
tr12.setTcSuccess(true);
} else {
tr12.appendTcDetail("Render parameter \"tr12\" is not present in ResourceRequest");
}
tr12.writeTo(writer);
} else if (action
.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET2")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET2 */
/* Details: "If the cache level is set to PORTLET, the resource URL */
/* contains the current portlet mode" */
TestResult tr13 = tcd
.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET2);
if (portletReq.getParameter("tr13") != null
&& portletReq.getParameter("tr13").equals(portletReq.getPortletMode().toString())) {
tr13.setTcSuccess(true);
} else {
tr13.appendTcDetail("Failed because ResourceURL is not in " + portletReq.getPortletMode()
+ " portlet mode.");
}
tr13.writeTo(writer);
} else if (action
.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET3")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET3 */
/* Details: "If the cache level is set to PORTLET, the resource URL */
/* contains the current window state" */
TestResult tr14 = tcd
.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET3);
if (portletReq.getParameter("tr14") != null
&& portletReq.getParameter("tr14").equals(portletReq.getWindowState().toString())) {
tr14.setTcSuccess(true);
} else {
tr14.appendTcDetail("Failed because ResourceURL is not in " + portletReq.getWindowState()
+ " window state.");
}
tr14.writeTo(writer);
} else if (action
.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET4")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET4 */
/* Details: "If the cache level is set to PORTLET, the resource URL */
/* does not contain the current page state" */
TestResult tr15 = tcd
.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET4);
if (portletReq.getParameter("tr15") != null
&& portletReq.getParameter("tr15").equals("true")
&& portletReq.getParameter("tr15_windowState") != null && portletReq
.getParameter("tr15_windowState").equals(portletReq.getWindowState().toString())) {
tr15.setTcSuccess(true);
} else {
tr15.appendTcDetail("Failed because ResourceURL is not in " + portletReq.getWindowState()
+ " window state or render parameter \"tr15\" is missing");
}
tr15.writeTo(writer);
} else if (action
.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET5")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET5 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, a resource URL with */
/* cacheability set to FULL may be generated" */
TestResult tr16 = tcd
.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET5);
try {
ResourceURL tr16_resourceURL = portletResp.createResourceURL();
tr16_resourceURL.setCacheability(FULL);
tr16.appendTcDetail("ResourceURL successfully created - " + tr16_resourceURL.toString());
tr16.setTcSuccess(true);
} catch (IllegalStateException e) {
tr16.setTcSuccess(false);
tr16.appendTcDetail(e.getMessage());
}
tr16.writeTo(writer);
} else if (action
.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET6")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET6 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, a resource URL with */
/* cacheability set to PORTLET may be generated" */
TestResult tr17 = tcd
.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET6);
try {
ResourceURL tr17_resourceURL = portletResp.createResourceURL();
tr17_resourceURL.setCacheability(PORTLET);
tr17.appendTcDetail("ResourceURL successfully created - " + tr17_resourceURL.toString());
tr17.setTcSuccess(true);
} catch (IllegalStateException e) {
tr17.setTcSuccess(false);
tr17.appendTcDetail(e.getMessage());
}
tr17.writeTo(writer);
} else if (action
.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET7")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET7 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, setting */
/* cacheability on a resource URL to PAGE results in an an */
/* IllegalStateException" */
TestResult tr18 = tcd
.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET7);
try {
ResourceURL tr18_resourceURL = portletResp.createResourceURL();
tr18_resourceURL.setCacheability(PAGE);
tr18.appendTcDetail("ResourceURL successfully created - " + tr18_resourceURL.toString());
} catch (IllegalStateException e) {
tr18.setTcSuccess(true);
tr18.appendTcDetail(e.getMessage());
}
tr18.writeTo(writer);
} else if (action
.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET8")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET8 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, an attempt to */
/* create a render URL results in an an IllegalStateException" */
TestResult tr19 = tcd
.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET8);
try {
PortletURL tr19_renderURL = portletResp.createRenderURL();
tr19.appendTcDetail("RenderURL successfully created - " + tr19_renderURL.toString());
} catch (IllegalStateException e) {
tr19.setTcSuccess(true);
tr19.appendTcDetail(e.getMessage());
}
tr19.writeTo(writer);
} else if (action
.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET9")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET9 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, an attempt to */
/* create an action URL results in an an IllegalStateException" */
TestResult tr20 = tcd
.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET9);
try {
PortletURL tr20_actionURL = portletResp.createActionURL();
tr20.appendTcDetail("ActionURL successfully created - " + tr20_actionURL.toString());
} catch (IllegalStateException e) {
tr20.setTcSuccess(true);
tr20.appendTcDetail(e.getMessage());
}
tr20.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE1")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE1 */
/* Details: "If the cache level is set to PAGE, the resource URL */
/* contains the current render parameters" */
TestResult tr21 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE1);
if (portletReq.getParameter("tr21") != null
&& portletReq.getParameter("tr21").equals("true")) {
tr21.setTcSuccess(true);
} else {
tr21.appendTcDetail("Render parameter \"tr21\" is not present in ResourceRequest");
}
tr21.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE2")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE2 */
/* Details: "If the cache level is set to PAGE, the resource URL */
/* contains the current PAGE mode" */
TestResult tr22 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE2);
if (portletReq.getParameter("tr22") != null
&& portletReq.getParameter("tr22").equals(portletReq.getPortletMode().toString())) {
tr22.setTcSuccess(true);
} else {
tr22.appendTcDetail("Failed because ResourceURL is not in " + portletReq.getPortletMode()
+ " portlet mode.");
}
tr22.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE3")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE3 */
/* Details: "If the cache level is set to PAGE, the resource URL */
/* contains the current window state" */
TestResult tr23 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE3);
if (portletReq.getParameter("tr23") != null
&& portletReq.getParameter("tr23").equals(portletReq.getWindowState().toString())) {
tr23.setTcSuccess(true);
} else {
tr23.appendTcDetail("Failed because ResourceURL is not in " + portletReq.getWindowState()
+ " window state.");
}
tr23.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE4")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE4 */
/* Details: "If the cache level is set to PAGE, the resource URL */
/* contains the current page state" */
TestResult tr24 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE4);
if (portletReq.getParameter("tr24") != null
&& portletReq.getParameter("tr24").equals("true")
&& portletReq.getParameter("tr24_windowState") != null && portletReq
.getParameter("tr24_windowState").equals(portletReq.getWindowState().toString())) {
tr24.setTcSuccess(true);
} else {
tr24.appendTcDetail("Failed because ResourceURL is not in " + portletReq.getWindowState()
+ " window state or render parameter \"tr24\" is missing");
}
tr24.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE5")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE5 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, a resource URL with */
/* cacheability set to FULL may be generated" */
TestResult tr25 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE5);
try {
ResourceURL tr25_resourceURL = portletResp.createResourceURL();
tr25_resourceURL.setCacheability(FULL);
tr25.appendTcDetail("ResourceURL successfully created - " + tr25_resourceURL.toString());
tr25.setTcSuccess(true);
} catch (IllegalStateException e) {
tr25.setTcSuccess(false);
tr25.appendTcDetail(e.getMessage());
}
tr25.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE6")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE6 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, a resource URL with */
/* cacheability set to PORTLET may be generated" */
TestResult tr26 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE6);
try {
ResourceURL tr26_resourceURL = portletResp.createResourceURL();
tr26_resourceURL.setCacheability(PORTLET);
tr26.appendTcDetail("ResourceURL successfully created - " + tr26_resourceURL.toString());
tr26.setTcSuccess(true);
} catch (IllegalStateException e) {
tr26.setTcSuccess(false);
tr26.appendTcDetail(e.getMessage());
}
tr26.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE7")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE7 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, a resource URL with */
/* cacheability set to PAGE may be generated" */
TestResult tr27 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE7);
try {
ResourceURL tr27_resourceURL = portletResp.createResourceURL();
tr27_resourceURL.setCacheability(PAGE);
tr27.appendTcDetail("ResourceURL successfully created - " + tr27_resourceURL.toString());
tr27.setTcSuccess(true);
} catch (IllegalStateException e) {
tr27.setTcSuccess(false);
tr27.appendTcDetail(e.getMessage());
}
tr27.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE8")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE8 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, a render URL may be */
/* generated" */
TestResult tr28 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE8);
try {
PortletURL tr28_renderURL = portletResp.createRenderURL();
tr28.appendTcDetail("ResourceURL successfully created - " + tr28_renderURL.toString());
tr28.setTcSuccess(true);
} catch (IllegalStateException e) {
tr28.setTcSuccess(false);
tr28.appendTcDetail(e.getMessage());
}
tr28.writeTo(writer);
} else if (action.equals("V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE9")) {
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE9 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, an action URL may be */
/* generated" */
TestResult tr29 =
tcd.getTestResultFailed(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE9);
try {
PortletURL tr29_actionURL = portletResp.createActionURL();
tr29.appendTcDetail("ResourceURL successfully created - " + tr29_actionURL.toString());
tr29.setTcSuccess(true);
} catch (IllegalStateException e) {
tr29.setTcSuccess(false);
tr29.appendTcDetail(e.getMessage());
}
tr29.writeTo(writer);
}
}
}
@Override
public void render(RenderRequest portletReq, RenderResponse portletResp)
throws PortletException, IOException {
long tid = Thread.currentThread().getId();
portletReq.setAttribute(THREADID_ATTR, tid);
PrintWriter writer = portletResp.getWriter();
writer.write("<script type=\"text/javascript\" id=\"getResourceCall\">");
writer.write(" function getResource(testCase, URL) {");
writer.write(" var xhr = new XMLHttpRequest();");
writer.write(" xhr.onreadystatechange=function() {");
writer.write(" if (xhr.readyState==4 && xhr.status==200) {");
writer.write(" document.getElementById(testCase).innerHTML = xhr.responseText;");
writer.write(" }");
writer.write(" };");
writer.write(" xhr.open(\"POST\",URL,true);");
writer.write(" xhr.send();");
writer.write(" }");
writer.write("</script>");
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_caching2 */
/* Details: "The portlet can use the setCacheability method to set */
/* the cache level for the ResourceURL" */
{
ResourceURL resurlTr1 = portletResp.createResourceURL();
resurlTr1.setCacheability(FULL);
resurlTr1.setParameter("action", "V2AddlPortletTests_SPEC2_13_ResourceServingCache_caching2");
writer.write("<DIV id=\"tr1_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr1_ResourceServingCache','" + resurlTr1.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_caching3 */
/* Details: "If the cache level is not set, a generated resource URL */
/* has the cacheability of the request in which it was created" */
{
ResourceURL resurlTr2 = portletResp.createResourceURL();
resurlTr2.setParameter("tr2", resurlTr2.getCacheability());
resurlTr2.setParameter("action", "V2AddlPortletTests_SPEC2_13_ResourceServingCache_caching3");
writer.write("<DIV id=\"tr2_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr2_ResourceServingCache','" + resurlTr2.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL1 */
/* Details: "If the cache level is set to FULL, the resource URL does */
/* not contain the current render parameters" */
{
if (portletReq.getParameter("tr3") == null) {
PortletURL purl = portletResp.createRenderURL();
purl.setParameter("tr3", "true");
TestLink tl =
new TestLink(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGFULL1, purl);
tl.writeTo(writer);
} else {
ResourceURL resurlTr3 = portletResp.createResourceURL();
resurlTr3.setCacheability(FULL);
resurlTr3.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL1");
writer.write("<DIV id=\"tr3_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr3_ResourceServingCache','" + resurlTr3.toString() + "');");
writer.write("</script>");
}
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL5 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, a resource URL with */
/* cacheability set to FULL may be generated" */
{
ResourceURL resurlTr7 = portletResp.createResourceURL();
resurlTr7.setCacheability(FULL);
resurlTr7.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL5");
writer.write("<DIV id=\"tr7_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr7_ResourceServingCache','" + resurlTr7.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL6 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, setting cacheability */
/* on a resource URL to PORTLET results in an an */
/* IllegalStateException" */
{
ResourceURL resurlTr8 = portletResp.createResourceURL();
resurlTr8.setCacheability(FULL);
resurlTr8.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL6");
writer.write("<DIV id=\"tr8_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr8_ResourceServingCache','" + resurlTr8.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL7 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, setting cacheability */
/* on a resource URL to PAGE results in an an IllegalStateException" */
{
ResourceURL resurlTr9 = portletResp.createResourceURL();
resurlTr9.setCacheability(FULL);
resurlTr9.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL7");
writer.write("<DIV id=\"tr9_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr9_ResourceServingCache','" + resurlTr9.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL8 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, an attempt to create a */
/* render URL results in an an IllegalStateException" */
{
ResourceURL resurlTr10 = portletResp.createResourceURL();
resurlTr10.setCacheability(FULL);
resurlTr10.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL8");
writer.write("<DIV id=\"tr10_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr10_ResourceServingCache','" + resurlTr10.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL9 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to FULL, an attempt to create */
/* an action URL results in an an IllegalStateException" */
{
ResourceURL resurlTr11 = portletResp.createResourceURL();
resurlTr11.setCacheability(FULL);
resurlTr11.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingFULL9");
writer.write("<DIV id=\"tr11_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr11_ResourceServingCache','" + resurlTr11.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET1 */
/* Details: "If the cache level is set to PORTLET, the resource URL */
/* contains the current render parameters" */
{
if (portletReq.getParameter("tr12") == null) {
PortletURL purl = portletResp.createRenderURL();
purl.setParameter("tr12", "true");
TestLink tl =
new TestLink(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET1, purl);
tl.writeTo(writer);
} else {
ResourceURL resurlTr12 = portletResp.createResourceURL();
resurlTr12.setCacheability(PORTLET);
resurlTr12.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET1");
writer.write("<DIV id=\"tr12_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr12_ResourceServingCache','" + resurlTr12.toString() + "');");
writer.write("</script>");
}
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET2 */
/* Details: "If the cache level is set to PORTLET, the resource URL */
/* contains the current portlet mode" */
{
ResourceURL resurlTr13 = portletResp.createResourceURL();
resurlTr13.setCacheability(PORTLET);
resurlTr13.setParameter("tr13", portletReq.getPortletMode().toString());
resurlTr13.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET2");
writer.write("<DIV id=\"tr13_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr13_ResourceServingCache','" + resurlTr13.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET3 */
/* Details: "If the cache level is set to PORTLET, the resource URL */
/* contains the current window state" */
{
ResourceURL resurlTr14 = portletResp.createResourceURL();
resurlTr14.setCacheability(PORTLET);
resurlTr14.setParameter("tr14", portletReq.getWindowState().toString());
resurlTr14.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET3");
writer.write("<DIV id=\"tr14_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr14_ResourceServingCache','" + resurlTr14.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET4 */
/* Details: "If the cache level is set to PORTLET, the resource URL */
/* does not contain the current page state" */
{
if (portletReq.getParameter("tr15") == null) {
PortletURL purl = portletResp.createRenderURL();
purl.setParameter("tr15", "true");
TestLink tl =
new TestLink(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPORTLET4, purl);
tl.writeTo(writer);
} else {
ResourceURL resurlTr15 = portletResp.createResourceURL();
resurlTr15.setCacheability(PORTLET);
resurlTr15.setParameter("tr15_windowState", portletReq.getWindowState().toString());
resurlTr15.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET4");
writer.write("<DIV id=\"tr15_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr15_ResourceServingCache','" + resurlTr15.toString() + "');");
writer.write("</script>");
}
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET5 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, a resource URL with */
/* cacheability set to FULL may be generated" */
{
ResourceURL resurlTr16 = portletResp.createResourceURL();
resurlTr16.setCacheability(PORTLET);
resurlTr16.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET5");
writer.write("<DIV id=\"tr16_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr16_ResourceServingCache','" + resurlTr16.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET6 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, a resource URL with */
/* cacheability set to PORTLET may be generated" */
{
ResourceURL resurlTr17 = portletResp.createResourceURL();
resurlTr17.setCacheability(PORTLET);
resurlTr17.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET6");
writer.write("<DIV id=\"tr17_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr17_ResourceServingCache','" + resurlTr17.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET7 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, setting */
/* cacheability on a resource URL to PAGE results in an an */
/* IllegalStateException" */
{
ResourceURL resurlTr18 = portletResp.createResourceURL();
resurlTr18.setCacheability(PORTLET);
resurlTr18.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET7");
writer.write("<DIV id=\"tr18_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr18_ResourceServingCache','" + resurlTr18.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET8 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, an attempt to */
/* create a render URL results in an an IllegalStateException" */
{
ResourceURL resurlTr19 = portletResp.createResourceURL();
resurlTr19.setCacheability(PORTLET);
resurlTr19.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET8");
writer.write("<DIV id=\"tr19_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr19_ResourceServingCache','" + resurlTr19.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET9 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PORTLET, an attempt to */
/* create an action URL results in an an IllegalStateException" */
{
ResourceURL resurlTr20 = portletResp.createResourceURL();
resurlTr20.setCacheability(PORTLET);
resurlTr20.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPORTLET9");
writer.write("<DIV id=\"tr20_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr20_ResourceServingCache','" + resurlTr20.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE1 */
/* Details: "If the cache level is set to PAGE, the resource URL */
/* contains the current render parameters" */
{
if (portletReq.getParameter("tr21") == null) {
PortletURL purl = portletResp.createRenderURL();
purl.setParameter("tr21", "true");
TestLink tl =
new TestLink(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE1, purl);
tl.writeTo(writer);
} else {
ResourceURL resurlTr21 = portletResp.createResourceURL();
resurlTr21.setCacheability(PORTLET);
resurlTr21.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE1");
writer.write("<DIV id=\"tr21_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr21_ResourceServingCache','" + resurlTr21.toString() + "');");
writer.write("</script>");
}
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE2 */
/* Details: "If the cache level is set to PAGE, the resource URL */
/* contains the current PAGE mode" */
{
ResourceURL resurlTr22 = portletResp.createResourceURL();
resurlTr22.setCacheability(PAGE);
resurlTr22.setParameter("tr22", portletReq.getPortletMode().toString());
resurlTr22.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE2");
writer.write("<DIV id=\"tr22_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr22_ResourceServingCache','" + resurlTr22.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE3 */
/* Details: "If the cache level is set to PAGE, the resource URL */
/* contains the current window state" */
{
ResourceURL resurlTr23 = portletResp.createResourceURL();
resurlTr23.setCacheability(PAGE);
resurlTr23.setParameter("tr23", portletReq.getWindowState().toString());
resurlTr23.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE3");
writer.write("<DIV id=\"tr23_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr23_ResourceServingCache','" + resurlTr23.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE4 */
/* Details: "If the cache level is set to PAGE, the resource URL */
/* contains the current page state" */
{
if (portletReq.getParameter("tr24") == null) {
PortletURL purl = portletResp.createRenderURL();
purl.setParameter("tr24", "true");
TestLink tl =
new TestLink(V2ADDLPORTLETTESTS_SPEC2_13_RESOURCESERVINGCACHE_CACHINGPAGE4, purl);
tl.writeTo(writer);
} else {
ResourceURL resurlTr24 = portletResp.createResourceURL();
resurlTr24.setCacheability(PAGE);
resurlTr24.setParameter("tr24_windowState", portletReq.getWindowState().toString());
resurlTr24.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE4");
writer.write("<DIV id=\"tr24_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr24_ResourceServingCache','" + resurlTr24.toString() + "');");
writer.write("</script>");
}
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE5 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, a resource URL with */
/* cacheability set to FULL may be generated" */
{
ResourceURL resurlTr25 = portletResp.createResourceURL();
resurlTr25.setCacheability(PAGE);
resurlTr25.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE5");
writer.write("<DIV id=\"tr25_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr25_ResourceServingCache','" + resurlTr25.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE6 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, a resource URL with */
/* cacheability set to PORTLET may be generated" */
{
ResourceURL resurlTr26 = portletResp.createResourceURL();
resurlTr26.setCacheability(PAGE);
resurlTr26.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE6");
writer.write("<DIV id=\"tr26_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr26_ResourceServingCache','" + resurlTr26.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE7 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, a resource URL with */
/* cacheability set to PAGE may be generated" */
{
ResourceURL resurlTr27 = portletResp.createResourceURL();
resurlTr27.setCacheability(PAGE);
resurlTr27.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE7");
writer.write("<DIV id=\"tr27_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr27_ResourceServingCache','" + resurlTr27.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE8 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, a render URL may be */
/* generated" */
{
ResourceURL resurlTr28 = portletResp.createResourceURL();
resurlTr28.setCacheability(PAGE);
resurlTr28.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE8");
writer.write("<DIV id=\"tr28_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr28_ResourceServingCache','" + resurlTr28.toString() + "');");
writer.write("</script>");
}
/* TestCase: V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE9 */
/* Details: "In a resource request resulting from triggering a */
/* resource URL with cacheability set to PAGE, an action URL may be */
/* generated" */
{
ResourceURL resurlTr29 = portletResp.createResourceURL();
resurlTr29.setCacheability(PAGE);
resurlTr29.setParameter("action",
"V2AddlPortletTests_SPEC2_13_ResourceServingCache_cachingPAGE9");
writer.write("<DIV id=\"tr29_ResourceServingCache\"></DIV>");
writer.write("<script type=\"text/javascript\">");
writer.write("getResource('tr29_ResourceServingCache','" + resurlTr29.toString() + "');");
writer.write("</script>");
}
}
}
| |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by:
// mojo/public/tools/bindings/mojom_bindings_generator.py
// For:
// services/service_manager/public/interfaces/connector.mojom
//
package org.chromium.service_manager.mojom;
import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.mojo.bindings.DeserializationException;
class PidReceiver_Internal {
public static final org.chromium.mojo.bindings.Interface.Manager<PidReceiver, PidReceiver.Proxy> MANAGER =
new org.chromium.mojo.bindings.Interface.Manager<PidReceiver, PidReceiver.Proxy>() {
public String getName() {
return "service_manager::mojom::PIDReceiver";
}
public int getVersion() {
return 0;
}
public Proxy buildProxy(org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) {
return new Proxy(core, messageReceiver);
}
public Stub buildStub(org.chromium.mojo.system.Core core, PidReceiver impl) {
return new Stub(core, impl);
}
public PidReceiver[] buildArray(int size) {
return new PidReceiver[size];
}
};
private static final int SET_PID_ORDINAL = 0;
static final class Proxy extends org.chromium.mojo.bindings.Interface.AbstractProxy implements PidReceiver.Proxy {
Proxy(org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) {
super(core, messageReceiver);
}
@Override
public void setPid(
int pid) {
PidReceiverSetPidParams _message = new PidReceiverSetPidParams();
_message.pid = pid;
getProxyHandler().getMessageReceiver().accept(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(SET_PID_ORDINAL)));
}
}
static final class Stub extends org.chromium.mojo.bindings.Interface.Stub<PidReceiver> {
Stub(org.chromium.mojo.system.Core core, PidReceiver impl) {
super(core, impl);
}
@Override
public boolean accept(org.chromium.mojo.bindings.Message message) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.NO_FLAG)) {
return false;
}
switch(header.getType()) {
case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_OR_CLOSE_PIPE_MESSAGE_ID:
return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRunOrClosePipe(
PidReceiver_Internal.MANAGER, messageWithHeader);
case SET_PID_ORDINAL: {
PidReceiverSetPidParams data =
PidReceiverSetPidParams.deserialize(messageWithHeader.getPayload());
getImpl().setPid(data.pid);
return true;
}
default:
return false;
}
} catch (org.chromium.mojo.bindings.DeserializationException e) {
System.err.println(e.toString());
return false;
}
}
@Override
public boolean acceptWithResponder(org.chromium.mojo.bindings.Message message, org.chromium.mojo.bindings.MessageReceiver receiver) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG)) {
return false;
}
switch(header.getType()) {
case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_MESSAGE_ID:
return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRun(
getCore(), PidReceiver_Internal.MANAGER, messageWithHeader, receiver);
default:
return false;
}
} catch (org.chromium.mojo.bindings.DeserializationException e) {
System.err.println(e.toString());
return false;
}
}
}
static final class PidReceiverSetPidParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public int pid;
private PidReceiverSetPidParams(int version) {
super(STRUCT_SIZE, version);
}
public PidReceiverSetPidParams() {
this(0);
}
public static PidReceiverSetPidParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static PidReceiverSetPidParams deserialize(java.nio.ByteBuffer data) {
if (data == null)
return null;
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static PidReceiverSetPidParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
PidReceiverSetPidParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
result = new PidReceiverSetPidParams(mainDataHeader.elementsOrVersion);
if (mainDataHeader.elementsOrVersion >= 0) {
result.pid = decoder0.readInt(8);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(pid, 8);
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (object == this)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
PidReceiverSetPidParams other = (PidReceiverSetPidParams) object;
if (this.pid!= other.pid)
return false;
return true;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = prime + getClass().hashCode();
result = prime * result + org.chromium.mojo.bindings.BindingsHelper.hashCode(pid);
return result;
}
}
}
| |
package de.craften.ui.swingmaterial;
import de.craften.ui.swingmaterial.util.FastGaussianBlur;
import org.jdesktop.core.animation.timing.KeyFrames;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
/**
* A renderer for Material shadows. Shadows are a sign of elevation, and help
* distinguishing elements inside a Material-based GUI.
*/
public class MaterialShadow {
/**
* The default offset between the border of the shadow and the top of a
* Material component.
*/
public static final int OFFSET_TOP = 10;
/**
* The default offset between the border of the shadow and the left of a
* Material component.
*/
public static final int OFFSET_LEFT = 20;
/**
* The default offset between the border of the shadow and the bottom of a
* Material component.
*/
public static final int OFFSET_BOTTOM = 20;
/**
* The default offset between the border of the shadow and the right of a
* Material component.
*/
public static final int OFFSET_RIGHT = 20;
private static KeyFrames<Float> opacity1 = new KeyFrames.Builder<>(0f)
.addFrame(0.12f, 1 / 5.0)
.addFrame(0.16f, 2 / 5.0)
.addFrame(0.19f, 3 / 5.0)
.addFrame(0.25f, 4 / 5.0)
.addFrame(0.30f, 5 / 5.0)
.build();
private static KeyFrames<Float> opacity2 = new KeyFrames.Builder<>(0f)
.addFrame(0.24f, 1 / 5.0)
.addFrame(0.23f, 2 / 5.0)
.addFrame(0.23f, 3 / 5.0)
.addFrame(0.22f, 4 / 5.0)
.addFrame(0.22f, 5 / 5.0)
.build();
private static KeyFrames<Float> radius1 = new KeyFrames.Builder<>(0f)
.addFrame(3f, 1 / 5.0)
.addFrame(6f, 2 / 5.0)
.addFrame(20f, 3 / 5.0)
.addFrame(28f, 4 / 5.0)
.addFrame(38f, 5 / 5.0)
.build();
private static KeyFrames<Float> radius2 = new KeyFrames.Builder<>(0f)
.addFrame(2f, 1 / 5.0)
.addFrame(6f, 2 / 5.0)
.addFrame(6f, 3 / 5.0)
.addFrame(10f, 4 / 5.0)
.addFrame(12f, 5 / 5.0)
.build();
private static KeyFrames<Float> offset1 = new KeyFrames.Builder<>(0f)
.addFrame(1f, 1 / 5.0)
.addFrame(3f, 2 / 5.0)
.addFrame(10f, 3 / 5.0)
.addFrame(14f, 4 / 5.0)
.addFrame(19f, 5 / 5.0)
.build();
private static KeyFrames<Float> offset2 = new KeyFrames.Builder<>(0f)
.addFrame(1f, 1 / 5.0)
.addFrame(3f, 2 / 5.0)
.addFrame(6f, 3 / 5.0)
.addFrame(10f, 4 / 5.0)
.addFrame(15f, 5 / 5.0)
.build();
/**
* Creates a {@link BufferedImage} containing a shadow projected from a
* square component of the given width and height.
*
* @param width the component's width, inpixels
* @param height the component's height, inpixels
* @param level the elevation level [0~5]
* @return A {@link BufferedImage} with the contents of the shadow for a
* circular component of the given radius.
*/
public static BufferedImage renderShadow(int width, int height, double level) {
return renderShadow(width, height, level, 3);
}
/**
* Creates a {@link BufferedImage} containing a shadow projected from a
* square component of the given width and height.
*
* @param width the component's width, inpixels
* @param height the component's height, inpixels
* @param level the elevation level [0~5]
* @param borderRadius an applicable radius to the border of the shadow
* @return A {@link BufferedImage} with the contents of the shadow for a
* circular component of the given radius.
*/
public static BufferedImage renderShadow(int width, int height, double level, int borderRadius) {
if (level < 0 || level > 5) {
throw new IllegalArgumentException("Shadow level must be between 1 and 5 (inclusive)");
}
BufferedImage shadow = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
if (width > 0 && height > 0 && level != 0) {
BufferedImage shadow2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = shadow.createGraphics();
g.setComposite(AlphaComposite.SrcOver);
makeShadow(shadow, opacity1.getInterpolatedValueAt(level / 5), radius1.getInterpolatedValueAt(level / 5),
0, offset1.getInterpolatedValueAt(level / 5), borderRadius);
makeShadow(shadow2, opacity2.getInterpolatedValueAt(level / 5), radius2.getInterpolatedValueAt(level / 5),
0, offset2.getInterpolatedValueAt(level / 5), borderRadius);
g.drawImage(shadow2, 0, 0, null);
g.dispose();
}
return shadow;
}
/**
* Creates a {@link BufferedImage} containing a shadow projected from a
* circular component of the given radius.
*
* @param radius the radius length, in pixels
* @param level the elevation level [0~5]
* @return A {@link BufferedImage} with the contents of the shadow for a
* circular component of the given radius.
*/
public static BufferedImage renderCircularShadow(int radius, double level) {
if (level < 0 || level > 5) {
throw new IllegalArgumentException("Shadow level must be between 1 and 5 (inclusive)");
}
BufferedImage shadow = new BufferedImage(radius, radius + OFFSET_TOP + OFFSET_BOTTOM, BufferedImage.TYPE_INT_ARGB);
if (level != 0) {
BufferedImage shadow2 = new BufferedImage(radius, radius + OFFSET_TOP + OFFSET_BOTTOM, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = shadow.createGraphics();
g.setComposite(AlphaComposite.SrcOver);
makeCircularShadow(shadow, opacity1.getInterpolatedValueAt(level / 5), radius1.getInterpolatedValueAt(level / 5),
0, offset1.getInterpolatedValueAt(level / 5));
makeCircularShadow(shadow2, opacity2.getInterpolatedValueAt(level / 5), radius2.getInterpolatedValueAt(level / 5),
0, offset2.getInterpolatedValueAt(level / 5));
g.drawImage(shadow2, 0, 0, null);
g.dispose();
}
return shadow;
}
private static void makeShadow(BufferedImage shadow, float opacity, float radius, float leftOffset, float topOffset, int borderRadius) {
Graphics2D g2 = shadow.createGraphics();
g2.setColor(new Color(0, 0, 0, opacity));
g2.fill(new RoundRectangle2D.Float(OFFSET_LEFT + leftOffset, OFFSET_TOP + topOffset,
shadow.getWidth() - OFFSET_LEFT - OFFSET_RIGHT, shadow.getHeight() - OFFSET_TOP - OFFSET_BOTTOM, borderRadius*2, borderRadius*2));
g2.dispose();
FastGaussianBlur.blur(shadow, radius);
}
private static void makeCircularShadow(BufferedImage shadow, float opacity, float radius, float leftOffset, float topOffset) {
Graphics2D g2 = shadow.createGraphics();
g2.setColor(new Color(0, 0, 0, opacity));
g2.fill(new Ellipse2D.Double(OFFSET_LEFT + leftOffset, OFFSET_TOP + topOffset,
shadow.getWidth() - OFFSET_LEFT - OFFSET_RIGHT, shadow.getWidth() - OFFSET_LEFT - OFFSET_RIGHT));
g2.dispose();
FastGaussianBlur.blur(shadow, radius);
}
private int pWd, pHt, pRd;
private double pLv;
private Type pTp;
private BufferedImage shadowBg;
/**
* The types of shadow available for rendering.
*/
public static enum Type {
/**
* A square, classic shadow. For panels, windows and paper components
* in general.
*/
SQUARE,
/**
* A circular, rounded shadow. Mainly for specific components like FABs.
*/
CIRCULAR
}
/**
* Default constructor for a {@code MaterialShadow}. It is recommended to
* keep a single instance for each component that requires it. The
* components bundled in this library already handle this by themselves.
*/
public MaterialShadow() {}
/**
* Renders this {@link MaterialShadow} into a {@link BufferedImage} and
* returns it. A copy of the latest render is kept in case a shadow of the
* same dimensions and elevation is needed in order to decrease CPU usage
* when the component is idle.
* @param width the witdh of the square component casting a shadow, or
* diameter if it is circular.
* @param height the height of the square component casting a shadow.
* @param radius the radius of the borders of a square component casting a
* shadow.
* @param level the depth of the shadow [0~5]
* @param type the type of projected shadow, either square or circular
* @return A {@link BufferedImage} with the contents of the shadow.
* @see Type#SQUARE
* @see Type#CIRCULAR
*/
public BufferedImage render(int width, int height, int radius, double level, Type type) {
if (pWd != width || pHt != height || pRd != radius || pLv != level || pTp != type) {
switch (type) {
case SQUARE:
shadowBg = MaterialShadow.renderShadow(width, height, level, radius);
break;
case CIRCULAR:
shadowBg = MaterialShadow.renderCircularShadow(width, level);
break;
}
pWd = width;
pHt = height;
pRd = radius;
pLv = level;
pTp = type;
}
return shadowBg;
}
}
| |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.actions;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.ClickListener;
import com.intellij.ui.LicensingFacade;
import com.intellij.ui.UI;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
/**
* @author Konstantin Bulenkov
*/
@SuppressWarnings("SSBasedInspection")
public class AboutDialog extends JDialog {
public AboutDialog(Window owner) {
super(owner);
init(owner);
}
private void init(Window window) {
ApplicationInfoEx appInfo = (ApplicationInfoEx)ApplicationInfo.getInstance();
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setFocusable(true); //doesn't work under Oracle 1.7 if nothing focusable
final JComponent closeListenerOwner;
Icon image = IconLoader.getIcon(appInfo.getAboutImageUrl());
final InfoSurface infoSurface;
if (appInfo.showLicenseeInfo()) {
infoSurface = new InfoSurface(image);
infoSurface.setPreferredSize(new Dimension(image.getIconWidth(), image.getIconHeight()));
mainPanel.add(infoSurface, BorderLayout.NORTH);
closeListenerOwner = infoSurface;
}
else {
infoSurface = null;
mainPanel.add(new JLabel(image), BorderLayout.NORTH);
closeListenerOwner = mainPanel;
}
setUndecorated(true);
setContentPane(mainPanel);
final Ref<Long> showTime = Ref.create(System.currentTimeMillis());
new DumbAwareAction() {
@Override
public void actionPerformed(AnActionEvent e) {
if (infoSurface != null) {
copyInfoToClipboard(infoSurface.getText());
}
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("meta C", "control C"), mainPanel);
new DumbAwareAction() {
@Override
public void actionPerformed(AnActionEvent e) {
dispose();
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString("ESCAPE"), mainPanel);
//final long delta = Patches.APPLE_BUG_ID_3716865 ? 100 : 0;
final long delta = 500; //reproducible on Windows too
addWindowFocusListener(new WindowFocusListener() {
public void windowGainedFocus(WindowEvent e) {
}
public void windowLostFocus(WindowEvent e) {
long eventTime = System.currentTimeMillis();
if (eventTime - showTime.get() > delta && e.getOppositeWindow() != e.getWindow()) {
dispose();
}
else {
IdeFocusManager.getGlobalInstance().requestFocus(AboutDialog.this, true);
}
}
});
new ClickListener() {
@Override
public boolean onClick(MouseEvent event, int clickCount) {
dispose();
return true;
}
}.installOn(closeListenerOwner);
pack();
setLocationRelativeTo(window);
}
private static void copyInfoToClipboard(String text) {
try {
CopyPasteManager.getInstance().setContents(new StringSelection(text));
}
catch (Exception ignore) {
}
}
private static class InfoSurface extends JPanel {
final Color col;
final Color linkCol;
private final Icon myImage;
private Font myFont;
private Font myBoldFont;
private final List<AboutBoxLine> myLines = new ArrayList<AboutBoxLine>();
private StringBuilder myInfo = new StringBuilder();
private static class Link {
private final Rectangle rectangle;
private final String url;
private Link(Rectangle rectangle, String url) {
this.rectangle = rectangle;
this.url = url;
}
}
private Link myActiveLink;
private final List<Link> myLinks = new ArrayList<Link>();
public InfoSurface(Icon image) {
myImage = image;
setOpaque(false);
col = Color.white;
final ApplicationInfoImpl ideInfo = (ApplicationInfoImpl)ApplicationInfoEx.getInstanceEx();
linkCol = ideInfo.getAboutLinkColor() != null ? ideInfo.getAboutLinkColor() : UI.getColor("link.foreground");
setBackground(col);
Calendar cal = ideInfo.getBuildDate();
myLines.add(new AboutBoxLine(ideInfo.getFullApplicationName(), true, null));
appendLast();
String buildInfo = IdeBundle.message("aboutbox.build.number", ideInfo.getBuild().asString());
String buildDate = "";
if (ideInfo.getBuild().isSnapshot()) {
buildDate = new SimpleDateFormat("HH:mm, ").format(cal.getTime());
}
buildDate += DateFormatUtil.formatAboutDialogDate(cal.getTime());
buildInfo += IdeBundle.message("aboutbox.build.date", buildDate);
myLines.add(new AboutBoxLine(buildInfo));
appendLast();
myLines.add(new AboutBoxLine(""));
LicensingFacade provider = LicensingFacade.getInstance();
if (provider != null) {
myLines.add(new AboutBoxLine(provider.getLicensedToMessage(), true, null));
for (String message : provider.getLicenseRestrictionsMessages()) {
myLines.add(new AboutBoxLine(message));
}
}
myLines.add(new AboutBoxLine(""));
final Properties properties = System.getProperties();
final String javaVersion = properties.getProperty("java.runtime.version", properties.getProperty("java.version", "unknown"));
final String arch = properties.getProperty("os.arch", "");
myLines.add(new AboutBoxLine(IdeBundle.message("aboutbox.jdk", javaVersion, arch), true, null));
appendLast();
myLines.add(new AboutBoxLine(IdeBundle.message("aboutbox.vm", properties.getProperty("java.vm.name", "unknown"),
properties.getProperty("java.vendor", "unknown"))));
appendLast();
/*
myLines.add(new AboutBoxLine(""));
myLines.add(new AboutBoxLine(info.getCompanyURL(), true, info.getCompanyURL()));
*/
String thirdParty = ideInfo.getThirdPartySoftwareURL();
if (thirdParty != null) {
myLines.add(new AboutBoxLine(""));
myLines.add(new AboutBoxLine(""));
myLines.add(new AboutBoxLine("Powered by ").keepWithNext());
myLines.add(new AboutBoxLine("open-source software", false, thirdParty).keepWithNext());
}
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent event) {
if (myActiveLink != null) {
event.consume();
BrowserUtil.launchBrowser(myActiveLink.url);
}
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent event) {
boolean hadLink = (myActiveLink != null);
myActiveLink = null;
for (Link link : myLinks) {
if (link.rectangle.contains(event.getPoint())) {
myActiveLink = link;
if (!hadLink) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
break;
}
}
if (hadLink && myActiveLink == null) {
setCursor(Cursor.getDefaultCursor());
}
}
});
}
private void appendLast() {
myInfo.append(myLines.get(myLines.size() - 1).getText()).append("\n");
}
@Override
protected void paintChildren(Graphics g) {
super.paintChildren(g);
Graphics2D g2 = (Graphics2D)g;
UIUtil.applyRenderingHints(g);
Font labelFont = UIUtil.getLabelFont();
for (int labelSize = 10; labelSize != 6; labelSize -= 1) {
myLinks.clear();
g2.setPaint(col);
myImage.paintIcon(this, g2, 0, 0);
g2.setColor(col);
TextRenderer renderer = new TextRenderer(0, 145, 398, 120, g2);
UIUtil.setupComposite(g2);
myFont = labelFont.deriveFont(Font.PLAIN, labelSize);
myBoldFont = labelFont.deriveFont(Font.BOLD, labelSize + 1);
try {
renderer.render(30, 0, myLines);
break;
}
catch (TextRenderer.OverflowException ignore) {
}
}
ApplicationInfo appInfo = ApplicationInfo.getInstance();
Rectangle aboutLogoRect = appInfo.getAboutLogoRect();
if (aboutLogoRect != null) {
myLinks.add(new Link(aboutLogoRect, appInfo.getCompanyURL()));
}
}
public String getText() {
return myInfo.toString();
}
public class TextRenderer {
private final int xBase;
private final int yBase;
private final int w;
private final int h;
private final Graphics2D g2;
private int x = 0;
private int y = 0;
private FontMetrics fontmetrics;
private int fontAscent;
private int fontHeight;
private Font font;
public class OverflowException extends Exception {
}
public TextRenderer(final int xBase, final int yBase, final int w, final int h, final Graphics2D g2) {
this.xBase = xBase;
this.yBase = yBase;
this.w = w;
this.h = h;
this.g2 = g2;
if (SystemInfo.isWindows) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
}
}
public void render(int indentX, int indentY, List<AboutBoxLine> lines) throws OverflowException {
x = indentX;
y = indentY;
ApplicationInfoEx appInfo = (ApplicationInfoEx)ApplicationInfo.getInstance();
for (AboutBoxLine line : lines) {
final String s = line.getText();
setFont(line.isBold() ? myBoldFont : myFont);
if (line.getUrl() != null) {
g2.setColor(linkCol);
FontMetrics metrics = g2.getFontMetrics(font);
myLinks.add(new Link(new Rectangle(x, yBase + y - fontAscent, metrics.stringWidth(s), fontHeight), line.getUrl()));
}
else {
g2.setColor(appInfo.getAboutForeground());
}
renderString(s, indentX);
if (!line.isKeepWithNext() && !line.equals(lines.get(lines.size()-1))) {
lineFeed(indentX, s);
}
}
}
private void renderString(final String s, final int indentX) throws OverflowException {
final List<String> words = StringUtil.split(s, " ");
for (String word : words) {
int wordWidth = fontmetrics.stringWidth(word);
if (x + wordWidth >= w) {
lineFeed(indentX, word);
}
else {
char c = ' ';
final int cW = fontmetrics.charWidth(c);
if (x + cW < w) {
g2.drawChars(new char[]{c}, 0, 1, xBase + x, yBase + y);
x += cW;
}
}
renderWord(word, indentX);
}
}
private void renderWord(final String s, final int indentX) throws OverflowException {
for (int j = 0; j != s.length(); ++j) {
final char c = s.charAt(j);
final int cW = fontmetrics.charWidth(c);
if (x + cW >= w) {
lineFeed(indentX, s);
}
g2.drawChars(new char[]{c}, 0, 1, xBase + x, yBase + y);
x += cW;
}
}
private void lineFeed(int indent, final String s) throws OverflowException {
x = indent;
if (s.length() == 0) {
y += fontHeight / 3;
}
else {
y += fontHeight;
}
if (y >= h) {
throw new OverflowException();
}
}
private void setFont(Font font) {
this.font = font;
fontmetrics = g2.getFontMetrics(font);
g2.setFont(font);
fontAscent = fontmetrics.getAscent();
fontHeight = fontmetrics.getHeight();
}
}
}
private static class AboutBoxLine {
private final String myText;
private final boolean myBold;
private final String myUrl;
private boolean myKeepWithNext;
public AboutBoxLine(final String text, final boolean bold, final String url) {
myText = text;
myBold = bold;
myUrl = url;
}
public AboutBoxLine(final String text) {
myText = text;
myBold = false;
myUrl = null;
}
public String getText() {
return myText;
}
public boolean isBold() {
return myBold;
}
public String getUrl() {
return myUrl;
}
public boolean isKeepWithNext() {
return myKeepWithNext;
}
public AboutBoxLine keepWithNext() {
myKeepWithNext = true;
return this;
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.basic;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.FilterDirectoryReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.util.English;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.MockEngineFactoryPlugin;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.engine.MockEngineSupport;
import org.elasticsearch.test.engine.ThrowingLeafReaderWrapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
public class SearchWithRandomExceptionsIT extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Arrays.asList(RandomExceptionDirectoryReaderWrapper.TestPlugin.class);
}
@Override
protected boolean addMockInternalEngine() {
return false;
}
public void testRandomExceptions() throws IOException, InterruptedException, ExecutionException {
String mapping = Strings.toString(XContentFactory.jsonBuilder().
startObject().
startObject("properties").
startObject("test")
.field("type", "keyword")
.endObject().endObject()
.endObject());
final double lowLevelRate;
final double topLevelRate;
if (frequently()) {
if (randomBoolean()) {
if (randomBoolean()) {
lowLevelRate = 1.0 / between(2, 10);
topLevelRate = 0.0d;
} else {
topLevelRate = 1.0 / between(2, 10);
lowLevelRate = 0.0d;
}
} else {
lowLevelRate = 1.0 / between(2, 10);
topLevelRate = 1.0 / between(2, 10);
}
} else {
// rarely no exception
topLevelRate = 0d;
lowLevelRate = 0d;
}
Builder settings = Settings.builder()
.put(indexSettings())
.put(EXCEPTION_TOP_LEVEL_RATIO_KEY, topLevelRate)
.put(EXCEPTION_LOW_LEVEL_RATIO_KEY, lowLevelRate)
.put(MockEngineSupport.WRAP_READER_RATIO.getKey(), 1.0d);
logger.info("creating index: [test] using settings: [{}]", settings.build());
assertAcked(prepareCreate("test")
.setSettings(settings)
.setMapping(mapping));
ensureSearchable();
final int numDocs = between(10, 100);
int numCreated = 0;
boolean[] added = new boolean[numDocs];
for (int i = 0; i < numDocs; i++) {
try {
IndexResponse indexResponse = client().prepareIndex("test").setId("" + i)
.setTimeout(TimeValue.timeValueSeconds(1)).setSource("test", English.intToEnglish(i)).get();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
numCreated++;
added[i] = true;
}
} catch (ElasticsearchException ex) {
}
}
logger.info("Start Refresh");
// don't assert on failures here
RefreshResponse refreshResponse = client().admin().indices().prepareRefresh("test").execute().get();
final boolean refreshFailed = refreshResponse.getShardFailures().length != 0 || refreshResponse.getFailedShards() != 0;
logger.info("Refresh failed [{}] numShardsFailed: [{}], shardFailuresLength: [{}], successfulShards: [{}], totalShards: [{}] ",
refreshFailed, refreshResponse.getFailedShards(), refreshResponse.getShardFailures().length,
refreshResponse.getSuccessfulShards(), refreshResponse.getTotalShards());
NumShards test = getNumShards("test");
final int numSearches = scaledRandomIntBetween(100, 200);
// we don't check anything here really just making sure we don't leave any open files or a broken index behind.
for (int i = 0; i < numSearches; i++) {
try {
int docToQuery = between(0, numDocs - 1);
int expectedResults = added[docToQuery] ? 1 : 0;
logger.info("Searching for [test:{}]", English.intToEnglish(docToQuery));
SearchResponse searchResponse = client().prepareSearch()
.setQuery(QueryBuilders.matchQuery("test", English.intToEnglish(docToQuery)))
.setSize(expectedResults).get();
logger.info("Successful shards: [{}] numShards: [{}]", searchResponse.getSuccessfulShards(), test.numPrimaries);
if (searchResponse.getSuccessfulShards() == test.numPrimaries && !refreshFailed) {
assertResultsAndLogOnFailure(expectedResults, searchResponse);
}
// check match all
searchResponse = client().prepareSearch().setQuery(QueryBuilders.matchAllQuery()).setSize(numCreated)
.addSort("_id", SortOrder.ASC).get();
logger.info("Match all Successful shards: [{}] numShards: [{}]", searchResponse.getSuccessfulShards(), test.numPrimaries);
if (searchResponse.getSuccessfulShards() == test.numPrimaries && !refreshFailed) {
assertResultsAndLogOnFailure(numCreated, searchResponse);
}
} catch (SearchPhaseExecutionException ex) {
logger.info("expected SearchPhaseException: [{}]", ex.getMessage());
}
}
}
public static final String EXCEPTION_TOP_LEVEL_RATIO_KEY = "index.engine.exception.ratio.top";
public static final String EXCEPTION_LOW_LEVEL_RATIO_KEY = "index.engine.exception.ratio.low";
public static class RandomExceptionDirectoryReaderWrapper extends MockEngineSupport.DirectoryReaderWrapper {
public static class TestPlugin extends MockEngineFactoryPlugin {
public static final Setting<Double> EXCEPTION_TOP_LEVEL_RATIO_SETTING =
Setting.doubleSetting(EXCEPTION_TOP_LEVEL_RATIO_KEY, 0.1d, 0.0d, Property.IndexScope);
public static final Setting<Double> EXCEPTION_LOW_LEVEL_RATIO_SETTING =
Setting.doubleSetting(EXCEPTION_LOW_LEVEL_RATIO_KEY, 0.1d, 0.0d, Property.IndexScope);
@Override
public List<Setting<?>> getSettings() {
List<Setting<?>> settings = new ArrayList<>();
settings.addAll(super.getSettings());
settings.add(EXCEPTION_TOP_LEVEL_RATIO_SETTING);
settings.add(EXCEPTION_LOW_LEVEL_RATIO_SETTING);
return settings;
}
@Override
protected Class<? extends FilterDirectoryReader> getReaderWrapperClass() {
return RandomExceptionDirectoryReaderWrapper.class;
}
}
private final Settings settings;
static class ThrowingSubReaderWrapper extends FilterDirectoryReader.SubReaderWrapper implements ThrowingLeafReaderWrapper.Thrower {
private final Random random;
private final double topLevelRatio;
private final double lowLevelRatio;
ThrowingSubReaderWrapper(Settings settings) {
final long seed = ESIntegTestCase.INDEX_TEST_SEED_SETTING.get(settings);
this.topLevelRatio = settings.getAsDouble(EXCEPTION_TOP_LEVEL_RATIO_KEY, 0.1d);
this.lowLevelRatio = settings.getAsDouble(EXCEPTION_LOW_LEVEL_RATIO_KEY, 0.1d);
this.random = new Random(seed);
}
@Override
public LeafReader wrap(LeafReader reader) {
return new ThrowingLeafReaderWrapper(reader, this);
}
@Override
public void maybeThrow(ThrowingLeafReaderWrapper.Flags flag) throws IOException {
switch (flag) {
case Fields:
case TermVectors:
case Terms:
case TermsEnum:
case Intersect:
case Norms:
case NumericDocValues:
case BinaryDocValues:
case SortedDocValues:
case SortedSetDocValues:
if (random.nextDouble() < topLevelRatio) {
throw new IOException("Forced top level Exception on [" + flag.name() + "]");
}
break;
case DocsEnum:
case DocsAndPositionsEnum:
if (random.nextDouble() < lowLevelRatio) {
throw new IOException("Forced low level Exception on [" + flag.name() + "]");
}
break;
}
}
@Override
public boolean wrapTerms(String field) {
return true;
}
}
public RandomExceptionDirectoryReaderWrapper(DirectoryReader in, Settings settings) throws IOException {
super(in, new ThrowingSubReaderWrapper(settings));
this.settings = settings;
}
@Override
protected DirectoryReader doWrapDirectoryReader(DirectoryReader in) throws IOException {
return new RandomExceptionDirectoryReaderWrapper(in, settings);
}
@Override
public CacheHelper getReaderCacheHelper() {
return in.getReaderCacheHelper();
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* IO helper class.
*
* @version
*/
public final class IOHelper {
public static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final Logger LOG = LoggerFactory.getLogger(IOHelper.class);
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
// allows to turn on backwards compatible to turn off regarding the first read byte with value zero (0b0) as EOL.
// See more at CAMEL-11672
private static final boolean ZERO_BYTE_EOL_ENABLED =
"true".equalsIgnoreCase(System.getProperty("camel.zeroByteEOLEnabled", "true"));
private IOHelper() {
// Utility Class
}
/**
* Use this function instead of new String(byte[]) to avoid surprises from non-standard default encodings.
*/
public static String newStringFromBytes(byte[] bytes) {
try {
return new String(bytes, UTF8_CHARSET.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Impossible failure: Charset.forName(\"UTF-8\") returns invalid name.", e);
}
}
/**
* Use this function instead of new String(byte[], int, int)
* to avoid surprises from non-standard default encodings.
*/
public static String newStringFromBytes(byte[] bytes, int start, int length) {
try {
return new String(bytes, start, length, UTF8_CHARSET.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Impossible failure: Charset.forName(\"UTF-8\") returns invalid name.", e);
}
}
/**
* Wraps the passed <code>in</code> into a {@link BufferedInputStream}
* object and returns that. If the passed <code>in</code> is already an
* instance of {@link BufferedInputStream} returns the same passed
* <code>in</code> reference as is (avoiding double wrapping).
*
* @param in the wrapee to be used for the buffering support
* @return the passed <code>in</code> decorated through a
* {@link BufferedInputStream} object as wrapper
*/
public static BufferedInputStream buffered(InputStream in) {
ObjectHelper.notNull(in, "in");
return (in instanceof BufferedInputStream) ? (BufferedInputStream)in : new BufferedInputStream(in);
}
/**
* Wraps the passed <code>out</code> into a {@link BufferedOutputStream}
* object and returns that. If the passed <code>out</code> is already an
* instance of {@link BufferedOutputStream} returns the same passed
* <code>out</code> reference as is (avoiding double wrapping).
*
* @param out the wrapee to be used for the buffering support
* @return the passed <code>out</code> decorated through a
* {@link BufferedOutputStream} object as wrapper
*/
public static BufferedOutputStream buffered(OutputStream out) {
ObjectHelper.notNull(out, "out");
return (out instanceof BufferedOutputStream) ? (BufferedOutputStream)out : new BufferedOutputStream(out);
}
/**
* Wraps the passed <code>reader</code> into a {@link BufferedReader} object
* and returns that. If the passed <code>reader</code> is already an
* instance of {@link BufferedReader} returns the same passed
* <code>reader</code> reference as is (avoiding double wrapping).
*
* @param reader the wrapee to be used for the buffering support
* @return the passed <code>reader</code> decorated through a
* {@link BufferedReader} object as wrapper
*/
public static BufferedReader buffered(Reader reader) {
ObjectHelper.notNull(reader, "reader");
return (reader instanceof BufferedReader) ? (BufferedReader)reader : new BufferedReader(reader);
}
/**
* Wraps the passed <code>writer</code> into a {@link BufferedWriter} object
* and returns that. If the passed <code>writer</code> is already an
* instance of {@link BufferedWriter} returns the same passed
* <code>writer</code> reference as is (avoiding double wrapping).
*
* @param writer the wrapee to be used for the buffering support
* @return the passed <code>writer</code> decorated through a
* {@link BufferedWriter} object as wrapper
*/
public static BufferedWriter buffered(Writer writer) {
ObjectHelper.notNull(writer, "writer");
return (writer instanceof BufferedWriter) ? (BufferedWriter)writer : new BufferedWriter(writer);
}
/**
* A factory method which creates an {@link IOException} from the given
* exception and message
*
* @deprecated IOException support nested exception in Java 1.6. Will be removed in Camel 3.0
*/
@Deprecated
public static IOException createIOException(Throwable cause) {
return createIOException(cause.getMessage(), cause);
}
/**
* A factory method which creates an {@link IOException} from the given
* exception and message
*
* @deprecated IOException support nested exception in Java 1.6. Will be removed in Camel 3.0
*/
@Deprecated
public static IOException createIOException(String message, Throwable cause) {
IOException answer = new IOException(message);
answer.initCause(cause);
return answer;
}
public static int copy(InputStream input, OutputStream output) throws IOException {
return copy(input, output, DEFAULT_BUFFER_SIZE);
}
public static int copy(final InputStream input, final OutputStream output, int bufferSize) throws IOException {
return copy(input, output, bufferSize, false);
}
public static int copy(final InputStream input, final OutputStream output, int bufferSize, boolean flushOnEachWrite) throws IOException {
if (input instanceof ByteArrayInputStream) {
// optimized for byte array as we only need the max size it can be
input.mark(0);
input.reset();
bufferSize = input.available();
} else {
int avail = input.available();
if (avail > bufferSize) {
bufferSize = avail;
}
}
if (bufferSize > 262144) {
// upper cap to avoid buffers too big
bufferSize = 262144;
}
if (LOG.isTraceEnabled()) {
LOG.trace("Copying InputStream: {} -> OutputStream: {} with buffer: {} and flush on each write {}",
new Object[]{input, output, bufferSize, flushOnEachWrite});
}
int total = 0;
final byte[] buffer = new byte[bufferSize];
int n = input.read(buffer);
boolean hasData;
if (ZERO_BYTE_EOL_ENABLED) {
// workaround issue on some application servers which can return 0 (instead of -1)
// as first byte to indicate end of stream (CAMEL-11672)
hasData = n > 0;
} else {
hasData = n > -1;
}
if (hasData) {
while (-1 != n) {
output.write(buffer, 0, n);
if (flushOnEachWrite) {
output.flush();
}
total += n;
n = input.read(buffer);
}
}
if (!flushOnEachWrite) {
// flush at end, if we didn't do it during the writing
output.flush();
}
return total;
}
public static void copyAndCloseInput(InputStream input, OutputStream output) throws IOException {
copyAndCloseInput(input, output, DEFAULT_BUFFER_SIZE);
}
public static void copyAndCloseInput(InputStream input, OutputStream output, int bufferSize) throws IOException {
copy(input, output, bufferSize);
close(input, null, LOG);
}
public static int copy(final Reader input, final Writer output, int bufferSize) throws IOException {
final char[] buffer = new char[bufferSize];
int n = input.read(buffer);
int total = 0;
while (-1 != n) {
output.write(buffer, 0, n);
total += n;
n = input.read(buffer);
}
output.flush();
return total;
}
/**
* Forces any updates to this channel's file to be written to the storage device that contains it.
*
* @param channel the file channel
* @param name the name of the resource
* @param log the log to use when reporting warnings, will use this class's own {@link Logger} if <tt>log == null</tt>
*/
public static void force(FileChannel channel, String name, Logger log) {
try {
if (channel != null) {
channel.force(true);
}
} catch (Exception e) {
if (log == null) {
// then fallback to use the own Logger
log = LOG;
}
if (name != null) {
log.warn("Cannot force FileChannel: " + name + ". Reason: " + e.getMessage(), e);
} else {
log.warn("Cannot force FileChannel. Reason: {}", e.getMessage(), e);
}
}
}
/**
* Forces any updates to a FileOutputStream be written to the storage device that contains it.
*
* @param os the file output stream
* @param name the name of the resource
* @param log the log to use when reporting warnings, will use this class's own {@link Logger} if <tt>log == null</tt>
*/
public static void force(FileOutputStream os, String name, Logger log) {
try {
if (os != null) {
os.getFD().sync();
}
} catch (Exception e) {
if (log == null) {
// then fallback to use the own Logger
log = LOG;
}
if (name != null) {
log.warn("Cannot sync FileDescriptor: " + name + ". Reason: " + e.getMessage(), e);
} else {
log.warn("Cannot sync FileDescriptor. Reason: {}", e.getMessage(), e);
}
}
}
/**
* Closes the given writer, logging any closing exceptions to the given log.
* An associated FileOutputStream can optionally be forced to disk.
*
* @param writer the writer to close
* @param os an underlying FileOutputStream that will to be forced to disk according to the force parameter
* @param name the name of the resource
* @param log the log to use when reporting warnings, will use this class's own {@link Logger} if <tt>log == null</tt>
* @param force forces the FileOutputStream to disk
*/
public static void close(Writer writer, FileOutputStream os, String name, Logger log, boolean force) {
if (writer != null && force) {
// flush the writer prior to syncing the FD
try {
writer.flush();
} catch (Exception e) {
if (log == null) {
// then fallback to use the own Logger
log = LOG;
}
if (name != null) {
log.warn("Cannot flush Writer: " + name + ". Reason: " + e.getMessage(), e);
} else {
log.warn("Cannot flush Writer. Reason: {}", e.getMessage(), e);
}
}
force(os, name, log);
}
close(writer, name, log);
}
/**
* Closes the given resource if it is available, logging any closing exceptions to the given log.
*
* @param closeable the object to close
* @param name the name of the resource
* @param log the log to use when reporting closure warnings, will use this class's own {@link Logger} if <tt>log == null</tt>
*/
public static void close(Closeable closeable, String name, Logger log) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
if (log == null) {
// then fallback to use the own Logger
log = LOG;
}
if (name != null) {
log.warn("Cannot close: " + name + ". Reason: " + e.getMessage(), e);
} else {
log.warn("Cannot close. Reason: {}", e.getMessage(), e);
}
}
}
}
/**
* Closes the given resource if it is available and don't catch the exception
*
* @param closeable the object to close
* @throws IOException
*/
public static void closeWithException(Closeable closeable) throws IOException {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// don't catch the exception here
throw e;
}
}
}
/**
* Closes the given channel if it is available, logging any closing exceptions to the given log.
* The file's channel can optionally be forced to disk.
*
* @param channel the file channel
* @param name the name of the resource
* @param log the log to use when reporting warnings, will use this class's own {@link Logger} if <tt>log == null</tt>
* @param force forces the file channel to disk
*/
public static void close(FileChannel channel, String name, Logger log, boolean force) {
if (force) {
force(channel, name, log);
}
close(channel, name, log);
}
/**
* Closes the given resource if it is available.
*
* @param closeable the object to close
* @param name the name of the resource
*/
public static void close(Closeable closeable, String name) {
close(closeable, name, LOG);
}
/**
* Closes the given resource if it is available.
*
* @param closeable the object to close
*/
public static void close(Closeable closeable) {
close(closeable, null, LOG);
}
/**
* Closes the given resources if they are available.
*
* @param closeables the objects to close
*/
public static void close(Closeable... closeables) {
for (Closeable closeable : closeables) {
close(closeable);
}
}
public static void closeIterator(Object it) throws IOException {
if (it instanceof java.util.Scanner) {
// special for Scanner which implement the Closeable since JDK7
java.util.Scanner scanner = (java.util.Scanner) it;
scanner.close();
IOException ioException = scanner.ioException();
if (ioException != null) {
throw ioException;
}
} else if (it instanceof Scanner) {
// special for Scanner which implement the Closeable since JDK7
Scanner scanner = (Scanner) it;
scanner.close();
IOException ioException = scanner.ioException();
if (ioException != null) {
throw ioException;
}
} else if (it instanceof Closeable) {
IOHelper.closeWithException((Closeable) it);
}
}
public static void validateCharset(String charset) throws UnsupportedCharsetException {
if (charset != null) {
if (Charset.isSupported(charset)) {
Charset.forName(charset);
return;
}
}
throw new UnsupportedCharsetException(charset);
}
/**
* This method will take off the quotes and double quotes of the charset
*/
public static String normalizeCharset(String charset) {
if (charset != null) {
String answer = charset.trim();
if (answer.startsWith("'") || answer.startsWith("\"")) {
answer = answer.substring(1);
}
if (answer.endsWith("'") || answer.endsWith("\"")) {
answer = answer.substring(0, answer.length() - 1);
}
return answer.trim();
} else {
return null;
}
}
/**
* @see #getCharsetName(org.apache.camel.Exchange, boolean)
*/
public static String getCharsetName(Exchange exchange) {
return getCharsetName(exchange, true);
}
/**
* Gets the charset name if set as header or property {@link Exchange#CHARSET_NAME}.
* <b>Notice:</b> The lookup from the header has priority over the property.
*
* @param exchange the exchange
* @param useDefault should we fallback and use JVM default charset if no property existed?
* @return the charset, or <tt>null</tt> if no found
*/
public static String getCharsetName(Exchange exchange, boolean useDefault) {
if (exchange != null) {
// header takes precedence
String charsetName = exchange.getIn().getHeader(Exchange.CHARSET_NAME, String.class);
if (charsetName == null) {
charsetName = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
}
if (charsetName != null) {
return IOHelper.normalizeCharset(charsetName);
}
}
if (useDefault) {
return getDefaultCharsetName();
} else {
return null;
}
}
private static String getDefaultCharsetName() {
return ObjectHelper.getSystemProperty(Exchange.DEFAULT_CHARSET_PROPERTY, "UTF-8");
}
/**
* Loads the entire stream into memory as a String and returns it.
* <p/>
* <b>Notice:</b> This implementation appends a <tt>\n</tt> as line
* terminator at the of the text.
* <p/>
* Warning, don't use for crazy big streams :)
*/
public static String loadText(InputStream in) throws IOException {
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(in);
try {
BufferedReader reader = buffered(isr);
while (true) {
String line = reader.readLine();
if (line != null) {
builder.append(line);
builder.append("\n");
} else {
break;
}
}
return builder.toString();
} finally {
close(isr, in);
}
}
/**
* Get the charset name from the content type string
* @param contentType
* @return the charset name, or <tt>UTF-8</tt> if no found
*/
public static String getCharsetNameFromContentType(String contentType) {
String[] values = contentType.split(";");
String charset = "";
for (String value : values) {
value = value.trim();
if (value.toLowerCase().startsWith("charset=")) {
// Take the charset name
charset = value.substring(8);
}
}
if ("".equals(charset)) {
charset = "UTF-8";
}
return IOHelper.normalizeCharset(charset);
}
}
| |
/*
* @(#)MouseEvent.java 1.56 06/07/11
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.awt.event;
import java.awt.Component;
import java.awt.Event;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.awt.IllegalComponentStateException;
/**
* An event which indicates that a mouse action occurred in a component.
* A mouse action is considered to occur in a particular component if and only
* if the mouse cursor is over the unobscured part of the component's bounds
* when the action happens.
* For lightweight components, such as Swing's components, mouse events
* are only dispatched to the component if the mouse event type has been
* enabled on the component. A mouse event type is enabled by adding the
* appropriate mouse-based {@code EventListener} to the component
* ({@link MouseListener} or {@link MouseMotionListener}), or by invoking
* {@link Component#enableEvents(long)} with the appropriate mask parameter
* ({@code AWTEvent.MOUSE_EVENT_MASK} or {@code AWTEvent.MOUSE_MOTION_EVENT_MASK}).
* If the mouse event type has not been enabled on the component, the
* corresponding mouse events are dispatched to the first ancestor that
* has enabled the mouse event type.
*<p>
* For example, if a {@code MouseListener} has been added to a component, or
* {@code enableEvents(AWTEvent.MOUSE_EVENT_MASK)} has been invoked, then all
* the events defined by {@code MouseListener} are dispatched to the component.
* On the other hand, if a {@code MouseMotionListener} has not been added and
* {@code enableEvents} has not been invoked with
* {@code AWTEvent.MOUSE_MOTION_EVENT_MASK}, then mouse motion events are not
* dispatched to the component. Instead the mouse motion events are
* dispatched to the first ancestors that has enabled mouse motion
* events.
* <P>
* This low-level event is generated by a component object for:
* <ul>
* <li>Mouse Events
* <ul>
* <li>a mouse button is pressed
* <li>a mouse button is released
* <li>a mouse button is clicked (pressed and released)
* <li>the mouse cursor enters the unobscured part of component's geometry
* <li>the mouse cursor exits the unobscured part of component's geometry
* </ul>
* <li> Mouse Motion Events
* <ul>
* <li>the mouse is moved
* <li>the mouse is dragged
* </ul>
* </ul>
* <P>
* A <code>MouseEvent</code> object is passed to every
* <code>MouseListener</code>
* or <code>MouseAdapter</code> object which is registered to receive
* the "interesting" mouse events using the component's
* <code>addMouseListener</code> method.
* (<code>MouseAdapter</code> objects implement the
* <code>MouseListener</code> interface.) Each such listener object
* gets a <code>MouseEvent</code> containing the mouse event.
* <P>
* A <code>MouseEvent</code> object is also passed to every
* <code>MouseMotionListener</code> or
* <code>MouseMotionAdapter</code> object which is registered to receive
* mouse motion events using the component's
* <code>addMouseMotionListener</code>
* method. (<code>MouseMotionAdapter</code> objects implement the
* <code>MouseMotionListener</code> interface.) Each such listener object
* gets a <code>MouseEvent</code> containing the mouse motion event.
* <P>
* When a mouse button is clicked, events are generated and sent to the
* registered <code>MouseListener</code>s.
* The state of modal keys can be retrieved using {@link InputEvent#getModifiers}
* and {@link InputEvent#getModifiersEx}.
* The button mask returned by {@link InputEvent#getModifiers} reflects
* only the button that changed state, not the current state of all buttons.
* (Note: Due to overlap in the values of ALT_MASK/BUTTON2_MASK and
* META_MASK/BUTTON3_MASK, this is not always true for mouse events involving
* modifier keys).
* To get the state of all buttons and modifier keys, use
* {@link InputEvent#getModifiersEx}.
* The button which has changed state is returned by {@link MouseEvent#getButton}
* <P>
* For example, if the first mouse button is pressed, events are sent in the
* following order:
* <PRE>
* <b >id </b > <b >modifiers </b > <b >button </b >
* <code>MOUSE_PRESSED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_RELEASED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_CLICKED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* </PRE>
* When multiple mouse buttons are pressed, each press, release, and click
* results in a separate event.
* <P>
* For example, if the user presses <b>button 1</b> followed by
* <b>button 2</b>, and then releases them in the same order,
* the following sequence of events is generated:
* <PRE>
* <b >id </b > <b >modifiers </b > <b >button </b >
* <code>MOUSE_PRESSED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_PRESSED</code>: <code>BUTTON2_MASK</code> <code>BUTTON2</code>
* <code>MOUSE_RELEASED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_CLICKED</code>: <code>BUTTON1_MASK</code> <code>BUTTON1</code>
* <code>MOUSE_RELEASED</code>: <code>BUTTON2_MASK</code> <code>BUTTON2</code>
* <code>MOUSE_CLICKED</code>: <code>BUTTON2_MASK</code> <code>BUTTON2</code>
* </PRE>
* If <b>button 2</b> is released first, the
* <code>MOUSE_RELEASED</code>/<code>MOUSE_CLICKED</code> pair
* for <code>BUTTON2_MASK</code> arrives first,
* followed by the pair for <code>BUTTON1_MASK</code>.
* <p>
*
* <code>MOUSE_DRAGGED</code> events are delivered to the <code>Component</code>
* in which the mouse button was pressed until the mouse button is released
* (regardless of whether the mouse position is within the bounds of the
* <code>Component</code>). Due to platform-dependent Drag&Drop implementations,
* <code>MOUSE_DRAGGED</code> events may not be delivered during a native
* Drag&Drop operation.
*
* In a multi-screen environment mouse drag events are delivered to the
* <code>Component</code> even if the mouse position is outside the bounds of the
* <code>GraphicsConfiguration</code> associated with that
* <code>Component</code>. However, the reported position for mouse drag events
* in this case may differ from the actual mouse position:
* <ul>
* <li>In a multi-screen environment without a virtual device:
* <br>
* The reported coordinates for mouse drag events are clipped to fit within the
* bounds of the <code>GraphicsConfiguration</code> associated with
* the <code>Component</code>.
* <li>In a multi-screen environment with a virtual device:
* <br>
* The reported coordinates for mouse drag events are clipped to fit within the
* bounds of the virtual device associated with the <code>Component</code>.
* </ul>
*
* @author Carl Quinn
* 1.56, 07/11/06
*
* @see MouseAdapter
* @see MouseListener
* @see MouseMotionAdapter
* @see MouseMotionListener
* @see MouseWheelListener
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/mouselistener.html">Tutorial: Writing a Mouse Listener</a>
* @see <a href="http://java.sun.com/docs/books/tutorial/post1.0/ui/mousemotionlistener.html">Tutorial: Writing a Mouse Motion Listener</a>
*
* @since 1.1
*/
public class MouseEvent extends InputEvent {
/**
* The first number in the range of ids used for mouse events.
*/
public static final int MOUSE_FIRST = 500;
/**
* The last number in the range of ids used for mouse events.
*/
public static final int MOUSE_LAST = 507;
/**
* The "mouse clicked" event. This <code>MouseEvent</code>
* occurs when a mouse button is pressed and released.
*/
public static final int MOUSE_CLICKED = MOUSE_FIRST;
/**
* The "mouse pressed" event. This <code>MouseEvent</code>
* occurs when a mouse button is pushed down.
*/
public static final int MOUSE_PRESSED = 1 + MOUSE_FIRST; //Event.MOUSE_DOWN
/**
* The "mouse released" event. This <code>MouseEvent</code>
* occurs when a mouse button is let up.
*/
public static final int MOUSE_RELEASED = 2 + MOUSE_FIRST; //Event.MOUSE_UP
/**
* The "mouse moved" event. This <code>MouseEvent</code>
* occurs when the mouse position changes.
*/
public static final int MOUSE_MOVED = 3 + MOUSE_FIRST; //Event.MOUSE_MOVE
/**
* The "mouse entered" event. This <code>MouseEvent</code>
* occurs when the mouse cursor enters the unobscured part of component's
* geometry.
*/
public static final int MOUSE_ENTERED = 4 + MOUSE_FIRST; //Event.MOUSE_ENTER
/**
* The "mouse exited" event. This <code>MouseEvent</code>
* occurs when the mouse cursor exits the unobscured part of component's
* geometry.
*/
public static final int MOUSE_EXITED = 5 + MOUSE_FIRST; //Event.MOUSE_EXIT
/**
* The "mouse dragged" event. This <code>MouseEvent</code>
* occurs when the mouse position changes while a mouse button is pressed.
*/
public static final int MOUSE_DRAGGED = 6 + MOUSE_FIRST; //Event.MOUSE_DRAG
/**
* The "mouse wheel" event. This is the only <code>MouseWheelEvent</code>.
* It occurs when a mouse equipped with a wheel has its wheel rotated.
* @since 1.4
*/
public static final int MOUSE_WHEEL = 7 + MOUSE_FIRST;
/**
* Indicates no mouse buttons; used by {@link #getButton}.
* @since 1.4
*/
public static final int NOBUTTON = 0;
/**
* Indicates mouse button #1; used by {@link #getButton}.
* @since 1.4
*/
public static final int BUTTON1 = 1;
/**
* Indicates mouse button #2; used by {@link #getButton}.
* @since 1.4
*/
public static final int BUTTON2 = 2;
/**
* Indicates mouse button #3; used by {@link #getButton}.
* @since 1.4
*/
public static final int BUTTON3 = 3;
/**
* The mouse event's x coordinate.
* The x value is relative to the component that fired the event.
*
* @serial
* @see #getX()
*/
int x;
/**
* The mouse event's y coordinate.
* The y value is relative to the component that fired the event.
*
* @serial
* @see #getY()
*/
int y;
/**
* The mouse event's x absolute coordinate.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* this coordinate is relative to the virtual coordinate system.
* Otherwise, this coordinate is relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @serial
*/
private int xAbs;
/**
* The mouse event's y absolute coordinate.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* this coordinate is relative to the virtual coordinate system.
* Otherwise, this coordinate is relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @serial
*/
private int yAbs;
/**
* Indicates the number of quick consecutive clicks of
* a mouse button.
* clickCount will be valid for only three mouse events :<BR>
* <code>MOUSE_CLICKED</code>,
* <code>MOUSE_PRESSED</code> and
* <code>MOUSE_RELEASED</code>.
* For the above, the <code>clickCount</code> will be at least 1.
* For all other events the count will be 0.
*
* @serial
* @see #getClickCount().
*/
int clickCount;
/**
* Indicates which, if any, of the mouse buttons has changed state.
*
* The only legal values are the following constants:
* <code>NOBUTTON</code>,
* <code>BUTTON1</code>,
* <code>BUTTON2</code> or
* <code>BUTTON3</code>.
* @serial
* @see #getButton().
*/
int button;
/**
* A property used to indicate whether a Popup Menu
* should appear with a certain gestures.
* If <code>popupTrigger</code> = <code>false</code>,
* no popup menu should appear. If it is <code>true</code>
* then a popup menu should appear.
*
* @serial
* @see java.awt.PopupMenu
* @see #isPopupTrigger()
*/
boolean popupTrigger = false;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -991214153494842848L;
static {
/* ensure that the necessary native libraries are loaded */
NativeLibLoader.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/**
* Initialize JNI field and method IDs for fields that may be
accessed from C.
*/
private static native void initIDs();
/**
* Returns the absolute x, y position of the event.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* these coordinates are relative to the virtual coordinate system.
* Otherwise, these coordinates are relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @return a <code>Point</code> object containing the absolute x
* and y coordinates.
*
* @see java.awt.GraphicsConfiguration
* @since 1.6
*/
public Point getLocationOnScreen(){
return new Point(xAbs, yAbs);
}
/**
* Returns the absolute horizontal x position of the event.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* this coordinate is relative to the virtual coordinate system.
* Otherwise, this coordinate is relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @return x an integer indicating absolute horizontal position.
*
* @see java.awt.GraphicsConfiguration
* @since 1.6
*/
public int getXOnScreen() {
return xAbs;
}
/**
* Returns the absolute vertical y position of the event.
* In a virtual device multi-screen environment in which the
* desktop area could span multiple physical screen devices,
* this coordinate is relative to the virtual coordinate system.
* Otherwise, this coordinate is relative to the coordinate system
* associated with the Component's GraphicsConfiguration.
*
* @return y an integer indicating absolute vertical position.
*
* @see java.awt.GraphicsConfiguration
* @since 1.6
*/
public int getYOnScreen() {
return yAbs;
}
/**
* Constructs a <code>MouseEvent</code> object with the
* specified source component,
* type, modifiers, coordinates, and click count.
* <p>
* Note that passing in an invalid <code>id</code> results in
* unspecified behavior. Creating an invalid event (such
* as by using more than one of the old _MASKs, or modifier/button
* values which don't match) results in unspecified behavior.
* An invocation of the form
* <tt>MouseEvent(source, id, when, modifiers, x, y, clickCount, popupTrigger, button)</tt>
* behaves in exactly the same way as the invocation
* <tt> {@link #MouseEvent(Component, int, long, int, int, int,
* int, int, int, boolean, int) MouseEvent}(source, id, when, modifiers,
* x, y, xAbs, yAbs, clickCount, popupTrigger, button)</tt>
* where xAbs and yAbs defines as source's location on screen plus
* relative coordinates x and y.
* xAbs and yAbs are set to zero if the source is not showing.
* This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id the integer that identifies the event
* @param when a long int that gives the time the event occurred
* @param modifiers the modifier keys down during event (e.g. shift, ctrl,
* alt, meta)
* Either extended _DOWN_MASK or old _MASK modifiers
* should be used, but both models should not be mixed
* in one event. Use of the extended modifiers is
* preferred.
* @param x the horizontal x coordinate for the mouse location
* @param y the vertical y coordinate for the mouse location
* @param clickCount the number of mouse clicks associated with event
* @param popupTrigger a boolean, true if this event is a trigger for a
* popup menu
* @param button which of the mouse buttons has changed state.
* <code>NOBUTTON</code>,
* <code>BUTTON1</code>,
* <code>BUTTON2</code> or
* <code>BUTTON3</code>.
* @throws IllegalArgumentException if an invalid <code>button</code>
* value is passed in
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.4
*/
public MouseEvent(Component source, int id, long when, int modifiers,
int x, int y, int clickCount, boolean popupTrigger,
int button)
{
this(source, id, when, modifiers, x, y, 0, 0, clickCount, popupTrigger, button);
Point eventLocationOnScreen = new Point(0, 0);
try {
eventLocationOnScreen = source.getLocationOnScreen();
this.xAbs = eventLocationOnScreen.x + x;
this.yAbs = eventLocationOnScreen.y + y;
} catch (IllegalComponentStateException e){
this.xAbs = 0;
this.yAbs = 0;
}
}
/**
* Constructs a <code>MouseEvent</code> object with the
* specified source component,
* type, modifiers, coordinates, and click count.
* <p>Note that passing in an invalid <code>id</code> results in
* unspecified behavior.
* An invocation of the form
* <tt>MouseEvent(source, id, when, modifiers, x, y, clickCount, popupTrigger)</tt>
* behaves in exactly the same way as the invocation
* <tt> {@link #MouseEvent(Component, int, long, int, int, int,
* int, int, int, boolean, int) MouseEvent}(source, id, when, modifiers,
* x, y, xAbs, yAbs, clickCount, popupTrigger, MouseEvent.NOBUTTON)</tt>
* where xAbs and yAbs defines as source's location on screen plus
* relative coordinates x and y.
* xAbs and yAbs are set to zero if the source is not showing.
* This method throws an <code>IllegalArgumentException</code>
* if <code>source</code> is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id the integer that identifies the event
* @param when a long int that gives the time the event occurred
* @param modifiers the modifier keys down during event (e.g. shift, ctrl,
* alt, meta)
* Either extended _DOWN_MASK or old _MASK modifiers
* should be used, but both models should not be mixed
* in one event. Use of the extended modifiers is
* preferred.
* @param x the horizontal x coordinate for the mouse location
* @param y the vertical y coordinate for the mouse location
* @param clickCount the number of mouse clicks associated with event
* @param popupTrigger a boolean, true if this event is a trigger for a
* popup menu
* @throws IllegalArgumentException if <code>source</code> is null
*/
public MouseEvent(Component source, int id, long when, int modifiers,
int x, int y, int clickCount, boolean popupTrigger) {
this(source, id, when, modifiers, x, y, clickCount, popupTrigger, NOBUTTON);
}
/**
* Constructs a <code>MouseEvent</code> object with the
* specified source component,
* type, modifiers, coordinates, absolute coordinates, and click count.
* <p>
* Note that passing in an invalid <code>id</code> results in
* unspecified behavior. Creating an invalid event (such
* as by using more than one of the old _MASKs, or modifier/button
* values which don't match) results in unspecified behavior.
* Even if inconsistent values for relative and absolute coordinates are
* passed to the constructor, the mouse event instance is still
* created and no exception is thrown.
* This method throws an
* <code>IllegalArgumentException</code> if <code>source</code>
* is <code>null</code>.
*
* @param source the <code>Component</code> that originated the event
* @param id the integer that identifies the event
* @param when a long int that gives the time the event occurred
* @param modifiers the modifier keys down during event (e.g. shift, ctrl,
* alt, meta)
* Either extended _DOWN_MASK or old _MASK modifiers
* should be used, but both models should not be mixed
* in one event. Use of the extended modifiers is
* preferred.
* @param x the horizontal x coordinate for the mouse location
* @param y the vertical y coordinate for the mouse location
* @param xAbs the absolute horizontal x coordinate for the mouse location
* @param yAbs the absolute vertical y coordinate for the mouse location
* @param clickCount the number of mouse clicks associated with event
* @param popupTrigger a boolean, true if this event is a trigger for a
* popup menu
* @param button which of the mouse buttons has changed state.
* <code>NOBUTTON</code>,
* <code>BUTTON1</code>,
* <code>BUTTON2</code> or
* <code>BUTTON3</code>.
* @throws IllegalArgumentException if an invalid <code>button</code>
* value is passed in
* @throws IllegalArgumentException if <code>source</code> is null
* @since 1.6
*/
public MouseEvent(Component source, int id, long when, int modifiers,
int x, int y, int xAbs, int yAbs,
int clickCount, boolean popupTrigger, int button)
{
super(source, id, when, modifiers);
this.x = x;
this.y = y;
this.xAbs = xAbs;
this.yAbs = yAbs;
this.clickCount = clickCount;
this.popupTrigger = popupTrigger;
if (button < NOBUTTON || button >BUTTON3) {
throw new IllegalArgumentException("Invalid button value");
}
this.button = button;
if ((getModifiers() != 0) && (getModifiersEx() == 0)) {
setNewModifiers();
} else if ((getModifiers() == 0) &&
(getModifiersEx() != 0 || button != NOBUTTON))
{
setOldModifiers();
}
}
/**
* Returns the horizontal x position of the event relative to the
* source component.
*
* @return x an integer indicating horizontal position relative to
* the component
*/
public int getX() {
return x;
}
/**
* Returns the vertical y position of the event relative to the
* source component.
*
* @return y an integer indicating vertical position relative to
* the component
*/
public int getY() {
return y;
}
/**
* Returns the x,y position of the event relative to the source component.
*
* @return a <code>Point</code> object containing the x and y coordinates
* relative to the source component
*
*/
public Point getPoint() {
int x;
int y;
synchronized (this) {
x = this.x;
y = this.y;
}
return new Point(x, y);
}
/**
* Translates the event's coordinates to a new position
* by adding specified <code>x</code> (horizontal) and <code>y</code>
* (vertical) offsets.
*
* @param x the horizontal x value to add to the current x
* coordinate position
* @param y the vertical y value to add to the current y
coordinate position
*/
public synchronized void translatePoint(int x, int y) {
this.x += x;
this.y += y;
}
/**
* Returns the number of mouse clicks associated with this event.
*
* @return integer value for the number of clicks
*/
public int getClickCount() {
return clickCount;
}
/**
* Returns which, if any, of the mouse buttons has changed state.
*
* @return one of the following constants:
* <code>NOBUTTON</code>,
* <code>BUTTON1</code>,
* <code>BUTTON2</code> or
* <code>BUTTON3</code>.
* @since 1.4
*/
public int getButton() {
return button;
}
/**
* Returns whether or not this mouse event is the popup menu
* trigger event for the platform.
* <p><b>Note</b>: Popup menus are triggered differently
* on different systems. Therefore, <code>isPopupTrigger</code>
* should be checked in both <code>mousePressed</code>
* and <code>mouseReleased</code>
* for proper cross-platform functionality.
*
* @return boolean, true if this event is the popup menu trigger
* for this platform
*/
public boolean isPopupTrigger() {
return popupTrigger;
}
/**
* Returns a <code>String</code> describing the modifier keys and
* mouse buttons that were down during the event, such as "Shift",
* or "Ctrl+Shift". These strings can be localized by changing
* the <code>awt.properties</code> file.
* <p>
* Note that <code>InputEvent.ALT_MASK</code> and
* <code>InputEvent.BUTTON2_MASK</code> have the same value,
* so the string "Alt" is returned for both modifiers. Likewise,
* <code>InputEvent.META_MASK</code> and
* <code>InputEvent.BUTTON3_MASK</code> have the same value,
* so the string "Meta" is returned for both modifiers.
*
* @param modifiers a modifier mask describing the modifier keys and
* mouse buttons that were down during the event
* @return string a text description of the combination of modifier
* keys and mouse buttons that were down during the event
* @see InputEvent#getModifiersExText(int)
* @since 1.4
*/
public static String getMouseModifiersText(int modifiers) {
StringBuffer buf = new StringBuffer();
if ((modifiers & InputEvent.ALT_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.alt", "Alt"));
buf.append("+");
}
if ((modifiers & InputEvent.META_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.meta", "Meta"));
buf.append("+");
}
if ((modifiers & InputEvent.CTRL_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.control", "Ctrl"));
buf.append("+");
}
if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.shift", "Shift"));
buf.append("+");
}
if ((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.altGraph", "Alt Graph"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON1_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button1", "Button1"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button2", "Button2"));
buf.append("+");
}
if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
buf.append(Toolkit.getProperty("AWT.button3", "Button3"));
buf.append("+");
}
if (buf.length() > 0) {
buf.setLength(buf.length()-1); // remove trailing '+'
}
return buf.toString();
}
/**
* Returns a parameter string identifying this event.
* This method is useful for event-logging and for debugging.
*
* @return a string identifying the event and its attributes
*/
public String paramString() {
StringBuffer str = new StringBuffer(80);
switch(id) {
case MOUSE_PRESSED:
str.append("MOUSE_PRESSED");
break;
case MOUSE_RELEASED:
str.append("MOUSE_RELEASED");
break;
case MOUSE_CLICKED:
str.append("MOUSE_CLICKED");
break;
case MOUSE_ENTERED:
str.append("MOUSE_ENTERED");
break;
case MOUSE_EXITED:
str.append("MOUSE_EXITED");
break;
case MOUSE_MOVED:
str.append("MOUSE_MOVED");
break;
case MOUSE_DRAGGED:
str.append("MOUSE_DRAGGED");
break;
case MOUSE_WHEEL:
str.append("MOUSE_WHEEL");
break;
default:
str.append("unknown type");
}
// (x,y) coordinates
str.append(",(").append(x).append(",").append(y).append(")");
str.append(",absolute(").append(xAbs).append(",").append(yAbs).append(")");
str.append(",button=").append(getButton());
if (getModifiers() != 0) {
str.append(",modifiers=").append(getMouseModifiersText(modifiers));
}
if (getModifiersEx() != 0) {
str.append(",extModifiers=").append(getModifiersExText(modifiers));
}
str.append(",clickCount=").append(clickCount);
return str.toString();
}
/**
* Sets new modifiers by the old ones.
* Also sets button.
*/
private void setNewModifiers() {
if ((modifiers & BUTTON1_MASK) != 0) {
modifiers |= BUTTON1_DOWN_MASK;
}
if ((modifiers & BUTTON2_MASK) != 0) {
modifiers |= BUTTON2_DOWN_MASK;
}
if ((modifiers & BUTTON3_MASK) != 0) {
modifiers |= BUTTON3_DOWN_MASK;
}
if (id == MOUSE_PRESSED
|| id == MOUSE_RELEASED
|| id == MOUSE_CLICKED)
{
if ((modifiers & BUTTON1_MASK) != 0) {
button = BUTTON1;
modifiers &= ~BUTTON2_MASK & ~BUTTON3_MASK;
if (id != MOUSE_PRESSED) {
modifiers &= ~BUTTON1_DOWN_MASK;
}
} else if ((modifiers & BUTTON2_MASK) != 0) {
button = BUTTON2;
modifiers &= ~BUTTON1_MASK & ~BUTTON3_MASK;
if (id != MOUSE_PRESSED) {
modifiers &= ~BUTTON2_DOWN_MASK;
}
} else if ((modifiers & BUTTON3_MASK) != 0) {
button = BUTTON3;
modifiers &= ~BUTTON1_MASK & ~BUTTON2_MASK;
if (id != MOUSE_PRESSED) {
modifiers &= ~BUTTON3_DOWN_MASK;
}
}
}
if ((modifiers & InputEvent.ALT_MASK) != 0) {
modifiers |= InputEvent.ALT_DOWN_MASK;
}
if ((modifiers & InputEvent.META_MASK) != 0) {
modifiers |= InputEvent.META_DOWN_MASK;
}
if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
modifiers |= InputEvent.SHIFT_DOWN_MASK;
}
if ((modifiers & InputEvent.CTRL_MASK) != 0) {
modifiers |= InputEvent.CTRL_DOWN_MASK;
}
if ((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) {
modifiers |= InputEvent.ALT_GRAPH_DOWN_MASK;
}
}
/**
* Sets old modifiers by the new ones.
*/
private void setOldModifiers() {
if (id == MOUSE_PRESSED
|| id == MOUSE_RELEASED
|| id == MOUSE_CLICKED)
{
switch(button) {
case BUTTON1:
modifiers |= BUTTON1_MASK;
break;
case BUTTON2:
modifiers |= BUTTON2_MASK;
break;
case BUTTON3:
modifiers |= BUTTON3_MASK;
break;
}
} else {
if ((modifiers & BUTTON1_DOWN_MASK) != 0) {
modifiers |= BUTTON1_MASK;
}
if ((modifiers & BUTTON2_DOWN_MASK) != 0) {
modifiers |= BUTTON2_MASK;
}
if ((modifiers & BUTTON3_DOWN_MASK) != 0) {
modifiers |= BUTTON3_MASK;
}
}
if ((modifiers & ALT_DOWN_MASK) != 0) {
modifiers |= ALT_MASK;
}
if ((modifiers & META_DOWN_MASK) != 0) {
modifiers |= META_MASK;
}
if ((modifiers & SHIFT_DOWN_MASK) != 0) {
modifiers |= SHIFT_MASK;
}
if ((modifiers & CTRL_DOWN_MASK) != 0) {
modifiers |= CTRL_MASK;
}
if ((modifiers & ALT_GRAPH_DOWN_MASK) != 0) {
modifiers |= ALT_GRAPH_MASK;
}
}
/**
* Sets new modifiers by the old ones.
* @serial
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
if (getModifiers() != 0 && getModifiersEx() == 0) {
setNewModifiers();
}
}
}
| |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.dxf2.metadata.objectbundle.hooks;
import java.util.Collection;
import java.util.function.Consumer;
import lombok.AllArgsConstructor;
import org.hibernate.Session;
import org.hisp.dhis.common.BaseAnalyticalObject;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.dxf2.metadata.DefaultAnalyticalObjectImportHandler;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle;
import org.hisp.dhis.feedback.ErrorReport;
import org.hisp.dhis.hibernate.HibernateProxyUtils;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.schema.Property;
import org.hisp.dhis.schema.PropertyType;
import org.hisp.dhis.schema.Schema;
import org.hisp.dhis.schema.validation.SchemaValidator;
import org.hisp.dhis.system.util.ReflectionUtils;
import org.springframework.stereotype.Component;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
@Component
@AllArgsConstructor
public class EmbeddedObjectObjectBundleHook
extends AbstractObjectBundleHook<IdentifiableObject>
{
private final DefaultAnalyticalObjectImportHandler analyticalObjectImportHandler;
private final SchemaValidator schemaValidator;
@Override
public void validate( IdentifiableObject object, ObjectBundle bundle, Consumer<ErrorReport> addReports )
{
Class<? extends IdentifiableObject> klass = object.getClass();
Schema schema = schemaService.getDynamicSchema( klass );
schema.getEmbeddedObjectProperties().keySet()
.stream()
.forEach( propertyName -> {
Property property = schema.getEmbeddedObjectProperties().get( propertyName );
Object propertyObject = ReflectionUtils.invokeMethod( object, property.getGetterMethod() );
if ( property.getPropertyType().equals( PropertyType.COMPLEX ) )
{
schemaValidator.validateEmbeddedObject( propertyObject, klass )
.forEach( unformattedError -> addReports
.accept( formatEmbeddedErrorReport( unformattedError, propertyName ) ) );
}
else if ( property.getPropertyType().equals( PropertyType.COLLECTION ) )
{
Collection<?> collection = (Collection<?>) propertyObject;
for ( Object item : collection )
{
schemaValidator.validateEmbeddedObject( property.getItemKlass().cast( item ), klass )
.forEach( unformattedError -> addReports
.accept( formatEmbeddedErrorReport( unformattedError, propertyName ) ) );
}
}
} );
}
private ErrorReport formatEmbeddedErrorReport( ErrorReport errorReport, String embeddedPropertyName )
{
errorReport.setErrorProperty( embeddedPropertyName + "." + errorReport.getErrorProperty() );
return errorReport;
}
@Override
public void preCreate( IdentifiableObject object, ObjectBundle bundle )
{
Schema schema = schemaService.getDynamicSchema( HibernateProxyUtils.getRealClass( object ) );
if ( schema == null || schema.getEmbeddedObjectProperties().isEmpty() )
{
return;
}
Collection<Property> properties = schema.getEmbeddedObjectProperties().values();
handleEmbeddedObjects( object, bundle, properties );
}
@Override
public void preUpdate( IdentifiableObject object, IdentifiableObject persistedObject, ObjectBundle bundle )
{
Schema schema = schemaService.getDynamicSchema( HibernateProxyUtils.getRealClass( object ) );
if ( schema == null || schema.getEmbeddedObjectProperties().isEmpty() )
{
return;
}
Collection<Property> properties = schema.getEmbeddedObjectProperties().values();
clearEmbeddedObjects( persistedObject, bundle, properties );
handleEmbeddedObjects( object, bundle, properties );
}
private void clearEmbeddedObjects( IdentifiableObject object, ObjectBundle bundle,
Collection<Property> properties )
{
for ( Property property : properties )
{
if ( property.isCollection() )
{
if ( ReflectionUtils.isSharingProperty( property ) && bundle.isSkipSharing() )
{
continue;
}
((Collection<?>) ReflectionUtils.invokeMethod( object, property.getGetterMethod() )).clear();
}
else
{
ReflectionUtils.invokeMethod( object, property.getSetterMethod(), (Object) null );
}
}
}
private void handleEmbeddedObjects( IdentifiableObject object, ObjectBundle bundle,
Collection<Property> properties )
{
for ( Property property : properties )
{
Object propertyObject = ReflectionUtils.invokeMethod( object, property.getGetterMethod() );
if ( property.isCollection() )
{
Collection<?> objects = (Collection<?>) propertyObject;
objects.forEach( itemPropertyObject -> {
handleProperty( itemPropertyObject, bundle, property );
handleEmbeddedAnalyticalProperty( itemPropertyObject, bundle, property );
} );
}
else
{
handleProperty( propertyObject, bundle, property );
handleEmbeddedAnalyticalProperty( propertyObject, bundle, property );
}
}
}
private void handleProperty( Object object, ObjectBundle bundle, Property property )
{
if ( object == null || bundle == null || property == null )
{
return;
}
if ( property.isIdentifiableObject() )
{
((BaseIdentifiableObject) object).setAutoFields();
}
Schema embeddedSchema = schemaService.getDynamicSchema( HibernateProxyUtils.getRealClass( object ) );
for ( Property embeddedProperty : embeddedSchema.getPropertyMap().values() )
{
if ( PeriodType.class.isAssignableFrom( embeddedProperty.getKlass() ) )
{
PeriodType periodType = ReflectionUtils.invokeMethod( object, embeddedProperty.getGetterMethod() );
if ( periodType != null )
{
periodType = bundle.getPreheat().getPeriodTypeMap().get( periodType.getName() );
ReflectionUtils.invokeMethod( object, embeddedProperty.getSetterMethod(), periodType );
}
}
}
preheatService.connectReferences( object, bundle.getPreheat(), bundle.getPreheatIdentifier() );
}
private void handleEmbeddedAnalyticalProperty( Object identifiableObject, ObjectBundle bundle, Property property )
{
if ( identifiableObject == null || property == null || !property.isAnalyticalObject() )
{
return;
}
Session session = sessionFactory.getCurrentSession();
Schema propertySchema = schemaService.getDynamicSchema( property.getItemKlass() );
analyticalObjectImportHandler.handleAnalyticalObject( session, propertySchema,
(BaseAnalyticalObject) identifiableObject, bundle );
}
}
| |
package org.pac4j.saml.transport;
import net.shibboleth.utilities.java.support.codec.Base64Support;
import net.shibboleth.utilities.java.support.collection.Pair;
import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
import net.shibboleth.utilities.java.support.net.URLBuilder;
import net.shibboleth.utilities.java.support.xml.SerializeSupport;
import org.opensaml.core.xml.XMLObject;
import org.opensaml.core.xml.io.MarshallingException;
import org.opensaml.core.xml.util.XMLObjectSupport;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.messaging.encoder.AbstractMessageEncoder;
import org.opensaml.messaging.encoder.MessageEncodingException;
import org.opensaml.saml.common.SAMLObject;
import org.opensaml.saml.common.SignableSAMLObject;
import org.opensaml.saml.common.binding.BindingException;
import org.opensaml.saml.common.binding.SAMLBindingSupport;
import org.opensaml.saml.common.messaging.SAMLMessageSecuritySupport;
import org.opensaml.saml.saml2.core.RequestAbstractType;
import org.opensaml.saml.saml2.core.StatusResponseType;
import org.opensaml.security.credential.Credential;
import org.opensaml.security.credential.CredentialSupport;
import org.opensaml.xmlsec.SignatureSigningParameters;
import org.opensaml.xmlsec.crypto.XMLSigningUtil;
import org.pac4j.core.exception.TechnicalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
/**
* Pac4j implementation extending directly the {@link AbstractMessageEncoder} as intermediate classes use the J2E HTTP response.
* It's mostly a copy/paste of the source code of these intermediate opensaml classes.
*
* @author Misagh Moayyed
* @since 1.8
*/
public class Pac4jHTTPRedirectDeflateEncoder extends AbstractMessageEncoder<SAMLObject> {
private final static Logger log = LoggerFactory.getLogger(Pac4jHTTPPostEncoder.class);
private final Pac4jSAMLResponse responseAdapter;
private final boolean forceSignRedirectBindingAuthnRequest;
public Pac4jHTTPRedirectDeflateEncoder(final Pac4jSAMLResponse responseAdapter,
final boolean forceSignRedirectBindingAuthnRequest) {
this.responseAdapter = responseAdapter;
this.forceSignRedirectBindingAuthnRequest = forceSignRedirectBindingAuthnRequest;
}
@Override
protected void doEncode() throws MessageEncodingException {
final MessageContext messageContext = this.getMessageContext();
final SAMLObject outboundMessage = (SAMLObject)messageContext.getMessage();
final String endpointURL = this.getEndpointURL(messageContext).toString();
if (!this.forceSignRedirectBindingAuthnRequest) {
this.removeSignature(outboundMessage);
}
final String encodedMessage = this.deflateAndBase64Encode(outboundMessage);
final String redirectURL = this.buildRedirectURL(messageContext, endpointURL, encodedMessage);
responseAdapter.init();
responseAdapter.setRedirectUrl(redirectURL);
}
@Override
protected void doInitialize() throws ComponentInitializationException {
log.debug("Initialized {}", this.getClass().getSimpleName());
}
/**
* Gets the response URL from the message context.
*
* @param messageContext current message context
*
* @return response URL from the message context
*
* @throws MessageEncodingException throw if no relying party endpoint is available
*/
protected URI getEndpointURL(MessageContext<SAMLObject> messageContext) throws MessageEncodingException {
try {
return SAMLBindingSupport.getEndpointURL(messageContext);
} catch (BindingException e) {
throw new MessageEncodingException("Could not obtain message endpoint URL", e);
}
}
/**
* Removes the signature from the protocol message.
*
* @param message current message context
*/
protected void removeSignature(SAMLObject message) {
if (message instanceof SignableSAMLObject) {
final SignableSAMLObject signableMessage = (SignableSAMLObject) message;
if (signableMessage.isSigned()) {
log.debug("Removing SAML protocol message signature");
signableMessage.setSignature(null);
}
}
}
/**
* DEFLATE (RFC1951) compresses the given SAML message.
*
* @param message SAML message
*
* @return DEFLATE compressed message
*
* @throws MessageEncodingException thrown if there is a problem compressing the message
*/
protected String deflateAndBase64Encode(SAMLObject message) throws MessageEncodingException {
log.debug("Deflating and Base64 encoding SAML message");
try {
String messageStr = SerializeSupport.nodeToString(marshallMessage(message));
log.trace("Output XML message: {}", messageStr);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
Deflater deflater = new Deflater(Deflater.DEFLATED, true);
DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
deflaterStream.write(messageStr.getBytes("UTF-8"));
deflaterStream.finish();
return Base64Support.encode(bytesOut.toByteArray(), Base64Support.UNCHUNKED);
} catch (IOException e) {
throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e);
}
}
/**
* Helper method that marshalls the given message.
*
* @param message message the marshall and serialize
*
* @return marshalled message
*
* @throws MessageEncodingException thrown if the give message can not be marshalled into its DOM representation
*/
protected Element marshallMessage(XMLObject message) throws MessageEncodingException {
log.debug("Marshalling message");
try {
return XMLObjectSupport.marshall(message);
} catch (MarshallingException e) {
throw new MessageEncodingException("Error marshalling message", e);
}
}
/**
* Builds the URL to redirect the client to.
*
* @param messageContext current message context
* @param endpoint endpoint URL to send encoded message to
* @param message Deflated and Base64 encoded message
*
* @return URL to redirect client to
*
* @throws MessageEncodingException thrown if the SAML message is neither a RequestAbstractType or Response
*/
protected String buildRedirectURL(MessageContext<SAMLObject> messageContext, String endpoint, String message)
throws MessageEncodingException {
log.debug("Building URL to redirect client to");
URLBuilder urlBuilder = null;
try {
urlBuilder = new URLBuilder(endpoint);
} catch (MalformedURLException e) {
throw new MessageEncodingException("Endpoint URL " + endpoint + " is not a valid URL", e);
}
List<Pair<String, String>> queryParams = urlBuilder.getQueryParams();
queryParams.clear();
SAMLObject outboundMessage = messageContext.getMessage();
if (outboundMessage instanceof RequestAbstractType) {
queryParams.add(new Pair<>("SAMLRequest", message));
} else if (outboundMessage instanceof StatusResponseType) {
queryParams.add(new Pair<>("SAMLResponse", message));
} else {
throw new MessageEncodingException(
"SAML message is neither a SAML RequestAbstractType or StatusResponseType");
}
String relayState = SAMLBindingSupport.getRelayState(messageContext);
if (SAMLBindingSupport.checkRelayState(relayState)) {
queryParams.add(new Pair<>("RelayState", relayState));
}
SignatureSigningParameters signingParameters =
SAMLMessageSecuritySupport.getContextSigningParameters(messageContext);
if (signingParameters != null && signingParameters.getSigningCredential() != null) {
String sigAlgURI = getSignatureAlgorithmURI(signingParameters);
Pair<String, String> sigAlg = new Pair<>("SigAlg", sigAlgURI);
queryParams.add(sigAlg);
String sigMaterial = urlBuilder.buildQueryString();
queryParams.add(new Pair<>("Signature", generateSignature(
signingParameters.getSigningCredential(), sigAlgURI, sigMaterial)));
} else {
log.debug("No signing credential was supplied, skipping HTTP-Redirect DEFLATE signing");
}
return urlBuilder.buildURL();
}
/**
* Gets the signature algorithm URI to use.
*
* @param signingParameters the signing parameters to use
*
* @return signature algorithm to use with the associated signing credential
*
* @throws MessageEncodingException thrown if the algorithm URI is not supplied explicitly and
* could not be derived from the supplied credential
*/
protected String getSignatureAlgorithmURI(SignatureSigningParameters signingParameters)
throws MessageEncodingException {
if (signingParameters.getSignatureAlgorithm() != null) {
return signingParameters.getSignatureAlgorithm();
}
throw new MessageEncodingException("The signing algorithm URI could not be determined");
}
/**
* Generates the signature over the query string.
*
* @param signingCredential credential that will be used to sign query string
* @param algorithmURI algorithm URI of the signing credential
* @param queryString query string to be signed
*
* @return base64 encoded signature of query string
*
* @throws MessageEncodingException there is an error computing the signature
*/
protected String generateSignature(Credential signingCredential, String algorithmURI, String queryString)
throws MessageEncodingException {
log.debug(String.format("Generating signature with key type '%s', algorithm URI '%s' over query string '%s'",
CredentialSupport.extractSigningKey(signingCredential).getAlgorithm(), algorithmURI, queryString));
String b64Signature = null;
try {
byte[] rawSignature =
XMLSigningUtil.signWithURI(signingCredential, algorithmURI, queryString.getBytes("UTF-8"));
b64Signature = Base64Support.encode(rawSignature, Base64Support.UNCHUNKED);
log.debug("Generated digital signature value (base64-encoded) {}", b64Signature);
} catch (final org.opensaml.security.SecurityException e) {
throw new MessageEncodingException("Unable to sign URL query string", e);
} catch (final UnsupportedEncodingException e) {
throw new TechnicalException(e);
}
return b64Signature;
}
}
| |
/*
* Copyright (c) Data Geekery GmbH (http://www.datageekery.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joou;
import java.io.ObjectStreamException;
import java.math.BigInteger;
/**
* The <code>unsigned byte</code> type
*
* @author Lukas Eder
* @author Ed Schaller
* @author Jens Nerche
*/
public final class UByte extends UNumber implements Comparable<UByte> {
/**
* Generated UID
*/
private static final long serialVersionUID = -6821055240959745390L;
/**
* Cached values
*/
private static final UByte[] VALUES = mkValues();
/**
* A constant holding the minimum value an <code>unsigned byte</code> can
* have, 0.
*/
public static final short MIN_VALUE = 0x00;
/**
* A constant holding the maximum value an <code>unsigned byte</code> can
* have, 2<sup>8</sup>-1.
*/
public static final short MAX_VALUE = 0xff;
/**
* A constant holding the minimum value an <code>unsigned byte</code> can
* have as UByte, 0.
*/
public static final UByte MIN = valueOf(0x00);
/**
* A constant holding the maximum value an <code>unsigned byte</code> can
* have as UByte, 2<sup>8</sup>-1.
*/
public static final UByte MAX = valueOf(0xff);
/**
* The value modelling the content of this <code>unsigned byte</code>
*/
private final short value;
/**
* Generate a cached value for each byte value.
*
* @return Array of cached values for UByte.
*/
private static final UByte[] mkValues() {
UByte[] ret = new UByte[256];
for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++)
ret[i & MAX_VALUE] = new UByte((byte) i);
return ret;
}
/**
* Get an instance of an <code>unsigned byte</code>
*
* @throws NumberFormatException If <code>value</code> does not contain a
* parsable <code>unsigned byte</code>.
*/
public static UByte valueOf(String value) throws NumberFormatException {
return valueOfUnchecked(rangeCheck(Short.parseShort(value)));
}
/**
* Get an instance of an <code>unsigned byte</code> by masking it with
* <code>0xFF</code> i.e. <code>(byte) -1</code> becomes
* <code>(ubyte) 255</code>
*/
public static UByte valueOf(byte value) {
return valueOfUnchecked((short) (value & MAX_VALUE));
}
/**
* Get the value of a short without checking the value.
*/
private static UByte valueOfUnchecked(short value) throws NumberFormatException {
return VALUES[value & MAX_VALUE];
}
/**
* Get an instance of an <code>unsigned byte</code>
*
* @throws NumberFormatException If <code>value</code> is not in the range
* of an <code>unsigned byte</code>
*/
public static UByte valueOf(short value) throws NumberFormatException {
return valueOfUnchecked(rangeCheck(value));
}
/**
* Get an instance of an <code>unsigned byte</code>
*
* @throws NumberFormatException If <code>value</code> is not in the range
* of an <code>unsigned byte</code>
*/
public static UByte valueOf(int value) throws NumberFormatException {
return valueOfUnchecked(rangeCheck(value));
}
/**
* Get an instance of an <code>unsigned byte</code>
*
* @throws NumberFormatException If <code>value</code> is not in the range
* of an <code>unsigned byte</code>
*/
public static UByte valueOf(long value) throws NumberFormatException {
return valueOfUnchecked(rangeCheck(value));
}
/**
* Create an <code>unsigned byte</code>
*
* @throws NumberFormatException If <code>value</code> is not in the range
* of an <code>unsigned byte</code>
*/
private UByte(long value) throws NumberFormatException {
this.value = rangeCheck(value);
}
/**
* Create an <code>unsigned byte</code>
*
* @throws NumberFormatException If <code>value</code> is not in the range
* of an <code>unsigned byte</code>
*/
private UByte(int value) throws NumberFormatException {
this.value = rangeCheck(value);
}
/**
* Create an <code>unsigned byte</code>
*
* @throws NumberFormatException If <code>value</code> is not in the range
* of an <code>unsigned byte</code>
*/
private UByte(short value) throws NumberFormatException {
this.value = rangeCheck(value);
}
/**
* Create an <code>unsigned byte</code> by masking it with <code>0xFF</code>
* i.e. <code>(byte) -1</code> becomes <code>(ubyte) 255</code>
*/
private UByte(byte value) {
this.value = (short) (value & MAX_VALUE);
}
/**
* Create an <code>unsigned byte</code>
*
* @throws NumberFormatException If <code>value</code> does not contain a
* parsable <code>unsigned byte</code>.
*/
private UByte(String value) throws NumberFormatException {
this.value = rangeCheck(Short.parseShort(value));
}
/**
* Throw exception if value out of range (short version)
*
* @param value Value to check
* @return value if it is in range
* @throws NumberFormatException if value is out of range
*/
private static short rangeCheck(short value) throws NumberFormatException {
if (value < MIN_VALUE || value > MAX_VALUE)
throw new NumberFormatException("Value is out of range : " + value);
return value;
}
/**
* Throw exception if value out of range (int version)
*
* @param value Value to check
* @return value if it is in range
* @throws NumberFormatException if value is out of range
*/
private static short rangeCheck(int value) throws NumberFormatException {
if (value < MIN_VALUE || value > MAX_VALUE)
throw new NumberFormatException("Value is out of range : " + value);
return (short) value;
}
/**
* Throw exception if value out of range (long version)
*
* @param value Value to check
* @return value if it is in range
* @throws NumberFormatException if value is out of range
*/
private static short rangeCheck(long value) throws NumberFormatException {
if (value < MIN_VALUE || value > MAX_VALUE)
throw new NumberFormatException("Value is out of range : " + value);
return (short) value;
}
/**
* Replace version read through deserialization with cached version. Note
* that this does not use the {@link #valueOfUnchecked(short)} as we have no
* guarantee that the value from the stream is valid.
*
* @return cached instance of this object's value
* @throws ObjectStreamException
*/
private Object readResolve() throws ObjectStreamException {
return valueOf(value);
}
@Override
public int intValue() {
return value;
}
@Override
public long longValue() {
return value;
}
@Override
public float floatValue() {
return value;
}
@Override
public double doubleValue() {
return value;
}
@Override
public int hashCode() {
/* [java-8] */
if (true) return Short.hashCode(value);
/* [/java-8] */
return Short.valueOf(value).hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj instanceof UByte)
return value == ((UByte) obj).value;
return false;
}
@Override
public String toString() {
return Short.toString(value);
}
@Override
public int compareTo(UByte o) {
return (value < o.value ? -1 : (value == o.value ? 0 : 1));
}
@Override
public BigInteger toBigInteger() {
return BigInteger.valueOf(value);
}
public UByte add(UByte val) throws NumberFormatException {
return valueOf(value + val.value);
}
public UByte add(int val) throws NumberFormatException {
return valueOf(value + val);
}
public UByte subtract(final UByte val) {
return valueOf(value - val.value);
}
public UByte subtract(final int val) {
return valueOf(value - val);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.xml.ns.security.provider;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.geronimo.xml.ns.security.util.SecurityAdapterFactory;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.edit.provider.ChangeNotifier;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IChangeNotifier;
import org.eclipse.emf.edit.provider.IDisposable;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.INotifyChangedListener;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITableItemLabelProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
/**
* This is the factory that is used to provide the interfaces needed to support Viewers.
* The adapters generated by this factory convert EMF adapter notifications into calls to {@link #fireNotifyChanged fireNotifyChanged}.
* The adapters also support Eclipse property sheets.
* Note that most of the adapters are shared among multiple instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class SecurityItemProviderAdapterFactory extends SecurityAdapterFactory implements ComposeableAdapterFactory, IChangeNotifier, IDisposable
{
/**
* This keeps track of the root adapter factory that delegates to this adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComposedAdapterFactory parentAdapterFactory;
/**
* This is used to implement {@link org.eclipse.emf.edit.provider.IChangeNotifier}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IChangeNotifier changeNotifier = new ChangeNotifier();
/**
* This keeps track of all the supported types checked by {@link #isFactoryForType isFactoryForType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection supportedTypes = new ArrayList();
/**
* This constructs an instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public SecurityItemProviderAdapterFactory()
{
supportedTypes.add(IEditingDomainItemProvider.class);
supportedTypes.add(IStructuredItemContentProvider.class);
supportedTypes.add(ITreeItemContentProvider.class);
supportedTypes.add(IItemLabelProvider.class);
supportedTypes.add(IItemPropertySource.class);
supportedTypes.add(ITableItemLabelProvider.class);
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.DefaultPrincipalType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DefaultPrincipalTypeItemProvider defaultPrincipalTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.DefaultPrincipalType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createDefaultPrincipalTypeAdapter()
{
if (defaultPrincipalTypeItemProvider == null)
{
defaultPrincipalTypeItemProvider = new DefaultPrincipalTypeItemProvider(this);
}
return defaultPrincipalTypeItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.DescriptionType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DescriptionTypeItemProvider descriptionTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.DescriptionType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createDescriptionTypeAdapter()
{
if (descriptionTypeItemProvider == null)
{
descriptionTypeItemProvider = new DescriptionTypeItemProvider(this);
}
return descriptionTypeItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.DistinguishedNameType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DistinguishedNameTypeItemProvider distinguishedNameTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.DistinguishedNameType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createDistinguishedNameTypeAdapter()
{
if (distinguishedNameTypeItemProvider == null)
{
distinguishedNameTypeItemProvider = new DistinguishedNameTypeItemProvider(this);
}
return distinguishedNameTypeItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.DocumentRoot} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DocumentRootItemProvider documentRootItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.DocumentRoot}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createDocumentRootAdapter()
{
if (documentRootItemProvider == null)
{
documentRootItemProvider = new DocumentRootItemProvider(this);
}
return documentRootItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.LoginDomainPrincipalType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected LoginDomainPrincipalTypeItemProvider loginDomainPrincipalTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.LoginDomainPrincipalType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createLoginDomainPrincipalTypeAdapter()
{
if (loginDomainPrincipalTypeItemProvider == null)
{
loginDomainPrincipalTypeItemProvider = new LoginDomainPrincipalTypeItemProvider(this);
}
return loginDomainPrincipalTypeItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.NamedUsernamePasswordCredentialType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected NamedUsernamePasswordCredentialTypeItemProvider namedUsernamePasswordCredentialTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.NamedUsernamePasswordCredentialType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createNamedUsernamePasswordCredentialTypeAdapter()
{
if (namedUsernamePasswordCredentialTypeItemProvider == null)
{
namedUsernamePasswordCredentialTypeItemProvider = new NamedUsernamePasswordCredentialTypeItemProvider(this);
}
return namedUsernamePasswordCredentialTypeItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.PrincipalType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PrincipalTypeItemProvider principalTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.PrincipalType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createPrincipalTypeAdapter()
{
if (principalTypeItemProvider == null)
{
principalTypeItemProvider = new PrincipalTypeItemProvider(this);
}
return principalTypeItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.RealmPrincipalType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RealmPrincipalTypeItemProvider realmPrincipalTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.RealmPrincipalType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createRealmPrincipalTypeAdapter()
{
if (realmPrincipalTypeItemProvider == null)
{
realmPrincipalTypeItemProvider = new RealmPrincipalTypeItemProvider(this);
}
return realmPrincipalTypeItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.RoleMappingsType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RoleMappingsTypeItemProvider roleMappingsTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.RoleMappingsType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createRoleMappingsTypeAdapter()
{
if (roleMappingsTypeItemProvider == null)
{
roleMappingsTypeItemProvider = new RoleMappingsTypeItemProvider(this);
}
return roleMappingsTypeItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.RoleType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RoleTypeItemProvider roleTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.RoleType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createRoleTypeAdapter()
{
if (roleTypeItemProvider == null)
{
roleTypeItemProvider = new RoleTypeItemProvider(this);
}
return roleTypeItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.apache.geronimo.xml.ns.security.SecurityType} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SecurityTypeItemProvider securityTypeItemProvider;
/**
* This creates an adapter for a {@link org.apache.geronimo.xml.ns.security.SecurityType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter createSecurityTypeAdapter()
{
if (securityTypeItemProvider == null)
{
securityTypeItemProvider = new SecurityTypeItemProvider(this);
}
return securityTypeItemProvider;
}
/**
* This returns the root adapter factory that contains this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ComposeableAdapterFactory getRootAdapterFactory()
{
return parentAdapterFactory == null ? this : parentAdapterFactory.getRootAdapterFactory();
}
/**
* This sets the composed adapter factory that contains this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParentAdapterFactory(ComposedAdapterFactory parentAdapterFactory)
{
this.parentAdapterFactory = parentAdapterFactory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isFactoryForType(Object type)
{
return supportedTypes.contains(type) || super.isFactoryForType(type);
}
/**
* This implementation substitutes the factory itself as the key for the adapter.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Adapter adapt(Notifier notifier, Object type)
{
return super.adapt(notifier, this);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object adapt(Object object, Object type)
{
if (isFactoryForType(type))
{
Object adapter = super.adapt(object, type);
if (!(type instanceof Class) || (((Class)type).isInstance(adapter)))
{
return adapter;
}
}
return null;
}
/**
* This adds a listener.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void addListener(INotifyChangedListener notifyChangedListener)
{
changeNotifier.addListener(notifyChangedListener);
}
/**
* This removes a listener.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void removeListener(INotifyChangedListener notifyChangedListener)
{
changeNotifier.removeListener(notifyChangedListener);
}
/**
* This delegates to {@link #changeNotifier} and to {@link #parentAdapterFactory}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void fireNotifyChanged(Notification notification)
{
changeNotifier.fireNotifyChanged(notification);
if (parentAdapterFactory != null)
{
parentAdapterFactory.fireNotifyChanged(notification);
}
}
/**
* This disposes all of the item providers created by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void dispose()
{
if (defaultPrincipalTypeItemProvider != null) defaultPrincipalTypeItemProvider.dispose();
if (descriptionTypeItemProvider != null) descriptionTypeItemProvider.dispose();
if (distinguishedNameTypeItemProvider != null) distinguishedNameTypeItemProvider.dispose();
if (documentRootItemProvider != null) documentRootItemProvider.dispose();
if (loginDomainPrincipalTypeItemProvider != null) loginDomainPrincipalTypeItemProvider.dispose();
if (namedUsernamePasswordCredentialTypeItemProvider != null) namedUsernamePasswordCredentialTypeItemProvider.dispose();
if (principalTypeItemProvider != null) principalTypeItemProvider.dispose();
if (realmPrincipalTypeItemProvider != null) realmPrincipalTypeItemProvider.dispose();
if (roleMappingsTypeItemProvider != null) roleMappingsTypeItemProvider.dispose();
if (roleTypeItemProvider != null) roleTypeItemProvider.dispose();
if (securityTypeItemProvider != null) securityTypeItemProvider.dispose();
}
}
| |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.intelliLang.inject.groovy;
import com.intellij.lang.Language;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.impl.light.LightElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.NullableFunction;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.plugins.intelliLang.Configuration;
import org.intellij.plugins.intelliLang.inject.AbstractLanguageInjectionSupport;
import org.intellij.plugins.intelliLang.inject.InjectorUtils;
import org.intellij.plugins.intelliLang.inject.LanguageInjectionSupport;
import org.intellij.plugins.intelliLang.inject.config.BaseInjection;
import org.intellij.plugins.intelliLang.inject.java.JavaLanguageInjectionSupport;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils;
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets;
import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteralContainer;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringContent;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl;
import org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyPatterns;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author Gregory.Shrago
*/
public class GroovyLanguageInjectionSupport extends AbstractLanguageInjectionSupport {
@NonNls public static final String GROOVY_SUPPORT_ID = "groovy";
@Override
@NotNull
public String getId() {
return GROOVY_SUPPORT_ID;
}
@Override
@NotNull
public Class[] getPatternClasses() {
return new Class[] {GroovyPatterns.class};
}
@Nullable
@Override
public BaseInjection findCommentInjection(@NotNull PsiElement host, @Nullable Ref<PsiElement> commentRef) {
PsiFile containingFile = host.getContainingFile();
boolean compiled = containingFile != null && containingFile.getOriginalFile() instanceof PsiCompiledFile;
return compiled ? null : super.findCommentInjection(host, commentRef);
}
@Override
public boolean isApplicableTo(PsiLanguageInjectionHost host) {
return host instanceof GroovyPsiElement;
}
@Override
public boolean useDefaultInjector(PsiLanguageInjectionHost host) {
return true;
}
@Override
public String getHelpId() {
return "reference.settings.language.injection.groovy";
}
@Override
public boolean addInjectionInPlace(Language language, @Nullable PsiLanguageInjectionHost psiElement) {
if (language == null) return false;
if (!isStringLiteral(psiElement)) return false;
return doInject(language.getID(), psiElement, psiElement);
}
@Override
public boolean removeInjectionInPlace(@Nullable final PsiLanguageInjectionHost psiElement) {
if (!isStringLiteral(psiElement)) return false;
GrLiteralContainer host = (GrLiteralContainer)psiElement;
final HashMap<BaseInjection, Pair<PsiMethod, Integer>> injectionsMap = ContainerUtil.newHashMap();
final ArrayList<PsiElement> annotations = new ArrayList<>();
final Project project = host.getProject();
final Configuration configuration = Configuration.getProjectInstance(project);
collectInjections(host, configuration, this, injectionsMap, annotations);
if (injectionsMap.isEmpty() && annotations.isEmpty()) return false;
final ArrayList<BaseInjection> originalInjections = new ArrayList<>(injectionsMap.keySet());
final List<BaseInjection> newInjections = ContainerUtil.mapNotNull(originalInjections,
(NullableFunction<BaseInjection, BaseInjection>)injection -> {
final Pair<PsiMethod, Integer> pair = injectionsMap.get(injection);
final String placeText = JavaLanguageInjectionSupport.getPatternStringForJavaPlace(pair.first, pair.second);
final BaseInjection newInjection = injection.copy();
newInjection.setPlaceEnabled(placeText, false);
return InjectorUtils.canBeRemoved(newInjection) ? null : newInjection;
});
configuration.replaceInjectionsWithUndo(project, newInjections, originalInjections, annotations);
return true;
}
private static void collectInjections(@NotNull GrLiteralContainer host,
@NotNull Configuration configuration,
@NotNull LanguageInjectionSupport support,
@NotNull final HashMap<BaseInjection, Pair<PsiMethod, Integer>> injectionsMap,
@NotNull final ArrayList<PsiElement> annotations) {
new GrConcatenationAwareInjector.InjectionProcessor(configuration, support, host) {
@Override
protected boolean processCommentInjectionInner(PsiVariable owner, PsiElement comment, BaseInjection injection) {
ContainerUtil.addAll(annotations, comment);
return true;
}
@Override
protected boolean processAnnotationInjectionInner(PsiModifierListOwner owner, PsiAnnotation[] annos) {
ContainerUtil.addAll(annotations, annos);
return true;
}
@Override
protected boolean processXmlInjections(BaseInjection injection, PsiModifierListOwner owner, PsiMethod method, int paramIndex) {
injectionsMap.put(injection, Pair.create(method, paramIndex));
return true;
}
}.processInjections();
}
private static boolean doInject(@NotNull String languageId,
@NotNull PsiElement psiElement,
@NotNull PsiLanguageInjectionHost host) {
final PsiElement target = getTopLevelInjectionTarget(psiElement);
final PsiElement parent = target.getParent();
final Project project = psiElement.getProject();
if (parent instanceof GrReturnStatement) {
final GrControlFlowOwner owner = ControlFlowUtils.findControlFlowOwner(parent);
if (owner instanceof GrOpenBlock && owner.getParent() instanceof GrMethod) {
return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (PsiMethod)owner.getParent(), -1, host, languageId);
}
}
else if (parent instanceof GrMethod) {
return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (GrMethod)parent, -1, host, languageId);
}
else if (parent instanceof GrAnnotationNameValuePair) {
final PsiReference ref = parent.getReference();
if (ref != null) {
final PsiElement resolved = ref.resolve();
if (resolved instanceof PsiMethod) {
return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (PsiMethod)resolved, -1, host, languageId);
}
}
}
else if (parent instanceof GrArgumentList && parent.getParent() instanceof GrMethodCall) {
final PsiMethod method = ((GrMethodCall)parent.getParent()).resolveMethod();
if (method != null) {
final int index = GrInjectionUtil.findParameterIndex(target, ((GrMethodCall)parent.getParent()));
if (index >= 0) {
return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, method, index, host, languageId);
}
}
}
else if (parent instanceof GrAssignmentExpression) {
final GrExpression expr = ((GrAssignmentExpression)parent).getLValue();
if (expr instanceof GrReferenceExpression) {
final PsiElement element = ((GrReferenceExpression)expr).resolve();
if (element != null) {
return doInject(languageId, element, host);
}
}
}
else {
if (parent instanceof PsiVariable) {
Processor<PsiLanguageInjectionHost> fixer = getAnnotationFixer(project, languageId);
if (JavaLanguageInjectionSupport.doAddLanguageAnnotation(project, (PsiModifierListOwner)parent, host, languageId, fixer)) return true;
}
else if (target instanceof PsiVariable && !(target instanceof LightElement)) {
Processor<PsiLanguageInjectionHost> fixer = getAnnotationFixer(project, languageId);
if (JavaLanguageInjectionSupport.doAddLanguageAnnotation(project, (PsiModifierListOwner)target, host, languageId, fixer)) return true;
}
}
return false;
}
private static Processor<PsiLanguageInjectionHost> getAnnotationFixer(@NotNull final Project project,
@NotNull final String languageId) {
return host -> {
if (host == null) return false;
final Configuration.AdvancedConfiguration configuration = Configuration.getProjectInstance(project).getAdvancedConfiguration();
boolean allowed = configuration.isSourceModificationAllowed();
configuration.setSourceModificationAllowed(true);
try {
return doInject(languageId, host, host);
}
finally {
configuration.setSourceModificationAllowed(allowed);
}
};
}
@Contract("null -> false")
private static boolean isStringLiteral(@Nullable PsiLanguageInjectionHost element) {
if (element instanceof GrStringContent) {
return true;
}
else if (element instanceof GrLiteral) {
final IElementType type = GrLiteralImpl.getLiteralType((GrLiteral)element);
return TokenSets.STRING_LITERALS.contains(type);
}
return false;
}
@NotNull
public static PsiElement getTopLevelInjectionTarget(@NotNull final PsiElement host) {
PsiElement target = host;
PsiElement parent = target.getParent();
for (; parent != null; target = parent, parent = target.getParent()) {
if (parent instanceof GrBinaryExpression) continue;
if (parent instanceof GrString) continue;
if (parent instanceof GrParenthesizedExpression) continue;
if (parent instanceof GrConditionalExpression && ((GrConditionalExpression)parent).getCondition() != target) continue;
if (parent instanceof GrAnnotationArrayInitializer) continue;
if (parent instanceof GrListOrMap) {
parent = parent.getParent(); continue;
}
break;
}
return target;
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.bucket;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.aggregations.bucket.sampler.DiversifiedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.sampler.Sampler;
import org.elasticsearch.search.aggregations.bucket.sampler.SamplerAggregator;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Max;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.test.ESIntegTestCase;
import java.util.Collection;
import java.util.List;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.search.aggregations.AggregationBuilders.max;
import static org.elasticsearch.search.aggregations.AggregationBuilders.sampler;
import static org.elasticsearch.search.aggregations.AggregationBuilders.terms;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
/**
* Tests the Sampler aggregation
*/
@ESIntegTestCase.SuiteScopeTestCase
public class DiversifiedSamplerIT extends ESIntegTestCase {
public static final int NUM_SHARDS = 2;
public String randomExecutionHint() {
return randomBoolean() ? null : randomFrom(SamplerAggregator.ExecutionMode.values()).toString();
}
@Override
public void setupSuiteScopeCluster() throws Exception {
assertAcked(prepareCreate("test").setSettings(
Settings.builder().put(SETTING_NUMBER_OF_SHARDS, NUM_SHARDS).put(SETTING_NUMBER_OF_REPLICAS, 0)).addMapping(
"book", "author", "type=keyword", "name", "type=keyword", "genre",
"type=keyword", "price", "type=float"));
createIndex("idx_unmapped");
// idx_unmapped_author is same as main index but missing author field
assertAcked(prepareCreate("idx_unmapped_author").setSettings(
Settings.builder().put(SETTING_NUMBER_OF_SHARDS, NUM_SHARDS).put(SETTING_NUMBER_OF_REPLICAS, 0))
.addMapping("book", "name", "type=keyword", "genre", "type=keyword", "price",
"type=float"));
ensureGreen();
String data[] = {
// "id,cat,name,price,inStock,author_t,series_t,sequence_i,genre_s",
"0553573403,book,A Game of Thrones,7.99,true,George R.R. Martin,A Song of Ice and Fire,1,fantasy",
"0553579908,book,A Clash of Kings,7.99,true,George R.R. Martin,A Song of Ice and Fire,2,fantasy",
"055357342X,book,A Storm of Swords,7.99,true,George R.R. Martin,A Song of Ice and Fire,3,fantasy",
"0553293354,book,Foundation,17.99,true,Isaac Asimov,Foundation Novels,1,scifi",
"0812521390,book,The Black Company,6.99,false,Glen Cook,The Chronicles of The Black Company,1,fantasy",
"0812550706,book,Ender's Game,6.99,true,Orson Scott Card,Ender,1,scifi",
"0441385532,book,Jhereg,7.95,false,Steven Brust,Vlad Taltos,1,fantasy",
"0380014300,book,Nine Princes In Amber,6.99,true,Roger Zelazny,the Chronicles of Amber,1,fantasy",
"0805080481,book,The Book of Three,5.99,true,Lloyd Alexander,The Chronicles of Prydain,1,fantasy",
"080508049X,book,The Black Cauldron,5.99,true,Lloyd Alexander,The Chronicles of Prydain,2,fantasy"
};
for (int i = 0; i < data.length; i++) {
String[] parts = data[i].split(",");
client().prepareIndex("test", "book", "" + i)
.setSource("author", parts[5], "name", parts[2], "genre", parts[8], "price", Float.parseFloat(parts[3])).get();
client().prepareIndex("idx_unmapped_author", "book", "" + i)
.setSource("name", parts[2], "genre", parts[8], "price", Float.parseFloat(parts[3])).get();
}
client().admin().indices().refresh(new RefreshRequest("test")).get();
}
public void testIssue10719() throws Exception {
// Tests that we can refer to nested elements under a sample in a path
// statement
boolean asc = randomBoolean();
SearchResponse response = client().prepareSearch("test").setTypes("book").setSearchType(SearchType.QUERY_THEN_FETCH)
.addAggregation(terms("genres")
.field("genre")
.order(BucketOrder.aggregation("sample>max_price.value", asc))
.subAggregation(sampler("sample").shardSize(100)
.subAggregation(max("max_price").field("price")))
).execute().actionGet();
assertSearchResponse(response);
Terms genres = response.getAggregations().get("genres");
Collection<? extends Bucket> genreBuckets = genres.getBuckets();
// For this test to be useful we need >1 genre bucket to compare
assertThat(genreBuckets.size(), greaterThan(1));
double lastMaxPrice = asc ? Double.MIN_VALUE : Double.MAX_VALUE;
for (Terms.Bucket genreBucket : genres.getBuckets()) {
Sampler sample = genreBucket.getAggregations().get("sample");
Max maxPriceInGenre = sample.getAggregations().get("max_price");
double price = maxPriceInGenre.getValue();
if (asc) {
assertThat(price, greaterThanOrEqualTo(lastMaxPrice));
} else {
assertThat(price, lessThanOrEqualTo(lastMaxPrice));
}
lastMaxPrice = price;
}
}
public void testSimpleDiversity() throws Exception {
int MAX_DOCS_PER_AUTHOR = 1;
DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100);
sampleAgg.field("author").maxDocsPerValue(MAX_DOCS_PER_AUTHOR).executionHint(randomExecutionHint());
sampleAgg.subAggregation(terms("authors").field("author"));
SearchResponse response = client().prepareSearch("test")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(new TermQueryBuilder("genre", "fantasy"))
.setFrom(0).setSize(60)
.addAggregation(sampleAgg)
.execute()
.actionGet();
assertSearchResponse(response);
Sampler sample = response.getAggregations().get("sample");
Terms authors = sample.getAggregations().get("authors");
List<? extends Bucket> testBuckets = authors.getBuckets();
for (Terms.Bucket testBucket : testBuckets) {
assertThat(testBucket.getDocCount(), lessThanOrEqualTo((long) NUM_SHARDS * MAX_DOCS_PER_AUTHOR));
}
}
public void testNestedDiversity() throws Exception {
// Test multiple samples gathered under buckets made by a parent agg
int MAX_DOCS_PER_AUTHOR = 1;
TermsAggregationBuilder rootTerms = terms("genres").field("genre");
DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100);
sampleAgg.field("author").maxDocsPerValue(MAX_DOCS_PER_AUTHOR).executionHint(randomExecutionHint());
sampleAgg.subAggregation(terms("authors").field("author"));
rootTerms.subAggregation(sampleAgg);
SearchResponse response = client().prepareSearch("test").setSearchType(SearchType.QUERY_THEN_FETCH)
.addAggregation(rootTerms).execute().actionGet();
assertSearchResponse(response);
Terms genres = response.getAggregations().get("genres");
List<? extends Bucket> genreBuckets = genres.getBuckets();
for (Terms.Bucket genreBucket : genreBuckets) {
Sampler sample = genreBucket.getAggregations().get("sample");
Terms authors = sample.getAggregations().get("authors");
List<? extends Bucket> testBuckets = authors.getBuckets();
for (Terms.Bucket testBucket : testBuckets) {
assertThat(testBucket.getDocCount(), lessThanOrEqualTo((long) NUM_SHARDS * MAX_DOCS_PER_AUTHOR));
}
}
}
public void testNestedSamples() throws Exception {
// Test samples nested under samples
int MAX_DOCS_PER_AUTHOR = 1;
int MAX_DOCS_PER_GENRE = 2;
DiversifiedAggregationBuilder rootSample = new DiversifiedAggregationBuilder("genreSample").shardSize(100)
.field("genre")
.maxDocsPerValue(MAX_DOCS_PER_GENRE);
DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100);
sampleAgg.field("author").maxDocsPerValue(MAX_DOCS_PER_AUTHOR).executionHint(randomExecutionHint());
sampleAgg.subAggregation(terms("authors").field("author"));
sampleAgg.subAggregation(terms("genres").field("genre"));
rootSample.subAggregation(sampleAgg);
SearchResponse response = client().prepareSearch("test").setSearchType(SearchType.QUERY_THEN_FETCH).addAggregation(rootSample)
.execute().actionGet();
assertSearchResponse(response);
Sampler genreSample = response.getAggregations().get("genreSample");
Sampler sample = genreSample.getAggregations().get("sample");
Terms genres = sample.getAggregations().get("genres");
List<? extends Bucket> testBuckets = genres.getBuckets();
for (Terms.Bucket testBucket : testBuckets) {
assertThat(testBucket.getDocCount(), lessThanOrEqualTo((long) NUM_SHARDS * MAX_DOCS_PER_GENRE));
}
Terms authors = sample.getAggregations().get("authors");
testBuckets = authors.getBuckets();
for (Terms.Bucket testBucket : testBuckets) {
assertThat(testBucket.getDocCount(), lessThanOrEqualTo((long) NUM_SHARDS * MAX_DOCS_PER_AUTHOR));
}
}
public void testPartiallyUnmappedDiversifyField() throws Exception {
// One of the indexes is missing the "author" field used for
// diversifying results
DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100).field("author")
.maxDocsPerValue(1);
sampleAgg.subAggregation(terms("authors").field("author"));
SearchResponse response = client().prepareSearch("idx_unmapped_author", "test").setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).addAggregation(sampleAgg)
.execute().actionGet();
assertSearchResponse(response);
Sampler sample = response.getAggregations().get("sample");
assertThat(sample.getDocCount(), greaterThan(0L));
Terms authors = sample.getAggregations().get("authors");
assertThat(authors.getBuckets().size(), greaterThan(0));
}
public void testWhollyUnmappedDiversifyField() throws Exception {
//All of the indices are missing the "author" field used for diversifying results
int MAX_DOCS_PER_AUTHOR = 1;
DiversifiedAggregationBuilder sampleAgg = new DiversifiedAggregationBuilder("sample").shardSize(100);
sampleAgg.field("author").maxDocsPerValue(MAX_DOCS_PER_AUTHOR).executionHint(randomExecutionHint());
sampleAgg.subAggregation(terms("authors").field("author"));
SearchResponse response = client().prepareSearch("idx_unmapped", "idx_unmapped_author").setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).addAggregation(sampleAgg).execute().actionGet();
assertSearchResponse(response);
Sampler sample = response.getAggregations().get("sample");
assertThat(sample.getDocCount(), equalTo(0L));
Terms authors = sample.getAggregations().get("authors");
assertNull(authors);
}
}
| |
/**
* Copyright (c) 2011-2014 SmeshLink Technology Corporation.
* All rights reserved.
*
* This file is part of the Misty, a sensor cloud for WSN.
*/
package com.smeshlink.misty.service.channel;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import com.smeshlink.misty.service.ICredential;
import com.smeshlink.misty.service.IServiceRequest;
import com.smeshlink.misty.service.IServiceResponse;
import com.smeshlink.misty.service.MistyService;
import com.smeshlink.misty.service.ServiceException;
import com.smeshlink.misty.service.UserCredential;
/**
* HTTP channel.
*
* @author Longshine
*
*/
public class HttpChannel implements IServiceChannel {
private String host;
private HttpClient client = new HttpClient();
public HttpChannel(String host) {
this.host = host;
}
public void setRequestListener(IRequestListener listener) {
// do nothing
}
public void setTimeout(int timeout) {
// TODO
}
public int getTimeout() {
// TODO
return 0;
}
public void setHost(String host) {
this.host = host;
}
public String getHost() {
return host;
}
public IServiceResponse execute(IServiceRequest request) {
if (request.getFormat() == null)
request.setFormat("json");
HttpMethod method = buildMethod(request);
try {
return new HttpResponse(request.getResource(), client.executeMethod(method), method);
} catch (IOException e) {
throw ServiceException.error(e);
}
}
private HttpMethod buildMethod(IServiceRequest request) {
String method = request.getMethod();
String entity = null;
String contentType = MistyService.getContentType(request.getFormat());
HttpMethod m = null;
if ("GET".equals(method)) {
m = new GetMethod();
} else if ("POST".equals(method)) {
PostMethod post = new PostMethod();
try {
post.setRequestEntity(new StringRequestEntity(entity, contentType, "utf-8"));
} catch (UnsupportedEncodingException e) {
ServiceException.badRequest(e.getMessage());
}
m = post;
} else if ("PUT".equals(method)) {
PutMethod put = new PutMethod();
try {
put.setRequestEntity(new StringRequestEntity(entity, contentType, "utf-8"));
} catch (UnsupportedEncodingException e) {
ServiceException.badRequest(e.getMessage());
}
m = put;
} else if ("DELETE".equals(method)) {
m = new DeleteMethod();
} else {
ServiceException.badRequest("Unknown request method " + method);
}
String path = request.getResource();
if (request.getFormat() != null)
path += "." + request.getFormat();
try {
m.setURI(new URI("http", host, path, null, null));
} catch (URIException e) {
ServiceException.badRequest("Invalid URI requested.");
}
Map headers = request.getHeaders();
if (headers != null) {
for (Iterator it = headers.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Entry) it.next();
if (entry.getKey() == null || entry.getValue() == null)
continue;
m.setRequestHeader(entry.getKey().toString(), entry.getValue().toString());
}
}
m.setRequestHeader(MistyService.HEADER_USER_AGENT, MistyService.VERSION);
m.setRequestHeader(MistyService.HEADER_ACCEPT, contentType);
ICredential cred = request.getCredential();
if (cred == null) {
client.getParams().setAuthenticationPreemptive(false);
client.getState().clearCredentials();
} else if (cred instanceof UserCredential) {
UserCredential uc = (UserCredential) cred;
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(uc.getUsername(), uc.getPassword()));
} else {
ICredential.Pair pair = cred.getCredential();
m.setRequestHeader(pair.getKey(), pair.getValue());
}
Map params = request.getParameters();
if (params != null) {
for (Iterator it = params.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Entry) it.next();
if (entry.getKey() == null || entry.getValue() == null)
continue;
m.getParams().setParameter(entry.getKey().toString(), entry.getValue());
}
}
return m;
}
class HttpResponse implements IServiceResponse {
private final String resource;
private final int statusCode;
private HttpMethod method;
public HttpResponse(String resource, int statusCode, HttpMethod method) {
this.resource = resource;
this.statusCode = statusCode;
this.method = method;
}
public String getResource() {
return resource;
}
public int getStatus() {
return statusCode;
}
public Object getBody() {
return null;
}
public Map getHeaders() {
Map map = new HashMap();
Header[] headers = method.getResponseHeaders();
for (int i = 0; i < headers.length; i++) {
map.put(headers[i].getName(), headers[i].getValue());
}
return map;
}
public String getToken() {
return null;
}
public void setToken(String token) {
// do nothing
}
public InputStream getResponseStream() throws IOException {
return method.getResponseBodyAsStream();
}
public void dispose() {
method.releaseConnection();
}
}
}
| |
/* Copyright (c) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.wave.api;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.wave.api.impl.WaveletData;
import junit.framework.TestCase;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* Test cases for {@link Wavelet}.
*/
public class WaveletTest extends TestCase {
private static final WaveId WAVE_ID = WaveId.deserialise("google.com!wave1");
private static final WaveletId WAVELET_ID = WaveletId.deserialise("google.com!wavelet1");
private OperationQueue opQueue;
private Wavelet wavelet;
private Blip rootBlip;
@Override
protected void setUp() throws Exception {
super.setUp();
rootBlip = mock(Blip.class);
Map<String, String> dataDocument = new HashMap<String, String>();
Set<String> tags = Collections.emptySet();
Map<String, Blip> blips = new HashMap<String, Blip>();
blips.put("blip1", rootBlip);
Set<String> participants = new LinkedHashSet<String>();
participants.add("foo@bar.com");
Map<String, String> roles = new HashMap<String, String>();
opQueue = mock(OperationQueue.class);
wavelet = new Wavelet(WAVE_ID, WAVELET_ID, "foo@bar.com", 1l, 1l, "Hello world", "blip1",
roles, participants, dataDocument, tags, blips, opQueue);
}
public void testSetTitle() throws Exception {
when(rootBlip.getContent()).thenReturn("\nOld title\n\nContent");
wavelet.setTitle("New title");
verify(opQueue).setTitleOfWavelet(wavelet, "New title");
verify(rootBlip).setContent("\nNew title\n\nContent");
}
public void testSetTitleAdjustRootBlipWithOneLineProperly() throws Exception {
when(rootBlip.getContent()).thenReturn("\nOld title");
wavelet.setTitle("New title");
verify(opQueue).setTitleOfWavelet(wavelet, "New title");
verify(rootBlip).setContent("\nNew title\n");
}
public void testSetTitleAdjustEmptyRootBlipProperly() throws Exception {
when(rootBlip.getContent()).thenReturn("\n");
wavelet.setTitle("New title");
verify(opQueue).setTitleOfWavelet(wavelet, "New title");
verify(rootBlip).setContent("\nNew title\n");
}
public void testSetRobotAddress() throws Exception {
assertNull(wavelet.getRobotAddress());
wavelet.setRobotAddress("foo@appspot.com");
assertEquals("foo@appspot.com", wavelet.getRobotAddress());
try {
wavelet.setRobotAddress("bar@appspot.com");
fail("Should have failed when trying to call Wavelet.setRobotAddress() for the second time");
} catch (IllegalStateException e) {
assertEquals("Robot address has been set previously to foo@appspot.com", e.getMessage());
}
}
public void testGetDomain() throws Exception {
assertEquals("google.com", wavelet.getDomain());
}
public void testProxyFor() throws Exception {
OperationQueue proxiedQueue = mock(OperationQueue.class);
when(opQueue.proxyFor("user2")).thenReturn(proxiedQueue);
wavelet.setRobotAddress("foo+user1#5@appspot.com");
Wavelet proxiedWavelet = wavelet.proxyFor("user2");
assertTrue(wavelet.getParticipants().contains("foo+user2#5@appspot.com"));
assertEquals(proxiedQueue, proxiedWavelet.getOperationQueue());
}
public void testProxyForShouldFailIfProxyIdIsInvalid() throws Exception {
try {
wavelet.proxyFor("foo@gmail.com");
fail("Should have failed since proxy id is not encoded.");
} catch (IllegalArgumentException e) {
// Expected.
}
}
public void testSubmitWith() throws Exception {
OperationQueue otherOpQueue = mock(OperationQueue.class);
Set<String> participants = new LinkedHashSet<String>();
participants.add("foo@bar.com");
Map<String, String> roles = new HashMap<String, String>();
Wavelet other = new Wavelet(WAVE_ID, WAVELET_ID, "foo@bar.com", 1l, 1l, "Hello world",
"blip1", roles, participants, new HashMap<String, String>(),
Collections.<String>emptySet(), new HashMap<String, Blip>(), otherOpQueue);
wavelet.submitWith(other);
verify(opQueue).submitWith(otherOpQueue);
}
public void testReply() throws Exception {
assertEquals(1, wavelet.getBlips().size());
Blip replyBlip1 = mock(Blip.class);
when(replyBlip1.getBlipId()).thenReturn("replyblip1");
Blip replyBlip2 = mock(Blip.class);
when(replyBlip2.getBlipId()).thenReturn("replyblip2");
when(opQueue.appendBlipToWavelet(wavelet, "\n")).thenReturn(replyBlip1);
when(opQueue.appendBlipToWavelet(wavelet, "\nFoo")).thenReturn(replyBlip2);
try {
wavelet.reply(null);
fail("Should have failed when calling Wavelet.reply(null).");
} catch (IllegalArgumentException e) {
// Expected.
}
try {
wavelet.reply("Foo");
fail("Should have failed when calling Wavelet.reply(String) with arg that doesn't start " +
"with a newline char.");
} catch (IllegalArgumentException e) {
// Expected.
}
wavelet.reply("\n");
wavelet.reply("\nFoo");
assertEquals(3, wavelet.getBlips().size());
assertTrue(wavelet.getBlips().keySet().contains("replyblip1"));
assertTrue(wavelet.getBlips().keySet().contains("replyblip2"));
}
public void testDeleteByBlip() throws Exception {
Blip parentBlip = mock(Blip.class);
when(parentBlip.getBlipId()).thenReturn("parentblipid");
Blip childBlip = mock(Blip.class);
when(childBlip.getBlipId()).thenReturn("childblipid");
when(childBlip.getParentBlip()).thenReturn(parentBlip);
Map<String, Blip> blips = new HashMap<String, Blip>();
blips.put("parentblipid", parentBlip);
blips.put("childblipid", childBlip);
Set<String> participants = new LinkedHashSet<String>();
participants.add("foo@bar.com");
Map<String, String> roles = new HashMap<String, String>();
wavelet = new Wavelet(WAVE_ID, WAVELET_ID, "foo@bar.com", 1l, 1l, "Hello world",
"parentblipid", roles, participants, new HashMap<String, String>(),
new LinkedHashSet<String>(), blips, opQueue);
assertEquals(2, wavelet.getBlips().size());
wavelet.delete(childBlip);
assertEquals(1, wavelet.getBlips().size());
verify(parentBlip).deleteChildBlipId("childblipid");
verify(opQueue).deleteBlip(wavelet, "childblipid");
}
public void testDeleteByBlipId() throws Exception {
assertEquals(1, wavelet.getBlips().size());
assertEquals("blip1", wavelet.getBlips().entrySet().iterator().next().getKey());
wavelet.delete("blip1");
assertEquals(0, wavelet.getBlips().size());
verify(opQueue).deleteBlip(wavelet, "blip1");
}
public void testSerializeAndDeserialize() throws Exception {
Blip blipOne = mock(Blip.class);
when(blipOne.getBlipId()).thenReturn("blip1");
Map<String, String> dataDocument = new HashMap<String, String>();
Set<String> tags = Collections.<String>emptySet();
Map<String, Blip> blips = new HashMap<String, Blip>();
blips.put("blip1", blipOne);
Set<String> participants = new LinkedHashSet<String>();
participants.add("foo@bar.com");
Map<String, String> roles = new HashMap<String, String>();
OperationQueue opQueue = mock(OperationQueue.class);
Wavelet expectedWavelet = new Wavelet(WaveId.deserialise("google.com!wave1"),
WaveletId.deserialise("google.com!wavelet1"), "foo@bar.com", 1l, 1l, "Hello world",
"blip1", roles, participants, dataDocument, tags, blips, opQueue);
WaveletData waveletData = expectedWavelet.serialize();
Wavelet actualWavelet = Wavelet.deserialize(opQueue, blips, waveletData);
assertEquals(expectedWavelet.getWaveId(), actualWavelet.getWaveId());
assertEquals(expectedWavelet.getWaveletId(), actualWavelet.getWaveletId());
assertEquals(expectedWavelet.getRootBlip().getBlipId(),
actualWavelet.getRootBlip().getBlipId());
assertEquals(expectedWavelet.getCreationTime(), actualWavelet.getCreationTime());
assertEquals(expectedWavelet.getCreator(), actualWavelet.getCreator());
assertEquals(expectedWavelet.getLastModifiedTime(), actualWavelet.getLastModifiedTime());
assertEquals(expectedWavelet.getTitle(), actualWavelet.getTitle());
assertEquals(expectedWavelet.getParticipants().size(), actualWavelet.getParticipants().size());
assertEquals(expectedWavelet.getTags().size(), actualWavelet.getTags().size());
assertEquals(expectedWavelet.getDataDocuments().size(),
actualWavelet.getDataDocuments().size());
}
}
| |
/****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package aos.t4f.activemq.demo;
/*
* Licensed to the AOS Community (AOS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The AOS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
* The Vendor synchronously, and in a single transaction, receives the
* order from VendorOrderQueue and sends messages to the two Suppliers via
* MonitorOrderQueue and StorageOrderQueue.
* The responses are received asynchronously; when both responses come
* back, the order confirmation message is sent back to the Retailer.
*/
public class Vendor implements Runnable, MessageListener {
private String url;
private String user;
private String password;
private Session asyncSession;
private int numSuppliers = 2;
private Object supplierLock = new Object();
public Vendor(String url, String user, String password) {
this.url = url;
this.user = user;
this.password = password;
}
public void run() {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
Session session = null;
Destination orderQueue;
Destination monitorOrderQueue;
Destination storageOrderQueue;
TemporaryQueue vendorConfirmQueue;
MessageConsumer orderConsumer = null;
MessageProducer monitorProducer = null;
MessageProducer storageProducer = null;
try {
Connection connection = connectionFactory.createConnection();
session = connection.createSession(true, Session.SESSION_TRANSACTED);
orderQueue = session.createQueue("VendorOrderQueue");
monitorOrderQueue = session.createQueue("MonitorOrderQueue");
storageOrderQueue = session.createQueue("StorageOrderQueue");
orderConsumer = session.createConsumer(orderQueue);
monitorProducer = session.createProducer(monitorOrderQueue);
storageProducer = session.createProducer(storageOrderQueue);
Connection asyncconnection = connectionFactory.createConnection();
asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED);
vendorConfirmQueue = asyncSession.createTemporaryQueue();
MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue);
confirmConsumer.setMessageListener(this);
asyncconnection.start();
connection.start();
while (true) {
Order order = null;
try {
Message inMessage = orderConsumer.receive();
MapMessage message;
if (inMessage instanceof MapMessage) {
message = (MapMessage) inMessage;
} else {
// end of stream
Message outMessage = session.createMessage();
outMessage.setJMSReplyTo(vendorConfirmQueue);
monitorProducer.send(outMessage);
storageProducer.send(outMessage);
session.commit();
break;
}
// Randomly throw an exception in here to simulate a Database error
// and trigger a rollback of the transaction
if (new Random().nextInt(3) == 0) {
throw new JMSException("Simulated Database Error.");
}
order = new Order(message);
MapMessage orderMessage = session.createMapMessage();
orderMessage.setJMSReplyTo(vendorConfirmQueue);
orderMessage.setInt("VendorOrderNumber", order.getOrderNumber());
int quantity = message.getInt("Quantity");
System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item"));
orderMessage.setInt("Quantity", quantity);
orderMessage.setString("Item", "Monitor");
monitorProducer.send(orderMessage);
System.out.println("Vendor: ordered " + quantity + " Monitor(s)");
orderMessage.setString("Item", "HardDrive");
storageProducer.send(orderMessage);
System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)");
session.commit();
System.out.println("Vendor: Comitted Transaction 1");
} catch (JMSException e) {
System.out.println("Vendor: JMSException Occured: " + e.getMessage());
e.printStackTrace();
session.rollback();
System.out.println("Vendor: Rolled Back Transaction.");
}
}
synchronized (supplierLock) {
while (numSuppliers > 0) {
try {
supplierLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
connection.close();
asyncconnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
public void onMessage(Message message) {
if (!(message instanceof MapMessage)) {
synchronized(supplierLock) {
numSuppliers--;
supplierLock.notifyAll();
}
try {
asyncSession.commit();
return;
} catch (JMSException e) {
e.printStackTrace();
}
}
int orderNumber = -1;
try {
MapMessage componentMessage = (MapMessage) message;
orderNumber = componentMessage.getInt("VendorOrderNumber");
Order order = Order.getOrder(orderNumber);
order.processSubOrder(componentMessage);
asyncSession.commit();
if (! "Pending".equals(order.getStatus())) {
System.out.println("Vendor: Completed processing for order " + orderNumber);
MessageProducer replyProducer = asyncSession.createProducer(order.getMessage().getJMSReplyTo());
MapMessage replyMessage = asyncSession.createMapMessage();
if ("Fulfilled".equals(order.getStatus())) {
replyMessage.setBoolean("OrderAccepted", true);
System.out.println("Vendor: sent " + order.quantity + " computer(s)");
} else {
replyMessage.setBoolean("OrderAccepted", false);
System.out.println("Vendor: unable to send " + order.quantity + " computer(s)");
}
replyProducer.send(replyMessage);
asyncSession.commit();
System.out.println("Vender: committed transaction 2");
}
} catch (JMSException e) {
e.printStackTrace();
}
}
public static class Order {
private static Map<Integer, Order> pendingOrders = new HashMap<Integer, Order>();
private static int nextOrderNumber = 1;
private int orderNumber;
private int quantity;
private MapMessage monitor = null;
private MapMessage storage = null;
private MapMessage message;
private String status;
public Order(MapMessage message) {
this.orderNumber = nextOrderNumber++;
this.message = message;
try {
this.quantity = message.getInt("Quantity");
} catch (JMSException e) {
e.printStackTrace();
this.quantity = 0;
}
status = "Pending";
pendingOrders.put(orderNumber, this);
}
public Object getStatus() {
return status;
}
public int getOrderNumber() {
return orderNumber;
}
public static int getOutstandingOrders() {
return pendingOrders.size();
}
public static Order getOrder(int number) {
return pendingOrders.get(number);
}
public MapMessage getMessage() {
return message;
}
public void processSubOrder(MapMessage message) {
String itemName = null;
try {
itemName = message.getString("Item");
} catch (JMSException e) {
e.printStackTrace();
}
if ("Monitor".equals(itemName)) {
monitor = message;
} else if ("HardDrive".equals(itemName)) {
storage = message;
}
if (null != monitor && null != storage) {
// Received both messages
try {
if (quantity > monitor.getInt("Quantity")) {
status = "Cancelled";
} else if (quantity > storage.getInt("Quantity")) {
status = "Cancelled";
} else {
status = "Fulfilled";
}
} catch (JMSException e) {
e.printStackTrace();
status = "Cancelled";
}
}
}
}
public static void main(String... args) {
String url = "tcp://localhost:61616";
String user = null;
String password = null;
if (args.length >= 1) {
url = args[0];
}
if (args.length >= 2) {
user = args[1];
}
if (args.length >= 3) {
password = args[2];
}
Vendor v = new Vendor(url, user, password);
new Thread(v, "Vendor").start();
}
}
| |
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticmapreduce.model;
import java.io.Serializable;
/**
* <p>
* This output contains the boostrap actions detail .
* </p>
*/
public class ListBootstrapActionsResult implements Serializable, Cloneable {
/**
* <p>
* The bootstrap actions associated with the cluster .
* </p>
*/
private com.amazonaws.internal.SdkInternalList<Command> bootstrapActions;
/**
* <p>
* The pagination token that indicates the next set of results to retrieve .
* </p>
*/
private String marker;
/**
* <p>
* The bootstrap actions associated with the cluster .
* </p>
*
* @return The bootstrap actions associated with the cluster .
*/
public java.util.List<Command> getBootstrapActions() {
if (bootstrapActions == null) {
bootstrapActions = new com.amazonaws.internal.SdkInternalList<Command>();
}
return bootstrapActions;
}
/**
* <p>
* The bootstrap actions associated with the cluster .
* </p>
*
* @param bootstrapActions
* The bootstrap actions associated with the cluster .
*/
public void setBootstrapActions(
java.util.Collection<Command> bootstrapActions) {
if (bootstrapActions == null) {
this.bootstrapActions = null;
return;
}
this.bootstrapActions = new com.amazonaws.internal.SdkInternalList<Command>(
bootstrapActions);
}
/**
* <p>
* The bootstrap actions associated with the cluster .
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setBootstrapActions(java.util.Collection)} or
* {@link #withBootstrapActions(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param bootstrapActions
* The bootstrap actions associated with the cluster .
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ListBootstrapActionsResult withBootstrapActions(
Command... bootstrapActions) {
if (this.bootstrapActions == null) {
setBootstrapActions(new com.amazonaws.internal.SdkInternalList<Command>(
bootstrapActions.length));
}
for (Command ele : bootstrapActions) {
this.bootstrapActions.add(ele);
}
return this;
}
/**
* <p>
* The bootstrap actions associated with the cluster .
* </p>
*
* @param bootstrapActions
* The bootstrap actions associated with the cluster .
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ListBootstrapActionsResult withBootstrapActions(
java.util.Collection<Command> bootstrapActions) {
setBootstrapActions(bootstrapActions);
return this;
}
/**
* <p>
* The pagination token that indicates the next set of results to retrieve .
* </p>
*
* @param marker
* The pagination token that indicates the next set of results to
* retrieve .
*/
public void setMarker(String marker) {
this.marker = marker;
}
/**
* <p>
* The pagination token that indicates the next set of results to retrieve .
* </p>
*
* @return The pagination token that indicates the next set of results to
* retrieve .
*/
public String getMarker() {
return this.marker;
}
/**
* <p>
* The pagination token that indicates the next set of results to retrieve .
* </p>
*
* @param marker
* The pagination token that indicates the next set of results to
* retrieve .
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ListBootstrapActionsResult withMarker(String marker) {
setMarker(marker);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getBootstrapActions() != null)
sb.append("BootstrapActions: " + getBootstrapActions() + ",");
if (getMarker() != null)
sb.append("Marker: " + getMarker());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListBootstrapActionsResult == false)
return false;
ListBootstrapActionsResult other = (ListBootstrapActionsResult) obj;
if (other.getBootstrapActions() == null
^ this.getBootstrapActions() == null)
return false;
if (other.getBootstrapActions() != null
&& other.getBootstrapActions().equals(
this.getBootstrapActions()) == false)
return false;
if (other.getMarker() == null ^ this.getMarker() == null)
return false;
if (other.getMarker() != null
&& other.getMarker().equals(this.getMarker()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getBootstrapActions() == null) ? 0 : getBootstrapActions()
.hashCode());
hashCode = prime * hashCode
+ ((getMarker() == null) ? 0 : getMarker().hashCode());
return hashCode;
}
@Override
public ListBootstrapActionsResult clone() {
try {
return (ListBootstrapActionsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| |
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2019 Guardsquare NV
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.optimize.info;
import proguard.classfile.*;
import proguard.classfile.attribute.*;
import proguard.classfile.attribute.visitor.AttributeVisitor;
import proguard.classfile.constant.*;
import proguard.classfile.constant.visitor.ConstantVisitor;
import proguard.classfile.instruction.*;
import proguard.classfile.instruction.visitor.InstructionVisitor;
import proguard.classfile.util.*;
import proguard.evaluation.*;
import proguard.evaluation.value.*;
import proguard.optimize.evaluation.*;
import proguard.util.ArrayUtil;
/**
* This AttributeVisitor can tell whether reference parameters and instances
* are escaping, are modified, or are returned.
*
* @see ParameterEscapeMarker
* @author Eric Lafortune
*/
public class ReferenceEscapeChecker
extends SimplifiedVisitor
implements AttributeVisitor,
InstructionVisitor,
ConstantVisitor
{
//*
private static final boolean DEBUG = false;
/*/
private static boolean DEBUG = System.getProperty("rec") != null;
//*/
private boolean[] instanceEscaping = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
private boolean[] instanceReturned = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
private boolean[] instanceModified = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
private boolean[] externalInstance = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
// private boolean[] exceptionEscaping = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
// private boolean[] exceptionReturned = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
// private boolean[] exceptionModified = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
private final PartialEvaluator partialEvaluator;
private final boolean runPartialEvaluator;
// Parameters and values for visitor methods.
private Method referencingMethod;
private int referencingOffset;
private int referencingPopCount;
/**
* Creates a new ReferenceEscapeChecker.
*/
public ReferenceEscapeChecker()
{
this(new ReferenceTracingValueFactory(new BasicValueFactory()));
}
/**
* Creates a new ReferenceEscapeChecker. This private constructor gets around
* the constraint that it's not allowed to add statements before calling
* 'this'.
*/
private ReferenceEscapeChecker(ReferenceTracingValueFactory referenceTracingValueFactory)
{
this(new PartialEvaluator(referenceTracingValueFactory,
new ParameterTracingInvocationUnit(new BasicInvocationUnit(referenceTracingValueFactory)),
true,
referenceTracingValueFactory),
true);
}
/**
* Creates a new ReferenceEscapeChecker.
* @param partialEvaluator the evaluator to be used for the analysis.
* @param runPartialEvaluator specifies whether to run this evaluator on
* every code attribute that is visited.
*/
public ReferenceEscapeChecker(PartialEvaluator partialEvaluator,
boolean runPartialEvaluator)
{
this.partialEvaluator = partialEvaluator;
this.runPartialEvaluator = runPartialEvaluator;
}
/**
* Returns whether the instance created or retrieved at the specified
* instruction offset is escaping.
*/
public boolean isInstanceEscaping(int instructionOffset)
{
return instanceEscaping[instructionOffset];
}
/**
* Returns whether the instance created or retrieved at the specified
* instruction offset is being returned.
*/
public boolean isInstanceReturned(int instructionOffset)
{
return instanceReturned[instructionOffset];
}
/**
* Returns whether the instance created or retrieved at the specified
* instruction offset is being modified.
*/
public boolean isInstanceModified(int instructionOffset)
{
return instanceModified[instructionOffset];
}
/**
* Returns whether the instance created or retrieved at the specified
* instruction offset is external to this method and its invoked methods.
*/
public boolean isInstanceExternal(int instructionOffset)
{
return externalInstance[instructionOffset];
}
// Implementations for AttributeVisitor.
public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
{
// Evaluate the method.
if (runPartialEvaluator)
{
partialEvaluator.visitCodeAttribute(clazz, method, codeAttribute);
}
int codeLength = codeAttribute.u4codeLength;
// Initialize the global arrays.
instanceEscaping = ArrayUtil.ensureArraySize(instanceEscaping, codeLength, false);
instanceReturned = ArrayUtil.ensureArraySize(instanceReturned, codeLength, false);
instanceModified = ArrayUtil.ensureArraySize(instanceModified, codeLength, false);
externalInstance = ArrayUtil.ensureArraySize(externalInstance, codeLength, false);
// Mark the parameters and instances that are escaping from the code.
codeAttribute.instructionsAccept(clazz, method, partialEvaluator.tracedInstructionFilter(this));
if (DEBUG)
{
System.out.println();
System.out.println("ReferenceEscapeChecker: ["+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"]");
for (int index = 0; index < codeLength; index++)
{
if (partialEvaluator.isInstruction(index))
{
System.out.println(" " +
(instanceEscaping[index] ? 'E' : '.') +
(instanceReturned[index] ? 'R' : '.') +
(instanceModified[index] ? 'M' : '.') +
(externalInstance[index] ? 'X' : '.') +
' ' +
InstructionFactory.create(codeAttribute.code, index).toString(index));
}
}
}
}
// Implementations for InstructionVisitor.
public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
{
switch (simpleInstruction.opcode)
{
case InstructionConstants.OP_AASTORE:
// Mark array reference values whose element is modified.
markModifiedReferenceValues(offset,
simpleInstruction.stackPopCount(clazz) - 1);
// Mark reference values that are put in the array.
markEscapingReferenceValues(offset, 0);
break;
case InstructionConstants.OP_IASTORE:
case InstructionConstants.OP_LASTORE:
case InstructionConstants.OP_FASTORE:
case InstructionConstants.OP_DASTORE:
case InstructionConstants.OP_BASTORE:
case InstructionConstants.OP_CASTORE:
case InstructionConstants.OP_SASTORE:
// Mark array reference values whose element is modified.
markModifiedReferenceValues(offset,
simpleInstruction.stackPopCount(clazz) - 1);
break;
case InstructionConstants.OP_ARETURN:
// Mark the returned reference values.
markReturnedReferenceValues(offset, 0);
break;
case InstructionConstants.OP_ATHROW:
// Mark the escaping reference values.
markEscapingReferenceValues(offset, 0);
break;
}
}
public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
{
switch (constantInstruction.opcode)
{
case InstructionConstants.OP_GETSTATIC:
case InstructionConstants.OP_GETFIELD:
// Mark external reference values.
markExternalReferenceValue(offset);
break;
case InstructionConstants.OP_PUTSTATIC:
// Mark reference values that are put in the field.
markEscapingReferenceValues(offset, 0);
break;
case InstructionConstants.OP_PUTFIELD:
// Mark reference reference values whose field is modified.
markModifiedReferenceValues(offset,
constantInstruction.stackPopCount(clazz) - 1);
// Mark reference values that are put in the field.
markEscapingReferenceValues(offset, 0);
break;
case InstructionConstants.OP_INVOKEVIRTUAL:
case InstructionConstants.OP_INVOKESPECIAL:
case InstructionConstants.OP_INVOKESTATIC:
case InstructionConstants.OP_INVOKEINTERFACE:
// Mark reference reference values that are modified as parameters
// of the invoked method.
// Mark reference values that are escaping as parameters
// of the invoked method.
// Mark escaped reference reference values in the invoked method.
referencingMethod = method;
referencingOffset = offset;
referencingPopCount = constantInstruction.stackPopCount(clazz);
clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
break;
}
}
// Implementations for ConstantVisitor.
public void visitAnyConstant(Clazz clazz, Constant constant) {}
public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant)
{
clazz.constantPoolEntryAccept(fieldrefConstant.u2classIndex, this);
}
public void visitAnyMethodrefConstant(Clazz clazz, RefConstant refConstant)
{
Method referencedMethod = (Method)refConstant.referencedMember;
// Mark reference reference values that are passed to the method.
for (int index = 0; index < referencingPopCount; index++)
{
int stackEntryIndex = referencingPopCount - index - 1;
TracedStack stackBefore = partialEvaluator.getStackBefore(referencingOffset);
Value stackEntry = stackBefore.getTop(stackEntryIndex);
if (stackEntry.computationalType() == Value.TYPE_REFERENCE)
{
// Is the parameter escaping from the referenced method?
if (referencedMethod == null ||
ParameterEscapeMarker.isParameterEscaping(referencedMethod, index))
{
markEscapingReferenceValues(referencingOffset,
stackEntryIndex);
}
// Is the parameter being modified in the referenced method?
if (referencedMethod == null ||
ParameterEscapeMarker.isParameterModified(referencedMethod, index))
{
markModifiedReferenceValues(referencingOffset,
stackEntryIndex);
}
}
}
// Is the return value from the referenced method external?
String returnType =
ClassUtil.internalMethodReturnType(refConstant.getType(clazz));
if (referencedMethod == null ||
((ClassUtil.isInternalClassType(returnType) ||
ClassUtil.isInternalArrayType(returnType)) &&
ParameterEscapeMarker.returnsExternalValues(referencedMethod)))
{
markExternalReferenceValue(referencingOffset);
}
}
// Small utility methods.
/**
* Marks the producing offsets of the specified stack entry at the given
* instruction offset.
*/
private void markEscapingReferenceValues(int instructionOffset,
int stackEntryIndex)
{
TracedStack stackBefore = partialEvaluator.getStackBefore(instructionOffset);
Value stackEntry = stackBefore.getTop(stackEntryIndex);
if (stackEntry.computationalType() == Value.TYPE_REFERENCE)
{
ReferenceValue referenceValue = stackEntry.referenceValue();
// The null reference value may not have a trace value.
if (referenceValue.isNull() != Value.ALWAYS)
{
markEscapingReferenceValues(referenceValue);
}
}
}
/**
* Marks the producing offsets of the given traced reference value.
*/
private void markEscapingReferenceValues(ReferenceValue referenceValue)
{
TracedReferenceValue tracedReferenceValue = (TracedReferenceValue)referenceValue;
InstructionOffsetValue instructionOffsetValue = tracedReferenceValue.getTraceValue().instructionOffsetValue();
int parameterCount = instructionOffsetValue.instructionOffsetCount();
for (int index = 0; index < parameterCount; index++)
{
if (!instructionOffsetValue.isMethodParameter(index))
{
instanceEscaping[instructionOffsetValue.instructionOffset(index)] = true;
}
}
}
/**
* Marks the producing offsets of the specified stack entry at the given
* instruction offset.
*/
private void markReturnedReferenceValues(int instructionOffset,
int stackEntryIndex)
{
TracedStack stackBefore = partialEvaluator.getStackBefore(instructionOffset);
ReferenceValue referenceValue = stackBefore.getTop(stackEntryIndex).referenceValue();
// The null reference value may not have a trace value.
if (referenceValue.isNull() != Value.ALWAYS)
{
markReturnedReferenceValues(referenceValue);
}
}
/**
* Marks the producing offsets of the given traced reference value.
*/
private void markReturnedReferenceValues(ReferenceValue referenceValue)
{
TracedReferenceValue tracedReferenceValue = (TracedReferenceValue)referenceValue;
InstructionOffsetValue instructionOffsetValue = tracedReferenceValue.getTraceValue().instructionOffsetValue();
int parameterCount = instructionOffsetValue.instructionOffsetCount();
for (int index = 0; index < parameterCount; index++)
{
if (!instructionOffsetValue.isMethodParameter(index))
{
instanceReturned[instructionOffsetValue.instructionOffset(index)] = true;
}
}
}
/**
* Marks the producing offsets of the specified stack entry at the given
* instruction offset.
*/
private void markModifiedReferenceValues(int instructionOffset,
int stackEntryIndex)
{
TracedStack stackBefore = partialEvaluator.getStackBefore(instructionOffset);
ReferenceValue referenceValue = stackBefore.getTop(stackEntryIndex).referenceValue();
// The null reference value may not have a trace value.
if (referenceValue.isNull() != Value.ALWAYS)
{
markModifiedReferenceValues(referenceValue);
}
}
/**
* Marks the producing offsets of the given traced reference value.
*/
private void markModifiedReferenceValues(ReferenceValue referenceValue)
{
TracedReferenceValue tracedReferenceValue = (TracedReferenceValue)referenceValue;
InstructionOffsetValue instructionOffsetValue = tracedReferenceValue.getTraceValue().instructionOffsetValue();
int parameterCount = instructionOffsetValue.instructionOffsetCount();
for (int index = 0; index < parameterCount; index++)
{
if (!instructionOffsetValue.isMethodParameter(index))
{
instanceModified[instructionOffsetValue.instructionOffset(index)] = true;
}
}
}
/**
* Marks the producing offsets of the specified stack entry at the given
* instruction offset.
*/
private void markExternalReferenceValue(int offset)
{
externalInstance[offset] = true;
}
}
| |
/*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.corba.se.impl.orbutil.threadpool;
import com.sun.corba.se.spi.orbutil.threadpool.NoSuchWorkQueueException;
import com.sun.corba.se.spi.orbutil.threadpool.ThreadPool;
import com.sun.corba.se.spi.orbutil.threadpool.Work;
import com.sun.corba.se.spi.orbutil.threadpool.WorkQueue;
import com.sun.corba.se.impl.orbutil.ORBConstants;
import com.sun.corba.se.impl.orbutil.threadpool.WorkQueueImpl;
import com.sun.corba.se.spi.monitoring.MonitoringConstants;
import com.sun.corba.se.spi.monitoring.MonitoredObject;
import com.sun.corba.se.spi.monitoring.MonitoringFactories;
import com.sun.corba.se.spi.monitoring.LongMonitoredAttributeBase;
public class ThreadPoolImpl implements ThreadPool
{
private static int threadCounter = 0; // serial counter useful for debugging
private WorkQueue workQueue;
// Stores the number of available worker threads
private int availableWorkerThreads = 0;
// Stores the number of threads in the threadpool currently
private int currentThreadCount = 0;
// Minimum number of worker threads created at instantiation of the threadpool
private int minWorkerThreads = 0;
// Maximum number of worker threads in the threadpool
private int maxWorkerThreads = 0;
// Inactivity timeout value for worker threads to exit and stop running
private long inactivityTimeout;
// Indicates if the threadpool is bounded or unbounded
private boolean boundedThreadPool = false;
// Running count of the work items processed
// Set the value to 1 so that divide by zero is avoided in
// averageWorkCompletionTime()
private long processedCount = 1;
// Running aggregate of the time taken in millis to execute work items
// processed by the threads in the threadpool
private long totalTimeTaken = 0;
// Lock for protecting state when required
private Object lock = new Object();
// Name of the ThreadPool
private String name;
// MonitoredObject for ThreadPool
private MonitoredObject threadpoolMonitoredObject;
// ThreadGroup in which threads should be created
private ThreadGroup threadGroup ;
/**
* This constructor is used to create an unbounded threadpool
*/
public ThreadPoolImpl(ThreadGroup tg, String threadpoolName) {
inactivityTimeout = ORBConstants.DEFAULT_INACTIVITY_TIMEOUT;
maxWorkerThreads = Integer.MAX_VALUE;
workQueue = new WorkQueueImpl(this);
threadGroup = tg ;
name = threadpoolName;
initializeMonitoring();
}
/**
* This constructor is used to create an unbounded threadpool
* in the ThreadGroup of the current thread
*/
public ThreadPoolImpl(String threadpoolName) {
this( Thread.currentThread().getThreadGroup(), threadpoolName ) ;
}
/**
* This constructor is used to create bounded threadpool
*/
public ThreadPoolImpl(int minSize, int maxSize, long timeout,
String threadpoolName)
{
minWorkerThreads = minSize;
maxWorkerThreads = maxSize;
inactivityTimeout = timeout;
boundedThreadPool = true;
workQueue = new WorkQueueImpl(this);
name = threadpoolName;
for (int i = 0; i < minWorkerThreads; i++) {
createWorkerThread();
}
initializeMonitoring();
}
// Setup monitoring for this threadpool
private void initializeMonitoring() {
// Get root monitored object
MonitoredObject root = MonitoringFactories.getMonitoringManagerFactory().
createMonitoringManager(MonitoringConstants.DEFAULT_MONITORING_ROOT, null).
getRootMonitoredObject();
// Create the threadpool monitoring root
MonitoredObject threadPoolMonitoringObjectRoot = root.getChild(
MonitoringConstants.THREADPOOL_MONITORING_ROOT);
if (threadPoolMonitoringObjectRoot == null) {
threadPoolMonitoringObjectRoot = MonitoringFactories.
getMonitoredObjectFactory().createMonitoredObject(
MonitoringConstants.THREADPOOL_MONITORING_ROOT,
MonitoringConstants.THREADPOOL_MONITORING_ROOT_DESCRIPTION);
root.addChild(threadPoolMonitoringObjectRoot);
}
threadpoolMonitoredObject = MonitoringFactories.
getMonitoredObjectFactory().
createMonitoredObject(name,
MonitoringConstants.THREADPOOL_MONITORING_DESCRIPTION);
threadPoolMonitoringObjectRoot.addChild(threadpoolMonitoredObject);
LongMonitoredAttributeBase b1 = new
LongMonitoredAttributeBase(MonitoringConstants.THREADPOOL_CURRENT_NUMBER_OF_THREADS,
MonitoringConstants.THREADPOOL_CURRENT_NUMBER_OF_THREADS_DESCRIPTION) {
public Object getValue() {
return new Long(ThreadPoolImpl.this.currentNumberOfThreads());
}
};
threadpoolMonitoredObject.addAttribute(b1);
LongMonitoredAttributeBase b2 = new
LongMonitoredAttributeBase(MonitoringConstants.THREADPOOL_NUMBER_OF_AVAILABLE_THREADS,
MonitoringConstants.THREADPOOL_CURRENT_NUMBER_OF_THREADS_DESCRIPTION) {
public Object getValue() {
return new Long(ThreadPoolImpl.this.numberOfAvailableThreads());
}
};
threadpoolMonitoredObject.addAttribute(b2);
LongMonitoredAttributeBase b3 = new
LongMonitoredAttributeBase(MonitoringConstants.THREADPOOL_NUMBER_OF_BUSY_THREADS,
MonitoringConstants.THREADPOOL_NUMBER_OF_BUSY_THREADS_DESCRIPTION) {
public Object getValue() {
return new Long(ThreadPoolImpl.this.numberOfBusyThreads());
}
};
threadpoolMonitoredObject.addAttribute(b3);
LongMonitoredAttributeBase b4 = new
LongMonitoredAttributeBase(MonitoringConstants.THREADPOOL_AVERAGE_WORK_COMPLETION_TIME,
MonitoringConstants.THREADPOOL_AVERAGE_WORK_COMPLETION_TIME_DESCRIPTION) {
public Object getValue() {
return new Long(ThreadPoolImpl.this.averageWorkCompletionTime());
}
};
threadpoolMonitoredObject.addAttribute(b4);
LongMonitoredAttributeBase b5 = new
LongMonitoredAttributeBase(MonitoringConstants.THREADPOOL_CURRENT_PROCESSED_COUNT,
MonitoringConstants.THREADPOOL_CURRENT_PROCESSED_COUNT_DESCRIPTION) {
public Object getValue() {
return new Long(ThreadPoolImpl.this.currentProcessedCount());
}
};
threadpoolMonitoredObject.addAttribute(b5);
// Add the monitored object for the WorkQueue
threadpoolMonitoredObject.addChild(
((WorkQueueImpl)workQueue).getMonitoredObject());
}
// Package private method to get the monitored object for this
// class
MonitoredObject getMonitoredObject() {
return threadpoolMonitoredObject;
}
public WorkQueue getAnyWorkQueue()
{
return workQueue;
}
public WorkQueue getWorkQueue(int queueId)
throws NoSuchWorkQueueException
{
if (queueId != 0)
throw new NoSuchWorkQueueException();
return workQueue;
}
/**
* To be called from the workqueue when work is added to the
* workQueue. This method would create new threads if required
* or notify waiting threads on the queue for available work
*/
void notifyForAvailableWork(WorkQueue aWorkQueue) {
synchronized (lock) {
if (availableWorkerThreads == 0) {
createWorkerThread();
} else {
aWorkQueue.notify();
}
}
}
/**
* To be called from the workqueue to create worker threads when none
* available.
*/
void createWorkerThread() {
WorkerThread thread;
synchronized (lock) {
if (boundedThreadPool) {
if (currentThreadCount < maxWorkerThreads) {
thread = new WorkerThread(threadGroup, getName());
currentThreadCount++;
} else {
// REVIST - Need to create a thread to monitor the
// the state for deadlock i.e. all threads waiting for
// something which can be got from the item in the
// workqueue, but there is no thread available to
// process that work item - DEADLOCK !!
return;
}
} else {
thread = new WorkerThread(threadGroup, getName());
currentThreadCount++;
}
}
// The thread must be set to a daemon thread so the
// VM can exit if the only threads left are PooledThreads
// or other daemons. We don't want to rely on the
// calling thread always being a daemon.
// Catch exceptions since setDaemon can cause a
// security exception to be thrown under netscape
// in the Applet mode
try {
thread.setDaemon(true);
} catch (Exception e) {
// REVISIT - need to do some logging here
}
thread.start();
}
/**
* This method will return the minimum number of threads maintained
* by the threadpool.
*/
public int minimumNumberOfThreads() {
return minWorkerThreads;
}
/**
* This method will return the maximum number of threads in the
* threadpool at any point in time, for the life of the threadpool
*/
public int maximumNumberOfThreads() {
return maxWorkerThreads;
}
/**
* This method will return the time in milliseconds when idle
* threads in the threadpool are removed.
*/
public long idleTimeoutForThreads() {
return inactivityTimeout;
}
/**
* This method will return the total number of threads currently in the
* threadpool. This method returns a value which is not synchronized.
*/
public int currentNumberOfThreads() {
synchronized (lock) {
return currentThreadCount;
}
}
/**
* This method will return the number of available threads in the
* threadpool which are waiting for work. This method returns a
* value which is not synchronized.
*/
public int numberOfAvailableThreads() {
synchronized (lock) {
return availableWorkerThreads;
}
}
/**
* This method will return the number of busy threads in the threadpool
* This method returns a value which is not synchronized.
*/
public int numberOfBusyThreads() {
synchronized (lock) {
return (currentThreadCount - availableWorkerThreads);
}
}
/**
* This method returns the average elapsed time taken to complete a Work
* item in milliseconds.
*/
public long averageWorkCompletionTime() {
synchronized (lock) {
return (totalTimeTaken / processedCount);
}
}
/**
* This method returns the number of Work items processed by the threadpool
*/
public long currentProcessedCount() {
synchronized (lock) {
return processedCount;
}
}
public String getName() {
return name;
}
/**
* This method will return the number of WorkQueues serviced by the threadpool.
*/
public int numberOfWorkQueues() {
return 1;
}
private static synchronized int getUniqueThreadId() {
return ThreadPoolImpl.threadCounter++;
}
private class WorkerThread extends Thread
{
private Work currentWork;
private int threadId = 0; // unique id for the thread
// thread pool this WorkerThread belongs too
private String threadPoolName;
// name seen by Thread.getName()
private StringBuffer workerThreadName = new StringBuffer();
WorkerThread(ThreadGroup tg, String threadPoolName) {
super(tg, "Idle");
this.threadId = ThreadPoolImpl.getUniqueThreadId();
this.threadPoolName = threadPoolName;
setName(composeWorkerThreadName(threadPoolName, "Idle"));
}
public void run() {
while (true) {
try {
synchronized (lock) {
availableWorkerThreads++;
}
// Get some work to do
currentWork = ((WorkQueueImpl)workQueue).requestWork(inactivityTimeout);
synchronized (lock) {
availableWorkerThreads--;
// It is possible in notifyForAvailableWork that the
// check for availableWorkerThreads = 0 may return
// false, because the availableWorkerThreads has not been
// decremented to zero before the producer thread added
// work to the queue. This may create a deadlock, if the
// executing thread needs information which is in the work
// item queued in the workqueue, but has no thread to work
// on it since none was created because availableWorkerThreads = 0
// returned false.
// The following code will ensure that a thread is always available
// in those situations
if ((availableWorkerThreads == 0) &&
(workQueue.workItemsInQueue() > 0)) {
createWorkerThread();
}
}
// Set the thread name for debugging.
setName(composeWorkerThreadName(threadPoolName,
Integer.toString(this.threadId)));
long start = System.currentTimeMillis();
try {
// Do the work
currentWork.doWork();
} catch (Throwable t) {
// Ignore all errors.
;
}
long end = System.currentTimeMillis();
synchronized (lock) {
totalTimeTaken += (end - start);
processedCount++;
}
// set currentWork to null so that the work item can be
// garbage collected
currentWork = null;
setName(composeWorkerThreadName(threadPoolName, "Idle"));
} catch (TimeoutException e) {
// This thread timed out waiting for something to do.
synchronized (lock) {
availableWorkerThreads--;
// This should for both bounded and unbounded case
if (currentThreadCount > minWorkerThreads) {
currentThreadCount--;
// This thread can exit.
return;
} else {
// Go back to waiting on workQueue
continue;
}
}
} catch (InterruptedException ie) {
// InterruptedExceptions are
// caught here. Thus, threads can be forced out of
// requestWork and so they have to reacquire the lock.
// Other options include ignoring or
// letting this thread die.
// Ignoring for now. REVISIT
synchronized (lock) {
availableWorkerThreads--;
}
} catch (Throwable e) {
// Ignore any exceptions that currentWork.process
// accidently lets through, but let Errors pass.
// Add debugging output? REVISIT
synchronized (lock) {
availableWorkerThreads--;
}
}
}
}
private String composeWorkerThreadName(String poolName, String workerName) {
workerThreadName.setLength(0);
workerThreadName.append("p: ").append(poolName);
workerThreadName.append("; w: ").append(workerName);
return workerThreadName.toString();
}
} // End of WorkerThread class
}
// End of file.
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.painless.node;
import org.elasticsearch.painless.Definition;
import org.elasticsearch.painless.Globals;
import org.elasticsearch.painless.Location;
import org.elasticsearch.painless.Definition.Type;
import org.elasticsearch.painless.AnalyzerCaster;
import org.elasticsearch.painless.DefBootstrap;
import org.elasticsearch.painless.Operation;
import org.elasticsearch.painless.Locals;
import org.objectweb.asm.Label;
import java.util.Objects;
import java.util.Set;
import org.elasticsearch.painless.MethodWriter;
import org.objectweb.asm.Opcodes;
/**
* Represents a unary math expression.
*/
public final class EUnary extends AExpression {
private final Operation operation;
private AExpression child;
private Type promote;
private boolean originallyExplicit = false; // record whether there was originally an explicit cast
public EUnary(Location location, Operation operation, AExpression child) {
super(location);
this.operation = Objects.requireNonNull(operation);
this.child = Objects.requireNonNull(child);
}
@Override
void extractVariables(Set<String> variables) {
child.extractVariables(variables);
}
@Override
void analyze(Locals locals) {
originallyExplicit = explicit;
if (operation == Operation.NOT) {
analyzeNot(locals);
} else if (operation == Operation.BWNOT) {
analyzeBWNot(locals);
} else if (operation == Operation.ADD) {
analyzerAdd(locals);
} else if (operation == Operation.SUB) {
analyzerSub(locals);
} else {
throw createError(new IllegalStateException("Illegal tree structure."));
}
}
void analyzeNot(Locals variables) {
child.expected = variables.getDefinition().booleanType;
child.analyze(variables);
child = child.cast(variables);
if (child.constant != null) {
constant = !(boolean)child.constant;
}
actual = variables.getDefinition().booleanType;
}
void analyzeBWNot(Locals variables) {
child.analyze(variables);
promote = variables.getDefinition().caster.promoteNumeric(child.actual, false);
if (promote == null) {
throw createError(new ClassCastException("Cannot apply not [~] to type [" + child.actual.name + "]."));
}
child.expected = promote;
child = child.cast(variables);
if (child.constant != null) {
Class<?> sort = promote.clazz;
if (sort == int.class) {
constant = ~(int)child.constant;
} else if (sort == long.class) {
constant = ~(long)child.constant;
} else {
throw createError(new IllegalStateException("Illegal tree structure."));
}
}
if (promote.dynamic && expected != null) {
actual = expected;
} else {
actual = promote;
}
}
void analyzerAdd(Locals variables) {
child.analyze(variables);
promote = variables.getDefinition().caster.promoteNumeric(child.actual, true);
if (promote == null) {
throw createError(new ClassCastException("Cannot apply positive [+] to type [" + child.actual.name + "]."));
}
child.expected = promote;
child = child.cast(variables);
if (child.constant != null) {
Class<?> sort = promote.clazz;
if (sort == int.class) {
constant = +(int)child.constant;
} else if (sort == long.class) {
constant = +(long)child.constant;
} else if (sort == float.class) {
constant = +(float)child.constant;
} else if (sort == double.class) {
constant = +(double)child.constant;
} else {
throw createError(new IllegalStateException("Illegal tree structure."));
}
}
if (promote.dynamic && expected != null) {
actual = expected;
} else {
actual = promote;
}
}
void analyzerSub(Locals variables) {
child.analyze(variables);
promote = variables.getDefinition().caster.promoteNumeric(child.actual, true);
if (promote == null) {
throw createError(new ClassCastException("Cannot apply negative [-] to type [" + child.actual.name + "]."));
}
child.expected = promote;
child = child.cast(variables);
if (child.constant != null) {
Class<?> sort = promote.clazz;
if (sort == int.class) {
constant = -(int)child.constant;
} else if (sort == long.class) {
constant = -(long)child.constant;
} else if (sort == float.class) {
constant = -(float)child.constant;
} else if (sort == double.class) {
constant = -(double)child.constant;
} else {
throw createError(new IllegalStateException("Illegal tree structure."));
}
}
if (promote.dynamic && expected != null) {
actual = expected;
} else {
actual = promote;
}
}
@Override
void write(MethodWriter writer, Globals globals) {
writer.writeDebugInfo(location);
if (operation == Operation.NOT) {
Label fals = new Label();
Label end = new Label();
child.write(writer, globals);
writer.ifZCmp(Opcodes.IFEQ, fals);
writer.push(false);
writer.goTo(end);
writer.mark(fals);
writer.push(true);
writer.mark(end);
} else {
Class<?> sort = promote.clazz;
child.write(writer, globals);
// Def calls adopt the wanted return value. If there was a narrowing cast,
// we need to flag that so that it's done at runtime.
int defFlags = 0;
if (originallyExplicit) {
defFlags |= DefBootstrap.OPERATOR_EXPLICIT_CAST;
}
if (operation == Operation.BWNOT) {
if (promote.dynamic) {
org.objectweb.asm.Type descriptor = org.objectweb.asm.Type.getMethodType(actual.type, child.actual.type);
writer.invokeDefCall("not", descriptor, DefBootstrap.UNARY_OPERATOR, defFlags);
} else {
if (sort == int.class) {
writer.push(-1);
} else if (sort == long.class) {
writer.push(-1L);
} else {
throw createError(new IllegalStateException("Illegal tree structure."));
}
writer.math(MethodWriter.XOR, actual.type);
}
} else if (operation == Operation.SUB) {
if (promote.dynamic) {
org.objectweb.asm.Type descriptor = org.objectweb.asm.Type.getMethodType(actual.type, child.actual.type);
writer.invokeDefCall("neg", descriptor, DefBootstrap.UNARY_OPERATOR, defFlags);
} else {
writer.math(MethodWriter.NEG, actual.type);
}
} else if (operation == Operation.ADD) {
if (promote.dynamic) {
org.objectweb.asm.Type descriptor = org.objectweb.asm.Type.getMethodType(actual.type, child.actual.type);
writer.invokeDefCall("plus", descriptor, DefBootstrap.UNARY_OPERATOR, defFlags);
}
} else {
throw createError(new IllegalStateException("Illegal tree structure."));
}
}
}
@Override
public String toString() {
return singleLineToString(operation.symbol, child);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.myfaces.trinidadinternal.skin;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import org.apache.myfaces.trinidad.context.LocaleContext;
import org.apache.myfaces.trinidad.context.RenderingContext;
import org.apache.myfaces.trinidad.logging.TrinidadLogger;
import org.apache.myfaces.trinidad.skin.Icon;
import org.apache.myfaces.trinidad.skin.Skin;
import org.apache.myfaces.trinidad.skin.SkinAddition;
import org.apache.myfaces.trinidadinternal.renderkit.core.CoreRenderingContext;
import org.apache.myfaces.trinidadinternal.skin.icon.NullIcon;
import org.apache.myfaces.trinidadinternal.skin.icon.ReferenceIcon;
import org.apache.myfaces.trinidadinternal.style.StyleContext;
import org.apache.myfaces.trinidadinternal.style.StyleProvider;
import org.apache.myfaces.trinidadinternal.style.xml.parse.StyleSheetDocument;
/**
* This is a Skin decorator which is used to store request-specific
* skin state. For example, the set of icons to use varies from
* request to request, eg. based on the browser/platform. We cannot
* store such request-specific state on our shared Skin instances.
* Instead, SkinFactoryImpl wraps shared Skin instances in RequestSkinWrappers
* so that request-specific state can be stored locally in the wrapper.
*
* Currently, the request-specific state for a skin is the icon map and the skin property map.
* They are retrieved from the StyleProvider one time per request and stored here.
* @see org.apache.myfaces.trinidadinternal.style.cache.FileSystemStyleCache
*/
public class RequestSkinWrapper extends Skin implements DocumentProviderSkin
{
// An alternate implementation strategy would be to enhance SkinImpl.getIcon()
// to serve up the request/context-specific Icons directly, rather than do so
// via a wrapper Skin class. There are two issues with the SkinImpl-based
// solution:
//
// 1. SkinImpl.getIcon() needs access to the StyleContext in order to retrieve
// the request/context-specific Icon map. However, Skin.getIcon() does not
// get take a StyleContext. We could change the Skin.getIcon() API to take
// a StyleContext, but since this is a public API we would prefer a solution
// which does not involve an API change. Alternatively, SkinImpl.getIcon()
// could get at the StyleContext by retrieving the RenderingContext, casting
// to CoreRenderingContext, and calling CoreRenderingContext.getStyleContext().
// However, that adds overhead to the SkinImpl.getIcon() implementation
// (mainly just a ThreadLocal look up, which isn't the end of the world,
// but nonetheless would prefer to avoid if possible).
//
// 2. Calls to registerIcon() need to behave differently depending on whether
// the Icon is being registered at Skin initialization time, or at
// request-time.
//
// At Skin initialization time, we simply want to register the Icon on the
// Skin instance itself, since such Icons are global to the Skin. However,
// we also use registerIcon() to register request-specific icon - for example,
// see CoreRenderingContext.getIcon()'s handling of rtl icons. We cannot
// register these request-specific Icons on the Skin as the Skin is reused
// across requests. Instead we want to register request-specific Icons on
// the request-specific Icon map.
//
// In order to deal with #2, we could have SkinImpl behave differently
// depending on whether it is at initialization time or request time. However,
// this is awkward and more cleanly solved via the request-specific wrapper
// approach.
public RequestSkinWrapper(Skin wrappedSkin)
{
_skin = wrappedSkin;
}
/**
* Returns the Skin that is wrapped by this request-specific
* wrapper skin.
*/
public Skin getWrappedSkin()
{
return _skin;
}
@Override
public String getId()
{
return _skin.getId();
}
@Override
public String getFamily()
{
return _skin.getFamily();
}
@Override
public String getRenderKitId()
{
return _skin.getRenderKitId();
}
@Override
public String getStyleSheetDocumentId(RenderingContext arc)
{
return _skin.getStyleSheetDocumentId(arc);
}
@Override
public Map<String, String> getStyleClassMap(RenderingContext arc)
{
return _skin.getStyleClassMap(arc);
}
@Override
public String getStyleSheetName()
{
return _skin.getStyleSheetName();
}
@Override
public String getTranslatedString(
LocaleContext lContext,
String key
) throws MissingResourceException
{
return _skin.getTranslatedString(lContext, key);
}
@Override
public Object getTranslatedValue(
LocaleContext lContext,
String key
) throws MissingResourceException
{
return _skin.getTranslatedValue(lContext, key);
}
@Override
public Icon getIcon(String iconName)
{
return this.getIcon(iconName, true);
}
@Override
public Icon getIcon(
String iconName,
boolean resolveIcon)
{
// We look for the icon in two places:
//
// 1. In the icon map provided by the StyleProvider.
// The StyleProvider serves up icons that are
// specific to this particular request, including
// agent-specific icons.
// 2. In the wrapped Skin instance. Any Icons that are
// manually registered via a call to registerIcon()
// will be stored in the wrapped skin.
// Note: no synchronization needed since we are in a
// a request-specific object.
Map<String, Icon> icons = _getRequestIcons();
assert(icons != null);
Icon icon = icons.get(iconName);
if (icon == null)
{
icon = _skin.getIcon(iconName, false);
// Resolve ReferenceIcons if necessary
if (resolveIcon)
{
if (icon instanceof ReferenceIcon)
icon = SkinUtils.resolveReferenceIcon(this, (ReferenceIcon)icon);
// We ended up having to do two lookups for icons
// which are not available in the StyleProvider
// icon map. To avoid having to do two lookups
// the next time this icon is requested, we promote
// the icon up from the wrapped skin into the
// StyleProvider icon map. Note that we only cache
// resolved icons in this way - we don't want to
// pollute our cache with unresolved ReferenceIcons.
registerIcon(iconName, icon);
}
}
return (icon == _NULL_ICON) ? null : icon;
}
@Override
public void registerIcon(
String iconName,
Icon icon)
{
// registerIcon() is called on a RequestSkinWrapper
// in two cases:
//
// 1. CoreRenderingContext.getIcon() contains special handling
// for icons when the reading direction is right-to-left. If a
// rtl variant of the icon is not available, CoreRenderingContext
// will look up the non-directional version of the icon and register
// that under the rtl name to avoid repeated lookups.
//
// 2. RequestSkinWrapper.getIcon() calls registerIcon() to register
// icons which were not found in the StyleProvider's icon map. This
// also is done as a performance optimization - to repeatedly looking
// up icons first in the StyleProvider icon map and then in the
// wrapped skin.
//
// In both of these cases storing the missing icon in the StyleProvider
// icon map is safe/appropriate, since lookups with the same set of
// StyleContext properties would return the same results. By storing
// the result in the StyleProvider icon map, we short-circuit, avoiding
// redundant work.
Map<String, Icon> icons = _getRequestIcons();
if (icons != _NULL_ICONS)
icons.put(iconName, (icon == null) ? _NULL_ICON : icon);
}
@Override
public Object getProperty(Object key)
{
// We look for the skin properties in two places:
//
// 1. In the skin property map provided by the StyleProvider (see _getRequestSkinProperties).
// The StyleProvider serves up skin properties that are
// specific to this particular request, including
// agent-specific skin properties.
// 2. In the wrapped Skin instance. Any skin properties that are
// manually registered via a call to setProperty(Object, Object)
// will be stored in the wrapped skin.
// Note: no synchronization needed since we are in a
// a request-specific object.
Map<Object, Object> properties = _getRequestSkinProperties();
assert(properties != null);
Object propertyValue = properties.get(key);
if (propertyValue == null)
{
propertyValue = _skin.getProperty(key);
}
return propertyValue;
}
@Override
public void setProperty(
Object key,
Object value)
{
Map<Object, Object> properties = _getRequestSkinProperties();
if (properties != _NULL_PROPERTIES)
properties.put(key, value);
}
/**
* @deprecated Use addSkinAddition instead
* */
@Override
public void registerStyleSheet(
String styleSheetName
)
{
_skin.registerStyleSheet(styleSheetName);
}
@Override
public void addSkinAddition (
SkinAddition skinAddition
)
{
_skin.addSkinAddition(skinAddition);
}
@Override
public List<SkinAddition> getSkinAdditions ()
{
return _skin.getSkinAdditions();
}
/**
* Implementation of DocumentProviderSkin.getStyleSheetDocument().
*/
public StyleSheetDocument getStyleSheetDocument(StyleContext styleContext)
{
// If getStyleSheetDocument() is being called on us, this implies
// that the wrapped Skin must also be a DocumentProviderSkin.
assert(_skin instanceof DocumentProviderSkin);
return ((DocumentProviderSkin)_skin).getStyleSheetDocument(styleContext);
}
// Returns request-specific map of icon names to Icons
private Map<String, Icon> _getRequestIcons()
{
if (_icons == null)
{
// We get to the request-specific icons via the
// StyleProvider. We need a CoreRenderingContext
// instance to get at the StyleProvider. This
// implementation assumes that the RenderingContext
// is going to be an instanceof CoreRenderingContext.
// This is a pretty good bet, since the only
// RenderingContext provided by Trinidad is
// CoreRenderingContext, and given the complexity of
// the CoreRenderingContext implementation, it seems
// unlikely that anyone would attempt to replace the
// implementation.
RenderingContext rc = RenderingContext.getCurrentInstance();
assert(rc instanceof CoreRenderingContext);
CoreRenderingContext crc = (CoreRenderingContext)rc;
StyleContext styleContext = crc.getStyleContext();
StyleProvider styleProvider = styleContext.getStyleProvider();
_icons = styleProvider.getIcons(styleContext);
// Under normal circumstances, the StyleProvider will return
// a non-null, modifiable map. If the skin/style subsystem
// has failed to initialize, however, the map may be null.
// Substitute an empty map so we don't need to check for null
// later.
if (_icons == null)
{
if (_LOG.isWarning())
_LOG.warning("_icons is an emptyMap because the skin/style " +
"subsystem has failed to initialize.");
_icons = _NULL_ICONS;
}
}
return _icons;
}
// Returns request-specific map of skin property key/values
private Map<Object, Object> _getRequestSkinProperties()
{
if (_properties == null)
{
// We get to the request-specific properties via the
// StyleProvider. We need a CoreRenderingContext
// instance to get at the StyleProvider. This
// implementation assumes that the RenderingContext
// is going to be an instanceof CoreRenderingContext.
// This is a pretty good bet, since the only
// RenderingContext provided by Trinidad is
// CoreRenderingContext, and given the complexity of
// the CoreRenderingContext implementation, it seems
// unlikely that anyone would attempt to replace the
// implementation.
RenderingContext rc = RenderingContext.getCurrentInstance();
assert(rc instanceof CoreRenderingContext);
CoreRenderingContext crc = (CoreRenderingContext)rc;
StyleContext styleContext = crc.getStyleContext();
StyleProvider styleProvider = styleContext.getStyleProvider();
// skin properties are stored in an Map<Object, Object>
_properties = styleProvider.getSkinProperties(styleContext);
// Under normal circumstances, the StyleProvider will return
// a non-null, modifiable map. If the skin/style subsystem
// has failed to initialize, however, the map may be null.
// Substitute an empty map so we don't need to check for null
// later.
if (_properties == null)
{
if (_LOG.isWarning())
_LOG.warning("_properties is an emptyMap because the skin/style " +
"subsystem has failed to initialize.");
_properties = _NULL_PROPERTIES;
}
}
return _properties;
}
// The wrapped skin
private final Skin _skin;
// The icon map specific to this request as served
// up by the StyleProvider.
private Map<String, Icon> _icons;
// The skin properties map specific to this request as served
// up by the StyleProvider.
private Map<Object, Object> _properties;
// Marker used to cache nulls.
private static final Icon _NULL_ICON = new NullIcon();
// Empty map used when StyleProvider.getIcons() fails;
private static final Map<String, Icon> _NULL_ICONS = Collections.emptyMap();
// Empty map used when StyleProvider.getSkinProperties() fails;
private static final Map<Object, Object> _NULL_PROPERTIES = Collections.emptyMap();
static final private TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(RequestSkinWrapper.class);
}
| |
package net.sf.jabref.gui.preftabs;
import java.awt.BorderLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import net.sf.jabref.gui.keyboard.EmacsKeyBindings;
import net.sf.jabref.logic.autocompleter.AutoCompleteFirstNameMode;
import net.sf.jabref.logic.autocompleter.AutoCompletePreferences;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.preferences.JabRefPreferences;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
class EntryEditorPrefsTab extends JPanel implements PrefsTab {
private final JCheckBox autoOpenForm;
private final JCheckBox defSource;
private final JCheckBox emacsMode;
private final JCheckBox emacsRebindCtrlA;
private final JCheckBox emacsRebindCtrlF;
private final JCheckBox autoComplete;
private final JRadioButton autoCompBoth;
private final JRadioButton autoCompFF;
private final JRadioButton autoCompLF;
private final JRadioButton firstNameModeFull;
private final JRadioButton firstNameModeAbbr;
private final JRadioButton firstNameModeBoth;
private final JSpinner shortestToComplete;
private final JTextField autoCompFields;
private final JabRefPreferences prefs;
private final AutoCompletePreferences autoCompletePreferences;
public EntryEditorPrefsTab(JabRefPreferences prefs) {
this.prefs = prefs;
autoCompletePreferences = new AutoCompletePreferences(prefs);
setLayout(new BorderLayout());
autoOpenForm = new JCheckBox(Localization.lang("Open editor when a new entry is created"));
defSource = new JCheckBox(Localization.lang("Show BibTeX source by default"));
emacsMode = new JCheckBox(Localization.lang("Use Emacs key bindings"));
emacsRebindCtrlA = new JCheckBox(Localization.lang("Rebind C-a, too"));
emacsRebindCtrlF = new JCheckBox(Localization.lang("Rebind C-f, too"));
autoComplete = new JCheckBox(Localization.lang("Enable word/name autocompletion"));
shortestToComplete = new JSpinner(
new SpinnerNumberModel(autoCompletePreferences.getShortestLengthToComplete(), 1, 5, 1));
// allowed name formats
autoCompFF = new JRadioButton(Localization.lang("Autocomplete names in 'Firstname Lastname' format only"));
autoCompLF = new JRadioButton(Localization.lang("Autocomplete names in 'Lastname, Firstname' format only"));
autoCompBoth = new JRadioButton(Localization.lang("Autocomplete names in both formats"));
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(autoCompLF);
buttonGroup.add(autoCompFF);
buttonGroup.add(autoCompBoth);
// treatment of first name
firstNameModeFull = new JRadioButton(Localization.lang("Use full firstname whenever possible"));
firstNameModeAbbr = new JRadioButton(Localization.lang("Use abbreviated firstname whenever possible"));
firstNameModeBoth = new JRadioButton(Localization.lang("Use abbreviated and full firstname"));
ButtonGroup firstNameModeButtonGroup = new ButtonGroup();
firstNameModeButtonGroup.add(firstNameModeFull);
firstNameModeButtonGroup.add(firstNameModeAbbr);
firstNameModeButtonGroup.add(firstNameModeBoth);
Insets marg = new Insets(0, 20, 3, 0);
emacsRebindCtrlA.setMargin(marg);
// We need a listener on showSource to enable and disable the source panel-related choices:
emacsMode.addChangeListener(event -> emacsRebindCtrlA.setEnabled(emacsMode.isSelected()));
emacsRebindCtrlF.setMargin(marg);
// We need a listener on showSource to enable and disable the source panel-related choices:
emacsMode.addChangeListener(event -> emacsRebindCtrlF.setEnabled(emacsMode.isSelected()));
autoCompFields = new JTextField(40);
// We need a listener on autoComplete to enable and disable the
// autoCompFields text field:
autoComplete.addChangeListener(event -> setAutoCompleteElementsEnabled(autoComplete.isSelected()));
FormLayout layout = new FormLayout
(// columns
"8dlu, left:pref, 8dlu, fill:150dlu, 4dlu, fill:pref", // 4dlu, left:pref, 4dlu",
// rows 1 to 10
"pref, 6dlu, pref, 6dlu, pref, 6dlu, pref, 6dlu, pref, 6dlu, " +
// rows 11 to 16
"pref, 6dlu, pref, 6dlu, pref, 6dlu, " +
// rows 17 to 27
"pref, 6dlu, pref, pref, pref, pref, 6dlu, pref, pref, pref, pref");
DefaultFormBuilder builder = new DefaultFormBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addSeparator(Localization.lang("Editor options"), cc.xyw(1, 1, 5));
builder.add(autoOpenForm, cc.xy(2, 3));
builder.add(defSource, cc.xy(2, 5));
builder.add(emacsMode, cc.xy(2, 7));
builder.add(emacsRebindCtrlA, cc.xy(2, 9));
builder.add(emacsRebindCtrlF, cc.xy(2, 11));
builder.addSeparator(Localization.lang("Autocompletion options"), cc.xyw(1, 13, 5));
builder.add(autoComplete, cc.xy(2, 15));
DefaultFormBuilder builder3 = new DefaultFormBuilder(new FormLayout("left:pref, 4dlu, fill:150dlu",""));
JLabel label = new JLabel(Localization.lang("Use autocompletion for the following fields")+":");
builder3.append(label);
builder3.append(autoCompFields);
JLabel label2 = new JLabel(Localization.lang("Autocomplete after following number of characters") + ":");
builder3.append(label2);
builder3.append(shortestToComplete);
builder.add(builder3.getPanel(), cc.xyw(2, 17, 3));
builder.addSeparator(Localization.lang("Name format used for autocompletion"), cc.xyw(2, 19, 4));
builder.add(autoCompFF, cc.xy(2, 20));
builder.add(autoCompLF, cc.xy(2, 21));
builder.add(autoCompBoth, cc.xy(2, 22));
builder.addSeparator(Localization.lang("Treatment of first names"), cc.xyw(2, 24, 4));
builder.add(firstNameModeAbbr, cc.xy(2, 25));
builder.add(firstNameModeFull, cc.xy(2, 26));
builder.add(firstNameModeBoth, cc.xy(2, 27));
JPanel pan = builder.getPanel();
pan.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
add(pan, BorderLayout.CENTER);
}
private void setAutoCompleteElementsEnabled(boolean enabled) {
autoCompFields.setEnabled(enabled);
autoCompLF.setEnabled(enabled);
autoCompFF.setEnabled(enabled);
autoCompBoth.setEnabled(enabled);
firstNameModeAbbr.setEnabled(enabled);
firstNameModeFull.setEnabled(enabled);
firstNameModeBoth.setEnabled(enabled);
shortestToComplete.setEnabled(enabled);
}
@Override
public void setValues() {
autoOpenForm.setSelected(prefs.getBoolean(JabRefPreferences.AUTO_OPEN_FORM));
defSource.setSelected(prefs.getBoolean(JabRefPreferences.DEFAULT_SHOW_SOURCE));
emacsMode.setSelected(prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS));
emacsRebindCtrlA.setSelected(prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS_REBIND_CA));
emacsRebindCtrlF.setSelected(prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS_REBIND_CF));
autoComplete.setSelected(prefs.getBoolean(JabRefPreferences.AUTO_COMPLETE));
autoCompFields.setText(autoCompletePreferences.getCompleteNamesAsString());
shortestToComplete.setValue(autoCompletePreferences.getShortestLengthToComplete());
if (autoCompletePreferences.getOnlyCompleteFirstLast()) {
autoCompFF.setSelected(true);
} else if (autoCompletePreferences.getOnlyCompleteLastFirst()) {
autoCompLF.setSelected(true);
} else {
autoCompBoth.setSelected(true);
}
switch (autoCompletePreferences.getFirstnameMode()) {
case ONLY_ABBREVIATED:
firstNameModeAbbr.setSelected(true);
break;
case ONLY_FULL:
firstNameModeFull.setSelected(true);
break;
default:
firstNameModeBoth.setSelected(true);
break;
}
// similar for emacs CTRL-a and emacs mode
emacsRebindCtrlA.setEnabled(emacsMode.isSelected());
// Autocomplete fields is only enabled when autocompletion is selected
setAutoCompleteElementsEnabled(autoComplete.isSelected());
}
@Override
public void storeSettings() {
prefs.putBoolean(JabRefPreferences.AUTO_OPEN_FORM, autoOpenForm.isSelected());
prefs.putBoolean(JabRefPreferences.DEFAULT_SHOW_SOURCE, defSource.isSelected());
boolean emacsModeChanged = prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS) != emacsMode.isSelected();
boolean emacsRebindCtrlAChanged = prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS_REBIND_CA) != emacsRebindCtrlA.isSelected();
boolean emacsRebindCtrlFChanged = prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS_REBIND_CF) != emacsRebindCtrlF.isSelected();
if (emacsModeChanged || emacsRebindCtrlAChanged || emacsRebindCtrlFChanged) {
prefs.putBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS, emacsMode.isSelected());
prefs.putBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS_REBIND_CA, emacsRebindCtrlA.isSelected());
prefs.putBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS_REBIND_CF, emacsRebindCtrlF.isSelected());
// immediately apply the change
if (emacsModeChanged) {
if (emacsMode.isSelected()) {
EmacsKeyBindings.load();
} else {
EmacsKeyBindings.unload();
}
} else {
// only rebinding of CTRL+a or CTRL+f changed
assert emacsMode.isSelected();
// we simply reload the emacs mode to activate the CTRL+a/CTRL+f change
EmacsKeyBindings.unload();
EmacsKeyBindings.load();
}
}
autoCompletePreferences.setShortestLengthToComplete((Integer) shortestToComplete.getValue());
prefs.putBoolean(JabRefPreferences.AUTO_COMPLETE, autoComplete.isSelected());
autoCompletePreferences.setCompleteNames(autoCompFields.getText());
if (autoCompBoth.isSelected()) {
autoCompletePreferences.setOnlyCompleteFirstLast(false);
autoCompletePreferences.setOnlyCompleteLastFirst(false);
}
else if (autoCompFF.isSelected()) {
autoCompletePreferences.setOnlyCompleteFirstLast(true);
autoCompletePreferences.setOnlyCompleteLastFirst(false);
}
else {
autoCompletePreferences.setOnlyCompleteFirstLast(false);
autoCompletePreferences.setOnlyCompleteLastFirst(true);
}
if (firstNameModeAbbr.isSelected()) {
autoCompletePreferences.setFirstnameMode(AutoCompleteFirstNameMode.ONLY_ABBREVIATED);
} else if (firstNameModeFull.isSelected()) {
autoCompletePreferences.setFirstnameMode(AutoCompleteFirstNameMode.ONLY_FULL);
} else {
autoCompletePreferences.setFirstnameMode(AutoCompleteFirstNameMode.BOTH);
}
}
@Override
public boolean validateSettings() {
return true;
}
@Override
public String getTabName() {
return Localization.lang("Entry editor");
}
}
| |
/*
* $Id: JSONParser.java,v 1.1 2006/04/15 14:10:48 platform Exp $
* Created on 2006-4-15
*/
package org.json.simple.parser;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
* Parser for JSON text. Please note that JSONParser is NOT thread-safe.
*
* @author FangYidong<fangyidong@yahoo.com.cn>
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class JSONParser {
public static final int S_INIT=0;
public static final int S_IN_FINISHED_VALUE=1;//string,number,boolean,null,object,array
public static final int S_IN_OBJECT=2;
public static final int S_IN_ARRAY=3;
public static final int S_PASSED_PAIR_KEY=4;
public static final int S_IN_PAIR_VALUE=5;
public static final int S_END=6;
public static final int S_IN_ERROR=-1;
private LinkedList handlerStatusStack;
private Yylex lexer = new Yylex((Reader)null);
private Yytoken token = null;
private int status = S_INIT;
private int peekStatus(LinkedList statusStack){
if(statusStack.size()==0)
return -1;
Integer status=(Integer)statusStack.getFirst();
return status.intValue();
}
/**
* Reset the parser to the initial state without resetting the underlying reader.
*
*/
public void reset(){
token = null;
status = S_INIT;
handlerStatusStack = null;
}
/**
* Reset the parser to the initial state with a new character reader.
*
* @param in - The new character reader.
* @throws IOException
* @throws ParseException
*/
public void reset(Reader in){
lexer.yyreset(in);
reset();
}
/**
* @return The position of the beginning of the current token.
*/
public int getPosition(){
return lexer.getPosition();
}
public Object parse(String s) throws ParseException{
return parse(s, (ContainerFactory)null);
}
public Object parse(String s, ContainerFactory containerFactory) throws ParseException{
StringReader in=new StringReader(s);
try{
return parse(in, containerFactory);
}
catch(IOException ie){
/*
* Actually it will never happen.
*/
throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie);
}
}
public Object parse(Reader in) throws IOException, ParseException{
return parse(in, (ContainerFactory)null);
}
/**
* Parse JSON text into java object from the input source.
*
* @param in
* @param containerFactory - Use this factory to createyour own JSON object and JSON array containers.
* @return Instance of the following:
* org.json.simple.JSONObject,
* org.json.simple.JSONArray,
* java.lang.String,
* java.lang.Number,
* java.lang.Boolean,
* null
*
* @throws IOException
* @throws ParseException
*/
public Object parse(Reader in, ContainerFactory containerFactory) throws IOException, ParseException{
reset(in);
LinkedList statusStack = new LinkedList();
LinkedList valueStack = new LinkedList();
try{
do{
nextToken();
switch(status){
case S_INIT:
switch(token.type){
case Yytoken.TYPE_VALUE:
status=S_IN_FINISHED_VALUE;
statusStack.addFirst(new Integer(status));
valueStack.addFirst(token.value);
break;
case Yytoken.TYPE_LEFT_BRACE:
status=S_IN_OBJECT;
statusStack.addFirst(new Integer(status));
valueStack.addFirst(createObjectContainer(containerFactory));
break;
case Yytoken.TYPE_LEFT_SQUARE:
status=S_IN_ARRAY;
statusStack.addFirst(new Integer(status));
valueStack.addFirst(createArrayContainer(containerFactory));
break;
default:
status=S_IN_ERROR;
}//inner switch
break;
case S_IN_FINISHED_VALUE:
if(token.type==Yytoken.TYPE_EOF)
return valueStack.removeFirst();
else
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
case S_IN_OBJECT:
switch(token.type){
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
if(token.value instanceof String){
String key=(String)token.value;
valueStack.addFirst(key);
status=S_PASSED_PAIR_KEY;
statusStack.addFirst(new Integer(status));
}
else{
status=S_IN_ERROR;
}
break;
case Yytoken.TYPE_RIGHT_BRACE:
if(valueStack.size()>1){
statusStack.removeFirst();
valueStack.removeFirst();
status=peekStatus(statusStack);
}
else{
status=S_IN_FINISHED_VALUE;
}
break;
default:
status=S_IN_ERROR;
break;
}//inner switch
break;
case S_PASSED_PAIR_KEY:
switch(token.type){
case Yytoken.TYPE_COLON:
break;
case Yytoken.TYPE_VALUE:
statusStack.removeFirst();
String key=(String)valueStack.removeFirst();
Map parent=(Map)valueStack.getFirst();
parent.put(key,token.value);
status=peekStatus(statusStack);
break;
case Yytoken.TYPE_LEFT_SQUARE:
statusStack.removeFirst();
key=(String)valueStack.removeFirst();
parent=(Map)valueStack.getFirst();
List newArray=createArrayContainer(containerFactory);
parent.put(key,newArray);
status=S_IN_ARRAY;
statusStack.addFirst(new Integer(status));
valueStack.addFirst(newArray);
break;
case Yytoken.TYPE_LEFT_BRACE:
statusStack.removeFirst();
key=(String)valueStack.removeFirst();
parent=(Map)valueStack.getFirst();
Map newObject=createObjectContainer(containerFactory);
parent.put(key,newObject);
status=S_IN_OBJECT;
statusStack.addFirst(new Integer(status));
valueStack.addFirst(newObject);
break;
default:
status=S_IN_ERROR;
}
break;
case S_IN_ARRAY:
switch(token.type){
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
List val=(List)valueStack.getFirst();
val.add(token.value);
break;
case Yytoken.TYPE_RIGHT_SQUARE:
if(valueStack.size()>1){
statusStack.removeFirst();
valueStack.removeFirst();
status=peekStatus(statusStack);
}
else{
status=S_IN_FINISHED_VALUE;
}
break;
case Yytoken.TYPE_LEFT_BRACE:
val=(List)valueStack.getFirst();
Map newObject=createObjectContainer(containerFactory);
val.add(newObject);
status=S_IN_OBJECT;
statusStack.addFirst(new Integer(status));
valueStack.addFirst(newObject);
break;
case Yytoken.TYPE_LEFT_SQUARE:
val=(List)valueStack.getFirst();
List newArray=createArrayContainer(containerFactory);
val.add(newArray);
status=S_IN_ARRAY;
statusStack.addFirst(new Integer(status));
valueStack.addFirst(newArray);
break;
default:
status=S_IN_ERROR;
}//inner switch
break;
case S_IN_ERROR:
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}//switch
if(status==S_IN_ERROR){
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
}while(token.type!=Yytoken.TYPE_EOF);
}
catch(IOException ie){
throw ie;
}
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
private void nextToken() throws ParseException, IOException{
token = lexer.yylex();
if(token == null)
token = new Yytoken(Yytoken.TYPE_EOF, null);
}
private Map createObjectContainer(ContainerFactory containerFactory){
if(containerFactory == null)
return new JSONObject();
Map m = containerFactory.createObjectContainer();
if(m == null)
return new JSONObject();
return m;
}
private List createArrayContainer(ContainerFactory containerFactory){
if(containerFactory == null)
return new JSONArray();
List l = containerFactory.creatArrayContainer();
if(l == null)
return new JSONArray();
return l;
}
public void parse(String s, ContentHandler contentHandler) throws ParseException{
parse(s, contentHandler, false);
}
public void parse(String s, ContentHandler contentHandler, boolean isResume) throws ParseException{
StringReader in=new StringReader(s);
try{
parse(in, contentHandler, isResume);
}
catch(IOException ie){
/*
* Actually it will never happen.
*/
throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie);
}
}
public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException{
parse(in, contentHandler, false);
}
/**
* Stream processing of JSON text.
*
* @see ContentHandler
*
* @param in
* @param contentHandler
* @param isResume - Indicates if it continues previous parsing operation.
* If set to true, resume parsing the old stream, and parameter 'in' will be ignored.
* If this method is called for the first time in this instance, isResume will be ignored.
*
* @throws IOException
* @throws ParseException
*/
public void parse(Reader in, ContentHandler contentHandler, boolean isResume) throws IOException, ParseException{
if(!isResume){
reset(in);
handlerStatusStack = new LinkedList();
}
else{
if(handlerStatusStack == null){
isResume = false;
reset(in);
handlerStatusStack = new LinkedList();
}
}
LinkedList statusStack = handlerStatusStack;
try{
do{
switch(status){
case S_INIT:
contentHandler.startJSON();
nextToken();
switch(token.type){
case Yytoken.TYPE_VALUE:
status=S_IN_FINISHED_VALUE;
statusStack.addFirst(new Integer(status));
if(!contentHandler.primitive(token.value))
return;
break;
case Yytoken.TYPE_LEFT_BRACE:
status=S_IN_OBJECT;
statusStack.addFirst(new Integer(status));
if(!contentHandler.startObject())
return;
break;
case Yytoken.TYPE_LEFT_SQUARE:
status=S_IN_ARRAY;
statusStack.addFirst(new Integer(status));
if(!contentHandler.startArray())
return;
break;
default:
status=S_IN_ERROR;
}//inner switch
break;
case S_IN_FINISHED_VALUE:
nextToken();
if(token.type==Yytoken.TYPE_EOF){
contentHandler.endJSON();
status = S_END;
return;
}
else{
status = S_IN_ERROR;
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
case S_IN_OBJECT:
nextToken();
switch(token.type){
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
if(token.value instanceof String){
String key=(String)token.value;
status=S_PASSED_PAIR_KEY;
statusStack.addFirst(new Integer(status));
if(!contentHandler.startObjectEntry(key))
return;
}
else{
status=S_IN_ERROR;
}
break;
case Yytoken.TYPE_RIGHT_BRACE:
if(statusStack.size()>1){
statusStack.removeFirst();
status=peekStatus(statusStack);
}
else{
status=S_IN_FINISHED_VALUE;
}
if(!contentHandler.endObject())
return;
break;
default:
status=S_IN_ERROR;
break;
}//inner switch
break;
case S_PASSED_PAIR_KEY:
nextToken();
switch(token.type){
case Yytoken.TYPE_COLON:
break;
case Yytoken.TYPE_VALUE:
statusStack.removeFirst();
status=peekStatus(statusStack);
if(!contentHandler.primitive(token.value))
return;
if(!contentHandler.endObjectEntry())
return;
break;
case Yytoken.TYPE_LEFT_SQUARE:
statusStack.removeFirst();
statusStack.addFirst(new Integer(S_IN_PAIR_VALUE));
status=S_IN_ARRAY;
statusStack.addFirst(new Integer(status));
if(!contentHandler.startArray())
return;
break;
case Yytoken.TYPE_LEFT_BRACE:
statusStack.removeFirst();
statusStack.addFirst(new Integer(S_IN_PAIR_VALUE));
status=S_IN_OBJECT;
statusStack.addFirst(new Integer(status));
if(!contentHandler.startObject())
return;
break;
default:
status=S_IN_ERROR;
}
break;
case S_IN_PAIR_VALUE:
/*
* S_IN_PAIR_VALUE is just a marker to indicate the end of an object entry, it doesn't proccess any token,
* therefore delay consuming token until next round.
*/
statusStack.removeFirst();
status = peekStatus(statusStack);
if(!contentHandler.endObjectEntry())
return;
break;
case S_IN_ARRAY:
nextToken();
switch(token.type){
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
if(!contentHandler.primitive(token.value))
return;
break;
case Yytoken.TYPE_RIGHT_SQUARE:
if(statusStack.size()>1){
statusStack.removeFirst();
status=peekStatus(statusStack);
}
else{
status=S_IN_FINISHED_VALUE;
}
if(!contentHandler.endArray())
return;
break;
case Yytoken.TYPE_LEFT_BRACE:
status=S_IN_OBJECT;
statusStack.addFirst(new Integer(status));
if(!contentHandler.startObject())
return;
break;
case Yytoken.TYPE_LEFT_SQUARE:
status=S_IN_ARRAY;
statusStack.addFirst(new Integer(status));
if(!contentHandler.startArray())
return;
break;
default:
status=S_IN_ERROR;
}//inner switch
break;
case S_END:
return;
case S_IN_ERROR:
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}//switch
if(status==S_IN_ERROR){
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
}while(token.type!=Yytoken.TYPE_EOF);
}
catch(IOException ie){
status = S_IN_ERROR;
throw ie;
}
catch(ParseException pe){
status = S_IN_ERROR;
throw pe;
}
catch(RuntimeException re){
status = S_IN_ERROR;
throw re;
}
catch(Error e){
status = S_IN_ERROR;
throw e;
}
status = S_IN_ERROR;
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
}
| |
/*
* Copyright 2014 Goldman Sachs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gs.collections.impl.lazy;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import com.gs.collections.api.LazyIterable;
import com.gs.collections.api.RichIterable;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.collection.primitive.MutableBooleanCollection;
import com.gs.collections.api.collection.primitive.MutableByteCollection;
import com.gs.collections.api.collection.primitive.MutableCharCollection;
import com.gs.collections.api.collection.primitive.MutableDoubleCollection;
import com.gs.collections.api.collection.primitive.MutableFloatCollection;
import com.gs.collections.api.collection.primitive.MutableIntCollection;
import com.gs.collections.api.collection.primitive.MutableLongCollection;
import com.gs.collections.api.collection.primitive.MutableShortCollection;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.map.sorted.MutableSortedMap;
import com.gs.collections.api.multimap.Multimap;
import com.gs.collections.api.multimap.MutableMultimap;
import com.gs.collections.api.partition.PartitionIterable;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.set.sorted.MutableSortedSet;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.impl.bag.mutable.HashBag;
import com.gs.collections.impl.block.factory.Comparators;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.IntegerPredicates;
import com.gs.collections.impl.block.factory.Predicates;
import com.gs.collections.impl.block.factory.Predicates2;
import com.gs.collections.impl.block.factory.PrimitiveFunctions;
import com.gs.collections.impl.block.factory.Procedures;
import com.gs.collections.impl.block.function.AddFunction;
import com.gs.collections.impl.block.function.NegativeIntervalFunction;
import com.gs.collections.impl.block.function.PassThruFunction0;
import com.gs.collections.impl.factory.Bags;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.list.Interval;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.list.mutable.primitive.BooleanArrayList;
import com.gs.collections.impl.list.mutable.primitive.ByteArrayList;
import com.gs.collections.impl.list.mutable.primitive.CharArrayList;
import com.gs.collections.impl.list.mutable.primitive.DoubleArrayList;
import com.gs.collections.impl.list.mutable.primitive.FloatArrayList;
import com.gs.collections.impl.list.mutable.primitive.IntArrayList;
import com.gs.collections.impl.list.mutable.primitive.LongArrayList;
import com.gs.collections.impl.list.mutable.primitive.ShortArrayList;
import com.gs.collections.impl.map.mutable.UnifiedMap;
import com.gs.collections.impl.map.sorted.mutable.TreeSortedMap;
import com.gs.collections.impl.multimap.list.FastListMultimap;
import com.gs.collections.impl.set.mutable.UnifiedSet;
import com.gs.collections.impl.set.sorted.mutable.TreeSortedSet;
import com.gs.collections.impl.test.Verify;
import org.junit.Assert;
import org.junit.Test;
import static com.gs.collections.impl.factory.Iterables.*;
public abstract class AbstractLazyIterableTestCase
{
private final LazyIterable<Integer> lazyIterable = this.newWith(1, 2, 3, 4, 5, 6, 7);
protected abstract <T> LazyIterable<T> newWith(T... elements);
@Test
public abstract void iterator();
@Test
public void toArray()
{
Assert.assertArrayEquals(
FastList.newListWith(1, 2).toArray(),
this.lazyIterable.select(Predicates.lessThan(3)).toArray());
Assert.assertArrayEquals(
FastList.newListWith(1, 2).toArray(),
this.lazyIterable.select(Predicates.lessThan(3)).toArray(new Object[2]));
}
@Test
public void contains()
{
Assert.assertTrue(this.lazyIterable.contains(3));
Assert.assertFalse(this.lazyIterable.contains(8));
}
@Test
public void containsAllIterable()
{
Assert.assertTrue(this.lazyIterable.containsAllIterable(FastList.newListWith(3)));
Assert.assertFalse(this.lazyIterable.containsAllIterable(FastList.newListWith(8)));
}
@Test
public void containsAllArray()
{
Assert.assertTrue(this.lazyIterable.containsAllArguments(3));
Assert.assertFalse(this.lazyIterable.containsAllArguments(8));
}
@Test
public void select()
{
Assert.assertEquals(
FastList.newListWith(1, 2),
this.lazyIterable.select(Predicates.lessThan(3)).toList());
}
@Test
public void selectWith()
{
Assert.assertEquals(
FastList.newListWith(1, 2),
this.lazyIterable.selectWith(Predicates2.<Integer>lessThan(), 3, FastList.<Integer>newList()));
}
@Test
public void selectWithTarget()
{
Assert.assertEquals(
FastList.newListWith(1, 2),
this.lazyIterable.select(Predicates.lessThan(3), FastList.<Integer>newList()));
}
@Test
public void reject()
{
Assert.assertEquals(FastList.newListWith(3, 4, 5, 6, 7), this.lazyIterable.reject(Predicates.lessThan(3)).toList());
}
@Test
public void rejectWith()
{
Assert.assertEquals(
FastList.newListWith(3, 4, 5, 6, 7),
this.lazyIterable.rejectWith(Predicates2.<Integer>lessThan(), 3, FastList.<Integer>newList()));
}
@Test
public void rejectWithTarget()
{
Assert.assertEquals(
FastList.newListWith(3, 4, 5, 6, 7),
this.lazyIterable.reject(Predicates.lessThan(3), FastList.<Integer>newList()));
}
@Test
public void partition()
{
PartitionIterable<Integer> partition = this.lazyIterable.partition(IntegerPredicates.isEven());
Assert.assertEquals(iList(2, 4, 6), partition.getSelected());
Assert.assertEquals(iList(1, 3, 5, 7), partition.getRejected());
}
@Test
public void partitionWith()
{
PartitionIterable<Integer> partition = this.lazyIterable.partitionWith(Predicates2.in(), this.lazyIterable.select(IntegerPredicates.isEven()));
Assert.assertEquals(iList(2, 4, 6), partition.getSelected());
Assert.assertEquals(iList(1, 3, 5, 7), partition.getRejected());
}
@Test
public void selectInstancesOf()
{
Assert.assertEquals(
FastList.newListWith(1, 3, 5),
this.newWith(1, 2.0, 3, 4.0, 5).selectInstancesOf(Integer.class).toList());
}
@Test
public void collect()
{
Assert.assertEquals(
FastList.newListWith("1", "2", "3", "4", "5", "6", "7"),
this.lazyIterable.collect(String::valueOf).toList());
}
@Test
public void collectBoolean()
{
Assert.assertEquals(
BooleanArrayList.newListWith(true, true, true, true, true, true, true),
this.lazyIterable.collectBoolean(PrimitiveFunctions.integerIsPositive()).toList());
}
@Test
public void collectBooleanWithTarget()
{
MutableBooleanCollection target = new BooleanArrayList();
MutableBooleanCollection result = this.lazyIterable.collectBoolean(PrimitiveFunctions.integerIsPositive(), target);
Assert.assertEquals(
BooleanArrayList.newListWith(true, true, true, true, true, true, true),
result.toList());
Assert.assertSame("Target list sent as parameter not returned", target, result);
}
@Test
public void collectByte()
{
Assert.assertEquals(ByteArrayList.newListWith((byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5, (byte) 6, (byte) 7), this.lazyIterable.collectByte(PrimitiveFunctions.unboxIntegerToByte()).toList());
}
@Test
public void collectByteWithTarget()
{
MutableByteCollection target = new ByteArrayList();
MutableByteCollection result = this.lazyIterable.collectByte(PrimitiveFunctions.unboxIntegerToByte(), target);
Assert.assertEquals(ByteArrayList.newListWith((byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5, (byte) 6, (byte) 7), result.toList());
Assert.assertSame("Target list sent as parameter not returned", target, result);
}
@Test
public void collectChar()
{
Assert.assertEquals(
CharArrayList.newListWith((char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7),
this.lazyIterable.collectChar(PrimitiveFunctions.unboxIntegerToChar()).toList());
}
@Test
public void collectCharWithTarget()
{
MutableCharCollection target = new CharArrayList();
MutableCharCollection result = this.lazyIterable.collectChar(PrimitiveFunctions.unboxIntegerToChar(), target);
Assert.assertEquals(CharArrayList.newListWith((char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7), result.toList());
Assert.assertSame("Target list sent as parameter not returned", target, result);
}
@Test
public void collectDouble()
{
Assert.assertEquals(DoubleArrayList.newListWith(1.0d, 2.0d, 3.0d, 4.0d, 5.0d, 6.0d, 7.0d), this.lazyIterable.collectDouble(PrimitiveFunctions.unboxIntegerToDouble()).toList());
}
@Test
public void collectDoubleWithTarget()
{
MutableDoubleCollection target = new DoubleArrayList();
MutableDoubleCollection result = this.lazyIterable.collectDouble(PrimitiveFunctions.unboxIntegerToDouble(), target);
Assert.assertEquals(
DoubleArrayList.newListWith(1.0d, 2.0d, 3.0d, 4.0d, 5.0d, 6.0d, 7.0d), result.toList());
Assert.assertSame("Target list sent as parameter not returned", target, result);
}
@Test
public void collectFloat()
{
Assert.assertEquals(
FloatArrayList.newListWith(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f),
this.lazyIterable.collectFloat(PrimitiveFunctions.unboxIntegerToFloat()).toList());
}
@Test
public void collectFloatWithTarget()
{
MutableFloatCollection target = new FloatArrayList();
MutableFloatCollection result = this.lazyIterable.collectFloat(PrimitiveFunctions.unboxIntegerToFloat(), target);
Assert.assertEquals(
FloatArrayList.newListWith(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f), result.toList());
Assert.assertSame("Target list sent as parameter not returned", target, result);
}
@Test
public void collectInt()
{
Assert.assertEquals(IntArrayList.newListWith(1, 2, 3, 4, 5, 6, 7), this.lazyIterable.collectInt(PrimitiveFunctions.unboxIntegerToInt()).toList());
}
@Test
public void collectIntWithTarget()
{
MutableIntCollection target = new IntArrayList();
MutableIntCollection result = this.lazyIterable.collectInt(PrimitiveFunctions.unboxIntegerToInt(), target);
Assert.assertEquals(IntArrayList.newListWith(1, 2, 3, 4, 5, 6, 7), result.toList());
Assert.assertSame("Target list sent as parameter not returned", target, result);
}
@Test
public void collectLong()
{
Assert.assertEquals(
LongArrayList.newListWith(1L, 2L, 3L, 4L, 5L, 6L, 7L),
this.lazyIterable.collectLong(PrimitiveFunctions.unboxIntegerToLong()).toList());
}
@Test
public void collectLongWithTarget()
{
MutableLongCollection target = new LongArrayList();
MutableLongCollection result = this.lazyIterable.collectLong(PrimitiveFunctions.unboxIntegerToLong(), target);
Assert.assertEquals(LongArrayList.newListWith(1L, 2L, 3L, 4L, 5L, 6L, 7L), result.toList());
Assert.assertSame("Target list sent as parameter not returned", target, result);
}
@Test
public void collectShort()
{
Assert.assertEquals(
ShortArrayList.newListWith((short) 1, (short) 2, (short) 3, (short) 4, (short) 5, (short) 6, (short) 7),
this.lazyIterable.collectShort(PrimitiveFunctions.unboxIntegerToShort()).toList());
}
@Test
public void collectShortWithTarget()
{
MutableShortCollection target = new ShortArrayList();
MutableShortCollection result = this.lazyIterable.collectShort(PrimitiveFunctions.unboxIntegerToShort(), target);
Assert.assertEquals(ShortArrayList.newListWith((short) 1, (short) 2, (short) 3, (short) 4, (short) 5, (short) 6, (short) 7), result.toList());
Assert.assertSame("Target list sent as parameter not returned", target, result);
}
@Test
public void collectWith()
{
Assert.assertEquals(
FastList.newListWith("1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 "),
this.lazyIterable.collectWith((argument1, argument2) -> argument1 + argument2, " ", FastList.<String>newList()));
}
@Test
public void collectWithTarget()
{
Assert.assertEquals(
FastList.newListWith("1", "2", "3", "4", "5", "6", "7"),
this.lazyIterable.collect(String::valueOf, FastList.<String>newList()));
}
@Test
public void take()
{
LazyIterable<Integer> lazyIterable = this.lazyIterable;
Assert.assertEquals(FastList.newList(), lazyIterable.take(0).toList());
Assert.assertEquals(FastList.newListWith(1), lazyIterable.take(1).toList());
Assert.assertEquals(FastList.newListWith(1, 2), lazyIterable.take(2).toList());
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4, 5, 6), lazyIterable.take(lazyIterable.size() - 1).toList());
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4, 5, 6, 7), lazyIterable.take(lazyIterable.size()).toList());
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4, 5, 6, 7), lazyIterable.take(10).toList());
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4, 5, 6, 7), lazyIterable.take(Integer.MAX_VALUE).toList());
}
@Test(expected = IllegalArgumentException.class)
public void take_negative_throws()
{
this.lazyIterable.take(-1);
}
@Test
public void drop()
{
LazyIterable<Integer> lazyIterable = this.lazyIterable;
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4, 5, 6, 7), lazyIterable.drop(0).toList());
Assert.assertEquals(FastList.newListWith(3, 4, 5, 6, 7), lazyIterable.drop(2).toList());
Assert.assertEquals(FastList.newListWith(7), lazyIterable.drop(lazyIterable.size() - 1).toList());
Assert.assertEquals(FastList.newList(), lazyIterable.drop(lazyIterable.size()).toList());
Assert.assertEquals(FastList.newList(), lazyIterable.drop(10).toList());
Assert.assertEquals(FastList.newList(), lazyIterable.drop(Integer.MAX_VALUE).toList());
}
@Test(expected = IllegalArgumentException.class)
public void drop_negative_throws()
{
this.lazyIterable.drop(-1);
}
@Test
public void detect()
{
Assert.assertEquals(Integer.valueOf(3), this.lazyIterable.detect(Integer.valueOf(3)::equals));
Assert.assertNull(this.lazyIterable.detect(Integer.valueOf(8)::equals));
}
@Test
public void detectWith()
{
Assert.assertEquals(Integer.valueOf(3), this.lazyIterable.detectWith(Object::equals, Integer.valueOf(3)));
Assert.assertNull(this.lazyIterable.detectWith(Object::equals, Integer.valueOf(8)));
}
@Test
public void detectWithIfNone()
{
Function0<Integer> function = new PassThruFunction0<>(Integer.valueOf(1000));
Assert.assertEquals(Integer.valueOf(3), this.lazyIterable.detectWithIfNone(Object::equals, Integer.valueOf(3), function));
Assert.assertEquals(Integer.valueOf(1000), this.lazyIterable.detectWithIfNone(Object::equals, Integer.valueOf(8), function));
}
@Test(expected = NoSuchElementException.class)
public void min_empty_throws()
{
this.<Integer>newWith().min(Integer::compareTo);
}
@Test(expected = NoSuchElementException.class)
public void max_empty_throws()
{
this.<Integer>newWith().max(Integer::compareTo);
}
@Test(expected = NullPointerException.class)
public void min_null_throws()
{
this.newWith(1, null, 2).min(Integer::compareTo);
}
@Test(expected = NullPointerException.class)
public void max_null_throws()
{
this.newWith(1, null, 2).max(Integer::compareTo);
}
@Test
public void min()
{
Assert.assertEquals(Integer.valueOf(1), this.newWith(1, 3, 2).min(Integer::compareTo));
}
@Test
public void max()
{
Assert.assertEquals(Integer.valueOf(3), this.newWith(1, 3, 2).max(Integer::compareTo));
}
@Test
public void minBy()
{
Assert.assertEquals(Integer.valueOf(1), this.newWith(1, 3, 2).minBy(String::valueOf));
}
@Test
public void maxBy()
{
Assert.assertEquals(Integer.valueOf(3), this.newWith(1, 3, 2).maxBy(String::valueOf));
}
@Test(expected = NoSuchElementException.class)
public void min_empty_throws_without_comparator()
{
this.newWith().min();
}
@Test(expected = NoSuchElementException.class)
public void max_empty_throws_without_comparator()
{
this.newWith().max();
}
@Test(expected = NullPointerException.class)
public void min_null_throws_without_comparator()
{
this.newWith(1, null, 2).min();
}
@Test(expected = NullPointerException.class)
public void max_null_throws_without_comparator()
{
this.newWith(1, null, 2).max();
}
@Test
public void min_without_comparator()
{
Assert.assertEquals(Integer.valueOf(1), this.newWith(3, 1, 2).min());
}
@Test
public void max_without_comparator()
{
Assert.assertEquals(Integer.valueOf(3), this.newWith(1, 3, 2).max());
}
@Test
public void detectIfNone()
{
Function0<Integer> function = new PassThruFunction0<>(9);
Assert.assertEquals(Integer.valueOf(3), this.lazyIterable.detectIfNone(Integer.valueOf(3)::equals, function));
Assert.assertEquals(Integer.valueOf(9), this.lazyIterable.detectIfNone(Integer.valueOf(8)::equals, function));
}
@Test
public void anySatisfy()
{
Assert.assertFalse(this.lazyIterable.anySatisfy(String.class::isInstance));
Assert.assertTrue(this.lazyIterable.anySatisfy(Integer.class::isInstance));
}
@Test
public void anySatisfyWith()
{
Assert.assertFalse(this.lazyIterable.anySatisfyWith(Predicates2.instanceOf(), String.class));
Assert.assertTrue(this.lazyIterable.anySatisfyWith(Predicates2.instanceOf(), Integer.class));
}
@Test
public void allSatisfy()
{
Assert.assertTrue(this.lazyIterable.allSatisfy(Integer.class::isInstance));
Assert.assertFalse(this.lazyIterable.allSatisfy(Integer.valueOf(1)::equals));
}
@Test
public void allSatisfyWith()
{
Assert.assertTrue(this.lazyIterable.allSatisfyWith(Predicates2.instanceOf(), Integer.class));
Assert.assertFalse(this.lazyIterable.allSatisfyWith(Object::equals, 1));
}
@Test
public void noneSatisfy()
{
Assert.assertFalse(this.lazyIterable.noneSatisfy(Integer.class::isInstance));
Assert.assertTrue(this.lazyIterable.noneSatisfy(String.class::isInstance));
}
@Test
public void noneSatisfyWith()
{
Assert.assertFalse(this.lazyIterable.noneSatisfyWith(Predicates2.instanceOf(), Integer.class));
Assert.assertTrue(this.lazyIterable.noneSatisfyWith(Predicates2.instanceOf(), String.class));
}
@Test
public void count()
{
Assert.assertEquals(7, this.lazyIterable.count(Integer.class::isInstance));
}
@Test
public void collectIf()
{
Assert.assertEquals(
FastList.newListWith("1", "2", "3"),
this.newWith(1, 2, 3).collectIf(
Integer.class::isInstance,
String::valueOf).toList());
}
@Test
public void collectIfWithTarget()
{
Assert.assertEquals(
FastList.newListWith("1", "2", "3"),
this.newWith(1, 2, 3).collectIf(
Integer.class::isInstance,
String::valueOf,
FastList.<String>newList()));
}
@Test
public void getFirst()
{
Assert.assertEquals(Integer.valueOf(1), this.newWith(1, 2, 3).getFirst());
Assert.assertNotEquals(Integer.valueOf(3), this.newWith(1, 2, 3).getFirst());
}
@Test
public void getLast()
{
Assert.assertNotEquals(Integer.valueOf(1), this.newWith(1, 2, 3).getLast());
Assert.assertEquals(Integer.valueOf(3), this.newWith(1, 2, 3).getLast());
}
@Test
public void isEmpty()
{
Assert.assertTrue(this.newWith().isEmpty());
Assert.assertTrue(this.newWith(1, 2).notEmpty());
}
@Test
public void injectInto()
{
RichIterable<Integer> objects = this.newWith(1, 2, 3);
Integer result = objects.injectInto(1, AddFunction.INTEGER);
Assert.assertEquals(Integer.valueOf(7), result);
}
@Test
public void toList()
{
MutableList<Integer> list = this.newWith(1, 2, 3, 4).toList();
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4), list);
}
@Test
public void toSortedListNaturalOrdering()
{
RichIterable<Integer> integers = this.newWith(2, 1, 5, 3, 4);
MutableList<Integer> list = integers.toSortedList();
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4, 5), list);
}
@Test
public void toSortedList()
{
RichIterable<Integer> integers = this.newWith(2, 4, 1, 3);
MutableList<Integer> list = integers.toSortedList(Collections.<Integer>reverseOrder());
Assert.assertEquals(FastList.newListWith(4, 3, 2, 1), list);
}
@Test
public void toSortedListBy()
{
LazyIterable<Integer> integers = this.newWith(2, 4, 1, 3);
MutableList<Integer> list = integers.toSortedListBy(String::valueOf);
Assert.assertEquals(FastList.newListWith(1, 2, 3, 4), list);
}
@Test
public void toSortedSet()
{
LazyIterable<Integer> integers = this.newWith(2, 4, 1, 3, 2, 1, 3, 4);
MutableSortedSet<Integer> set = integers.toSortedSet();
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(1, 2, 3, 4), set);
}
@Test
public void toSortedSet_with_comparator()
{
LazyIterable<Integer> integers = this.newWith(2, 4, 4, 2, 1, 4, 1, 3);
MutableSortedSet<Integer> set = integers.toSortedSet(Collections.<Integer>reverseOrder());
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(Collections.<Integer>reverseOrder(), 1, 2, 3, 4), set);
}
@Test
public void toSortedSetBy()
{
LazyIterable<Integer> integers = this.newWith(2, 4, 1, 3);
MutableSortedSet<Integer> set = integers.toSortedSetBy(String::valueOf);
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(1, 2, 3, 4), set);
}
@Test
public void toSet()
{
RichIterable<Integer> integers = this.newWith(1, 2, 3, 4);
MutableSet<Integer> set = integers.toSet();
Assert.assertEquals(UnifiedSet.newSetWith(1, 2, 3, 4), set);
}
@Test
public void toMap()
{
RichIterable<Integer> integers = this.newWith(1, 2, 3, 4);
MutableMap<String, String> map =
integers.toMap(String::valueOf, String::valueOf);
Assert.assertEquals(UnifiedMap.newWithKeysValues("1", "1", "2", "2", "3", "3", "4", "4"), map);
}
@Test
public void toSortedMap()
{
LazyIterable<Integer> integers = this.newWith(1, 2, 3);
MutableSortedMap<Integer, String> map = integers.toSortedMap(Functions.getIntegerPassThru(), String::valueOf);
Verify.assertMapsEqual(TreeSortedMap.newMapWith(1, "1", 2, "2", 3, "3"), map);
Verify.assertListsEqual(FastList.newListWith(1, 2, 3), map.keySet().toList());
}
@Test
public void toSortedMap_with_comparator()
{
LazyIterable<Integer> integers = this.newWith(1, 2, 3);
MutableSortedMap<Integer, String> map = integers.toSortedMap(Comparators.<Integer>reverseNaturalOrder(),
Functions.getIntegerPassThru(), String::valueOf);
Verify.assertMapsEqual(TreeSortedMap.newMapWith(Comparators.<Integer>reverseNaturalOrder(), 1, "1", 2, "2", 3, "3"), map);
Verify.assertListsEqual(FastList.newListWith(3, 2, 1), map.keySet().toList());
}
@Test
public void testToString()
{
Assert.assertEquals("[1, 2, 3]", this.newWith(1, 2, 3).toString());
}
@Test
public void makeString()
{
Assert.assertEquals("[1, 2, 3]", '[' + this.newWith(1, 2, 3).makeString() + ']');
}
@Test
public void appendString()
{
Appendable builder = new StringBuilder();
this.newWith(1, 2, 3).appendString(builder);
Assert.assertEquals("1, 2, 3", builder.toString());
}
@Test
public void groupBy()
{
Function<Integer, Boolean> isOddFunction = object -> IntegerPredicates.isOdd().accept(object);
MutableMap<Boolean, RichIterable<Integer>> expected =
UnifiedMap.<Boolean, RichIterable<Integer>>newWithKeysValues(
Boolean.TRUE, FastList.newListWith(1, 3, 5, 7),
Boolean.FALSE, FastList.newListWith(2, 4, 6));
Multimap<Boolean, Integer> multimap =
this.lazyIterable.groupBy(isOddFunction);
Assert.assertEquals(expected, multimap.toMap());
Multimap<Boolean, Integer> multimap2 =
this.lazyIterable.groupBy(isOddFunction, FastListMultimap.<Boolean, Integer>newMultimap());
Assert.assertEquals(expected, multimap2.toMap());
}
@Test
public void groupByEach()
{
MutableMultimap<Integer, Integer> expected = FastListMultimap.newMultimap();
for (int i = 1; i < 8; i++)
{
expected.putAll(-i, Interval.fromTo(i, 7));
}
Multimap<Integer, Integer> actual =
this.lazyIterable.groupByEach(new NegativeIntervalFunction());
Assert.assertEquals(expected, actual);
Multimap<Integer, Integer> actualWithTarget =
this.lazyIterable.groupByEach(new NegativeIntervalFunction(), FastListMultimap.<Integer, Integer>newMultimap());
Assert.assertEquals(expected, actualWithTarget);
}
@Test
public void groupByUniqueKey()
{
Assert.assertEquals(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3), this.newWith(1, 2, 3).groupByUniqueKey(id -> id));
}
@Test(expected = IllegalStateException.class)
public void groupByUniqueKey_throws()
{
this.newWith(1, 2, 3).groupByUniqueKey(Functions.getFixedValue(1));
}
@Test
public void groupByUniqueKey_target()
{
MutableMap<Integer, Integer> integers = this.newWith(1, 2, 3).groupByUniqueKey(id -> id, UnifiedMap.newWithKeysValues(0, 0));
Assert.assertEquals(UnifiedMap.newWithKeysValues(0, 0, 1, 1, 2, 2, 3, 3), integers);
}
@Test(expected = IllegalStateException.class)
public void groupByUniqueKey_target_throws()
{
this.newWith(1, 2, 3).groupByUniqueKey(id -> id, UnifiedMap.newWithKeysValues(2, 2));
}
@Test
public void zip()
{
List<Object> nulls = Collections.nCopies(this.lazyIterable.size(), null);
List<Object> nullsPlusOne = Collections.nCopies(this.lazyIterable.size() + 1, null);
List<Object> nullsMinusOne = Collections.nCopies(this.lazyIterable.size() - 1, null);
LazyIterable<Pair<Integer, Object>> pairs = this.lazyIterable.zip(nulls);
Assert.assertEquals(
this.lazyIterable.toSet(),
pairs.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).toSet());
Assert.assertEquals(
nulls,
pairs.collect((Function<Pair<?, Object>, Object>) Pair::getTwo, Lists.mutable.of()));
LazyIterable<Pair<Integer, Object>> pairsPlusOne = this.lazyIterable.zip(nullsPlusOne);
Assert.assertEquals(
this.lazyIterable.toSet(),
pairsPlusOne.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).toSet());
Assert.assertEquals(nulls, pairsPlusOne.collect((Function<Pair<?, Object>, Object>) Pair::getTwo, Lists.mutable.of()));
LazyIterable<Pair<Integer, Object>> pairsMinusOne = this.lazyIterable.zip(nullsMinusOne);
Assert.assertEquals(this.lazyIterable.size() - 1, pairsMinusOne.size());
Assert.assertTrue(this.lazyIterable.containsAllIterable(pairsMinusOne.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne)));
Assert.assertEquals(
this.lazyIterable.zip(nulls).toSet(),
this.lazyIterable.zip(nulls, UnifiedSet.<Pair<Integer, Object>>newSet()));
}
@Test
public void zipWithIndex()
{
LazyIterable<Pair<Integer, Integer>> pairs = this.lazyIterable.zipWithIndex();
Assert.assertEquals(
this.lazyIterable.toSet(),
pairs.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).toSet());
Assert.assertEquals(
Interval.zeroTo(this.lazyIterable.size() - 1).toSet(),
pairs.collect((Function<Pair<?, Integer>, Integer>) Pair::getTwo, UnifiedSet.<Integer>newSet()));
Assert.assertEquals(
this.lazyIterable.zipWithIndex().toSet(),
this.lazyIterable.zipWithIndex(UnifiedSet.<Pair<Integer, Integer>>newSet()));
}
@Test
public void chunk()
{
LazyIterable<RichIterable<Integer>> groups = this.lazyIterable.chunk(2);
RichIterable<Integer> sizes = groups.collect(RichIterable::size);
Assert.assertEquals(Bags.mutable.of(2, 2, 2, 1), sizes.toBag());
}
@Test(expected = IllegalArgumentException.class)
public void chunk_zero_throws()
{
this.lazyIterable.chunk(0);
}
@Test
public void chunk_large_size()
{
Assert.assertEquals(this.lazyIterable.toBag(), this.lazyIterable.chunk(10).getFirst().toBag());
}
@Test
public void tap()
{
StringBuilder tapStringBuilder = new StringBuilder();
Procedure<Integer> appendProcedure = Procedures.append(tapStringBuilder);
LazyIterable<Integer> list = this.lazyIterable.tap(appendProcedure);
Verify.assertIterablesEqual(this.lazyIterable, list);
Assert.assertEquals("1234567", tapStringBuilder.toString());
}
@Test
public void asLazy()
{
Assert.assertSame(this.lazyIterable, this.lazyIterable.asLazy());
}
@Test
public void flatCollect()
{
LazyIterable<Integer> collection = this.newWith(1, 2, 3, 4);
Function<Integer, MutableList<String>> function = object -> FastList.newListWith(String.valueOf(object));
Verify.assertListsEqual(
FastList.newListWith("1", "2", "3", "4"),
collection.flatCollect(function).toSortedList());
Verify.assertSetsEqual(
UnifiedSet.newSetWith("1", "2", "3", "4"),
collection.flatCollect(function, UnifiedSet.<String>newSet()));
}
@Test
public void distinct()
{
LazyIterable<Integer> integers = this.newWith(3, 2, 2, 4, 1, 3, 1, 5);
Assert.assertEquals(
HashBag.newBagWith(1, 2, 3, 4, 5),
integers.distinct().toBag());
}
}
| |
/**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.regionserver;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.mob.MobConstants;
import org.apache.hadoop.hbase.mob.MobUtils;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.hbase.util.HFileArchiveUtil;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(MediumTests.class)
public class TestMobStoreScanner {
private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private final static byte [] row1 = Bytes.toBytes("row1");
private final static byte [] family = Bytes.toBytes("family");
private final static byte [] qf1 = Bytes.toBytes("qualifier1");
private final static byte [] qf2 = Bytes.toBytes("qualifier2");
protected final byte[] qf3 = Bytes.toBytes("qualifier3");
private static HTable table;
private static HBaseAdmin admin;
private static HColumnDescriptor hcd;
private static HTableDescriptor desc;
private static Random random = new Random();
private static long defaultThreshold = 10;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
TEST_UTIL.getConfiguration().setInt("hbase.master.info.port", 0);
TEST_UTIL.getConfiguration().setBoolean("hbase.regionserver.info.port.auto", true);
TEST_UTIL.getConfiguration().setInt("hbase.client.keyvalue.maxsize", 100*1024*1024);
TEST_UTIL.startMiniCluster(1);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
TEST_UTIL.shutdownMiniCluster();
}
public void setUp(long threshold, String TN) throws Exception {
desc = new HTableDescriptor(TableName.valueOf(TN));
hcd = new HColumnDescriptor(family);
hcd.setMobEnabled(true);
hcd.setMobThreshold(threshold);
hcd.setMaxVersions(4);
desc.addFamily(hcd);
admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
admin.createTable(desc);
table = new HTable(TEST_UTIL.getConfiguration(), TN);
}
/**
* Generate the mob value.
*
* @param size the size of the value
* @return the mob value generated
*/
private static byte[] generateMobValue(int size) {
byte[] mobVal = new byte[size];
random.nextBytes(mobVal);
return mobVal;
}
/**
* Set the scan attribute
*
* @param reversed if true, scan will be backward order
* @param mobScanRaw if true, scan will get the mob reference
* @return this
*/
public void setScan(Scan scan, boolean reversed, boolean mobScanRaw) {
scan.setReversed(reversed);
scan.setMaxVersions(4);
if(mobScanRaw) {
scan.setAttribute(MobConstants.MOB_SCAN_RAW, Bytes.toBytes(Boolean.TRUE));
}
}
@Test
public void testMobStoreScanner() throws Exception {
testGetFromFiles(false);
testGetFromMemStore(false);
testGetReferences(false);
testMobThreshold(false);
testGetFromArchive(false);
}
@Test
public void testReversedMobStoreScanner() throws Exception {
testGetFromFiles(true);
testGetFromMemStore(true);
testGetReferences(true);
testMobThreshold(true);
testGetFromArchive(true);
}
@Test(timeout=60000)
public void testGetMassive() throws Exception {
String TN = "testGetMassive";
setUp(defaultThreshold, TN);
// Put some data 5 10, 15, 20 mb ok (this would be right below protobuf default max size of 64MB.
// 25, 30, 40 fail. these is above protobuf max size of 64MB
byte[] bigValue = new byte[25*1024*1024];
Put put = new Put(row1);
put.add(family, qf1, bigValue);
put.add(family, qf2, bigValue);
put.add(family, qf3, bigValue);
table.put(put);
Get g = new Get(row1);
Result r = table.get(g);
// should not have blown up.
}
public void testGetFromFiles(boolean reversed) throws Exception {
String TN = "testGetFromFiles" + reversed;
setUp(defaultThreshold, TN);
long ts1 = System.currentTimeMillis();
long ts2 = ts1 + 1;
long ts3 = ts1 + 2;
byte [] value = generateMobValue((int)defaultThreshold+1);
Put put1 = new Put(row1);
put1.add(family, qf1, ts3, value);
put1.add(family, qf2, ts2, value);
put1.add(family, qf3, ts1, value);
table.put(put1);
table.flushCommits();
admin.flush(TN);
Scan scan = new Scan();
setScan(scan, reversed, false);
ResultScanner results = table.getScanner(scan);
int count = 0;
for (Result res : results) {
List<Cell> cells = res.listCells();
for(Cell cell : cells) {
// Verify the value
Assert.assertEquals(Bytes.toString(value),
Bytes.toString(CellUtil.cloneValue(cell)));
count++;
}
}
results.close();
Assert.assertEquals(3, count);
}
public void testGetFromMemStore(boolean reversed) throws Exception {
String TN = "testGetFromMemStore" + reversed;
setUp(defaultThreshold, TN);
long ts1 = System.currentTimeMillis();
long ts2 = ts1 + 1;
long ts3 = ts1 + 2;
byte [] value = generateMobValue((int)defaultThreshold+1);;
Put put1 = new Put(row1);
put1.add(family, qf1, ts3, value);
put1.add(family, qf2, ts2, value);
put1.add(family, qf3, ts1, value);
table.put(put1);
Scan scan = new Scan();
setScan(scan, reversed, false);
ResultScanner results = table.getScanner(scan);
int count = 0;
for (Result res : results) {
List<Cell> cells = res.listCells();
for(Cell cell : cells) {
// Verify the value
Assert.assertEquals(Bytes.toString(value),
Bytes.toString(CellUtil.cloneValue(cell)));
count++;
}
}
results.close();
Assert.assertEquals(3, count);
}
public void testGetReferences(boolean reversed) throws Exception {
String TN = "testGetReferences" + reversed;
setUp(defaultThreshold, TN);
long ts1 = System.currentTimeMillis();
long ts2 = ts1 + 1;
long ts3 = ts1 + 2;
byte [] value = generateMobValue((int)defaultThreshold+1);;
Put put1 = new Put(row1);
put1.add(family, qf1, ts3, value);
put1.add(family, qf2, ts2, value);
put1.add(family, qf3, ts1, value);
table.put(put1);
table.flushCommits();
admin.flush(TN);
Scan scan = new Scan();
setScan(scan, reversed, true);
ResultScanner results = table.getScanner(scan);
int count = 0;
for (Result res : results) {
List<Cell> cells = res.listCells();
for(Cell cell : cells) {
// Verify the value
assertIsMobReference(cell, row1, family, value, TN);
count++;
}
}
results.close();
Assert.assertEquals(3, count);
}
public void testMobThreshold(boolean reversed) throws Exception {
String TN = "testMobThreshold" + reversed;
setUp(defaultThreshold, TN);
byte [] valueLess = generateMobValue((int)defaultThreshold-1);
byte [] valueEqual = generateMobValue((int)defaultThreshold);
byte [] valueGreater = generateMobValue((int)defaultThreshold+1);
long ts1 = System.currentTimeMillis();
long ts2 = ts1 + 1;
long ts3 = ts1 + 2;
Put put1 = new Put(row1);
put1.add(family, qf1, ts3, valueLess);
put1.add(family, qf2, ts2, valueEqual);
put1.add(family, qf3, ts1, valueGreater);
table.put(put1);
table.flushCommits();
admin.flush(TN);
Scan scan = new Scan();
setScan(scan, reversed, true);
Cell cellLess= null;
Cell cellEqual = null;
Cell cellGreater = null;
ResultScanner results = table.getScanner(scan);
int count = 0;
for (Result res : results) {
List<Cell> cells = res.listCells();
for(Cell cell : cells) {
// Verify the value
String qf = Bytes.toString(CellUtil.cloneQualifier(cell));
if(qf.equals(Bytes.toString(qf1))) {
cellLess = cell;
}
if(qf.equals(Bytes.toString(qf2))) {
cellEqual = cell;
}
if(qf.equals(Bytes.toString(qf3))) {
cellGreater = cell;
}
count++;
}
}
Assert.assertEquals(3, count);
assertNotMobReference(cellLess, row1, family, valueLess);
assertNotMobReference(cellEqual, row1, family, valueEqual);
assertIsMobReference(cellGreater, row1, family, valueGreater, TN);
results.close();
}
public void testGetFromArchive(boolean reversed) throws Exception {
String TN = "testGetFromArchive" + reversed;
setUp(defaultThreshold, TN);
long ts1 = System.currentTimeMillis();
long ts2 = ts1 + 1;
long ts3 = ts1 + 2;
byte [] value = generateMobValue((int)defaultThreshold+1);;
// Put some data
Put put1 = new Put(row1);
put1.add(family, qf1, ts3, value);
put1.add(family, qf2, ts2, value);
put1.add(family, qf3, ts1, value);
table.put(put1);
table.flushCommits();
admin.flush(TN);
// Get the files in the mob path
Path mobFamilyPath;
mobFamilyPath = new Path(MobUtils.getMobRegionPath(TEST_UTIL.getConfiguration(),
TableName.valueOf(TN)), hcd.getNameAsString());
FileSystem fs = FileSystem.get(TEST_UTIL.getConfiguration());
FileStatus[] files = fs.listStatus(mobFamilyPath);
// Get the archive path
Path rootDir = FSUtils.getRootDir(TEST_UTIL.getConfiguration());
Path tableDir = FSUtils.getTableDir(rootDir, TableName.valueOf(TN));
HRegionInfo regionInfo = MobUtils.getMobRegionInfo(TableName.valueOf(TN));
Path storeArchiveDir = HFileArchiveUtil.getStoreArchivePath(TEST_UTIL.getConfiguration(),
regionInfo, tableDir, family);
// Move the files from mob path to archive path
fs.mkdirs(storeArchiveDir);
int fileCount = 0;
for(FileStatus file : files) {
fileCount++;
Path filePath = file.getPath();
Path src = new Path(mobFamilyPath, filePath.getName());
Path dst = new Path(storeArchiveDir, filePath.getName());
fs.rename(src, dst);
}
// Verify the moving success
FileStatus[] files1 = fs.listStatus(mobFamilyPath);
Assert.assertEquals(0, files1.length);
FileStatus[] files2 = fs.listStatus(storeArchiveDir);
Assert.assertEquals(fileCount, files2.length);
// Scan from archive
Scan scan = new Scan();
setScan(scan, reversed, false);
ResultScanner results = table.getScanner(scan);
int count = 0;
for (Result res : results) {
List<Cell> cells = res.listCells();
for(Cell cell : cells) {
// Verify the value
Assert.assertEquals(Bytes.toString(value),
Bytes.toString(CellUtil.cloneValue(cell)));
count++;
}
}
results.close();
Assert.assertEquals(3, count);
}
/**
* Assert the value is not store in mob.
*/
private static void assertNotMobReference(Cell cell, byte[] row, byte[] family,
byte[] value) throws IOException {
Assert.assertEquals(Bytes.toString(row),
Bytes.toString(CellUtil.cloneRow(cell)));
Assert.assertEquals(Bytes.toString(family),
Bytes.toString(CellUtil.cloneFamily(cell)));
Assert.assertTrue(Bytes.toString(value).equals(
Bytes.toString(CellUtil.cloneValue(cell))));
}
/**
* Assert the value is store in mob.
*/
private static void assertIsMobReference(Cell cell, byte[] row, byte[] family,
byte[] value, String TN) throws IOException {
Assert.assertEquals(Bytes.toString(row),
Bytes.toString(CellUtil.cloneRow(cell)));
Assert.assertEquals(Bytes.toString(family),
Bytes.toString(CellUtil.cloneFamily(cell)));
Assert.assertFalse(Bytes.toString(value).equals(
Bytes.toString(CellUtil.cloneValue(cell))));
byte[] referenceValue = CellUtil.cloneValue(cell);
String fileName = Bytes.toString(referenceValue, Bytes.SIZEOF_INT,
referenceValue.length - Bytes.SIZEOF_INT);
int valLen = Bytes.toInt(referenceValue, 0, Bytes.SIZEOF_INT);
Assert.assertEquals(value.length, valLen);
Path mobFamilyPath;
mobFamilyPath = new Path(MobUtils.getMobRegionPath(TEST_UTIL.getConfiguration(),
TableName.valueOf(TN)), hcd.getNameAsString());
Path targetPath = new Path(mobFamilyPath, fileName);
FileSystem fs = FileSystem.get(TEST_UTIL.getConfiguration());
Assert.assertTrue(fs.exists(targetPath));
}
}
| |
package com.artursworld.reactiontest.view.games;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.session.MediaSession;
import android.media.session.PlaybackState;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.TextView;
import com.artursworld.reactiontest.R;
import com.artursworld.reactiontest.controller.helper.GameStatus;
import com.artursworld.reactiontest.controller.helper.Type;
import com.artursworld.reactiontest.controller.util.UtilsRG;
import com.artursworld.reactiontest.model.persistence.manager.ReactionGameManager;
import com.artursworld.reactiontest.model.persistence.manager.TrialManager;
import com.sdsmdg.tastytoast.TastyToast;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class GoNoGoGameView extends AppCompatActivity {
// by the app user selected attributes
private String medicalUserId;
private String operationIssueName;
private String testType;
private String gameType;
// game attributes
private String reactionGameId;
private GameStatus currentGameStatus;
private long startTimeOfGame_millis;
private long stopTimeOfGame_millis;
private int tryCounter = 0;
private List<Boolean> booleanBoxList;
private int usersTapCount = 0;
private long usersTapStartTime = 0;
private MediaSession audioSession;
// game settings
private int minWaitTimeBeforeGameStartInSeconds = 1;
private int maxWaitTimeBeforeGameStartsInSeconds = 2;
private int usersMaxAcceptedReactionTime_sec = 5;
private int countDown_sec = 1;
private int triesPerGameCount;
private int fakeRedStateDuration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UtilsRG.info("onCreate " + GoNoGoGameView.class.getSimpleName());
setContentView(R.layout.activity_go_no_go_game_view);
}
@Override
protected void onResume() {
super.onResume();
UtilsRG.info("onResume " + GoNoGoGameView.class.getSimpleName());
addAudioButtonClickListener();
// init attributes, shows count down and starts game
initSelectedGameAttributes();
}
@Override
protected void onPause() {
super.onPause();
try {
if (audioSession != null)
audioSession.release();
} catch (Exception e) {
UtilsRG.info("could not release audio session");
}
}
/**
* Initializes by the user selected game attributes and starts game on settings loaded
*/
private void initSelectedGameAttributes() {
final Activity activity = this;
if (medicalUserId == null) {
medicalUserId = UtilsRG.getStringByKey(UtilsRG.MEDICAL_USER, this);
}
if (operationIssueName == null) {
operationIssueName = UtilsRG.getStringByKey(UtilsRG.OPERATION_ISSUE, this);
}
if (gameType == null) {
gameType = UtilsRG.getStringByKey(UtilsRG.GAME_TYPE, this);
}
if (testType == null) {
testType = UtilsRG.getStringByKey(UtilsRG.TEST_TYPE, this);
}
if (reactionGameId == null) {
reactionGameId = UtilsRG.getStringByKey(UtilsRG.REACTION_GAME_ID, this);
}
try {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
triesPerGameCount = mySharedPreferences.getInt(activity.getApplicationContext().getResources().getString(R.string.go_no_go_game_tries_per_game), 3);
countDown_sec = mySharedPreferences.getInt(activity.getApplicationContext().getResources().getString(R.string.go_no_go_game_count_down_count), 4);
fakeRedStateDuration = mySharedPreferences.getInt(activity.getApplicationContext().getResources().getString(R.string.go_no_go_game_show_fake_red_state_time_count), 2);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
initReactionGameId(new Date());
// init game UI stuff
prepareGameSetStatusAndDisplayUIElements(GameStatus.WAITING);
// startGame
runCountDownAndStartGame(countDown_sec);
}
}.execute();
} catch (Exception e) {
UtilsRG.error("Exception! " + e.getLocalizedMessage());
}
UtilsRG.info("Received user(" + medicalUserId + "), operation name(" + operationIssueName + ")");
UtilsRG.info("Test type=" + testType + ", GameType=" + gameType + ", reactionGameId=" + reactionGameId);
}
/**
* Creates a new reaction game via database, if not created yet
*
* @param date the date timestamp equals the id (primary key) of the reaction game
*/
private void initReactionGameId(final Date date) {
final Activity activity = this;
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
reactionGameId = UtilsRG.dateFormat.format(date);
if ((getApplicationContext() != null) && (reactionGameId != null)) {
ReactionGameManager db = new ReactionGameManager(getApplicationContext());
db.insertReactionGameByOperationIssueNameAsync(reactionGameId, operationIssueName, gameType, testType);
UtilsRG.putString(UtilsRG.REACTION_GAME_ID, reactionGameId, activity);
}
return null;
}
}.execute();
}
/**
* Sets game status and displays corresponding UI Elements for the user
*
* @param gameStatus the current game status
*/
public void prepareGameSetStatusAndDisplayUIElements(GameStatus gameStatus) {
this.currentGameStatus = gameStatus;
if (gameStatus == GameStatus.WAITING) {
UtilsRG.setBackgroundColor(this, R.color.colorPrimary);
}
}
/**
* Displays a countdown and after that the game starts
*
* @param countDown_sec the count down in seconds to wait before game start
*/
private void runCountDownAndStartGame(long countDown_sec) {
//UtilsRG.info("runCountDownAndStartGame with countdown: " + countDown_sec + ",tryCounter = " + tryCounter + ",triesPerGameCount = " +triesPerGameCount);
boolean userFinishedGameSuccessfully = (tryCounter >= triesPerGameCount);
if (!userFinishedGameSuccessfully) {
UtilsRG.info("start countdown: " + countDown_sec + " for the " + tryCounter + ". time of max. " + triesPerGameCount);
UtilsRG.setBackgroundColor(this, R.color.colorPrimary);
if (countDown_sec > 0) {
final TextView countDownText = (TextView) findViewById(R.id.gonogogamecountdown);
new CountDownTimer((countDown_sec + 1) * 1000, 1000) {
public void onTick(long millisUntilFinished) {
long countdownNumber = (millisUntilFinished / 1000) - 1;
if (countDownText != null) {
if (countdownNumber != 0) {
countDownText.setText("" + countdownNumber);
} else {
countDownText.setText(R.string.attention);
}
}
}
public void onFinish() {
UtilsRG.info("Countdown has been finished");
waitTimeAndStartGame(minWaitTimeBeforeGameStartInSeconds, maxWaitTimeBeforeGameStartsInSeconds);
}
}.start();
}
} else {
UtilsRG.info("runCountDownAndStartGame with countdown: " + countDown_sec + ",tryCounter = " + tryCounter + ",triesPerGameCount = " + triesPerGameCount);
onGameFinished();
}
}
/**
* Waits random time in defined range and starts the game
*
* @param minWaitTimeInSeconds the minimum waiting time
* @param maxWaitTimeInSeconds the maximum waiting time
*/
private void waitTimeAndStartGame(int minWaitTimeInSeconds, int maxWaitTimeInSeconds) {
UtilsRG.info("Waiting random time between " + minWaitTimeInSeconds + " and " + maxWaitTimeInSeconds);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
onStartGame();
}
}, UtilsRG.getRandomNumberInRange((minWaitTimeInSeconds * 1000), (maxWaitTimeInSeconds * 1000)));
}
private void onStartGame() {
UtilsRG.info(Type.GameTypes.GoNoGoGame.name() + " has been started now!");
TextView countDownText = (TextView) findViewById(R.id.gonogogamecountdown);
fillBooleanBox(triesPerGameCount);
UtilsRG.info("BooleanBox=" + booleanBoxList.toString());
if (booleanBoxList != null) {
if (booleanBoxList.size() > 0) {
int randomIndex = new Random().nextInt(booleanBoxList.size());
boolean isWrongColor = booleanBoxList.get(randomIndex);
booleanBoxList.remove(randomIndex);
if (isWrongColor) {
UtilsRG.info("Wrong color. The user should not hit screen.");
UtilsRG.setBackgroundColor(this, R.color.colorAccentLight);
this.currentGameStatus = GameStatus.WRONG_COLOR;
if (countDownText != null)
countDownText.setText(R.string.do_not_click);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
tryCounter++;
runCountDownAndStartGame(countDown_sec);
}
}, fakeRedStateDuration * 1000);
} else {
this.startTimeOfGame_millis = startTimeOfGame_millis;//System.currentTimeMillis();
UtilsRG.info("Now the user should hit screen.");
if (countDownText != null)
countDownText.setText(R.string.click);
UtilsRG.setBackgroundColor(this, R.color.goGameGreen);
this.currentGameStatus = GameStatus.CLICK;
}
} else {
onGameFinished();
}
}
}
/**
* Fills a boolean list with same amount of true and false values
*
* @param amount the amount of elements to add
*/
private void fillBooleanBox(int amount) {
if (booleanBoxList == null) {
booleanBoxList = new ArrayList<Boolean>();
for (int i = 0; i < amount; i++) {
if (i % 2 == 0) {
booleanBoxList.add(false);
} else {
booleanBoxList.add(true);
}
}
}
}
/**
* called than a user touches the display
*
* @param event the touch event
* @return Return true if user have consumed the event, false if user haven't.
* The default implementation always returns false.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
this.stopTimeOfGame_millis = android.os.SystemClock.uptimeMillis();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
checkTouchEvent();
}
if (findOutIfUserTapsLikeATapMaster(event, 3, 5)) return true;
return false;
}
private void checkTouchEvent() {
double usersReactionTime = (this.stopTimeOfGame_millis - this.startTimeOfGame_millis) / 1000.0;
if (currentGameStatus == GameStatus.CLICK) {
prepareGameSetStatusAndDisplayUIElements(GameStatus.WAITING);
if (usersMaxAcceptedReactionTime_sec < usersReactionTime) {
UtilsRG.info("User was to slow touching on the screen.");
runCountDownAndStartGame(this.countDown_sec);
} else {
onCorrectTouch(usersReactionTime);
}
} else if (currentGameStatus == GameStatus.WRONG_COLOR) {
UtilsRG.info("User touched the screen while the wrong color was displayed.");
onWrongTouch();
} else {
UtilsRG.info("User hit the screen at the wrong status(" + this.currentGameStatus + ")");
}
}
private boolean findOutIfUserTapsLikeATapMaster(MotionEvent event, int withinXseconds, int userTabCount) {
int eventaction = event.getAction();
if (eventaction == MotionEvent.ACTION_UP) {
//get system current milliseconds
long time = System.currentTimeMillis();
//if it is the first time, or if it has been more than 3 seconds since the first tap ( so it is like a new try), we reset everything
if (usersTapStartTime == 0 || (time - usersTapStartTime > (withinXseconds * 1000))) {
usersTapStartTime = time;
usersTapCount = 1;
}
//it is not the first, and it has been less than 3 seconds since the first
else {
usersTapCount++;
}
if (usersTapCount == userTabCount) {
UtilsRG.info("User taped " + userTabCount + " times within " + withinXseconds + " seconds");
}
return true;
}
return false;
}
/**
* User touched the screen at the wrong time (wrong color)
*/
private void onWrongTouch() {
String clickedAtWrongMoment = getResources().getString(R.string.wrong_moment);
TastyToast.makeText(getApplicationContext(), clickedAtWrongMoment, TastyToast.LENGTH_LONG, TastyToast.ERROR);
insertTrialAsync(0, false);
}
/**
* User hit the screen at the correct time
*
* @param usersReactionTime the users reaction time
*/
private void onCorrectTouch(final double usersReactionTime) {
tryCounter++;
TastyToast.makeText(getApplicationContext(), usersReactionTime + " s", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
UtilsRG.info("Users reaction time = " + usersReactionTime + " s");
insertTrialAsync(usersReactionTime, true);
boolean userFinishedGameSuccessfully = (tryCounter >= triesPerGameCount);
if (!userFinishedGameSuccessfully) {
runCountDownAndStartGame(this.countDown_sec);
} else {
onGameFinished();
}
}
/**
* Opens new activity depending on the test type
*/
private void onGameFinished() {
// User finished the Go-No-Go-Game successfully.
UtilsRG.info("User finished the Go-No-Go-Game successfully.");
if (testType != null) {
Intent intent;
//TODO: delete the first if?
if (testType.equals(Type.TestTypes.InOperation.name())) {
intent = new Intent(this, OperationModeView.class);
} else {
intent = new Intent(this, SingleGameResultView.class);
}
startActivity(intent);
}
}
/**
* Inserts a trial asynchroniously by users reaction time
*
* @param usersReactionTime the users reaction time
* @param isValid is the trial valid or did the user touch the screen at wrong time
*/
private void insertTrialAsync(final double usersReactionTime, final boolean isValid) {
final Activity activity = this;
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... unusedParams) {
TrialManager trialManager = new TrialManager(activity);
trialManager.insertTrialtoReactionGameAsync(reactionGameId, isValid, usersReactionTime);
return null;
}
}.execute();
}
private void addAudioButtonClickListener() {
try {
audioSession = new MediaSession(getApplicationContext(), "TAG");
audioSession.setCallback(new MediaSession.Callback() {
@Override
public boolean onMediaButtonEvent(final Intent mediaButtonIntent) {
String intentAction = mediaButtonIntent.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
KeyEvent event = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event != null) {
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
stopTimeOfGame_millis = event.getDownTime();
double usersReactionTime = (event.getDownTime() - startTimeOfGame_millis) / 1000.0;
UtilsRG.info("event.getDownTime(): " + usersReactionTime);
checkTouchEvent();
}
}
}
//int intentDelta = 50;
//stopTimeOfGame_millis = System.currentTimeMillis() - intentDelta;
//checkTouchEvent();
return super.onMediaButtonEvent(mediaButtonIntent);
}
});
PlaybackState state = new PlaybackState.Builder()
.setActions(PlaybackState.ACTION_PLAY_PAUSE)
.setState(PlaybackState.STATE_PLAYING, 0, 0, 0)
.build();
audioSession.setPlaybackState(state);
audioSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
audioSession.setActive(true);
} catch (Exception e) {
UtilsRG.info("could not addAudioButtonClickListener:" + e.getLocalizedMessage());
}
}
}
| |
/**
* Copyright (c) 2012, 2014, Credit Suisse (Anatole Tresch), Werner Keil and others by the @author tag.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.javamoney.moneta.internal.loader;
import org.javamoney.moneta.spi.LoaderService;
import javax.money.spi.Bootstrap;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class provides a mechanism to register resources, that may be updated
* regularly. The implementation, based on the {@link UpdatePolicy}
* loads/updates the resources from arbitrary locations and stores it to the
* format file cache. Default loading tasks can be configured within the javamoney.properties
* file, @see org.javamoney.moneta.loader.format.LoaderConfigurator .
* <p>
* @author Anatole Tresch
*/
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
public class DefaultLoaderService implements LoaderService {
/**
* Logger used.
*/
private static final Logger LOG = Logger.getLogger(DefaultLoaderService.class.getName());
/**
* The data resources managed by this instance.
*/
private Map<String, LoadableResource> resources = new ConcurrentHashMap<>();
/**
* The registered {@link LoaderListener} instances.
*/
private final Map<String, List<LoaderListener>> listenersMap = new ConcurrentHashMap<>();
/**
* The local resource cache, to allow keeping current data on the local
* system.
*/
private static final ResourceCache CACHE = loadResourceCache();
/**
* The thread pool used for loading of data, triggered by the timer.
*/
private ExecutorService executors = Executors.newCachedThreadPool();
/**
* The timer used for schedules.
*/
private volatile Timer timer;
/**
* Constructor, initializing from config.
*/
public DefaultLoaderService() {
initialize();
}
/**
* This method reads initial loads from the javamoney.properties and installs the according timers.
*/
protected void initialize() {
// Cancel any running tasks
Timer oldTimer = timer;
timer = new Timer();
if (Objects.nonNull(oldTimer)) {
oldTimer.cancel();
}
// (re)initialize
LoaderConfigurator configurator = new LoaderConfigurator(this);
configurator.load();
}
/**
* Loads the cache to be used.
*
* @return the cache to be used, not null.
*/
private static ResourceCache loadResourceCache() {
try {
return Optional.ofNullable(Bootstrap.getService(ResourceCache.class)).orElseGet(
DefaultResourceCache::new);
} catch (Exception e) {
LOG.log(Level.SEVERE, "Error loading ResourceCache instance.", e);
return new DefaultResourceCache();
}
}
/**
* Get the resource cache loaded.
*
* @return the resource cache, not null.
*/
static ResourceCache getResourceCache() {
return DefaultLoaderService.CACHE;
}
/**
* Removes a resource managed.
*
* @param resourceId the resource id.
*/
public void unload(String resourceId) {
LoadableResource res = this.resources.get(resourceId);
if (Objects.nonNull(res)) {
res.unload();
}
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.spi.LoaderService#registerData(java.lang.String,
* org.javamoney.moneta.spi.LoaderService.UpdatePolicy, java.util.Map,
* java.net.URL, java.net.URL[])
*/
@Override
public void registerData(String resourceId, UpdatePolicy updatePolicy, Map<String, String> properties,
LoaderListener loaderListener,
URI backupResource, URI... resourceLocations) {
if (resources.containsKey(resourceId)) {
throw new IllegalArgumentException("Resource : " + resourceId + " already registered.");
}
LoadableResource res = new LoadableResource(resourceId, CACHE, updatePolicy, properties, backupResource, resourceLocations);
this.resources.put(resourceId, res);
if (loaderListener != null) {
this.addLoaderListener(loaderListener, resourceId);
}
switch (updatePolicy) {
case NEVER:
loadDataLocal(resourceId);
break;
case ONSTARTUP:
loadDataAsync(resourceId);
break;
case SCHEDULED:
addScheduledLoad(res);
break;
case LAZY:
default:
break;
}
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.spi.LoaderService#registerAndLoadData(java.lang.String,
* org.javamoney.moneta.spi.LoaderService.UpdatePolicy, java.util.Map,
* java.net.URL, java.net.URL[])
*/
@Override
public void registerAndLoadData(String resourceId, UpdatePolicy updatePolicy, Map<String, String> properties,
LoaderListener loaderListener,
URI backupResource, URI... resourceLocations) {
if (resources.containsKey(resourceId)) {
throw new IllegalArgumentException("Resource : " + resourceId + " already registered.");
}
LoadableResource res = new LoadableResource(resourceId, CACHE, updatePolicy, properties, backupResource, resourceLocations);
this.resources.put(resourceId, res);
if (loaderListener != null) {
this.addLoaderListener(loaderListener, resourceId);
}
switch (updatePolicy) {
case SCHEDULED:
addScheduledLoad(res);
break;
case LAZY:
default:
break;
}
loadData(resourceId);
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.spi.LoaderService#getUpdateConfiguration(java.lang
* .String)
*/
@Override
public Map<String, String> getUpdateConfiguration(String resourceId) {
LoadableResource load = this.resources.get(resourceId);
if (Objects.nonNull(load)) {
return load.getProperties();
}
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.spi.LoaderService#isResourceRegistered(java.lang.String)
*/
@Override
public boolean isResourceRegistered(String dataId) {
return this.resources.containsKey(dataId);
}
/*
* (non-Javadoc)
*
* @see org.javamoney.moneta.spi.LoaderService#getResourceIds()
*/
@Override
public Set<String> getResourceIds() {
return this.resources.keySet();
}
/*
* (non-Javadoc)
*
* @see org.javamoney.moneta.spi.LoaderService#getData(java.lang.String)
*/
@Override
public InputStream getData(String resourceId) throws IOException {
LoadableResource load = this.resources.get(resourceId);
if (Objects.nonNull(load)) {
load.getDataStream();
}
throw new IllegalArgumentException("No such resource: " + resourceId);
}
/*
* (non-Javadoc)
*
* @see org.javamoney.moneta.spi.LoaderService#loadData(java.lang.String)
*/
@Override
public boolean loadData(String resourceId) {
return loadDataSynch(resourceId);
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.spi.LoaderService#loadDataAsync(java.lang.String)
*/
@Override
public Future<Boolean> loadDataAsync(final String resourceId) {
return executors.submit(() -> loadDataSynch(resourceId));
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.spi.LoaderService#loadDataLocal(java.lang.String)
*/
@Override
public boolean loadDataLocal(String resourceId) {
LoadableResource load = this.resources.get(resourceId);
if (Objects.nonNull(load)) {
try {
if (load.loadFallback()) {
triggerListeners(resourceId, load.getDataStream());
return true;
}
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to load resource locally: " + resourceId, e);
}
} else {
throw new IllegalArgumentException("No such resource: " + resourceId);
}
return false;
}
/**
* Reload data for a resource synchronously.
*
* @param resourceId the resource id, not null.
* @return true, if loading succeeded.
*/
private boolean loadDataSynch(String resourceId) {
LoadableResource load = this.resources.get(resourceId);
if (Objects.nonNull(load)) {
try {
if (load.load()) {
triggerListeners(resourceId, load.getDataStream());
return true;
}
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to load resource: " + resourceId, e);
}
} else {
throw new IllegalArgumentException("No such resource: " + resourceId);
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.javamoney.moneta.spi.LoaderService#resetData(java.lang.String)
*/
@Override
public void resetData(String dataId) throws IOException {
LoadableResource load = Optional.ofNullable(this.resources.get(dataId))
.orElseThrow(() -> new IllegalArgumentException("No such resource: " + dataId));
if (load.resetToFallback()) {
triggerListeners(dataId, load.getDataStream());
}
}
/**
* Trigger the listeners registered for the given dataId.
*
* @param dataId the data id, not null.
* @param is the InputStream, containing the latest data.
*/
private void triggerListeners(String dataId, InputStream is) {
List<LoaderListener> listeners = getListeners("");
synchronized (listeners) {
for (LoaderListener ll : listeners) {
try {
ll.newDataLoaded(dataId, is);
} catch (Exception e) {
LOG.log(Level.SEVERE, "Error calling LoadListener: " + ll, e);
}
}
}
if (!(Objects.isNull(dataId) || dataId.isEmpty())) {
listeners = getListeners(dataId);
synchronized (listeners) {
for (LoaderListener ll : listeners) {
try {
ll.newDataLoaded(dataId, is);
} catch (Exception e) {
LOG.log(Level.SEVERE, "Error calling LoadListener: " + ll, e);
}
}
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.spi.LoaderService#addLoaderListener(org.javamoney
* .moneta.spi.LoaderService.LoaderListener, java.lang.String[])
*/
@Override
public void addLoaderListener(LoaderListener l, String... dataIds) {
if (dataIds.length == 0) {
List<LoaderListener> listeners = getListeners("");
synchronized (listeners) {
listeners.add(l);
}
} else {
for (String dataId : dataIds) {
List<LoaderListener> listeners = getListeners(dataId);
synchronized (listeners) {
listeners.add(l);
}
}
}
}
/**
* Evaluate the {@link LoaderListener} instances, listening fo a dataId
* given.
*
* @param dataId The dataId, not null
* @return the according listeners
*/
private List<LoaderListener> getListeners(String dataId) {
if (Objects.isNull(dataId)) {
dataId = "";
}
List<LoaderListener> listeners = this.listenersMap.get(dataId);
if (Objects.isNull(listeners)) {
synchronized (listenersMap) {
listeners = this.listenersMap.get(dataId);
if (Objects.isNull(listeners)) {
listeners = Collections.synchronizedList(new ArrayList<>());
this.listenersMap.put(dataId, listeners);
}
}
}
return listeners;
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.spi.LoaderService#removeLoaderListener(org.javamoney
* .moneta.spi.LoaderService.LoaderListener, java.lang.String[])
*/
@Override
public void removeLoaderListener(LoaderListener l, String... dataIds) {
if (dataIds.length == 0) {
List<LoaderListener> listeners = getListeners("");
synchronized (listeners) {
listeners.remove(l);
}
} else {
for (String dataId : dataIds) {
List<LoaderListener> listeners = getListeners(dataId);
synchronized (listeners) {
listeners.remove(l);
}
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.spi.LoaderService#getUpdatePolicy(java.lang.String)
*/
@Override
public UpdatePolicy getUpdatePolicy(String resourceId) {
LoadableResource load = Optional.of(this.resources.get(resourceId))
.orElseThrow(() -> new IllegalArgumentException("No such resource: " + resourceId));
return load.getUpdatePolicy();
}
/**
* Create the schedule for the given {@link LoadableResource}.
*
* @param load the load item to be managed, not null.
*/
private void addScheduledLoad(final LoadableResource load) {
Objects.requireNonNull(load);
TimerTask task = new TimerTask() {
@Override
public void run() {
try {
load.load();
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to update remote resource: " + load.getResourceId(), e);
}
}
};
Map<String, String> props = load.getProperties();
if (Objects.nonNull(props)) {
String value = props.get("period");
long periodMS = parseDuration(value);
value = props.get("delay");
long delayMS = parseDuration(value);
if (periodMS > 0) {
timer.scheduleAtFixedRate(task, delayMS, periodMS);
} else {
value = props.get("at");
if (Objects.nonNull(value)) {
List<GregorianCalendar> dates = parseDates(value);
dates.forEach(date -> timer.schedule(task, date.getTime(), 3_600_000 * 24 /* daily */));
}
}
}
}
/**
* Parse the dates of type HH:mm:ss:nnn, whereas minutes and smaller are
* optional.
*
* @param value the input text
* @return the parsed
*/
private List<GregorianCalendar> parseDates(String value) {
String[] parts = value.split(",");
List<GregorianCalendar> result = new ArrayList<>();
for (String part : parts) {
if (part.isEmpty()) {
continue;
}
String[] subparts = part.split(":");
GregorianCalendar cal = new GregorianCalendar();
for (int i = 0; i < subparts.length; i++) {
switch (i) {
case 0:
cal.set(GregorianCalendar.HOUR_OF_DAY, Integer.parseInt(subparts[i]));
break;
case 1:
cal.set(GregorianCalendar.MINUTE, Integer.parseInt(subparts[i]));
break;
case 2:
cal.set(GregorianCalendar.SECOND, Integer.parseInt(subparts[i]));
break;
case 3:
cal.set(GregorianCalendar.MILLISECOND, Integer.parseInt(subparts[i]));
break;
}
}
result.add(cal);
}
return result;
}
/**
* Parse a duration of the form HH:mm:ss:nnn, whereas only hours are non
* optional.
*
* @param value the input value
* @return the duration in ms.
*/
protected long parseDuration(String value) {
long periodMS = 0L;
if (Objects.nonNull(value)) {
String[] parts = value.split(":");
for (int i = 0; i < parts.length; i++) {
switch (i) {
case 0: // hours
periodMS += (Integer.parseInt(parts[i])) * 3600000L;
break;
case 1: // minutes
periodMS += (Integer.parseInt(parts[i])) * 60000L;
break;
case 2: // seconds
periodMS += (Integer.parseInt(parts[i])) * 1000L;
break;
case 3: // ms
periodMS += (Integer.parseInt(parts[i]));
break;
default:
break;
}
}
}
return periodMS;
}
@Override
public String toString() {
return "DefaultLoaderService [resources=" + resources + ']';
}
}
| |
/**
* Copyright Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.azure.storage.table;
import java.text.ParseException;
import java.util.Date;
import java.util.UUID;
import com.microsoft.azure.storage.Constants;
import com.microsoft.azure.storage.core.Base64;
import com.microsoft.azure.storage.core.SR;
import com.microsoft.azure.storage.core.Utility;
/**
* A class which represents a single typed property value in a table entity. An {@link EntityProperty} stores the data
* type as an {@link EdmType}. The value, which may be <code>null</code> for object types, but not for primitive types,
* is serialized and stored as a <code>String</code>.
* <p>
* {@link EntityProperty} provides overloaded constructors and overloads of the <code>setValue</code> method for
* supported value types. Each overloaded constructor or <code>setValue</code> method sets the {@link EdmType} and
* serializes the value appropriately based on the parameter type.
* <p>
* Use one of the <code>getValueAs</code><em>Type</em> methods to deserialize an {@link EntityProperty} as the
* appropriate Java type. The method will throw a {@link ParseException} or {@link IllegalArgumentException} if the
* {@link EntityProperty} cannot be deserialized as the Java type.
*/
public final class EntityProperty {
private String value;
private Class<?> type;
private EdmType edmType = EdmType.NULL;
private boolean isNull = false;
/**
* Flag that specifies whether the client should look to correct Date values stored on a {@link TableEntity}
* that may have been written using versions of this library prior to 2.0.0.
* See <a href="http://go.microsoft.com/fwlink/?LinkId=523753">here</a> for more details.
*/
private boolean dateBackwardCompatibility = false;
/**
* Reserved for internal use. Constructs an {@link EntityProperty} instance from a <code>Object</code> value type,
* and verifies that the value can be interpreted as the specified data type.
*
* @param value
* The <code>Object</code> to convert to a string and store.
*/
protected EntityProperty(final String value, final Class<?> type) {
this.type = type;
this.value = value;
if (type.equals(byte[].class)) {
this.getValueAsByteArray();
this.edmType = EdmType.BINARY;
}
else if (type.equals(Byte[].class)) {
this.getValueAsByteObjectArray();
this.edmType = EdmType.BINARY;
}
else if (type.equals(String.class)) {
this.edmType = EdmType.STRING;
}
else if (type.equals(boolean.class)) {
this.getValueAsBoolean();
this.edmType = EdmType.BOOLEAN;
}
else if (type.equals(Boolean.class)) {
this.getValueAsBooleanObject();
this.edmType = EdmType.BOOLEAN;
}
else if (type.equals(Date.class)) {
this.getValueAsDate();
this.edmType = EdmType.DATE_TIME;
}
else if (type.equals(double.class)) {
this.getValueAsDouble();
this.edmType = EdmType.DOUBLE;
}
else if (type.equals(Double.class)) {
this.getValueAsDoubleObject();
this.edmType = EdmType.DOUBLE;
}
else if (type.equals(UUID.class)) {
this.getValueAsUUID();
this.edmType = EdmType.GUID;
}
else if (type.equals(int.class)) {
this.getValueAsInteger();
this.edmType = EdmType.INT32;
}
else if (type.equals(Integer.class)) {
this.getValueAsIntegerObject();
this.edmType = EdmType.INT32;
}
else if (type.equals(long.class)) {
this.getValueAsLong();
this.edmType = EdmType.INT64;
}
else if (type.equals(Long.class)) {
this.getValueAsLongObject();
this.edmType = EdmType.INT64;
}
else {
throw new IllegalArgumentException(String.format(SR.TYPE_NOT_SUPPORTED, type.toString()));
}
}
/**
* Reserved for internal use. Constructs an {@link EntityProperty} instance from a <code>Object</code> value and a
* data type, and verifies that the value can be interpreted as the specified data type.
*
* @param value
* The <code>Object</code> to convert to a string and store.
* @param edmType
* The <code>Class<?></code> type of the value to construct.
*/
protected EntityProperty(final Object value, final Class<?> type) {
if (type.equals(byte[].class)) {
setValue((byte[]) value);
this.type = type;
}
else if (type.equals(Byte[].class)) {
setValue((Byte[]) value);
this.type = type;
}
else if (type.equals(String.class)) {
setValue((String) value);
this.type = type;
}
else if (type.equals(boolean.class)) {
setValue(((Boolean) value).booleanValue());
this.type = type;
}
else if (type.equals(Boolean.class)) {
setValue((Boolean) value);
this.type = type;
}
else if (type.equals(double.class)) {
setValue(((Double) value).doubleValue());
this.type = type;
}
else if (type.equals(Double.class)) {
setValue((Double) value);
this.type = type;
}
else if (type.equals(UUID.class)) {
setValue((UUID) value);
this.type = type;
}
else if (type.equals(int.class)) {
setValue(((Integer) value).intValue());
this.type = type;
}
else if (type.equals(Integer.class)) {
setValue((Integer) value);
this.type = type;
}
else if (type.equals(long.class)) {
setValue(((Long) value).longValue());
this.type = type;
}
else if (type.equals(Long.class)) {
setValue((Long) value);
this.type = type;
}
else if (type.equals(Date.class)) {
setValue((Date) value);
this.type = type;
}
else {
throw new IllegalArgumentException(String.format(SR.TYPE_NOT_SUPPORTED, type.toString()));
}
}
/**
* Reserved for internal use. Constructs an {@link EntityProperty} instance from a <code>String</code> value and a
* data type, and verifies that the value can be interpreted as the specified data type.
*
* @param value
* The <code>String</code> representation of the value to construct.
* @param edmType
* The {@link EdmType} data type of the value to construct.
*/
protected EntityProperty(final String value, final EdmType edmType) {
this.edmType = edmType;
this.value = value;
// validate data is encoded correctly
if (edmType == EdmType.STRING) {
this.type = String.class;
return;
}
else if (edmType == EdmType.BINARY) {
this.getValueAsByteArray();
this.type = Byte[].class;
}
else if (edmType == EdmType.BOOLEAN) {
this.getValueAsBoolean();
this.type = Boolean.class;
}
else if (edmType == EdmType.DOUBLE) {
this.getValueAsDouble();
this.type = Double.class;
}
else if (edmType == EdmType.GUID) {
this.getValueAsUUID();
this.type = UUID.class;
}
else if (edmType == EdmType.INT32) {
this.getValueAsInteger();
this.type = Integer.class;
}
else if (edmType == EdmType.INT64) {
this.getValueAsLong();
this.type = Long.class;
}
else if (edmType == EdmType.DATE_TIME) {
this.getValueAsDate();
this.type = Date.class;
}
else {
// these are overwritten when this is called from the table parser with a more informative message
if (edmType == null) {
throw new IllegalArgumentException(SR.EDMTYPE_WAS_NULL);
}
throw new IllegalArgumentException(String.format(SR.INVALID_EDMTYPE_VALUE, edmType.toString()));
}
}
/**
* Reserved for internal use. Constructs an {@link EntityProperty} instance as a <code>null</code> value with the
* specified type.
*
* @param type
* The {@link EdmType} to set as the entity property type.
*/
protected EntityProperty(EdmType type) {
this.value = null;
this.edmType = type;
this.isNull = true;
}
/**
* Constructs an {@link EntityProperty} instance from a <code>boolean</code> value.
*
* @param value
* The <code>boolean</code> value of the entity property to set.
*/
public EntityProperty(final boolean value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from a <code>Boolean</code> value.
*
* @param value
* The <code>Boolean</code> value of the entity property to set.
*/
public EntityProperty(final Boolean value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from a <code>byte[]</code> value.
*
* @param value
* The <code>byte[]</code> value of the entity property to set.
*/
public EntityProperty(final byte[] value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from a <code>Byte[]</code>.
*
* @param value
* The <code>Byte[]</code> to set as the entity property value.
*/
public EntityProperty(final Byte[] value) {
this.setValue(value);
this.type = Byte[].class;
}
/**
* Constructs an {@link EntityProperty} instance from a <code>java.util.Date</code> value.
*
* @param value
* The <code>java.util.Date</code> to set as the entity property value.
*/
public EntityProperty(final Date value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from a <code>double</code> value.
*
* @param value
* The <code>double</code> value of the entity property to set.
*/
public EntityProperty(final double value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from a <code>Double</code> value.
*
* @param value
* The <code>Double</code> value of the entity property to set.
*/
public EntityProperty(final Double value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from an <code>int</code> value.
*
* @param value
* The <code>int</code> value of the entity property to set.
*/
public EntityProperty(final int value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from an <code>Integer</code> value.
*
* @param value
* The <code>Integer</code> value of the entity property to set.
*/
public EntityProperty(final Integer value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from a <code>long</code> value.
*
* @param value
* The <code>long</code> value of the entity property to set.
*/
public EntityProperty(final long value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from a <code>Long</code> value.
*
* @param value
* The <code>Long</code> value of the entity property to set.
*/
public EntityProperty(final Long value) {
this.setValue(value);
}
/**
* Constructs an {@link EntityProperty} instance from a <code>String</code> value.
*
* @param value
* The <code>String</code> to set as the entity property value.
*/
public EntityProperty(final String value) {
this.setValue(value);
this.type = String.class;
}
/**
* Constructs an {@link EntityProperty} instance from a <code>java.util.UUID</code> value.
*
* @param value
* The <code>java.util.UUID</code> to set as the entity property value.
*/
public EntityProperty(final UUID value) {
this.setValue(value);
}
/**
* Gets the {@link EdmType} storage data type for the {@link EntityProperty}.
*
* @return
* The {@link EdmType} enumeration value for the data type of the {@link EntityProperty}.
*/
public EdmType getEdmType() {
return this.edmType;
}
/**
* Gets a flag indicating that the {@link EntityProperty} value is <code>null</code>.
*
* @return
* A <code>boolean</code> flag indicating that the {@link EntityProperty} value is <code>null</code>.
*/
public boolean getIsNull() {
return this.isNull;
}
/**
* Gets the class type of the {@link EntityProperty}.
*
* @return
* The <code>Class<?></code> of the {@link EntityProperty}.
*/
public Class<?> getType() {
return this.type;
}
/**
* Gets the value of this {@link EntityProperty} as a <code>boolean</code>.
*
* @return
* A <code>boolean</code> representation of the {@link EntityProperty} value.
*
* @throws IllegalArgumentException
* If the value is <code>null</code> or cannot be parsed as a <code>Boolean</code>.
*/
public boolean getValueAsBoolean() {
if (this.isNull) {
throw new IllegalArgumentException(SR.ENTITY_PROPERTY_CANNOT_BE_NULL_FOR_PRIMITIVES);
}
return Boolean.parseBoolean(this.value);
}
/**
* Gets the value of this {@link EntityProperty} as a <code>Boolean</code>.
*
* @return
* A <code>Boolean</code> representation of the {@link EntityProperty} value.
*
* @throws IllegalArgumentException
* If the value is <code>null</code> or cannot be parsed as a <code>Boolean</code>.
*/
public Boolean getValueAsBooleanObject() {
if (this.isNull) {
return null;
}
return Boolean.parseBoolean(this.value);
}
/**
* Gets the value of this {@link EntityProperty} as a <code>byte</code> array.
*
* @return
* A <code>byte[]</code> representation of the {@link EntityProperty} value, or <code>null</code>.
*/
public byte[] getValueAsByteArray() {
return this.isNull ? null : Base64.decode(this.value);
}
/**
* Gets the value of this {@link EntityProperty} as a <code>Byte</code> array.
*
* @return
* A <code>Byte[]</code> representation of the {@link EntityProperty} value, or <code>null</code>.
*/
public Byte[] getValueAsByteObjectArray() {
return this.isNull ? null : Base64.decodeAsByteObjectArray(this.value);
}
/**
* Gets the value of this {@link EntityProperty} as a <code>java.util.Date</code>.
*
* @return
* A <code>java.util.Date</code> representation of the {@link EntityProperty} value, or <code>null</code>.
*
* @throws IllegalArgumentException
* If the value is not <code>null</code> and cannot be parsed as a <code>java.util.Date</code>.
*/
public Date getValueAsDate() {
if (this.isNull) {
return null;
}
return Utility.parseDate(this.value, this.dateBackwardCompatibility);
}
/**
* Gets the value of this {@link EntityProperty} as a <code>double</code>.
*
* @return
* A <code>double</code> representation of the {@link EntityProperty} value.
*
* @throws IllegalArgumentException
* If the value is <code>null</code> or cannot be parsed as a <code>double</code>.
*/
public double getValueAsDouble() {
if (this.isNull) {
throw new IllegalArgumentException(SR.ENTITY_PROPERTY_CANNOT_BE_NULL_FOR_PRIMITIVES);
}
else if (this.value.equals("Infinity") || this.value.equals("INF")) {
return Double.POSITIVE_INFINITY;
}
else if (this.value.equals("-Infinity") || this.value.equals("-INF")) {
return Double.NEGATIVE_INFINITY;
}
else if (this.value.equals("NaN")) {
return Double.NaN;
}
else {
return Double.parseDouble(this.value);
}
}
/**
* Gets the value of this {@link EntityProperty} as a <code>double</code>.
*
* @return
* A <code>double</code> representation of the {@link EntityProperty} value.
*
* @throws IllegalArgumentException
* If the value is <code>null</code> or cannot be parsed as a <code>double</code>.
*/
public Double getValueAsDoubleObject() {
if (this.isNull) {
return null;
}
else if (this.value.equals("Infinity") || this.value.equals("INF")) {
return Double.POSITIVE_INFINITY;
}
else if (this.value.equals("-Infinity") || this.value.equals("-INF")) {
return Double.NEGATIVE_INFINITY;
}
else if (this.value.equals("NaN")) {
return Double.NaN;
}
else {
return Double.parseDouble(this.value);
}
}
/**
* Gets the value of this {@link EntityProperty} as an <code>int</code>.
*
* @return
* An <code>int</code> representation of the {@link EntityProperty} value.
*
* @throws IllegalArgumentException
* If the value is <code>null</code> or cannot be parsed as an <code>int</code>.
*/
public int getValueAsInteger() {
if (this.isNull) {
throw new IllegalArgumentException(SR.ENTITY_PROPERTY_CANNOT_BE_NULL_FOR_PRIMITIVES);
}
return Integer.parseInt(this.value);
}
/**
* Gets the value of this {@link EntityProperty} as an <code>Integer</code>.
*
* @return
* An <code>Integer</code> representation of the {@link EntityProperty} value.
*
* @throws IllegalArgumentException
* If the value is <code>null</code> or cannot be parsed as an <code>int</code>.
*/
public Integer getValueAsIntegerObject() {
if (this.isNull) {
return null;
}
return Integer.parseInt(this.value);
}
/**
* Gets the value of this {@link EntityProperty} as a <code>long</code>.
*
* @return
* A <code>long</code> representation of the {@link EntityProperty} value.
*
* @throws IllegalArgumentException
* If the value is <code>null</code> or cannot be parsed as a <code>long</code>.
*/
public long getValueAsLong() {
if (this.isNull) {
throw new IllegalArgumentException(SR.ENTITY_PROPERTY_CANNOT_BE_NULL_FOR_PRIMITIVES);
}
return Long.parseLong(this.value);
}
/**
* Gets the value of this {@link EntityProperty} as a <code>Long</code>.
*
* @return
* A <code>long</code> representation of the {@link EntityProperty} value.
*
* @throws IllegalArgumentException
* If the value is <code>null</code> or cannot be parsed as a <code>long</code>.
*/
public Long getValueAsLongObject() {
if (this.isNull) {
return null;
}
return Long.parseLong(this.value);
}
/**
* Gets the value of this {@link EntityProperty} as a <code>String</code>.
*
* @return
* A <code>String</code> representation of the {@link EntityProperty} value, or <code>null</code>.
*/
public String getValueAsString() {
return this.isNull ? null : this.value;
}
/**
* Gets the value of this {@link EntityProperty} as a <code>java.util.UUID</code>.
*
* @return
* A <code>java.util.UUID</code> representation of the {@link EntityProperty} value, or <code>null</code>.
*
* @throws IllegalArgumentException
* If the value cannot be parsed as a <code>java.util.UUID</code>.
*/
public UUID getValueAsUUID() {
return this.isNull ? null : UUID.fromString(this.value);
}
/**
* Sets this {@link EntityProperty} using the serialized <code>boolean</code> value.
*
* @param value
* The <code>boolean</code> value to set as the {@link EntityProperty} value.
*/
public synchronized final void setValue(final boolean value) {
this.edmType = EdmType.BOOLEAN;
this.type = boolean.class;
this.isNull = false;
this.value = value ? Constants.TRUE : Constants.FALSE;
}
/**
* Sets this {@link EntityProperty} using the serialized <code>Boolean</code> value.
*
* @param value
* The <code>Boolean</code> value to set as the {@link EntityProperty} value.
*/
public synchronized final void setValue(final Boolean value) {
this.edmType = EdmType.BOOLEAN;
this.type = Boolean.class;
if (value == null) {
this.value = null;
this.isNull = true;
}
else {
this.isNull = false;
this.value = value ? Constants.TRUE : Constants.FALSE;
}
}
/**
* Sets this {@link EntityProperty} using the serialized <code>byte[]</code> value.
*
* @param value
* The <code>byte[]</code> value to set as the {@link EntityProperty} value. This value may be
* <code>null</code>.
*/
public synchronized final void setValue(final byte[] value) {
this.edmType = EdmType.BINARY;
this.type = byte[].class;
if (value == null) {
this.value = null;
this.isNull = true;
return;
}
else {
this.isNull = false;
}
this.value = Base64.encode(value);
}
/**
* Sets this {@link EntityProperty} using the serialized <code>Byte[]</code> value.
*
* @param value
* The <code>Byte[]</code> value to set as the {@link EntityProperty} value. This value may be
* <code>null</code>.
*/
public synchronized final void setValue(final Byte[] value) {
this.edmType = EdmType.BINARY;
this.type = Byte[].class;
if (value == null) {
this.value = null;
this.isNull = true;
return;
}
else {
this.isNull = false;
}
this.value = Base64.encode(value);
}
/**
* Sets this {@link EntityProperty} using the serialized <code>java.util.Date</code> value.
*
* @param value
* The <code>java.util.Date</code> value to set as the {@link EntityProperty} value. This value may be
* <code>null</code>.
*/
public synchronized final void setValue(final Date value) {
this.edmType = EdmType.DATE_TIME;
this.type = Date.class;
if (value == null) {
this.value = null;
this.isNull = true;
return;
}
else {
this.isNull = false;
}
this.value = Utility.getJavaISO8601Time(value);
}
/**
* Sets this {@link EntityProperty} using the serialized <code>double</code> value.
*
* @param value
* The <code>double</code> value to set as the {@link EntityProperty} value.
*/
public synchronized final void setValue(final double value) {
this.edmType = EdmType.DOUBLE;
this.type = double.class;
this.isNull = false;
this.value = Double.toString(value);
}
/**
* Sets this {@link EntityProperty} using the serialized <code>Double</code> value.
*
* @param value
* The <code>Double</code> value to set as the {@link EntityProperty} value.
*/
public synchronized final void setValue(final Double value) {
this.edmType = EdmType.DOUBLE;
this.type = Double.class;
if (value == null) {
this.value = null;
this.isNull = true;
}
else {
this.isNull = false;
this.value = Double.toString(value);
}
}
/**
* Sets this {@link EntityProperty} using the serialized <code>int</code> value.
*
* @param value
* The <code>int</code> value to set as the {@link EntityProperty} value.
*/
public synchronized final void setValue(final int value) {
this.edmType = EdmType.INT32;
this.type = int.class;
this.isNull = false;
this.value = Integer.toString(value);
}
/**
* Sets this {@link EntityProperty} using the serialized <code>Integer</code> value.
*
* @param value
* The <code>Integer</code> value to set as the {@link EntityProperty} value.
*/
public synchronized final void setValue(final Integer value) {
this.edmType = EdmType.INT32;
this.type = Integer.class;
if (value == null) {
this.value = null;
this.isNull = true;
}
else {
this.isNull = false;
this.value = Integer.toString(value);
}
}
/**
* Sets this {@link EntityProperty} using the serialized <code>long</code> value.
*
* @param value
* The <code>long</code> value to set as the {@link EntityProperty} value.
*/
public synchronized final void setValue(final long value) {
this.edmType = EdmType.INT64;
this.type = long.class;
this.isNull = false;
this.value = Long.toString(value);
}
/**
* Sets this {@link EntityProperty} using the serialized <code>Long</code> value.
*
* @param value
* The <code>Long</code> value to set as the {@link EntityProperty} value.
*/
public synchronized final void setValue(final Long value) {
this.edmType = EdmType.INT64;
this.type = Long.class;
if (value == null) {
this.value = null;
this.isNull = true;
}
else {
this.isNull = false;
this.value = Long.toString(value);
}
}
/**
* Sets this {@link EntityProperty} using the <code>String</code> value.
*
* @param value
* The <code>String</code> value to set as the {@link EntityProperty} value. This value may be
* <code>null</code>.
*/
public synchronized final void setValue(final String value) {
this.edmType = EdmType.STRING;
this.type = String.class;
if (value == null) {
this.value = null;
this.isNull = true;
return;
}
else {
this.isNull = false;
}
this.value = value;
}
/**
* Sets this {@link EntityProperty} using the serialized <code>java.util.UUID</code> value.
*
* @param value
* The <code>java.util.UUID</code> value to set as the {@link EntityProperty} value.
* This value may be <code>null</code>.
*/
public synchronized final void setValue(final UUID value) {
this.edmType = EdmType.GUID;
this.type = UUID.class;
if (value == null) {
this.value = null;
this.isNull = true;
return;
}
else {
this.isNull = false;
}
this.value = value.toString();
}
/**
* Sets whether the client should look to correct Date values stored on a {@link TableEntity}
* that may have been written using versions of this library prior to 2.0.0.
* <p>
* {@link #dateBackwardCompatibility} is by default <code>false</code>, indicating a post 2.0.0 version or
* mixed-platform usage.
* <p>
* See <a href="http://go.microsoft.com/fwlink/?LinkId=523753">here</a> for more details.
*
* @param dateBackwardCompatibility
* <code>true</code> to enable <code>dateBackwardCompatibility</code>; otherwise, <code>false</code>
*/
void setDateBackwardCompatibility(boolean dateBackwardCompatibility) {
this.dateBackwardCompatibility = dateBackwardCompatibility;
}
}
| |
/*
Copyright [2016] [Taqdir Ali]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.uclab.mm.datamodel.sc.dataadapter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.mm.datamodel.DataAccessInterface;
import org.uclab.mm.datamodel.sc.Recommendation;
import org.uclab.mm.datamodel.sc.Situation;
/**
* This is RecommendationAdapter class which implements the Data Access Interface for CRUD operations
* @author Taqdir Ali
*/
public class RecommendationAdapter implements DataAccessInterface {
private Connection objConn;
private static final Logger logger = LoggerFactory.getLogger(RecommendationAdapter.class);
public RecommendationAdapter()
{
}
/**
* This is implementation function for saving Recommendation.
* @param objRecommendation
* @return List of String
*/
@Override
public List<String> Save(Object objRecommendation) {
Recommendation objInnerRecommendation = new Recommendation();
objInnerRecommendation = (Recommendation) objRecommendation;
List<String> objDbResponse = new ArrayList<>();
try
{
CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Add_Recommendation(?, ?, ?, ?, ?, ?, ?, ?, ?)}");
objCallableStatement.setString("RecommendationIdentifier", objInnerRecommendation.getRecommendationIdentifier());
objCallableStatement.setLong("SituationID", objInnerRecommendation.getSituationID());
objCallableStatement.setString("RecommendationDescription", objInnerRecommendation.getRecommendationDescription());
objCallableStatement.setString("ConditionValue", objInnerRecommendation.getConditionValue());
objCallableStatement.setInt("RecommendationTypeID", objInnerRecommendation.getRecommendationTypeID());
objCallableStatement.setInt("RecommendationLevelID", objInnerRecommendation.getRecommendationLevelID());
objCallableStatement.setInt("RecommendationStatusID", objInnerRecommendation.getRecommendationStatusID());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
Date dtDate = sdf.parse(objInnerRecommendation.getRecommendationDate());
Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
objCallableStatement.setTimestamp("RecommendationDate", tsDate);
objCallableStatement.registerOutParameter("RecommendationID", Types.BIGINT);
objCallableStatement.execute();
Long intRecommendationID = objCallableStatement.getLong("RecommendationID");
objDbResponse.add(String.valueOf(intRecommendationID));
objDbResponse.add("No Error");
objConn.close();
logger.info("Recommendation saved successfully, Recommendation Details="+objRecommendation);
}
catch (Exception e)
{
logger.info("Error in adding Recommendation");
objDbResponse.add("Error in adding Recommendation");
}
return objDbResponse;
}
/**
* This is implementation function for updating Recommendation.
* @param objRecommendation
* @return List of String
*/
@Override
public List<String> Update(Object objRecommendation) {
Recommendation objInnerRecommendation = new Recommendation();
objInnerRecommendation = (Recommendation) objRecommendation;
List<String> objDbResponse = new ArrayList<>();
try
{
CallableStatement objCallableStatement = objConn.prepareCall("{call dbo.usp_Update_Recommendation(?, ?, ?, ?, ?, ?, ?, ?, ?)}");
objCallableStatement.setLong("RecommendationID", objInnerRecommendation.getRecommendationID());
objCallableStatement.setString("RecommendationIdentifier", objInnerRecommendation.getRecommendationIdentifier());
objCallableStatement.setLong("SituationID", objInnerRecommendation.getSituationID());
objCallableStatement.setString("RecommendationDescription", objInnerRecommendation.getRecommendationDescription());
objCallableStatement.setString("ConditionValue", objInnerRecommendation.getConditionValue());
objCallableStatement.setInt("RecommendationTypeID", objInnerRecommendation.getRecommendationTypeID());
objCallableStatement.setInt("RecommendationLevelID", objInnerRecommendation.getRecommendationLevelID());
objCallableStatement.setInt("RecommendationStatusID", objInnerRecommendation.getRecommendationStatusID());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
Date dtDate = sdf.parse(objInnerRecommendation.getRecommendationDate());
Timestamp tsDate = new Timestamp(dtDate.getYear(),dtDate.getMonth(), dtDate.getDate(), dtDate.getHours(), dtDate.getMinutes(), dtDate.getSeconds(), 00);
objCallableStatement.setTimestamp("RecommendationDate", tsDate);
objCallableStatement.execute();
Long intRecommendationID = objInnerRecommendation.getRecommendationID();
objDbResponse.add(String.valueOf(intRecommendationID));
objDbResponse.add("No Error");
objConn.close();
logger.info("Recommendation saved successfully, Recommendation Details="+objRecommendation);
}
catch (Exception e)
{
logger.info("Error in updating Recommendation");
objDbResponse.add("Error in updating Recommendation");
}
return objDbResponse;
}
/**
* This is implementation function for retrieving Recommendation.
* @param objRecommendation
* @return List of Recommendation
*/
@Override
public List<Recommendation> RetriveData(Object objRecommendation) {
Recommendation objOuterRecommendation = new Recommendation();
List<Recommendation> objListInnerRecommendation = new ArrayList<Recommendation>();
objOuterRecommendation = (Recommendation) objRecommendation;
try
{
CallableStatement objCallableStatement = null;
if(objOuterRecommendation.getRequestType() == "ByUserOnly")
{
objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationByUser(?)}");
objCallableStatement.setLong("UserID", objOuterRecommendation.getUserID());
}
else if(objOuterRecommendation.getRequestType() == "ByUserandDate")
{
objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationByUserIDDate(?, ?, ?)}");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
Date dtStartDate = sdf.parse(objOuterRecommendation.getStartDate());
Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
Date dtEndDate =sdf.parse( objOuterRecommendation.getEndDate()); //.getTime();
Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
objCallableStatement.setLong("UserID", objOuterRecommendation.getUserID());
objCallableStatement.setTimestamp("StartTime", tsStartDate);
objCallableStatement.setTimestamp("EndTime", tsEndDate);
}
else if(objOuterRecommendation.getRequestType() == "ByActivityIDsAndDate")
{
objCallableStatement = objConn.prepareCall("{call dbo.usp_Get_RecommendationsByDateRangeActivityIDs(?, ?, ?)}");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss"); // month updated to MM from mm
Date dtStartDate = sdf.parse(objOuterRecommendation.getStartDate());
Timestamp tsStartDate = new Timestamp(dtStartDate.getYear(),dtStartDate.getMonth(), dtStartDate.getDate(), dtStartDate.getHours(), dtStartDate.getMinutes(),dtStartDate.getSeconds(),0);
Date dtEndDate =sdf.parse( objOuterRecommendation.getEndDate()); //.getTime();
Timestamp tsEndDate = new Timestamp(dtEndDate.getYear(),dtEndDate.getMonth(), dtEndDate.getDate(), dtEndDate.getHours(), dtEndDate.getMinutes(),dtEndDate.getSeconds(),0);
objCallableStatement.setString("ActivityIDs", objOuterRecommendation.getSituationCategoryIDs());
objCallableStatement.setTimestamp("StartDate", tsStartDate);
objCallableStatement.setTimestamp("EndDate", tsEndDate);
}
ResultSet objResultSet = objCallableStatement.executeQuery();
while(objResultSet.next())
{
Recommendation objInnerRecommendation = new Recommendation();
objInnerRecommendation.setRecommendationID(objResultSet.getLong("RecommendationID"));
objInnerRecommendation.setRecommendationIdentifier(objResultSet.getString("RecommendationIdentifier"));
objInnerRecommendation.setSituationID(objResultSet.getLong("SituationID"));
objInnerRecommendation.setRecommendationDescription(objResultSet.getString("RecommendationDescription"));
objInnerRecommendation.setRecommendationTypeID(objResultSet.getInt("RecommendationTypeID"));
objInnerRecommendation.setConditionValue(objResultSet.getString("ConditionValue"));
objInnerRecommendation.setRecommendationLevelID(objResultSet.getInt("RecommendationLevelID"));
objInnerRecommendation.setRecommendationStatusID(objResultSet.getInt("RecommendationStatusID"));
if(objResultSet.getTimestamp("RecommendationDate") != null)
{
Timestamp tsRecommendationDate = objResultSet.getTimestamp("RecommendationDate");
objInnerRecommendation.setRecommendationDate(tsRecommendationDate.toString());
}
objInnerRecommendation.setRecommendationTypeDescription(objResultSet.getString("RecommendationTypeDescription"));
objInnerRecommendation.setRecommendationLevelDescription(objResultSet.getString("RecommendationLevelDescription"));
objInnerRecommendation.setRecommendationStatusDescription(objResultSet.getString("RecommendationStatusDescription"));
objInnerRecommendation.setSituationCategoryID(objResultSet.getInt("SituationCategoryID"));
objInnerRecommendation.setSituationCategoryDescription(objResultSet.getString("SituationCategoryDescription"));
objListInnerRecommendation.add(objInnerRecommendation);
}
objConn.close();
logger.info("Recommendation loaded successfully");
}
catch (Exception e)
{
logger.info("Error in loading Recommendation");
}
return objListInnerRecommendation;
}
@Override
public <T> List<T> Delete(T objEntity) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* This is implementation function for connection database.
* @param objConf
*/
@Override
public void ConfigureAdapter(Object objConf) {
try
{
objConn = (Connection)objConf;
logger.info("Database connected successfully");
}
catch(Exception ex)
{
logger.info("Error in connection to Database");
}
}
}
| |
/**
*
*/
package uk.ac.lkl.shared;
import java.util.ArrayList;
/**
* Produces a sequence of identifiers, strings, brackets, HTML elements
* skips over NetLogo comments
*
* @author Ken Kahn
*
*/
public class NetLogoTokenizer {
private String code;
private int start = -1;
private int end = -1;
// acts like a stack where the first element is the current things being searched for
// e.g. <foo a="...">
private ArrayList<Character> searchingForStack = new ArrayList<Character>();
private ArrayList<String> elementStack = new ArrayList<String>();
private boolean incrementEndNextCharacter = true;
private static String validIdentifierCharacters = ".?=*!<>:#+/%$_^'&-";
public NetLogoTokenizer(String code) {
// PRE elements do cause line breaks, hence the use of "\n" below
// < and the like get confused for comments without calling removeHTMLTokens
this.code = CommonUtils.removeHTMLTokens(CommonUtils.removeTags("pre", code, "\n", -1));
}
public String peekToken() {
return peekToken(1);
}
public String peekToken(int n) {
int saveStart = start;
int saveEnd = end;
ArrayList<Character> savedSearchingForStack = new ArrayList<Character>(searchingForStack);
ArrayList<String> savedEementStack = new ArrayList<String>(elementStack);
boolean savedIncrementEndNextCharacter = incrementEndNextCharacter;
String nextToken = nextToken();
n--;
while (n > 0) {
nextToken = nextToken();
n--;
}
start = saveStart;
end = saveEnd;
searchingForStack = savedSearchingForStack;
elementStack = savedEementStack;
incrementEndNextCharacter = savedIncrementEndNextCharacter;
return nextToken;
}
public String nextToken() {
return nextToken(false);
}
public String nextToken(boolean includeComments) {
searchingForStack.clear();
if (incrementEndNextCharacter) {
end++;
} else {
incrementEndNextCharacter = true;
}
start = end;
Character previousCharacter = 0;
while (end < code.length()) {
Character character = code.charAt(end);
char searchingFor = getSearchingFor();
if (searchingFor == '>' && character != '>' && peekSearchingFor() != '>') {
// if inside an HTML element ignore everything except closes
end++;
} else if (searchingFor == '\n') {
if (character == '\n' || character == '\r') {
// end of a comment
popSearchingFor();
if (includeComments) {
if (code.charAt(end) == '\r') {
end++;
}
// end++;
// incrementEndNextCharacter = false;
return code.substring(start, end);
} else {
end++;
start = end;
}
} else {
end++;
}
} else if (elementStack.isEmpty() && character == '"' && previousCharacter != '\\') {
if (searchingFor == character) {
popSearchingFor(); // reset it
searchingFor = getSearchingFor();
if (searchingFor == 0) {
return code.substring(start, end+1); // include the closing quote
} else {
end++; // continue searching after popping the search for quotes
}
} else {
end++;
pushSearchingFor('"');
}
} else if (searchingFor == '"') {
if (character == '\n') {
// Strings (words) can't span multiple lines so terminate the string
// unless inside an HTML element
searchingFor = 0;
return code.substring(start, end);
} else {
end++;
}
} else if (character == '<' &&
(start == end || !elementStack.isEmpty()) &&
searchingFor == 0 &&
alphaNextCharacter(start)) {
// HTML element -- not inside an identifier
// if (start != end) {
// // return the token inside the HTML element
// // next time around it'll deal with closing tag.
// end--;
// return code.substring(start, end+1);
// }
pushSearchingFor('>');
end++;
} else if (character == '>' && searchingFor == '>' && possiblePenultimateCloseTagCharacter(previousCharacter)) {
// if previous character is space then not closing an HTML element
popSearchingFor();
searchingFor = getSearchingFor();
if (searchingFor == 0) {
String element = code.substring(start, end+1);
if (!elementStack.isEmpty() && pairedElements(element)) {
elementStack.remove(0);
return element; // include the starting tag and the the closing tag (including >)
} else {
elementStack.add(element);
end++;
}
} else {
end++; // continue searching after popping the search for >
}
} else if (elementStack.isEmpty() && code.substring(end, end+1).matches("\\s")) {
// else if (Character.isWhitespace(character)) {
// Character.isWhitespace not available in GWT due to UNICODE dependence
if (searchingFor != 0) {
end++;
} else if (start == end) {
start++;
end++;
} else {
return code.substring(start, end);
}
} else if (Character.isLetterOrDigit(character) || validIdentifierCharacters.indexOf(character) >= 0) {
end++;
} else if (elementStack.isEmpty() && (character == '[' || character == ']' || character == '(' || character == ')')) {
if (start == end) {
// return the bracket
return code.substring(start, end+1);
} else {
incrementEndNextCharacter = false;
return code.substring(start, end);
}
} else if (character == ';') { // && elementStack.isEmpty()) && searchingFor == 0) {
if (start == end) {
end++;
pushSearchingFor('\n');
} else {
// return before the comment and set up to revisit the ; next time
end--;
return code.substring(start, end+1);
}
} else {
end++;
}
previousCharacter = character;
}
if (start != end) {
if (getSearchingFor() == '\n' && !includeComments) {
return null;
} else {
return code.substring(start, end);
}
} else {
return null;
}
}
private boolean pairedElements(String element) {
// e.g. <textarea ...> ... </textarea>
// TODO: determine if it is worth checking this and if its false what to do
return true;
}
private boolean possiblePenultimateCloseTagCharacter(Character previousCharacter) {
// true if can be before > in a closing tag
return previousCharacter == '\\' || previousCharacter == '\'' || previousCharacter == '\"' || Character.isLetter(previousCharacter);
}
private boolean alphaNextCharacter(int index) {
if (index+1 >= code.length()) {
return false;
} else {
return Character.isLetter(code.charAt(index+1));
}
}
private Character popSearchingFor() {
return searchingForStack.remove(0);
}
private char getSearchingFor() {
if (searchingForStack.isEmpty()) {
return 0;
} else {
return searchingForStack.get(0);
}
}
private char peekSearchingFor() {
if (searchingForStack.size() < 2) {
return 0;
} else {
return searchingForStack.get(1);
}
}
private void pushSearchingFor(char character) {
searchingForStack.add(0, character);
}
public void replaceCurrentToken(String replacement) {
String before = code.substring(0, start);
String after = code.substring(end);
code = before + replacement + after;
end = start+replacement.length(); //-1;
start = end;
}
public String getCode() {
return code;
}
}
| |
package br.com.cybereagle.eagledatetime.internal.gregorian;
import br.com.cybereagle.eagledatetime.AmountOfTime;
import br.com.cybereagle.eagledatetime.TimeUnit;
import br.com.cybereagle.eagledatetime.internal.util.DateTimeUtil;
import java.util.Locale;
import static br.com.cybereagle.eagledatetime.internal.util.DateTimeUtil.checkRange;
public class AmountOfTimeImpl implements AmountOfTime {
private Integer years;
private Integer months;
private Integer days;
private Integer hours;
private Integer minutes;
private Integer seconds;
private Integer nanoseconds;
private TimeUnit upperTimeUnit;
public AmountOfTimeImpl(Integer years, Integer months, Integer days, Integer hours, Integer minutes, Integer seconds, Integer nanoseconds) {
this.years = years;
this.months = months;
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.nanoseconds = nanoseconds;
if(years != null){
upperTimeUnit = TimeUnit.YEAR;
}
else if(months != null){
upperTimeUnit = TimeUnit.MONTH;
}
else if(days != null){
upperTimeUnit = TimeUnit.DAY;
}
else if(hours != null){
upperTimeUnit = TimeUnit.HOUR;
}
else if(minutes != null){
upperTimeUnit = TimeUnit.MINUTE;
}
else if(seconds != null){
upperTimeUnit = TimeUnit.SECOND;
}
else if(nanoseconds != null){
upperTimeUnit = TimeUnit.NANOSECONDS;
}
else {
throw new NullPointerException("All the properties of AmountOfTime are null.");
}
validateState();
}
private void validateState() {
switch (upperTimeUnit){
case YEAR:
checkRange(years, 1, Integer.MAX_VALUE, "Years");
case MONTH:
checkRange(months, 1, 12, "Months");
case DAY:
checkRange(days, 1, 31, "Days");
case HOUR:
checkRange(hours, 0, 23, "Hours");
case MINUTE:
checkRange(minutes, 0, 59, "Minutes");
case SECOND:
checkRange(seconds, 0, 59, "Second");
case NANOSECONDS:
checkRange(nanoseconds, 0, 999999999, "Nanoseconds");
}
}
@Override
public Integer getYears() {
return years;
}
@Override
public Integer getMonths() {
return months;
}
@Override
public Integer getDays() {
return days;
}
@Override
public Integer getHours() {
return hours;
}
@Override
public Integer getMinutes() {
return minutes;
}
@Override
public Integer getSeconds() {
return seconds;
}
@Override
public Integer getNanoseconds() {
return nanoseconds;
}
@Override
public TimeUnit getUpperTimeUnit() {
return upperTimeUnit;
}
/**
* This method is used to convert an amount of time from one upper time unit to another. <br />
* OBS: The conversion of years, months and days is not very accurate, since it considers the following
* conversions:<br />
* 1 year = 365 days<br />
* 1 month = 30 days<br />
* So, be careful when using this method.
* @param upperTimeUnit
* @return
*/
@Override
public AmountOfTime convert(TimeUnit upperTimeUnit) {
Integer years = this.years;
Integer months = this.months;
Integer days = this.days;
Integer hours = this.hours;
Integer minutes = this.minutes;
Integer seconds = this.seconds;
Integer nanoseconds = this.nanoseconds;
TimeUnit currentUpperTimeUnit = this.upperTimeUnit;
while (currentUpperTimeUnit != upperTimeUnit){
boolean upConversion = currentUpperTimeUnit.compareTo(upperTimeUnit) < 0;
switch (currentUpperTimeUnit){
case YEAR:
if(upConversion){
// Shouldn't ever get here
throw new IllegalStateException();
}
else {
months += years * 12;
years = null;
}
break;
case MONTH:
if(upConversion){
years = months / 365;
months = months % 365;
}
else {
days += months * 30;
months = null;
}
break;
case DAY:
if(upConversion){
months = days / 30;
days = days % 30;
}
else {
hours += days * 24;
days = null;
}
break;
case HOUR:
if(upConversion){
days = hours / 24;
hours = hours % 24;
}
else {
minutes += hours * 60;
hours = null;
}
break;
case MINUTE:
if(upConversion){
hours = minutes / 60;
minutes = minutes % 60;
}
else {
seconds += minutes * 60;
minutes = null;
}
break;
case SECOND:
if(upConversion){
minutes = seconds / 60;
seconds = seconds % 60;
}
else {
nanoseconds += seconds * 1000000000;
seconds = null;
}
break;
case NANOSECONDS:
if(upConversion){
seconds = nanoseconds / 1000000000;
nanoseconds = nanoseconds % 1000000000;
}
else {
// Shouldn't ever get here
throw new IllegalStateException();
}
break;
}
}
return null;
}
@Override
public String format(String format) {
return null;
}
@Override
public String format(String format, Locale locale) {
return null;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common.compress;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Exception;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4SafeDecompressor;
import net.jpountz.xxhash.XXHash32;
import net.jpountz.xxhash.XXHashFactory;
import org.apache.kafka.common.compress.KafkaLZ4BlockOutputStream.BD;
import org.apache.kafka.common.compress.KafkaLZ4BlockOutputStream.FLG;
import org.apache.kafka.common.utils.BufferSupplier;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import static org.apache.kafka.common.compress.KafkaLZ4BlockOutputStream.LZ4_FRAME_INCOMPRESSIBLE_MASK;
import static org.apache.kafka.common.compress.KafkaLZ4BlockOutputStream.MAGIC;
/**
* A partial implementation of the v1.5.1 LZ4 Frame format.
*
* @see <a href="https://github.com/lz4/lz4/wiki/lz4_Frame_format.md">LZ4 Frame Format</a>
*
* This class is not thread-safe.
*/
public final class KafkaLZ4BlockInputStream extends InputStream {
public static final String PREMATURE_EOS = "Stream ended prematurely";
public static final String NOT_SUPPORTED = "Stream unsupported (invalid magic bytes)";
public static final String BLOCK_HASH_MISMATCH = "Block checksum mismatch";
public static final String DESCRIPTOR_HASH_MISMATCH = "Stream frame descriptor corrupted";
private static final LZ4SafeDecompressor DECOMPRESSOR = LZ4Factory.fastestInstance().safeDecompressor();
private static final XXHash32 CHECKSUM = XXHashFactory.fastestInstance().hash32();
private static final RuntimeException BROKEN_LZ4_EXCEPTION;
// https://issues.apache.org/jira/browse/KAFKA-9203
// detect buggy lz4 libraries on the classpath
static {
RuntimeException exception = null;
try {
detectBrokenLz4Version();
} catch (RuntimeException e) {
exception = e;
}
BROKEN_LZ4_EXCEPTION = exception;
}
private final ByteBuffer in;
private final boolean ignoreFlagDescriptorChecksum;
private final BufferSupplier bufferSupplier;
private final ByteBuffer decompressionBuffer;
// `flg` and `maxBlockSize` are effectively final, they are initialised in the `readHeader` method that is only
// invoked from the constructor
private FLG flg;
private int maxBlockSize;
// If a block is compressed, this is the same as `decompressionBuffer`. If a block is not compressed, this is
// a slice of `in` to avoid unnecessary copies.
private ByteBuffer decompressedBuffer;
private boolean finished;
/**
* Create a new {@link InputStream} that will decompress data using the LZ4 algorithm.
*
* @param in The byte buffer to decompress
* @param ignoreFlagDescriptorChecksum for compatibility with old kafka clients, ignore incorrect HC byte
* @throws IOException
*/
public KafkaLZ4BlockInputStream(ByteBuffer in, BufferSupplier bufferSupplier, boolean ignoreFlagDescriptorChecksum) throws IOException {
if (BROKEN_LZ4_EXCEPTION != null) {
throw BROKEN_LZ4_EXCEPTION;
}
this.ignoreFlagDescriptorChecksum = ignoreFlagDescriptorChecksum;
this.in = in.duplicate().order(ByteOrder.LITTLE_ENDIAN);
this.bufferSupplier = bufferSupplier;
readHeader();
decompressionBuffer = bufferSupplier.get(maxBlockSize);
finished = false;
}
/**
* Check whether KafkaLZ4BlockInputStream is configured to ignore the
* Frame Descriptor checksum, which is useful for compatibility with
* old client implementations that use incorrect checksum calculations.
*/
public boolean ignoreFlagDescriptorChecksum() {
return this.ignoreFlagDescriptorChecksum;
}
/**
* Reads the magic number and frame descriptor from input buffer.
*
* @throws IOException
*/
private void readHeader() throws IOException {
// read first 6 bytes into buffer to check magic and FLG/BD descriptor flags
if (in.remaining() < 6) {
throw new IOException(PREMATURE_EOS);
}
if (MAGIC != in.getInt()) {
throw new IOException(NOT_SUPPORTED);
}
// mark start of data to checksum
in.mark();
flg = FLG.fromByte(in.get());
maxBlockSize = BD.fromByte(in.get()).getBlockMaximumSize();
if (flg.isContentSizeSet()) {
if (in.remaining() < 8) {
throw new IOException(PREMATURE_EOS);
}
in.position(in.position() + 8);
}
// Final byte of Frame Descriptor is HC checksum
// Old implementations produced incorrect HC checksums
if (ignoreFlagDescriptorChecksum) {
in.position(in.position() + 1);
return;
}
int len = in.position() - in.reset().position();
int hash = CHECKSUM.hash(in, in.position(), len, 0);
in.position(in.position() + len);
if (in.get() != (byte) ((hash >> 8) & 0xFF)) {
throw new IOException(DESCRIPTOR_HASH_MISMATCH);
}
}
/**
* Decompresses (if necessary) buffered data, optionally computes and validates a XXHash32 checksum, and writes the
* result to a buffer.
*
* @throws IOException
*/
private void readBlock() throws IOException {
if (in.remaining() < 4) {
throw new IOException(PREMATURE_EOS);
}
int blockSize = in.getInt();
boolean compressed = (blockSize & LZ4_FRAME_INCOMPRESSIBLE_MASK) == 0;
blockSize &= ~LZ4_FRAME_INCOMPRESSIBLE_MASK;
// Check for EndMark
if (blockSize == 0) {
finished = true;
if (flg.isContentChecksumSet())
in.getInt(); // TODO: verify this content checksum
return;
} else if (blockSize > maxBlockSize) {
throw new IOException(String.format("Block size %s exceeded max: %s", blockSize, maxBlockSize));
}
if (in.remaining() < blockSize) {
throw new IOException(PREMATURE_EOS);
}
if (compressed) {
try {
final int bufferSize = DECOMPRESSOR.decompress(in, in.position(), blockSize, decompressionBuffer, 0,
maxBlockSize);
decompressionBuffer.position(0);
decompressionBuffer.limit(bufferSize);
decompressedBuffer = decompressionBuffer;
} catch (LZ4Exception e) {
throw new IOException(e);
}
} else {
decompressedBuffer = in.slice();
decompressedBuffer.limit(blockSize);
}
// verify checksum
if (flg.isBlockChecksumSet()) {
int hash = CHECKSUM.hash(in, in.position(), blockSize, 0);
in.position(in.position() + blockSize);
if (hash != in.getInt()) {
throw new IOException(BLOCK_HASH_MISMATCH);
}
} else {
in.position(in.position() + blockSize);
}
}
@Override
public int read() throws IOException {
if (finished) {
return -1;
}
if (available() == 0) {
readBlock();
}
if (finished) {
return -1;
}
return decompressedBuffer.get() & 0xFF;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
net.jpountz.util.SafeUtils.checkRange(b, off, len);
if (finished) {
return -1;
}
if (available() == 0) {
readBlock();
}
if (finished) {
return -1;
}
len = Math.min(len, available());
decompressedBuffer.get(b, off, len);
return len;
}
@Override
public long skip(long n) throws IOException {
if (finished) {
return 0;
}
if (available() == 0) {
readBlock();
}
if (finished) {
return 0;
}
int skipped = (int) Math.min(n, available());
decompressedBuffer.position(decompressedBuffer.position() + skipped);
return skipped;
}
@Override
public int available() {
return decompressedBuffer == null ? 0 : decompressedBuffer.remaining();
}
@Override
public void close() {
bufferSupplier.release(decompressionBuffer);
}
@Override
public void mark(int readlimit) {
throw new RuntimeException("mark not supported");
}
@Override
public void reset() {
throw new RuntimeException("reset not supported");
}
@Override
public boolean markSupported() {
return false;
}
/**
* Checks whether the version of lz4 on the classpath has the fix for reading from ByteBuffers with
* non-zero array offsets (see https://github.com/lz4/lz4-java/pull/65)
*/
static void detectBrokenLz4Version() {
byte[] source = new byte[]{1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3};
final LZ4Compressor compressor = LZ4Factory.fastestInstance().fastCompressor();
final byte[] compressed = new byte[compressor.maxCompressedLength(source.length)];
final int compressedLength = compressor.compress(source, 0, source.length, compressed, 0,
compressed.length);
// allocate an array-backed ByteBuffer with non-zero array-offset containing the compressed data
// a buggy decompressor will read the data from the beginning of the underlying array instead of
// the beginning of the ByteBuffer, failing to decompress the invalid data.
final byte[] zeroes = {0, 0, 0, 0, 0};
ByteBuffer nonZeroOffsetBuffer = ByteBuffer
.allocate(zeroes.length + compressed.length) // allocates the backing array with extra space to offset the data
.put(zeroes) // prepend invalid bytes (zeros) before the compressed data in the array
.slice() // create a new ByteBuffer sharing the underlying array, offset to start on the compressed data
.put(compressed); // write the compressed data at the beginning of this new buffer
ByteBuffer dest = ByteBuffer.allocate(source.length);
try {
DECOMPRESSOR.decompress(nonZeroOffsetBuffer, 0, compressedLength, dest, 0, source.length);
} catch (Exception e) {
throw new RuntimeException("Kafka has detected detected a buggy lz4-java library (< 1.4.x) on the classpath."
+ " If you are using Kafka client libraries, make sure your application does not"
+ " accidentally override the version provided by Kafka or include multiple versions"
+ " of the library on the classpath. The lz4-java version on the classpath should"
+ " match the version the Kafka client libraries depend on. Adding -verbose:class"
+ " to your JVM arguments may help understand which lz4-java version is getting loaded.", e);
}
}
}
| |
/*
* Copyright 2014-2016 Media for Mobile
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.m4m.domain.dsl;
import org.m4m.Uri;
import org.m4m.domain.Frame;
import org.m4m.domain.IMediaExtractor;
import org.m4m.domain.MediaFormat;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.FileDescriptor;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
public class MediaExtractorFather {
private final Father create;
private List<MediaFormat> tracks = new LinkedList<MediaFormat>();
public void withFilePath(String filePath) {
when(mediaExtractor.getFilePath()).thenReturn(filePath);
}
public void withFileDescriptor(FileDescriptor fileDescriptor) {
when(mediaExtractor.getFileDescriptor()).thenReturn(fileDescriptor);
}
public void withUri(Uri uri) {
when(mediaExtractor.getUri()).thenReturn(uri);
}
public void withInfinite(Frame frame) {
withFrame(frame);
advanceAnswer.turnInfiniteModeOn();
}
private class MyAnswer<T> implements Answer {
private Queue<T> dataQueue = new LinkedList<T>();
public void add(T value) {
dataQueue.add(value);
}
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
if (!dataQueue.isEmpty()) {
return peek();
} else {
return -1;
}
}
public boolean isEmpty() {
return dataQueue.isEmpty();
}
public void poll() {
dataQueue.poll();
}
public T peek() {
return dataQueue.peek();
}
}
private class AdvanceAnswer implements Answer {
private MyAnswer<Long> ptsAnswer;
private MyAnswer<Integer> flagsAnswer;
private MyAnswer<Integer> trackIdAnswer;
private ReadSampleDataAnswer readSampleDataAnswer;
private boolean isInfiniteMode = false;
public AdvanceAnswer(MyAnswer<Long> ptsAnswer, MyAnswer<Integer> flagsAnswer, MyAnswer<Integer> trackIdAnswer, ReadSampleDataAnswer readSampleDataAnswer) {
this.ptsAnswer = ptsAnswer;
this.flagsAnswer = flagsAnswer;
this.trackIdAnswer = trackIdAnswer;
this.readSampleDataAnswer = readSampleDataAnswer;
}
public void turnInfiniteModeOn() {
isInfiniteMode = true;
}
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
if (isInfiniteMode) return null;
if (!ptsAnswer.isEmpty()) {
ptsAnswer.poll();
flagsAnswer.poll();
trackIdAnswer.poll();
readSampleDataAnswer.poll();
}
return null;
}
}
private class ReadSampleDataAnswer implements Answer {
private Queue<ByteBuffer> dataQueue = new LinkedList<ByteBuffer>();
private Queue<Integer> lenQueue = new LinkedList<Integer>();
public void add(ByteBuffer b) {
dataQueue.add(b);
}
public void add(int len) {
lenQueue.add(len);
}
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 0 && arguments[0] != null) {
ByteBuffer buffer = (ByteBuffer) arguments[0];
buffer.clear();
ByteBuffer myBuffer = dataQueue.peek();
if (myBuffer != null && myBuffer.capacity() > 0) {
myBuffer.rewind();
buffer.rewind();
buffer.put(myBuffer);
buffer.rewind();
myBuffer.rewind();
}
}
Integer length = lenQueue.peek();
return length != null ? length : -1;
}
public void poll() {
dataQueue.poll();
lenQueue.poll();
}
}
private class SeekAnswer implements Answer {
private MyAnswer<Long> ptsAnswer;
private MyAnswer<Integer> flagsAnswer;
private MyAnswer<Integer> trackIdAnswer;
private ReadSampleDataAnswer readSampleDataAnswer;
public SeekAnswer(MyAnswer<Long> ptsAnswer, MyAnswer<Integer> flagsAnswer, MyAnswer<Integer> trackIdAnswer, ReadSampleDataAnswer readSampleDataAnswer) {
this.ptsAnswer = ptsAnswer;
this.flagsAnswer = flagsAnswer;
this.trackIdAnswer = trackIdAnswer;
this.readSampleDataAnswer = readSampleDataAnswer;
}
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
Long seekPosition = (Long) arguments[0];
while (ptsAnswer.peek() != null && ptsAnswer.peek() < seekPosition) {
ptsAnswer.poll();
flagsAnswer.poll();
trackIdAnswer.poll();
readSampleDataAnswer.poll();
}
return null;
}
}
MyAnswer<Long> ptsAnswer = new MyAnswer<Long>();
MyAnswer<Integer> flagsAnswer = new MyAnswer<Integer>();
MyAnswer<Integer> trackIdAnswer = new MyAnswer<Integer>();
ReadSampleDataAnswer readSampleDataAnswer = new ReadSampleDataAnswer();
AdvanceAnswer advanceAnswer = new AdvanceAnswer(ptsAnswer, flagsAnswer, trackIdAnswer, readSampleDataAnswer);
SeekAnswer seekAnswer = new SeekAnswer(ptsAnswer, flagsAnswer, trackIdAnswer, readSampleDataAnswer);
private final IMediaExtractor mediaExtractor;
public MediaExtractorFather(Father create) {
this.create = create;
mediaExtractor = mock(IMediaExtractor.class);
doAnswer(readSampleDataAnswer).when(mediaExtractor).readSampleData(any(ByteBuffer.class));
doAnswer(ptsAnswer).when(mediaExtractor).getSampleTime();
doAnswer(flagsAnswer).when(mediaExtractor).getSampleFlags();
doAnswer(trackIdAnswer).when(mediaExtractor).getSampleTrackIndex();
doAnswer(advanceAnswer).when(mediaExtractor).advance();
doAnswer(seekAnswer).when(mediaExtractor).seekTo(anyLong(), anyInt());
}
public MediaExtractorFather withSampleData(final ByteBuffer buffer, final int length) {
readSampleDataAnswer.add(buffer);
readSampleDataAnswer.add(length);
return this;
}
public MediaExtractorFather withTimeStamp(long pts) {
ptsAnswer.add(pts);
return this;
}
public MediaExtractorFather withFrame(final Frame frame) {
readSampleDataAnswer.add(frame.getByteBuffer());
readSampleDataAnswer.add(frame.getLength());
withTimeStamp(frame.getSampleTime());
withFlag(frame.getFlags());
withTrackId(frame.getTrackId());
return this;
}
private MediaExtractorFather withFlag(int flags) {
flagsAnswer.add(flags);
return this;
}
private MediaExtractorFather withTrackId(int trackId) {
trackIdAnswer.add(trackId);
return this;
}
public MediaExtractorFather withTrack(MediaFormat format) {
tracks.add(format);
return this;
}
public IMediaExtractor construct() {
if (tracks.size() == 0) {
withTrack(create.videoFormat().construct());
}
when(mediaExtractor.getTrackCount()).thenReturn(tracks.size());
for (int i = 0; i < tracks.size(); i++) {
when(mediaExtractor.getTrackFormat(i)).thenReturn(tracks.get(i));
}
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
if ((Integer)args[0] > tracks.size() - 1) {
throw new IllegalStateException("");
}
return null;
}}).
when(mediaExtractor).selectTrack(anyInt());
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
if ((Integer)args[0] > tracks.size() - 1) {
throw new IllegalStateException("");
}
return null;
}}).
when(mediaExtractor).unselectTrack(anyInt());
return mediaExtractor;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.jdbc;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Drill-specific {@link ResultSet}.
* @see #unwrap
*/
public interface DrillResultSet extends ResultSet {
/**
* Gets the ID of the associated query (the query whose results this ResultSet
* presents).
*
* @throws SQLException if this method is called on a closed result set
*/
String getQueryId() throws SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* Accepts {@code DrillResultSet.class}.
* </p>
*/
@Override
<T> T unwrap(Class<T> iface) throws SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* Returns true for {@code DrillResultSet.class}.
* </p>
*/
@Override
boolean isWrapperFor(Class<?> iface) throws SQLException;
// Note: The commented-out methods are left in to make it easier to match
// the method order from ResultSet when adding method declarations at this
// level (e.g., to document Drill-specific behavior for more) in the future
// (so the resulting documentation page matches the order in
// java.sql.ResultSet's page).
// (Temporary, re matching ResultSet's method order:
// next()
// close()
// wasNull()
// )
/**
* {@inheritDoc}
* <p>
* <strong>Drill: Conversions</strong>: Supports conversion from all types.
* </p>
*/
@Override
String getString(int columnIndex) throws SQLException;
// (Temporary, re matching ResultSet's method order:)
// getBoolean(int)
// )
/**
* {@inheritDoc}
* <p>
* <strong>Drill: Conversions</strong>: Supports conversion from types:
* </p>
* <ul>
* <li>{@code SMALLINT} ({@code short}),
* {@code INTEGER} ({@code int}), and
* {@code BIGINT} ({@code long})
* </li>
* <li>{@code REAL} ({@code float}),
* {@code DOUBLE PRECISION} ({@code double}), and
* {@code FLOAT} ({@code float} or {@code double})
* </li>
* <li>{@code DECIMAL} ({@code BigDecimal})
* </li>
* </ul>
* <p>
* Conversion throws {@link SQLConversionOverflowException} for a source
* value whose magnitude is outside the range of {@code byte} values.
* </p>
* @throws SQLConversionOverflowException if a source value was too large
* to convert to {@code byte}
*/
@Override
byte getByte(int columnIndex) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill: Conversions</strong>: Supports conversion from types:
* </p>
* <ul>
* <li>{@code TINYINT} ({@code byte}),
* {@code INTEGER} ({@code int}), and
* {@code BIGINT} ({@code long})
* </li>
* <li>{@code REAL} ({@code float}),
* {@code DOUBLE PRECISION} ({@code double}), and
* {@code FLOAT} ({@code float} or {@code double})
* </li>
* <li>{@code DECIMAL} ({@code BigDecimal})
* </li>
* </ul>
* <p>
* Conversion throws {@link SQLConversionOverflowException} for a source
* value whose magnitude is outside the range of {@code short} values.
* </p>
* @throws SQLConversionOverflowException if a source value was too large
* to convert to {@code short}
*/
@Override
short getShort(int columnIndex) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill: Conversions</strong>: Supports conversion from types:
* </p>
* <ul>
* <li>{@code TINYINT} ({@code byte}),
* {@code SMALLINT} ({@code short}), and
* {@code BIGINT} ({@code long})
* </li>
* <li>{@code REAL} ({@code float}),
* {@code DOUBLE PRECISION} ({@code double}), and
* {@code FLOAT} ({@code float} or {@code double})
* </li>
* <li>{@code DECIMAL} ({@code BigDecimal})
* </li>
* </ul>
* <p>
* Conversion throws {@link SQLConversionOverflowException} for a source
* value whose magnitude is outside the range of {@code int} values.
* </p>
* @throws SQLConversionOverflowException if a source value was too large
* to convert to {@code int}
*/
@Override
int getInt(int columnIndex) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill: Conversions</strong>: Supports conversion from types:
* </p>
* <ul>
* <li>{@code TINYINT} ({@code byte}),
* {@code SMALLINT} ({@code short}), and
* {@code INTEGER} ({@code int})
* </li>
* <li>{@code REAL} ({@code float}),
* {@code DOUBLE PRECISION} ({@code double}), and
* {@code FLOAT} ({@code float} or {@code double})
* </li>
* <li>{@code DECIMAL} ({@code BigDecimal})
* </li>
* </ul>
* <p>
* Conversion throws {@link SQLConversionOverflowException} for a source
* value whose magnitude is outside the range of {@code long} values.
* </p>
* @throws SQLConversionOverflowException if a source value was too large
* to convert to {@code long}
*/
@Override
long getLong(int columnIndex) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill: Conversions</strong>: Supports conversion from types:
* </p>
* <ul>
* <li>{@code TINYINT} ({@code byte}),
* {@code SMALLINT} ({@code short}), and
* {@code INTEGER} ({@code int}),
* {@code BIGINT} ({@code long})
* </li>
* <li>{@code DOUBLE PRECISION} ({@code double}) and
* {@code FLOAT} (when {@code double})
* </li>
* <li>{@code DECIMAL} ({@code BigDecimal})
* </li>
* </ul>
* <p>
* Conversion throws {@link SQLConversionOverflowException} for a source
* value whose magnitude is outside the range of {@code float} values.
* </p>
* @throws SQLConversionOverflowException if a source value was too large
* to convert to {@code float}
*/
@Override
float getFloat(int columnIndex) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill: Conversions</strong>: Supports conversion from types:
* </p>
* <ul>
* <li>{@code TINYINT} ({@code byte}),
* {@code SMALLINT} ({@code short}),
* {@code INTEGER} ({@code int}), and
* {@code BIGINT} ({@code long})
* </li>
* <li>{@code REAL} ({@code float}),
* {@code FLOAT} (when {@code float})
* </li>
* <li>{@code DECIMAL} ({@code BigDecimal})
* </li>
* </ul>
* <p>
* Conversion throws {@link SQLConversionOverflowException} for a source
* value whose magnitude is outside the range of {@code double} values.
* </p>
* @throws SQLConversionOverflowException if a source value was too large
* to convert to {@code double}
*/
@Override
double getDouble(int columnIndex) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill: Conversions</strong>: Supports conversion from types:
* </p>
* <ul>
* <li>{@code TINYINT} ({@code byte}),
* {@code SMALLINT} ({@code short}),
* {@code INTEGER} ({@code int}), and
* {@code BIGINT} ({@code long})
* </li>
* <li>{@code REAL} ({@code float}),
* {@code DOUBLE PRECISION} ({@code double}), and
* {@code FLOAT} ({@code float} or {@code double})
* </li>
* </ul>
*/
@Override
BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException;
// (Temporary, re matching ResultSet's method order:)
// getBytes(int)
// getDate(int)
// getTime(int)
// getTimestamp(int)
// getAsciiStream(int)
// getUnicodeStream(int)
// getBinaryStream(int)
// )
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* For conversions, see {@link DrillResultSet#getString(int)}.
* </p>
*/
@Override
String getString(String columnLabel) throws SQLException;
// (Temporary, re matching ResultSet's method order:)
// getBoolean(String)
// )
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* For conversions, see {@link DrillResultSet#getByte(int)}.
* </p>
*/
@Override
byte getByte(String columnLabel) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* For conversions, see {@link DrillResultSet#getShort(int)}.
* </p>
*/
@Override
short getShort(String columnLabel) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* For conversions, see {@link DrillResultSet#getInt(int)}.
* </p>
*/
@Override
int getInt(String columnLabel) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* For conversions, see {@link DrillResultSet#getLong(int)}.
* </p>
*/
@Override
long getLong(String columnLabel) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* For conversions, see {@link DrillResultSet#getFloat(int)}.
* </p>
*/
@Override
float getFloat(String columnLabel) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* For conversions, see {@link DrillResultSet#getDouble(int)}.
* </p>
*/
@Override
double getDouble(String columnLabel) throws SQLConversionOverflowException,
SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* For conversions, see {@link DrillResultSet#getBigDecimal(int)}.
* </p>
*/
@Override
BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException;
// (Temporary, re matching ResultSet's method order:)
// getBytes(String)
// getDate(String)
// getTime(String)
// getTimestamp(String)
// getAsciiStream(String)
// getUnicodeStream(String)
// getBinaryStream(String)
// getWarnings()
// clearWarnings()
// getCursorName()
// getMetaData()
// )
/**
* {@inheritDoc}
* <p>
* <strong>Drill: Conversions</strong>: Supports conversion from all types.
* </p>
*/
@Override
Object getObject(int columnIndex) throws SQLException;
/**
* {@inheritDoc}
* <p>
* <strong>Drill</strong>:
* For conversions, see {@link DrillResultSet#getObject(int)}.
* </p>
*/
@Override
Object getObject(String columnLabel) throws SQLException;
// (Temporary, re matching ResultSet's method order:)
// findColumn(String)
// getCharacterStream(int)
// getCharacterStream(String)
// getBigDecimal(int)
// getBigDecimal(String)
// isBeforeFirst()
// isAfterLast()
// isFirst()
// isLast()
// beforeFirst()
// afterLast()
// first()
// last()
// getRow()
// absolute(int)
// relative(int)
// previous()
// setFetchDirection(int)
// getFetchDirection()
// setFetchSize(int)
// getFetchSize()
// getType()
// getConcurrency()
// rowUpdated()
// rowInserted()
// rowDeleted()
// updateNull(int)
// updateBoolean(int, boolean)
// updateByte(int, byte)
// updateShort(int, short)
// updateInt(int, int)
// updateLong(int, long)
// updateFloat(int, float)
// updateDouble(int, double)
// updateBigDecimal(int, BigDecimal)
// updateString(int, String)
// updateBytes(int, byte[])
// updateDate(int, Date)
// updateTime(int, Time)
// updateTimestamp(int, Timestamp)
// updateAsciiStream(int, InputStream, int)
// updateBinaryStream(int, InputStream, int)
// updateCharacterStream(int, Reader, int)
// updateObject(int, Object, int)
// updateObject(int, Object)
// updateNull(String)
// updateBoolean(String, boolean)
// updateByte(String, byte)
// updateShort(String, short)
// updateInt(String, int)
// updateLong(String, long)
// updateFloat(String, float)
// updateDouble(String, double)
// updateBigDecimal(String, BigDecimal)
// updateString(String, String)
// updateBytes(String, byte[])
// updateDate(String, Date)
// updateTime(String, Time)
// updateTimestamp(String, Timestamp)
// updateAsciiStream(String, InputStream, int)
// updateBinaryStream(String, InputStream, int)
// updateCharacterStream(String, Reader, int)
// updateObject(String, Object, int)
// updateObject(String, Object)
// insertRow()
// updateRow()
// deleteRow()
// refreshRow()
// cancelRowUpdates()
// moveToInsertRow()
// moveToCurrentRow()
// getStatement()
// getObject(int, Map<String, Class<?>>)
// getRef(int)
// getBlob(int)
// getClob(int)
// getArray(int)
// getObject(String, Map<String, Class<?>>)
// getRef(String)
// getBlob(String)
// getClob(String)
// getArray(String)
// getDate(int, Calendar)
// getDate(String, Calendar)
// getTime(int, Calendar)
// getTime(String, Calendar)
// getTimestamp(int, Calendar)
// getTimestamp(String, Calendar)
// getURL(int)
// getURL(String)
// updateRef(int, Ref)
// updateRef(String, Ref)
// updateBlob(int, Blob)
// updateBlob(String, Blob)
// updateClob(int, Clob)
// updateClob(String, Clob)
// updateArray(int, Array)
// updateArray(String, Array)
// getRowId(int)
// getRowId(String)
// updateRowId(int, RowId)
// updateRowId(String, RowId)
// getHoldability()
// isClosed()
// updateNString(int, String)
// updateNString(String, String)
// updateNClob(int, NClob)
// updateNClob(String, NClob)
// getNClob(int)
// getNClob(String)
// getSQLXML(int)
// getSQLXML(String)
// updateSQLXML(int, SQLXML)
// updateSQLXML(String, SQLXML)
// getNString(int)
// getNString(String)
// getNCharacterStream(int)
// getNCharacterStream(String)
// updateNCharacterStream(int, Reader, long)
// updateNCharacterStream(String, Reader, long)
// updateAsciiStream(int, InputStream, long)
// updateBinaryStream(int, InputStream, long)
// updateCharacterStream(int, Reader, long)
// updateAsciiStream(String, InputStream, long)
// updateBinaryStream(String, InputStream, long)
// updateCharacterStream(String, Reader, long)
// updateBlob(int, InputStream, long)
// updateBlob(String, InputStream, long)
// updateClob(int, Reader, long)
// updateClob(String, Reader, long)
// updateNClob(int, Reader, long)
// updateNClob(String, Reader, long)
// updateNCharacterStream(int, Reader)
// updateNCharacterStream(String, Reader)
// updateAsciiStream(int, InputStream)
// updateBinaryStream(int, InputStream)
// updateCharacterStream(int, Reader)
// updateAsciiStream(String, InputStream)
// updateBinaryStream(String, InputStream)
// updateCharacterStream(String, Reader)
// updateBlob(int, InputStream)
// updateBlob(String, InputStream)
// updateClob(int, Reader)
// updateClob(String, Reader)
// updateNClob(int, Reader)
// updateNClob(String, Reader)
// getObject(int, Class<T>)
// getObject(String, Class<T>)
// )
}
| |
package com.jivesoftware.os.miru.stream.plugins.filter;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jivesoftware.os.filer.io.api.StackBuffer;
import com.jivesoftware.os.miru.api.MiruPartitionCoord;
import com.jivesoftware.os.miru.api.activity.schema.MiruFieldDefinition;
import com.jivesoftware.os.miru.api.activity.schema.MiruFieldDefinition.Feature;
import com.jivesoftware.os.miru.api.activity.schema.MiruSchema;
import com.jivesoftware.os.miru.api.base.MiruStreamId;
import com.jivesoftware.os.miru.api.base.MiruTermId;
import com.jivesoftware.os.miru.api.field.MiruFieldType;
import com.jivesoftware.os.miru.api.query.filter.MiruFilter;
import com.jivesoftware.os.miru.api.query.filter.MiruValue;
import com.jivesoftware.os.miru.plugin.bitmap.MiruBitmaps;
import com.jivesoftware.os.miru.plugin.bitmap.MiruBitmapsDebug;
import com.jivesoftware.os.miru.plugin.context.MiruRequestContext;
import com.jivesoftware.os.miru.plugin.index.BitmapAndLastId;
import com.jivesoftware.os.miru.plugin.index.MiruFieldIndex;
import com.jivesoftware.os.miru.plugin.index.MiruTermComposer;
import com.jivesoftware.os.miru.plugin.index.TimeVersionRealtime;
import com.jivesoftware.os.miru.plugin.solution.MiruAggregateUtil;
import com.jivesoftware.os.miru.plugin.solution.MiruRequest;
import com.jivesoftware.os.miru.plugin.solution.MiruSolutionLog;
import com.jivesoftware.os.miru.plugin.solution.MiruTimeRange;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkState;
/**
*
*/
public class AggregateCounts {
private static final MetricLogger LOG = MetricLoggerFactory.getLogger();
private final MiruAggregateUtil aggregateUtil = new MiruAggregateUtil();
private final MiruBitmapsDebug bitmapsDebug = new MiruBitmapsDebug();
public <BM extends IBM, IBM> AggregateCountsAnswer getAggregateCounts(String name,
MiruSolutionLog solutionLog,
MiruBitmaps<BM, IBM> bitmaps,
MiruRequestContext<BM, IBM, ?> requestContext,
MiruRequest<AggregateCountsQuery> request,
MiruPartitionCoord coord,
Optional<AggregateCountsReport> lastReport,
BM answer,
Optional<BM> counter,
boolean verbose)
throws Exception {
LOG.debug("Get aggregate counts for answer={} request={}", answer, request);
Map<String, AggregateCountsAnswerConstraint> results = Maps.newHashMapWithExpectedSize(request.query.constraints.size());
for (Map.Entry<String, AggregateCountsQueryConstraint> entry : request.query.constraints.entrySet()) {
Optional<AggregateCountsReportConstraint> lastReportConstraint = Optional.absent();
if (lastReport.isPresent()) {
lastReportConstraint = Optional.of(lastReport.get().constraints.get(entry.getKey()));
}
results.put(entry.getKey(),
answerConstraint(name,
solutionLog,
bitmaps,
requestContext,
coord,
request.query.streamId,
request.query.collectTimeRange,
request.query.includeUnreadState,
entry.getValue(),
lastReportConstraint,
answer,
counter,
verbose));
}
boolean resultsExhausted = request.query.answerTimeRange.smallestTimestamp > requestContext.getTimeIndex().getLargestTimestamp();
AggregateCountsAnswer result = new AggregateCountsAnswer(results, resultsExhausted);
LOG.debug("result={}", result);
return result;
}
private <BM extends IBM, IBM> AggregateCountsAnswerConstraint answerConstraint(String name,
MiruSolutionLog solutionLog,
MiruBitmaps<BM, IBM> bitmaps,
MiruRequestContext<BM, IBM, ?> requestContext,
MiruPartitionCoord coord,
MiruStreamId streamId,
MiruTimeRange collectTimeRange,
boolean includeUnreadState,
AggregateCountsQueryConstraint constraint,
Optional<AggregateCountsReportConstraint> lastReport,
BM answer,
Optional<BM> counter,
boolean verbose) throws Exception {
StackBuffer stackBuffer = new StackBuffer();
MiruSchema schema = requestContext.getSchema();
int fieldId = schema.getFieldId(constraint.aggregateCountAroundField);
MiruFieldDefinition fieldDefinition = schema.getFieldDefinition(fieldId);
Preconditions.checkArgument(fieldDefinition.type.hasFeature(Feature.stored), "You can only aggregate stored fields");
MiruFieldDefinition[] gatherFieldDefinitions;
if (constraint.gatherTermsForFields != null && constraint.gatherTermsForFields.length > 0) {
gatherFieldDefinitions = new MiruFieldDefinition[constraint.gatherTermsForFields.length];
for (int i = 0; i < gatherFieldDefinitions.length; i++) {
gatherFieldDefinitions[i] = schema.getFieldDefinition(schema.getFieldId(constraint.gatherTermsForFields[i]));
Preconditions.checkArgument(gatherFieldDefinitions[i].type.hasFeature(Feature.stored),
"You can only gather stored fields");
}
} else {
gatherFieldDefinitions = new MiruFieldDefinition[0];
}
// don't mutate the original
answer = bitmaps.copy(answer);
int collectedDistincts = 0;
int skippedDistincts = 0;
Set<MiruValue> aggregated;
Set<MiruValue> uncollected;
if (lastReport.isPresent()) {
collectedDistincts = lastReport.get().collectedDistincts;
skippedDistincts = lastReport.get().skippedDistincts;
aggregated = Sets.newHashSet(lastReport.get().aggregateTerms);
uncollected = Sets.newHashSet(lastReport.get().uncollectedTerms);
if (verbose) {
LOG.info("Aggregate counts report coord:{} streamId:{} aggregated:{} uncollected:{}", coord, streamId, aggregated, uncollected);
}
} else {
aggregated = Sets.newHashSet();
uncollected = Sets.newHashSet();
if (verbose) {
LOG.info("Aggregate counts no report coord:{} streamId:{}", coord, streamId);
}
}
if (!MiruFilter.NO_FILTER.equals(constraint.constraintsFilter)) {
int lastId = requestContext.getActivityIndex().lastId(stackBuffer);
BM filtered = aggregateUtil.filter(name, bitmaps, requestContext, constraint.constraintsFilter, solutionLog, null, lastId, -1, -1, stackBuffer);
bitmaps.inPlaceAnd(answer, filtered);
if (counter.isPresent()) {
bitmaps.inPlaceAnd(counter.get(), filtered);
}
}
MiruTermComposer termComposer = requestContext.getTermComposer();
//MiruActivityInternExtern activityInternExtern = miruProvider.getActivityInternExtern(coord.tenantId);
MiruFieldIndex<BM, IBM> fieldIndex = requestContext.getFieldIndexProvider().getFieldIndex(MiruFieldType.primary);
LOG.debug("fieldId={}", fieldId);
List<AggregateCount> aggregateCounts = new ArrayList<>();
BitmapAndLastId<BM> container = new BitmapAndLastId<>();
if (fieldId >= 0) {
IBM unreadAnswer = null;
if (includeUnreadState && !MiruStreamId.NULL.equals(streamId)) {
container.clear();
requestContext.getUnreadTrackingIndex().getUnread(streamId).getIndex(container, stackBuffer);
if (container.isSet()) {
unreadAnswer = bitmaps.and(Arrays.asList(container.getBitmap(), answer));
}
}
long beforeCount = counter.isPresent() ? bitmaps.cardinality(counter.get()) : bitmaps.cardinality(answer);
for (MiruValue aggregateTerm : aggregated) {
MiruTermId aggregateTermId = termComposer.compose(schema, fieldDefinition, stackBuffer, aggregateTerm.parts);
container.clear();
fieldIndex.get(name, fieldId, aggregateTermId).getIndex(container, stackBuffer);
if (!container.isSet()) {
continue;
}
IBM termIndex = container.getBitmap();
// docs: aaabbaccaaabbbcbbcbaac
// unread: 0000000000000000000000
// query: 1111111111111111111111
// read a: 0001101100011111111001
// docs: abcabc
// query: 0001101100011111111001111111
// read b: 0000001100000010010001101101
// a? 000 0 000 00 1 1 any=1, oldest=0, latest=1
// b? 00 000 00 0 0 0 any=0, oldest=0, latest=0
// c? 11 1 1 1 1 1 any=1, oldest=1, latest=1
int firstIntersectingBit = bitmaps.firstIntersectingBit(answer, termIndex);
boolean anyUnread = false;
boolean oldestUnread = false;
if (firstIntersectingBit != -1 && unreadAnswer != null) {
anyUnread = bitmaps.intersects(unreadAnswer, termIndex);
oldestUnread = bitmaps.isSet(unreadAnswer, firstIntersectingBit);
}
bitmaps.inPlaceAndNot(answer, termIndex);
long afterCount;
if (counter.isPresent()) {
bitmaps.inPlaceAndNot(counter.get(), termIndex);
afterCount = bitmaps.cardinality(counter.get());
} else {
afterCount = bitmaps.cardinality(answer);
}
TimeVersionRealtime oldestTVR;
MiruValue[][] oldestValues;
if (firstIntersectingBit != -1) {
oldestTVR = requestContext.getActivityIndex().getTimeVersionRealtime(name, firstIntersectingBit, stackBuffer);
//TODO much more efficient to accumulate bits and gather these once at the end
oldestValues = new MiruValue[gatherFieldDefinitions.length][];
for (int i = 0; i < gatherFieldDefinitions.length; i++) {
MiruFieldDefinition gatherFieldDefinition = gatherFieldDefinitions[i];
MiruTermId[] termIds = requestContext.getActivityIndex().get(name, firstIntersectingBit, gatherFieldDefinition, stackBuffer);
oldestValues[i] = termsToValues(stackBuffer, schema, termComposer, gatherFieldDefinition, termIds);
}
//TODO much more efficient to accumulate bits and gather these once at the end
} else {
oldestTVR = null;
oldestValues = null;
}
aggregateCounts.add(new AggregateCount(aggregateTerm,
null,
oldestValues,
beforeCount - afterCount,
-1L,
oldestTVR == null ? -1 : oldestTVR.timestamp,
anyUnread,
false,
oldestUnread));
beforeCount = afterCount;
}
for (MiruValue uncollectedTerm : uncollected) {
MiruTermId uncollectedTermId = termComposer.compose(schema, fieldDefinition, stackBuffer, uncollectedTerm.parts);
container.clear();
fieldIndex.get(name, fieldId, uncollectedTermId).getIndex(container, stackBuffer);
if (!container.isSet()) {
continue;
}
IBM termIndex = container.getBitmap();
bitmaps.inPlaceAndNot(answer, termIndex);
if (counter.isPresent()) {
bitmaps.inPlaceAndNot(counter.get(), termIndex);
}
}
while (true) {
int lastSetBit = bitmaps.lastSetBit(answer);
LOG.trace("lastSetBit={}", lastSetBit);
if (lastSetBit < 0) {
break;
}
MiruTermId[] fieldValues = requestContext.getActivityIndex().get(name, lastSetBit, fieldDefinition, stackBuffer);
if (LOG.isTraceEnabled()) {
LOG.trace("fieldValues={}", Arrays.toString(fieldValues));
}
if (fieldValues == null || fieldValues.length == 0) {
BM removeUnknownField = bitmaps.createWithBits(lastSetBit);
bitmaps.inPlaceAndNot(answer, removeUnknownField);
beforeCount--;
} else {
MiruTermId aggregateTermId = fieldValues[0]; // Kinda lame but for now we don't see a need for multi field aggregation.
MiruValue aggregateValue = new MiruValue(termComposer.decompose(schema, fieldDefinition, stackBuffer, aggregateTermId));
container.clear();
fieldIndex.get(name, fieldId, aggregateTermId).getIndex(container, stackBuffer);
checkState(container.isSet(), "Unable to load inverted index for aggregateTermId: %s", aggregateTermId);
IBM termIndex = container.getBitmap();
int firstIntersectingBit = bitmaps.firstIntersectingBit(answer, termIndex);
TimeVersionRealtime latestTVR, oldestTVR;
if (lastSetBit == firstIntersectingBit) {
latestTVR = requestContext.getActivityIndex().getTimeVersionRealtime(name, lastSetBit, stackBuffer);
oldestTVR = latestTVR;
} else {
TimeVersionRealtime[] tvr = requestContext.getActivityIndex().getAllTimeVersionRealtime(name,
new int[] { lastSetBit, firstIntersectingBit },
stackBuffer);
latestTVR = tvr[0];
oldestTVR = tvr[1];
}
boolean collected = contains(collectTimeRange, latestTVR.monoTimestamp);
if (collected) {
aggregated.add(aggregateValue);
collectedDistincts++;
if (verbose) {
LOG.info("Aggregate counts aggregated coord:{} streamId:{} value:{} timestamp:{} collect:{}",
coord, streamId, aggregateValue, latestTVR.monoTimestamp, collectTimeRange);
}
} else {
uncollected.add(aggregateValue);
skippedDistincts++;
if (verbose) {
LOG.info("Aggregate counts uncollected coord:{} streamId:{} value:{} timestamp:{} collect:{}",
coord, streamId, aggregateValue, latestTVR.monoTimestamp, collectTimeRange);
}
}
boolean anyUnread = false;
boolean latestUnread = false;
boolean oldestUnread = false;
if (collected && collectedDistincts > constraint.startFromDistinctN && unreadAnswer != null) {
anyUnread = bitmaps.intersects(unreadAnswer, termIndex);
latestUnread = lastSetBit != -1 && bitmaps.isSet(unreadAnswer, lastSetBit);
oldestUnread = firstIntersectingBit != -1 && bitmaps.isSet(unreadAnswer, firstIntersectingBit);
}
bitmaps.inPlaceAndNot(answer, termIndex);
long afterCount;
if (counter.isPresent()) {
bitmaps.inPlaceAndNot(counter.get(), termIndex);
afterCount = bitmaps.cardinality(counter.get());
} else {
afterCount = bitmaps.cardinality(answer);
}
if (collected && collectedDistincts > constraint.startFromDistinctN) {
//TODO much more efficient to accumulate bits and gather these once at the end
MiruValue[][] latestValues = new MiruValue[gatherFieldDefinitions.length][];
MiruValue[][] oldestValues = new MiruValue[gatherFieldDefinitions.length][];
for (int i = 0; i < gatherFieldDefinitions.length; i++) {
MiruFieldDefinition gatherFieldDefinition = gatherFieldDefinitions[i];
if (lastSetBit == firstIntersectingBit) {
MiruTermId[] termIds = requestContext.getActivityIndex().get(name, lastSetBit, gatherFieldDefinition, stackBuffer);
MiruValue[] values = termsToValues(stackBuffer, schema, termComposer, gatherFieldDefinition, termIds);
latestValues[i] = values;
oldestValues[i] = values;
} else {
MiruTermId[][] termIds = requestContext.getActivityIndex().getAll(name,
new int[] { lastSetBit, firstIntersectingBit },
gatherFieldDefinition,
stackBuffer);
latestValues[i] = termsToValues(stackBuffer, schema, termComposer, gatherFieldDefinition, termIds[0]);
oldestValues[i] = termsToValues(stackBuffer, schema, termComposer, gatherFieldDefinition, termIds[1]);
}
}
//TODO much more efficient to accumulate bits and gather these once at the end
AggregateCount aggregateCount = new AggregateCount(
aggregateValue,
latestValues,
oldestValues,
beforeCount - afterCount,
latestTVR.timestamp,
oldestTVR.timestamp,
anyUnread,
latestUnread,
oldestUnread);
aggregateCounts.add(aggregateCount);
if (aggregateCounts.size() >= constraint.desiredNumberOfDistincts) {
break;
}
}
beforeCount = afterCount;
}
}
}
return new AggregateCountsAnswerConstraint(aggregateCounts, aggregated, uncollected, skippedDistincts, collectedDistincts);
}
private MiruValue[] termsToValues(StackBuffer stackBuffer,
MiruSchema schema,
MiruTermComposer termComposer,
MiruFieldDefinition gatherFieldDefinition,
MiruTermId[] termIds) throws IOException {
MiruValue[] values = new MiruValue[termIds.length];
for (int j = 0; j < values.length; j++) {
values[j] = new MiruValue(termComposer.decompose(schema,
gatherFieldDefinition,
stackBuffer,
termIds[j]));
}
return values;
}
private static boolean contains(MiruTimeRange timeRange, long timestamp) {
return timeRange.smallestTimestamp <= timestamp && timeRange.largestTimestamp >= timestamp;
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ipc.invalidation.ticl.android2;
import com.google.ipc.invalidation.external.client.SystemResources;
import com.google.ipc.invalidation.external.client.SystemResources.Logger;
import com.google.ipc.invalidation.external.client.SystemResources.Scheduler;
import com.google.ipc.invalidation.ticl.RecurringTask;
import com.google.ipc.invalidation.ticl.proto.AndroidService.AndroidSchedulerEvent;
import com.google.ipc.invalidation.util.NamedRunnable;
import com.google.ipc.invalidation.util.Preconditions;
import com.google.ipc.invalidation.util.TypedUtil;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import java.util.HashMap;
import java.util.Map;
/**
* Scheduler for controlling access to internal Ticl state in Android.
* <p>
* This class maintains a map from recurring task names to the recurring task instances in the
* associated Ticl. To schedule a recurring task, it uses the {@link AlarmManager} to schedule
* an intent to itself at the appropriate time in the future. This intent contains the name of
* the task to run; when it is received, this class looks up the appropriate recurring task
* instance and runs it.
* <p>
* Note that this class only supports scheduling recurring tasks, not ordinary runnables. In
* order for it to be used, the application must declare the AlarmReceiver of the scheduler
* in the application's manifest file; see the implementation comment in AlarmReceiver for
* details.
*
*/
public final class AndroidInternalScheduler implements Scheduler {
/** Class that receives AlarmManager broadcasts and reissues them as intents for this service. */
public static final class AlarmReceiver extends BroadcastReceiver {
/*
* This class needs to be public so that it can be instantiated by the Android runtime.
* Additionally, it should be declared as a broadcast receiver in the application manifest:
* <receiver android:name="com.google.ipc.invalidation.ticl.android2.\
* AndroidInternalScheduler$AlarmReceiver" android:enabled="true"/>
*/
@Override
public void onReceive(Context context, Intent intent) {
// Resend the intent to the service so that it's processed on the handler thread and with
// the automatic shutdown logic provided by IntentService.
intent.setClassName(context, new AndroidTiclManifest(context).getTiclServiceClass());
context.startService(intent);
}
}
/**
* If {@code true}, {@link #isRunningOnThread} will verify that calls are being made from either
* the {@link TiclService} or the {@link TestableTiclService.TestableClient}.
*/
public static boolean checkStackForTest = false;
/** Class name of the testable client class, for checking call stacks in tests. */
private static final String TESTABLE_CLIENT_CLASSNAME_FOR_TEST =
"com.google.ipc.invalidation.ticl.android2.TestableTiclService$TestableClient";
/**
* {@link RecurringTask}-created runnables that can be executed by this instance, by their names.
*/
private final Map<String, Runnable> registeredTasks = new HashMap<String, Runnable>();
/** Android system context. */
private final Context context;
/** Source of time for computing scheduling delays. */
private final AndroidClock clock;
private Logger logger;
/** Id of the Ticl for which this scheduler will process events. */
private long ticlId = -1;
AndroidInternalScheduler(Context context, AndroidClock clock) {
this.context = Preconditions.checkNotNull(context);
this.clock = Preconditions.checkNotNull(clock);
}
@Override
public void setSystemResources(SystemResources resources) {
this.logger = Preconditions.checkNotNull(resources.getLogger());
}
@Override
public void schedule(int delayMs, Runnable runnable) {
if (!(runnable instanceof NamedRunnable)) {
throw new RuntimeException("Unsupported: can only schedule named runnables, not " + runnable);
}
// Create an intent that will cause the service to run the right recurring task. We explicitly
// target it to our AlarmReceiver so that no other process in the system can receive it and so
// that our AlarmReceiver will not be able to receive events from any other broadcaster (which
// it would be if we used action-based targeting).
String taskName = ((NamedRunnable) runnable).getName();
Intent eventIntent = ProtocolIntents.newSchedulerIntent(taskName, ticlId);
eventIntent.setClass(context, AlarmReceiver.class);
// Create a pending intent that will cause the AlarmManager to fire the above intent.
PendingIntent sender = PendingIntent.getBroadcast(context,
(int) (Integer.MAX_VALUE * Math.random()), eventIntent, PendingIntent.FLAG_ONE_SHOT);
// Schedule the pending intent after the appropriate delay.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
long executeMs = clock.nowMs() + delayMs;
try {
alarmManager.set(AlarmManager.RTC, executeMs, sender);
} catch (SecurityException exception) {
logger.warning("Unable to schedule delayed registration: %s", exception);
}
}
/**
* Handles an event intent created in {@link #schedule} by running the corresponding recurring
* task.
* <p>
* REQUIRES: a recurring task with the name in the intent be present in {@link #registeredTasks}.
*/
void handleSchedulerEvent(AndroidSchedulerEvent event) {
Runnable recurringTaskRunnable = TypedUtil.mapGet(registeredTasks, event.getEventName());
if (recurringTaskRunnable == null) {
throw new NullPointerException("No task registered for " + event.getEventName());
}
if (ticlId != event.getTiclId()) {
logger.warning("Ignoring event with wrong ticl id (not %s): %s", ticlId, event);
return;
}
recurringTaskRunnable.run();
}
/**
* Registers {@code task} so that it can be subsequently run by the scheduler.
* <p>
* REQUIRES: no recurring task with the same name be already present in {@link #registeredTasks}.
*/
void registerTask(String name, Runnable runnable) {
Runnable previous = registeredTasks.put(name, runnable);
if (previous != null) {
String message = new StringBuilder()
.append("Cannot overwrite task registered on ")
.append(name)
.append(", ")
.append(this)
.append("; tasks = ")
.append(registeredTasks.keySet())
.toString();
throw new IllegalStateException(message);
}
}
@Override
public boolean isRunningOnThread() {
if (!checkStackForTest) {
return true;
}
// If requested, check that the current stack looks legitimate.
for (StackTraceElement stackElement : Thread.currentThread().getStackTrace()) {
if (stackElement.getMethodName().equals("onHandleIntent") &&
stackElement.getClassName().contains("TiclService")) {
// Called from the TiclService.
return true;
}
if (stackElement.getClassName().equals(TESTABLE_CLIENT_CLASSNAME_FOR_TEST)) {
// Called from the TestableClient.
return true;
}
}
return false;
}
@Override
public long getCurrentTimeMs() {
return clock.nowMs();
}
/** Removes the registered tasks. */
void reset() {
logger.fine("Clearing registered tasks on %s", this);
registeredTasks.clear();
}
/**
* Sets the id of the ticl for which this scheduler will process events. We do not know the
* Ticl id until done constructing the Ticl, and we need the scheduler to construct a Ticl. This
* method breaks what would otherwise be a dependency cycle on getting the Ticl id.
*/
void setTiclId(long ticlId) {
this.ticlId = ticlId;
}
}
| |
/*
* $Id$
*
* Copyright 2006, The jCoderZ.org Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the jCoderZ.org Project nor the names of
* its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jcoderz.phoenix.sqlparser;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.types.FileSet;
/**
* Ant task for the SQL Transformer.
*
* @author Michael Griffel
*/
public class SqlTransformerTask
extends MatchingTask
{
/** list of input files. */
private final List mFilesets = new ArrayList();
/** the output directory. */
private File mOutputDir;
/** terminate ant build on error. */
private boolean mFailOnError = false;
/** force output of target files even if they already exist. */
private boolean mForce = false;
/** the metaInf file (optional). */
private File mMetaInfFile = null;
/**
* Specifies the output directory.
* @param d the output directory.
*/
public void setTodir (File d)
{
mOutputDir = d;
}
/**
* Set whether we should fail on an error.
*
* @param b Whether we should fail on an error.
*/
public void setFailonerror (boolean b)
{
mFailOnError = b;
}
/**
* Sets the force output of target files flag to the given value.
*
* @param b Whether we should force the generation of output files.
*/
public void setForce (boolean b)
{
mForce = b;
}
/**
* Specifies the MetaInf file (optional parameter).
* @param f the MetaInf file.
*/
public void setMetainf (File f)
{
mMetaInfFile = f;
}
/**
* Adds the given files to the file set.
* @param set the file set to add.
*/
public void addFileset (FileSet set)
{
mFilesets.add(set);
}
/**
*
* Execute this task.
*
* @throws BuildException An building exception occurred.
*/
public void execute ()
throws BuildException
{
try
{
checkAttributes();
final File[] files = getSuiteFiles();
int transformedFiles = 0;
for (int i = 0; i < files.length; i++)
{
final File inFile = files[i];
final File outFile = new File(mOutputDir, inFile.getName());
if (mForce || inFile.lastModified() > outFile.lastModified())
{
log("Transforming file: " + inFile, Project.MSG_INFO);
final SqlTransformer transformer
= new SqlTransformer(
inFile.getAbsolutePath(),
outFile.getAbsolutePath(),
mMetaInfFile != null
? mMetaInfFile.getAbsolutePath() : null, false);
transformer.execute();
transformedFiles++;
}
else
{
log(inFile + " omitted as "
+ outFile + " is up to date.", Project.MSG_VERBOSE);
}
}
if (transformedFiles > 0)
{
log(transformedFiles + " of " + files.length
+ " files transformed successfully", Project.MSG_INFO);
}
}
catch (BuildException e)
{
if (mFailOnError)
{
throw e;
}
log(e.getMessage(), Project.MSG_ERR);
}
}
private void checkAttributes ()
{
if (mOutputDir == null)
{
throw new BuildException(
"Missing mandatory attribute 'todir'.", getLocation());
}
ensureDirectoryFor(mOutputDir);
if (mMetaInfFile != null && !mMetaInfFile.exists())
{
throw new BuildException(
"Cannot find META-INF file '" + mMetaInfFile + "'.",
getLocation());
}
}
/**
* Ensure the directory exists for a given directory name.
*
* @param targetFile the directory name that is required.
* @exception BuildException if the directories cannot be created.
*/
private static void ensureDirectoryFor (File directory)
throws BuildException
{
if (!directory.exists())
{
if (!directory.mkdirs())
{
throw new BuildException("Unable to create directory: "
+ directory.getAbsolutePath());
}
}
}
private File[] getSuiteFiles ()
{
final Set set = new HashSet();
final Iterator iterator = mFilesets.iterator();
while (iterator.hasNext())
{
final FileSet fs = (FileSet) iterator.next();
final DirectoryScanner ds = fs.getDirectoryScanner(getProject());
final File dir = fs.getDir(getProject());
final String[] filenames = ds.getIncludedFiles();
for (int i = 0; i < filenames.length; i++)
{
set.add(new File(dir, filenames[i]));
}
}
final int size = set.size();
log("Found " + size + " files in " + mFilesets.size() + " filesets",
Project.MSG_VERBOSE);
return (File[]) set.toArray(new File[size]);
}
}
| |
package org.apache.lucene.index.collocations;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import km.lucene.constants.FieldName;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.index.*;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.PriorityQueue;
import java.io.IOException;
import java.util.*;
/**
* See:
* http://issues.apache.org/jira/browse/LUCENE-474
*
* @author iprovalov (some clean up, refactoring, unit tests, ant/maven, etc...)
*
* Class used to find collocated terms in an index created with TermVector support
*
* @author MAHarwood
*/
public class CollocationExtractor {
static int DEFAULT_MAX_NUM_DOCS_TO_ANALYZE = 1200;
static int maxNumDocsToAnalyze = DEFAULT_MAX_NUM_DOCS_TO_ANALYZE;
String fieldName = FieldName.CONTENT;
static float DEFAULT_MIN_TERM_POPULARITY = 0.0002f;
float minTermPopularity = DEFAULT_MIN_TERM_POPULARITY;
static float DEFAULT_MAX_TERM_POPULARITY = 1f;
float maxTermPopularity = DEFAULT_MAX_TERM_POPULARITY;
int numCollocatedTermsPerTerm = 20;
IndexReader reader;
int slopSize = 5;
TermFilter filter = new TermFilter();
public CollocationExtractor(IndexReader reader) {
this.reader = reader;
}
public void extract(CollocationIndexer logger) throws IOException {
// TermEnum te = reader.terms(new Term(fieldName, ""));
// http://stackoverflow.com/questions/19208523/how-to-get-all-terms-in-index-directory-created-by-lucene-4-4-0
Terms terms = MultiFields.getTerms(this.reader, this.fieldName);
TermsEnum te = terms.iterator(null);
BytesRef bytesRef = null;
while (te.next()!=null) { // iterate item A
bytesRef = te.term();
if(!StringUtils.isAlpha(bytesRef.utf8ToString())){
continue;
}
// only process non-numbers
/*
if (!fieldName.equals(bytesRef.field())) {
break;
}
*/
processTerm(bytesRef, logger, slopSize);
}
}
/**
* Called for every term in the index
* docsAndPositions, possible speed up by http://lucene.apache.org/core/4_2_0/core/org/apache/lucene/index/TermsEnum.html
* http://stackoverflow.com/questions/15771843/get-word-position-in-document-with-lucene
* Migration Guide: http://lucene.apache.org/core/4_8_1/MIGRATE.html
* http://stackoverflow.com/questions/15370652/retrieving-all-term-positions-from-docsandpositionsenum
* @param bytesRef
* @param logger
* @param slop
* @throws IOException
*/
void processTerm(BytesRef bytesRef, CollocationIndexer logger, int slop) throws IOException {
Term term = new Term(this.fieldName, bytesRef);
if (!filter.processTerm(term.text())) {
return;
}
System.out.println("Processing term: "+term);
// TermEnum te = reader.terms(term);
// int numDocsForTerm = Math.min(te.docFreq(), maxNumDocsToAnalyze);
int numDocsForTerm = Math.min(this.reader.docFreq(term), maxNumDocsToAnalyze);
int totalNumDocs = reader.numDocs();
float percent = (float) numDocsForTerm / (float) totalNumDocs;
isTermTooPopularOrNotPopularEnough(term, percent);
// get a list of all the docs with this term
// Apache Lucene Migration Guide
// TermDocs td = reader.termDocs(term);
// get dpe in first hand
DocsAndPositionsEnum dpe = MultiFields.getTermPositionsEnum(this.reader, null, this.fieldName, bytesRef);
HashMap<String, CollocationScorer> phraseTerms = new HashMap<String, CollocationScorer>();
int MAX_TERMS_PER_DOC = 100000;
BitSet termPos = new BitSet(MAX_TERMS_PER_DOC);
int numDocsAnalyzed = 0;
// for all docs that contain this term
int docSeq;
while ((docSeq = dpe.nextDoc())!=DocsEnum.NO_MORE_DOCS) {
int docId = dpe.docID();
// System.out.println("Processing docId: "+docId);
numDocsAnalyzed++;
if (numDocsAnalyzed > maxNumDocsToAnalyze) {
break;
}
// get TermPositions for matching doc
// TermPositionVector tpv = (TermPositionVector) reader.getTermFreqVector(docId, fieldName);
// String[] terms_str = tpv.getTerms();
Terms tv = this.reader.getTermVector(docId, this.fieldName);
TermsEnum te = tv.iterator(null);
// TODO refactor iteration
List<String> terms_list = new ArrayList<>();
while(te.next()!=null) {
terms_list.add(te.term().utf8ToString());
}
String[] terms_str = terms_list.toArray(new String[terms_list.size()]);
// System.out.println("terms_str: "+Arrays.toString(terms_str));
termPos.clear();
int index = recordAllPositionsOfTheTermInCurrentDocumentBitset(docSeq, term, termPos, tv, terms_str);
// now look at all OTHER terms_str in this doc and see if they are
// positioned in a pre-defined sized window around the current term
/*
for (int j = 0; j < terms_str.length; j++) {
if (j == index) { // (item A)
continue;
}
if (!filter.processTerm(terms_str[j])) {
continue;
}
if (!StringUtils.isAlpha(terms_str[j])) {
continue;
}
// sequential code
boolean matchFound = false;
for (int k = 0; ((k < dpe.freq()) && (!matchFound)); k++) {
try {
// inefficient
// iterate through all other items (item B)
Integer position = dpe.nextPosition();
Integer startpos = Math.max(0, position - slop);
Integer endpos = position + slop;
matchFound = populateHashMapWithPhraseTerms(term,
numDocsForTerm, totalNumDocs, phraseTerms, termPos,
terms_str, j, matchFound, startpos, endpos);
}
catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
break;
}
catch (IOException e) {
e.printStackTrace();
break;
}
}
}
*/
///
boolean[] matchFound = new boolean[terms_str.length]; // single match is sufficient, no duplicate process
for(int j=0; j < matchFound.length; j++)
matchFound[j] = false;
for (int k = 0; (k < dpe.freq()); k++) {
Integer position = dpe.nextPosition();
Integer startpos = Math.max(0, position - slop);
Integer endpos = position + slop;
for (int j = 0; j < terms_str.length && !matchFound[j]; j++) {
if (j == index) { // (item A)
continue;
}
if (!filter.processTerm(terms_str[j])) {
continue;
}
if (!StringUtils.isAlpha(terms_str[j])) {
continue;
}
// inefficient
// iterate through all other items (item B)
populateHashMapWithPhraseTerms(
term,
numDocsForTerm,
totalNumDocs,
phraseTerms,
termPos,
terms_str, j,
matchFound,
startpos,
endpos);
}
}
}// end docs loop
sortTopTermsAndAddToCollocationsIndexForThisTerm(logger, phraseTerms);
}
private void populateHashMapWithPhraseTerms(Term term,
int numDocsForTerm,
int totalNumDocs,
HashMap<String, CollocationScorer> phraseTerms,
BitSet termPos,
String[] terms,
int j,
boolean[] matchFound,
int startpos,
int endpos
) throws IOException {
for (int prevpos = startpos; (prevpos <= endpos) && (!matchFound[j]); prevpos++) {
if (termPos.get(prevpos)) {
// Add term to hashmap containing co-occurrence
// counts for this term
CollocationScorer pt = (CollocationScorer) phraseTerms.get(terms[j]);
if (pt == null) {
// TermEnum otherTe = reader.terms(new Term(fieldName, terms[j]));
Term otherTe = new Term(this.fieldName, terms[j]);
int numDocsForOtherTerm = Math.min(this.reader.docFreq(otherTe), maxNumDocsToAnalyze);
float otherPercent = (float) numDocsForOtherTerm / (float) totalNumDocs;
// check other term is not too rare or frequent
if (otherPercent < minTermPopularity) {
System.out.println(term.text() + " not popular enough " + otherPercent);
matchFound[j] = true;
continue;
}
if (otherPercent > maxTermPopularity) {
System.out.println(term.text() + " too popular " + otherPercent);
matchFound[j] = true;
continue;
}
// public CollocationScorer(String term, String coincidentalTerm, int termADocFreq, int termBDocFreq)
pt = new CollocationScorer(term.text(), terms[j], numDocsForTerm, numDocsForOtherTerm, 0, 0);
phraseTerms.put(pt.coincidentalTerm, pt);
}
pt.incCoIncidenceDocCount();
matchFound[j] = true;
}
}
}
private int recordAllPositionsOfTheTermInCurrentDocumentBitset(int docSeq, Term term, BitSet termPos, Terms tv, String[] terms) throws IOException {
// first record all of the positions of the term in a bitset which represents terms in the current doc.
int index = Arrays.binarySearch(terms, term.text());
if (index >= 0) { // found
// Bits liveDocs = MultiFields.getLiveDocs(this.reader);
// int[] pos = tpv.getTermPositions(index);
DocsAndPositionsEnum dpe = MultiFields.getTermPositionsEnum(this.reader, null, this.fieldName, new BytesRef(terms[index]));
dpe.advance(docSeq);
// remember all positions of the term in this doc
for (int j = 0; j < dpe.freq(); j++) {
termPos.set(dpe.nextPosition());
}
}
return index;
}
private void sortTopTermsAndAddToCollocationsIndexForThisTerm(
CollocationIndexer collocationIndexer, HashMap<String, CollocationScorer> phraseTerms) throws IOException {
TopTerms topTerms = new TopTerms(numCollocatedTermsPerTerm);
for (CollocationScorer pt: phraseTerms.values()) {
topTerms.insertWithOverflow(pt);
}
CollocationScorer[] tops = new CollocationScorer[topTerms.size()];
int tp = tops.length - 1;
while (topTerms.size() > 0) {
CollocationScorer top = (CollocationScorer) topTerms.pop();
tops[tp--] = top;
}
for (int j = 0; j < tops.length; j++) {
collocationIndexer.indexCollocation(tops[j]);
}
}
private void isTermTooPopularOrNotPopularEnough(Term term, float percent) {
// check term is not too rare or frequent
if (percent < minTermPopularity) {
System.out.println(term.text() + " not popular enough " + percent);
return;
}
if (percent > maxTermPopularity) {
System.out.println(term.text() + " too popular " + percent);
return;
}
}
static class TopTerms extends PriorityQueue<Object> {
public TopTerms(int size) {
super(size);
}
protected boolean lessThan(Object a, Object b) {
CollocationScorer pta = (CollocationScorer) a;
CollocationScorer ptb = (CollocationScorer) b;
return pta.getScore() < ptb.getScore();
}
}
public static int getMaxNumDocsToAnalyze() {
return maxNumDocsToAnalyze;
}
public static void setMaxNumDocsToAnalyze(int maxNumDocsToAnalyze) {
CollocationExtractor.maxNumDocsToAnalyze = maxNumDocsToAnalyze;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public float getMaxTermPopularity() {
return maxTermPopularity;
}
public void setMaxTermPopularity(float maxTermPopularity) {
this.maxTermPopularity = maxTermPopularity;
}
public float getMinTermPopularity() {
return minTermPopularity;
}
public void setMinTermPopularity(float minTermPopularity) {
this.minTermPopularity = minTermPopularity;
}
public int getNumCollocatedTermsPerTerm() {
return numCollocatedTermsPerTerm;
}
public void setNumCollocatedTermsPerTerm(int numCollocatedTermsPerTerm) {
this.numCollocatedTermsPerTerm = numCollocatedTermsPerTerm;
}
public int getSlopSize() {
return slopSize;
}
public void setSlopSize(int slopSize) {
this.slopSize = slopSize;
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.servicemanagement.model;
/**
* `Service` is the root object of Google service configuration schema. It describes basic
* information about a service, such as the name and the title, and delegates other aspects to sub-
* sections. Each sub-section is either a proto message or a repeated proto message that configures
* a specific aspect, such as auth. See each proto message definition for details.
*
* Example:
*
* type: google.api.Service config_version: 3 name: calendar.googleapis.com title:
* Google Calendar API apis: - name: google.calendar.v3.Calendar authentication:
* providers: - id: google_calendar_auth jwks_uri:
* https://www.googleapis.com/oauth2/v1/certs issuer: https://securetoken.google.com
* rules: - selector: "*" requirements: provider_id: google_calendar_auth
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Service Management API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Service extends com.google.api.client.json.GenericJson {
/**
* A list of API interfaces exported by this service. Only the `name` field of the
* google.protobuf.Api needs to be provided by the configuration author, as the remaining fields
* will be derived from the IDL during the normalization process. It is an error to specify an API
* interface here which cannot be resolved against the associated IDL files.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Api> apis;
static {
// hack to force ProGuard to consider Api used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(Api.class);
}
/**
* Auth configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Authentication authentication;
/**
* API backend configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Backend backend;
/**
* Billing configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Billing billing;
/**
* The semantic version of the service configuration. The config version affects the
* interpretation of the service configuration. For example, certain features are enabled by
* default for certain config versions. The latest config version is `3`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Long configVersion;
/**
* Context configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Context context;
/**
* Configuration for the service control plane.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Control control;
/**
* Custom error configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomError customError;
/**
* Additional API documentation.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Documentation documentation;
/**
* Configuration for network endpoints. If this is empty, then an endpoint with the same name as
* the service is automatically generated to service all defined APIs.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Endpoint> endpoints;
static {
// hack to force ProGuard to consider Endpoint used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(Endpoint.class);
}
/**
* A list of all enum types included in this API service. Enums referenced directly or indirectly
* by the `apis` are automatically included. Enums which are not referenced but shall be included
* should be listed here by name. Example:
*
* enums: - name: google.someapi.v1.SomeEnum
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<ServiceManagementEnum> enums;
static {
// hack to force ProGuard to consider ServiceManagementEnum used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(ServiceManagementEnum.class);
}
/**
* HTTP configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Http http;
/**
* A unique ID for a specific instance of this message, typically assigned by the client for
* tracking purpose. Must be no longer than 63 characters and only lower case letters, digits,
* '.', '_' and '-' are allowed. If empty, the server may choose to generate one instead.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Logging configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Logging logging;
/**
* Defines the logs used by this service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<LogDescriptor> logs;
static {
// hack to force ProGuard to consider LogDescriptor used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(LogDescriptor.class);
}
/**
* Defines the metrics used by this service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<MetricDescriptor> metrics;
static {
// hack to force ProGuard to consider MetricDescriptor used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(MetricDescriptor.class);
}
/**
* Defines the monitored resources used by this service. This is required by the
* Service.monitoring and Service.logging configurations.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<MonitoredResourceDescriptor> monitoredResources;
static {
// hack to force ProGuard to consider MonitoredResourceDescriptor used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(MonitoredResourceDescriptor.class);
}
/**
* Monitoring configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Monitoring monitoring;
/**
* The service name, which is a DNS-like logical identifier for the service, such as
* `calendar.googleapis.com`. The service name typically goes through DNS verification to make
* sure the owner of the service also owns the DNS name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The Google project that owns this service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String producerProjectId;
/**
* Quota configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Quota quota;
/**
* Output only. The source information for this configuration if available.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private SourceInfo sourceInfo;
/**
* System parameter configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private SystemParameters systemParameters;
/**
* A list of all proto message types included in this API service. It serves similar purpose as
* [google.api.Service.types], except that these types are not needed by user-defined APIs.
* Therefore, they will not show up in the generated discovery doc. This field should only be used
* to define system APIs in ESF.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Type> systemTypes;
/**
* The product title for this service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String title;
/**
* A list of all proto message types included in this API service. Types referenced directly or
* indirectly by the `apis` are automatically included. Messages which are not referenced but
* shall be included, such as types used by the `google.protobuf.Any` type, should be listed here
* by name. Example:
*
* types: - name: google.protobuf.Int32
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Type> types;
/**
* Configuration controlling usage of this service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Usage usage;
/**
* A list of API interfaces exported by this service. Only the `name` field of the
* google.protobuf.Api needs to be provided by the configuration author, as the remaining fields
* will be derived from the IDL during the normalization process. It is an error to specify an API
* interface here which cannot be resolved against the associated IDL files.
* @return value or {@code null} for none
*/
public java.util.List<Api> getApis() {
return apis;
}
/**
* A list of API interfaces exported by this service. Only the `name` field of the
* google.protobuf.Api needs to be provided by the configuration author, as the remaining fields
* will be derived from the IDL during the normalization process. It is an error to specify an API
* interface here which cannot be resolved against the associated IDL files.
* @param apis apis or {@code null} for none
*/
public Service setApis(java.util.List<Api> apis) {
this.apis = apis;
return this;
}
/**
* Auth configuration.
* @return value or {@code null} for none
*/
public Authentication getAuthentication() {
return authentication;
}
/**
* Auth configuration.
* @param authentication authentication or {@code null} for none
*/
public Service setAuthentication(Authentication authentication) {
this.authentication = authentication;
return this;
}
/**
* API backend configuration.
* @return value or {@code null} for none
*/
public Backend getBackend() {
return backend;
}
/**
* API backend configuration.
* @param backend backend or {@code null} for none
*/
public Service setBackend(Backend backend) {
this.backend = backend;
return this;
}
/**
* Billing configuration.
* @return value or {@code null} for none
*/
public Billing getBilling() {
return billing;
}
/**
* Billing configuration.
* @param billing billing or {@code null} for none
*/
public Service setBilling(Billing billing) {
this.billing = billing;
return this;
}
/**
* The semantic version of the service configuration. The config version affects the
* interpretation of the service configuration. For example, certain features are enabled by
* default for certain config versions. The latest config version is `3`.
* @return value or {@code null} for none
*/
public java.lang.Long getConfigVersion() {
return configVersion;
}
/**
* The semantic version of the service configuration. The config version affects the
* interpretation of the service configuration. For example, certain features are enabled by
* default for certain config versions. The latest config version is `3`.
* @param configVersion configVersion or {@code null} for none
*/
public Service setConfigVersion(java.lang.Long configVersion) {
this.configVersion = configVersion;
return this;
}
/**
* Context configuration.
* @return value or {@code null} for none
*/
public Context getContext() {
return context;
}
/**
* Context configuration.
* @param context context or {@code null} for none
*/
public Service setContext(Context context) {
this.context = context;
return this;
}
/**
* Configuration for the service control plane.
* @return value or {@code null} for none
*/
public Control getControl() {
return control;
}
/**
* Configuration for the service control plane.
* @param control control or {@code null} for none
*/
public Service setControl(Control control) {
this.control = control;
return this;
}
/**
* Custom error configuration.
* @return value or {@code null} for none
*/
public CustomError getCustomError() {
return customError;
}
/**
* Custom error configuration.
* @param customError customError or {@code null} for none
*/
public Service setCustomError(CustomError customError) {
this.customError = customError;
return this;
}
/**
* Additional API documentation.
* @return value or {@code null} for none
*/
public Documentation getDocumentation() {
return documentation;
}
/**
* Additional API documentation.
* @param documentation documentation or {@code null} for none
*/
public Service setDocumentation(Documentation documentation) {
this.documentation = documentation;
return this;
}
/**
* Configuration for network endpoints. If this is empty, then an endpoint with the same name as
* the service is automatically generated to service all defined APIs.
* @return value or {@code null} for none
*/
public java.util.List<Endpoint> getEndpoints() {
return endpoints;
}
/**
* Configuration for network endpoints. If this is empty, then an endpoint with the same name as
* the service is automatically generated to service all defined APIs.
* @param endpoints endpoints or {@code null} for none
*/
public Service setEndpoints(java.util.List<Endpoint> endpoints) {
this.endpoints = endpoints;
return this;
}
/**
* A list of all enum types included in this API service. Enums referenced directly or indirectly
* by the `apis` are automatically included. Enums which are not referenced but shall be included
* should be listed here by name. Example:
*
* enums: - name: google.someapi.v1.SomeEnum
* @return value or {@code null} for none
*/
public java.util.List<ServiceManagementEnum> getEnums() {
return enums;
}
/**
* A list of all enum types included in this API service. Enums referenced directly or indirectly
* by the `apis` are automatically included. Enums which are not referenced but shall be included
* should be listed here by name. Example:
*
* enums: - name: google.someapi.v1.SomeEnum
* @param enums enums or {@code null} for none
*/
public Service setEnums(java.util.List<ServiceManagementEnum> enums) {
this.enums = enums;
return this;
}
/**
* HTTP configuration.
* @return value or {@code null} for none
*/
public Http getHttp() {
return http;
}
/**
* HTTP configuration.
* @param http http or {@code null} for none
*/
public Service setHttp(Http http) {
this.http = http;
return this;
}
/**
* A unique ID for a specific instance of this message, typically assigned by the client for
* tracking purpose. Must be no longer than 63 characters and only lower case letters, digits,
* '.', '_' and '-' are allowed. If empty, the server may choose to generate one instead.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* A unique ID for a specific instance of this message, typically assigned by the client for
* tracking purpose. Must be no longer than 63 characters and only lower case letters, digits,
* '.', '_' and '-' are allowed. If empty, the server may choose to generate one instead.
* @param id id or {@code null} for none
*/
public Service setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Logging configuration.
* @return value or {@code null} for none
*/
public Logging getLogging() {
return logging;
}
/**
* Logging configuration.
* @param logging logging or {@code null} for none
*/
public Service setLogging(Logging logging) {
this.logging = logging;
return this;
}
/**
* Defines the logs used by this service.
* @return value or {@code null} for none
*/
public java.util.List<LogDescriptor> getLogs() {
return logs;
}
/**
* Defines the logs used by this service.
* @param logs logs or {@code null} for none
*/
public Service setLogs(java.util.List<LogDescriptor> logs) {
this.logs = logs;
return this;
}
/**
* Defines the metrics used by this service.
* @return value or {@code null} for none
*/
public java.util.List<MetricDescriptor> getMetrics() {
return metrics;
}
/**
* Defines the metrics used by this service.
* @param metrics metrics or {@code null} for none
*/
public Service setMetrics(java.util.List<MetricDescriptor> metrics) {
this.metrics = metrics;
return this;
}
/**
* Defines the monitored resources used by this service. This is required by the
* Service.monitoring and Service.logging configurations.
* @return value or {@code null} for none
*/
public java.util.List<MonitoredResourceDescriptor> getMonitoredResources() {
return monitoredResources;
}
/**
* Defines the monitored resources used by this service. This is required by the
* Service.monitoring and Service.logging configurations.
* @param monitoredResources monitoredResources or {@code null} for none
*/
public Service setMonitoredResources(java.util.List<MonitoredResourceDescriptor> monitoredResources) {
this.monitoredResources = monitoredResources;
return this;
}
/**
* Monitoring configuration.
* @return value or {@code null} for none
*/
public Monitoring getMonitoring() {
return monitoring;
}
/**
* Monitoring configuration.
* @param monitoring monitoring or {@code null} for none
*/
public Service setMonitoring(Monitoring monitoring) {
this.monitoring = monitoring;
return this;
}
/**
* The service name, which is a DNS-like logical identifier for the service, such as
* `calendar.googleapis.com`. The service name typically goes through DNS verification to make
* sure the owner of the service also owns the DNS name.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* The service name, which is a DNS-like logical identifier for the service, such as
* `calendar.googleapis.com`. The service name typically goes through DNS verification to make
* sure the owner of the service also owns the DNS name.
* @param name name or {@code null} for none
*/
public Service setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The Google project that owns this service.
* @return value or {@code null} for none
*/
public java.lang.String getProducerProjectId() {
return producerProjectId;
}
/**
* The Google project that owns this service.
* @param producerProjectId producerProjectId or {@code null} for none
*/
public Service setProducerProjectId(java.lang.String producerProjectId) {
this.producerProjectId = producerProjectId;
return this;
}
/**
* Quota configuration.
* @return value or {@code null} for none
*/
public Quota getQuota() {
return quota;
}
/**
* Quota configuration.
* @param quota quota or {@code null} for none
*/
public Service setQuota(Quota quota) {
this.quota = quota;
return this;
}
/**
* Output only. The source information for this configuration if available.
* @return value or {@code null} for none
*/
public SourceInfo getSourceInfo() {
return sourceInfo;
}
/**
* Output only. The source information for this configuration if available.
* @param sourceInfo sourceInfo or {@code null} for none
*/
public Service setSourceInfo(SourceInfo sourceInfo) {
this.sourceInfo = sourceInfo;
return this;
}
/**
* System parameter configuration.
* @return value or {@code null} for none
*/
public SystemParameters getSystemParameters() {
return systemParameters;
}
/**
* System parameter configuration.
* @param systemParameters systemParameters or {@code null} for none
*/
public Service setSystemParameters(SystemParameters systemParameters) {
this.systemParameters = systemParameters;
return this;
}
/**
* A list of all proto message types included in this API service. It serves similar purpose as
* [google.api.Service.types], except that these types are not needed by user-defined APIs.
* Therefore, they will not show up in the generated discovery doc. This field should only be used
* to define system APIs in ESF.
* @return value or {@code null} for none
*/
public java.util.List<Type> getSystemTypes() {
return systemTypes;
}
/**
* A list of all proto message types included in this API service. It serves similar purpose as
* [google.api.Service.types], except that these types are not needed by user-defined APIs.
* Therefore, they will not show up in the generated discovery doc. This field should only be used
* to define system APIs in ESF.
* @param systemTypes systemTypes or {@code null} for none
*/
public Service setSystemTypes(java.util.List<Type> systemTypes) {
this.systemTypes = systemTypes;
return this;
}
/**
* The product title for this service.
* @return value or {@code null} for none
*/
public java.lang.String getTitle() {
return title;
}
/**
* The product title for this service.
* @param title title or {@code null} for none
*/
public Service setTitle(java.lang.String title) {
this.title = title;
return this;
}
/**
* A list of all proto message types included in this API service. Types referenced directly or
* indirectly by the `apis` are automatically included. Messages which are not referenced but
* shall be included, such as types used by the `google.protobuf.Any` type, should be listed here
* by name. Example:
*
* types: - name: google.protobuf.Int32
* @return value or {@code null} for none
*/
public java.util.List<Type> getTypes() {
return types;
}
/**
* A list of all proto message types included in this API service. Types referenced directly or
* indirectly by the `apis` are automatically included. Messages which are not referenced but
* shall be included, such as types used by the `google.protobuf.Any` type, should be listed here
* by name. Example:
*
* types: - name: google.protobuf.Int32
* @param types types or {@code null} for none
*/
public Service setTypes(java.util.List<Type> types) {
this.types = types;
return this;
}
/**
* Configuration controlling usage of this service.
* @return value or {@code null} for none
*/
public Usage getUsage() {
return usage;
}
/**
* Configuration controlling usage of this service.
* @param usage usage or {@code null} for none
*/
public Service setUsage(Usage usage) {
this.usage = usage;
return this;
}
@Override
public Service set(String fieldName, Object value) {
return (Service) super.set(fieldName, value);
}
@Override
public Service clone() {
return (Service) super.clone();
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/**
* .created at 1:14:57 AM Jan 14, 2011
*/
package org.jbox2d.testbed.tests;
import org.jbox2d.collision.shapes.EdgeShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.joints.PrismaticJointDef;
import org.jbox2d.dynamics.joints.RevoluteJointDef;
import org.jbox2d.testbed.framework.TestbedSettings;
import org.jbox2d.testbed.framework.TestbedTest;
/**
* @author Daniel Murphy
*/
public class BodyTypes extends TestbedTest {
private final static long ATTACHMENT_TAG = 19;
private final static long PLATFORM_TAG = 20;
Body m_attachment;
Body m_platform;
float m_speed;
@Override
public Long getTag(Body body) {
if (body == m_attachment)
return ATTACHMENT_TAG;
if (body == m_platform)
return PLATFORM_TAG;
return super.getTag(body);
}
@Override
public void processBody(Body body, Long tag) {
if (tag == ATTACHMENT_TAG) {
m_attachment = body;
} else if (tag == PLATFORM_TAG) {
m_platform = body;
} else {
super.processBody(body, tag);
}
}
@Override
public boolean isSaveLoadEnabled() {
return true;
}
@Override
public void initTest(boolean deserialized) {
m_speed = 3.0f;
if (deserialized) {
return;
}
Body ground = null;
{
BodyDef bd = new BodyDef();
ground = getWorld().createBody(bd);
EdgeShape shape = new EdgeShape();
shape.set(new Vec2(-20.0f, 0.0f), new Vec2(20.0f, 0.0f));
FixtureDef fd = new FixtureDef();
fd.shape = shape;
ground.createFixture(fd);
}
// Define attachment
{
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(0.0f, 3.0f);
m_attachment = getWorld().createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(0.5f, 2.0f);
m_attachment.createFixture(shape, 2.0f);
}
// Define platform
{
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(-4.0f, 5.0f);
m_platform = getWorld().createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(0.5f, 4.0f, new Vec2(4.0f, 0.0f), 0.5f * MathUtils.PI);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.friction = 0.6f;
fd.density = 2.0f;
m_platform.createFixture(fd);
RevoluteJointDef rjd = new RevoluteJointDef();
rjd.initialize(m_attachment, m_platform, new Vec2(0.0f, 5.0f));
rjd.maxMotorTorque = 50.0f;
rjd.enableMotor = true;
getWorld().createJoint(rjd);
PrismaticJointDef pjd = new PrismaticJointDef();
pjd.initialize(ground, m_platform, new Vec2(0.0f, 5.0f), new Vec2(1.0f, 0.0f));
pjd.maxMotorForce = 1000.0f;
pjd.enableMotor = true;
pjd.lowerTranslation = -10.0f;
pjd.upperTranslation = 10.0f;
pjd.enableLimit = true;
getWorld().createJoint(pjd);
}
// .create a payload
{
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(0.0f, 8.0f);
Body body = getWorld().createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(0.75f, 0.75f);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.friction = 0.6f;
fd.density = 2.0f;
body.createFixture(fd);
}
}
@Override
public void step(TestbedSettings settings) {
super.step(settings);
addTextLine("Keys: (d) dynamic, (s) static, (k) kinematic");
// Drive the kinematic body.
if (m_platform.getType() == BodyType.KINEMATIC) {
Vec2 p = m_platform.getTransform().p;
Vec2 v = m_platform.getLinearVelocity();
if ((p.x < -10.0f && v.x < 0.0f) || (p.x > 10.0f && v.x > 0.0f)) {
v.x = -v.x;
m_platform.setLinearVelocity(v);
}
}
}
@Override
public void keyPressed(char argKeyChar, int argKeyCode) {
switch (argKeyChar) {
case 'd':
m_platform.setType(BodyType.DYNAMIC);
break;
case 's':
m_platform.setType(BodyType.STATIC);
break;
case 'k':
m_platform.setType(BodyType.KINEMATIC);
m_platform.setLinearVelocity(new Vec2(-m_speed, 0.0f));
m_platform.setAngularVelocity(0.0f);
break;
}
}
@Override
public String getTestName() {
return "Body Types";
}
}
| |
package se.devscout.scoutapi;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.auth.AuthDynamicFeature;
import io.dropwizard.auth.AuthFilter;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.chained.ChainedAuthFilter;
import io.dropwizard.auth.oauth.OAuthCredentialAuthFilter;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.hibernate.HibernateBundle;
import io.dropwizard.migrations.MigrationsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.dropwizard.views.ViewBundle;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.context.internal.ManagedSessionContext;
import se.devscout.scoutapi.activityimporter.ActivitiesImporter;
import se.devscout.scoutapi.auth.AuthResult;
import se.devscout.scoutapi.auth.apikey.ApiKeyAuthenticator;
import se.devscout.scoutapi.auth.google.GoogleAuthenticator;
import se.devscout.scoutapi.dao.*;
import se.devscout.scoutapi.model.*;
import se.devscout.scoutapi.resource.*;
import se.devscout.scoutapi.resource.v1.ActivityResourceV1;
import se.devscout.scoutapi.resource.v1.CategoryResource;
import se.devscout.scoutapi.resource.v1.FavouritesResourceV1;
import se.devscout.scoutapi.textanalyzer.RelatedActivitiesUpdater;
import se.devscout.scoutapi.util.MediaFileUtils;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class ScoutAPIApplication extends Application<ScoutAPIConfiguration> {
public static final SimpleFilterProvider DEFAULT_FILTER_PROVIDER = new SimpleFilterProvider().addFilter("custom", SimpleBeanPropertyFilter.serializeAll());
private final HibernateBundle<ScoutAPIConfiguration> hibernate = new HibernateBundle<ScoutAPIConfiguration>(
SystemMessage.class,
Tag.class,
TagDerived.class,
MediaFile.class,
Activity.class,
ActivityDerived.class,
ActivityRating.class,
ActivityProperties.class,
ActivityPropertiesTag.class,
ActivityPropertiesMediaFile.class,
ActivityRelation.class,
User.class,
UserIdentity.class) {
public DataSourceFactory getDataSourceFactory(ScoutAPIConfiguration scoutAPIConfiguration) {
return scoutAPIConfiguration.getDatabase();
}
@Override
public SessionFactory getSessionFactory() {
return super.getSessionFactory();
}
};
public static final String REALM = "Scout Admin Tool";
private ScheduledExecutorService crawler;
public static void main(String[] args) throws Exception {
new ScoutAPIApplication().run(args);
}
@Override
public void run(ScoutAPIConfiguration scoutAPIConfiguration, Environment environment) throws Exception {
initTags(scoutAPIConfiguration.getDefaultTags());
initUsers(scoutAPIConfiguration.getDefaultUsers());
initFolder(scoutAPIConfiguration.getMediaFilesFolder());
initFolder(scoutAPIConfiguration.getTempFolder());
initSystemMessages(scoutAPIConfiguration.getDefaultSystemMessages());
initResources(scoutAPIConfiguration, environment);
// Add support for logging all requests and responses. Logging configuration must also be changed/set.
// environment.jersey().register(new LoggingFilter(Logger.getLogger(LoggingFilter.class.getName()), true));
environment.getObjectMapper().setFilterProvider(DEFAULT_FILTER_PROVIDER);
environment.getObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'"));
final ConfigurationHealthCheck healthCheck = new ConfigurationHealthCheck();
environment.healthChecks().register("config-health-check", healthCheck);
initAuthentication(environment, scoutAPIConfiguration);
initTasks(scoutAPIConfiguration, environment);
if (scoutAPIConfiguration.getAutoUpdateIntervalSeconds() > 0) {
initActivityUpdater(scoutAPIConfiguration, environment);
}
// ChainedAuthFactory<AuthResult> chainedFactory = new ChainedAuthFactory<>(
// new OAuthFactory<AuthResult>(new ApiKeyAuthenticator(userDao), REALM, AuthResult.class).prefix(ApiKeyAuthenticator.ID),
// new OAuthFactory<AuthResult>(new GoogleAuthenticator(userDao), REALM, AuthResult.class).prefix(GoogleAuthenticator.ID)
// );
// environment.jersey().register(AuthFactory.binder(chainedFactory));
}
private void initTasks(ScoutAPIConfiguration cfg, Environment environment) {
//TODO: Task should only be available to administrators.
environment.admin().addTask(new ActivitiesImporter.Task(
getCrawlerTempFolder(cfg),
cfg.getCrawlerUser(),
hibernate.getSessionFactory()));
//TODO: Task should only be available to administrators.
environment.admin().addTask(new MediaFileUtils.CleanResizedImagesCacheTask(cfg.getMediaFilesFolder()));
//TODO: Task should only be available to administrators.
environment.admin().addTask(new MediaFileUtils.AutoAssignMediaFileToTags(
hibernate.getSessionFactory(),
cfg.getMediaFilesFolder(),
cfg.getCrawlerUser()));
}
private File getCrawlerTempFolder(ScoutAPIConfiguration cfg) {
return new File(cfg.getTempFolder(), "crawler");
}
private void initAuthentication(Environment environment, ScoutAPIConfiguration configuration) {
List<AuthFilter> filters = Lists.newArrayList(
new OAuthCredentialAuthFilter.Builder<>()
.setAuthenticator((Authenticator) new ApiKeyAuthenticator(
hibernate.getSessionFactory()))
.setPrefix(ApiKeyAuthenticator.ID)
.buildAuthFilter(),
new OAuthCredentialAuthFilter.Builder<>()
.setAuthenticator((Authenticator) new GoogleAuthenticator(
hibernate.getSessionFactory(),
configuration.getGoogleAuthentication()))
.setPrefix(GoogleAuthenticator.ID)
.buildAuthFilter()
);
environment.jersey().register(new AuthDynamicFeature(new ChainedAuthFilter(filters)));
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthResult.class));
}
private void initResources(ScoutAPIConfiguration scoutAPIConfiguration, Environment environment) throws IOException {
SystemMessageDao systemMessageDao = new SystemMessageDao(hibernate.getSessionFactory());
UserDao userDao = new UserDao(hibernate.getSessionFactory());
TagDao tagDao = new TagDao(hibernate.getSessionFactory());
MediaFileDao mediaFileDao = new MediaFileDao(hibernate.getSessionFactory());
ActivityDao activityDao = new ActivityDao(hibernate.getSessionFactory());
ActivityRatingDao activityRatingDao = new ActivityRatingDao(hibernate.getSessionFactory());
environment.jersey().register(new UserResource(userDao));
environment.jersey().register(new SystemMessageResource(systemMessageDao));
environment.jersey().register(new TagResource(tagDao));
environment.jersey().register(new CategoryResource(tagDao));
environment.jersey().register(new MediaFileResource(mediaFileDao, scoutAPIConfiguration.getMediaFilesFolder()));
environment.jersey().register(new ActivityResourceV2(activityDao, activityRatingDao));
environment.jersey().register(new ActivityResourceV1(activityDao, activityRatingDao));
environment.jersey().register(new SystemResource());
environment.jersey().register(new FavouritesResourceV1(activityRatingDao, activityDao));
environment.jersey().register(MultiPartFeature.class);
environment.jersey().register(new ApiListingResource());
environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
BeanConfig config = new BeanConfig();
config.setTitle("API for Aktivitetsbanken");
config.setVersion("1.0 and 2.0");
config.setContact("/dev/scout");
config.setBasePath("api");
config.setDescription("An open API for searching activities suitable for boy scouts and girl guides. The data is mirrored from www.aktivitetsbanken.se.");
config.setResourcePackage(Joiner.on(',').join("se.devscout.scoutapi.resource", "se.devscout.scoutapi.resource.v1"));
config.setScan(true);
}
private void initActivityUpdater(final ScoutAPIConfiguration cfg, Environment environment) throws IOException, TransformerException, ParserConfigurationException, JAXBException {
crawler = environment.lifecycle().scheduledExecutorService("crawler").build();
crawler.scheduleAtFixedRate(
() -> {
long abortTime = System.currentTimeMillis() + ((int) (0.9 * cfg.getAutoUpdateIntervalSeconds()) * 1000);
new ActivitiesImporter(
getCrawlerTempFolder(cfg),
cfg.getCrawlerUser(),
hibernate.getSessionFactory(),
abortTime)
.run();
new RelatedActivitiesUpdater(
cfg.getSimilarityCalculatorConfiguration(),
hibernate.getSessionFactory(),
abortTime)
.run();
},
10L,
cfg.getAutoUpdateIntervalSeconds(),
TimeUnit.SECONDS);
}
private void initFolder(File folder) {
if (folder.exists()) {
if (!folder.isDirectory()) {
throw new IllegalArgumentException(folder.getAbsolutePath() + " exists and is not a folder");
}
} else {
if (!folder.mkdirs()) {
throw new IllegalArgumentException("Could not create " + folder.getAbsolutePath());
}
}
}
private void initTags(List<Tag> tags) {
Session session = hibernate.getSessionFactory().openSession();
ManagedSessionContext.bind(session);
Transaction transaction = session.beginTransaction();
TagDao tagDao = new TagDao(hibernate.getSessionFactory());
tags.stream().forEach(tag -> {
Tag existingTag = tagDao.read(tag.getGroup(), tag.getName());
if (existingTag == null) {
tagDao.create(tag);
}
});
transaction.commit();
session.close();
}
private void initSystemMessages(List<SystemMessage> msgs) {
Session session = hibernate.getSessionFactory().openSession();
ManagedSessionContext.bind(session);
Transaction transaction = session.beginTransaction();
SystemMessageDao dao = new SystemMessageDao(hibernate.getSessionFactory());
List<String> existingMessages = dao.all().stream().map(sm -> sm.getKey()).collect(Collectors.toList());
msgs.stream().forEach(msg -> {
if (!existingMessages.contains(msg.getKey())) {
dao.create(msg);
}
});
transaction.commit();
session.close();
}
private void initUsers(List<User> users) {
Session session = hibernate.getSessionFactory().openSession();
ManagedSessionContext.bind(session);
Transaction transaction = session.beginTransaction();
UserDao userDao = new UserDao(hibernate.getSessionFactory());
users.stream().forEach(user -> {
List<User> existingUsers = userDao.byName(user.getName());
if (existingUsers.isEmpty()) {
// We need to re-add each identity since the identities read from the configuration lack back-reference to the user itself (required when saving using JPA).
ArrayList<UserIdentity> userIdentities = new ArrayList<UserIdentity>(user.getIdentities());
user.getIdentities().clear();
userIdentities.stream().forEach(userIdentity1 -> user.addIdentity(userIdentity1.getType(), userIdentity1.getValue()));
// Save
userDao.create(user);
}
});
transaction.commit();
session.close();
}
@Override
public String getName() {
return "scout-api";
}
@Override
public void initialize(Bootstrap<ScoutAPIConfiguration> bootstrap) {
bootstrap.addBundle(hibernate);
// AttributeTypeDao attributeTypeDao = new AttributeTypeDao(hibernate.getSessionFactory());
// attributeTypeDao.initDefaultTypes(adminToolConfiguration.getDefaultAttributes());
bootstrap.addBundle(new MigrationsBundle<ScoutAPIConfiguration>() {
public DataSourceFactory getDataSourceFactory(ScoutAPIConfiguration scoutAPIConfiguration) {
return scoutAPIConfiguration.getDatabase();
}
});
bootstrap.addBundle(new ViewBundle<ScoutAPIConfiguration>());
bootstrap.addBundle(new AssetsBundle("/assets", "/static", "assets/index.html"));
super.initialize(bootstrap);
}
}
| |
/*
* (C) Copyright IBM Corp. 2014
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.ibm.portal.samples.mvc.controller;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.portlet.MimeResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
import com.ibm.portal.samples.common.Marshaller;
import com.ibm.portal.samples.mvc.model.TemplateActions.ACTION;
import com.ibm.portal.samples.mvc.model.TemplateActions.KEY;
import com.ibm.portal.samples.mvc.model.TemplateModel;
/**
* Implementation of the controller that generates URLs to modify the model.
* Each URL should work on a clone of the {@link TemplateModel} and modify the
* cloned model.
*
* @author cleue
*/
public class TemplateController {
/**
* Representation to dependencies on external services
*/
public interface Dependencies {
/**
* Marshaller for private render parameters
*
* @return the marshaller
*/
Marshaller getPrivateParameterMarshaller();
/**
* TODO add dependencies via parameterless getter methods
*/
}
/** class name for the logger */
private static final String LOG_CLASS = TemplateController.class.getName();
/** logging level */
private static final Level LOG_LEVEL = Level.FINER;
/** class logger */
private static final Logger LOGGER = Logger.getLogger(LOG_CLASS);
/**
* logging can be an instance variable, since the lifecycle of the
* controller is the request
*/
private final boolean bIsLogging = LOGGER.isLoggable(LOG_LEVEL);
/**
* base model
*/
private final TemplateModel model;
private final MimeResponse response;
/**
* controls how private parameters are marshalled
*/
private final Marshaller privateMarshaller;
/**
* Initializes the controller on top of a model
*
* @param aModel
* the model
* @param aRequest
* the request
* @param aResponse
* the response
* @param aDeps
* the dependencies
*/
public TemplateController(final TemplateModel aModel,
final PortletRequest aRequest, final MimeResponse aResponse,
final Dependencies aDeps) {
// sanity check
assert aModel != null;
assert aRequest != null;
assert aResponse != null;
assert aDeps != null;
// logging support
final String LOG_METHOD = "TemplateController(aModel, aBean, aDeps)";
if (bIsLogging) {
LOGGER.entering(LOG_CLASS, LOG_METHOD);
}
// TODO copy dependencies from the interface into fields
response = aResponse;
model = aModel;
privateMarshaller = aDeps.getPrivateParameterMarshaller();
// exit trace
if (bIsLogging) {
LOGGER.exiting(LOG_CLASS, LOG_METHOD);
}
}
/**
* Returns a clone of the current model
*
* @return the clone
*/
private final TemplateModel cloneModel() {
// clones the current model
return model.clone();
}
/**
* Constructs a render URL that encodes the given model
*
* @param aModel
* the model
* @return the render URL
*
* @throws PortletException
* @throws IOException
*/
private final PortletURL createRenderURL(final TemplateModel aModel)
throws PortletException, IOException {
// sanity check
assert aModel != null;
// construct a new render URL
final PortletURL url = response.createRenderURL();
aModel.encode(url);
// ok
return url;
}
/**
* Performs a cleanup of resources held by the controller
*/
public void dispose() {
// TODO cleanup here
}
/**
* Returns the action URL that encodes the current model. We use the same
* action URL for all actions, since the distinction of the individual
* action is encoded as a hidden form data value.
*
* @return the action URL.
*
* @throws PortletException
* @throws IOException
*/
public PortletURL getActionURL() throws PortletException, IOException {
// construct a new render URL
final PortletURL url = response.createActionURL();
model.encode(url);
// ok
return url;
}
/**
* Creates a render URL that clears the model
*
* @return the render URL
*
* @throws PortletException
* @throws IOException
*/
public PortletURL getClearURL() throws PortletException, IOException {
// clone the model
final TemplateModel clone = cloneModel();
// modify the cloned model
clone.clear();
// represent the cloned model via a URL
return createRenderURL(clone);
}
/**
* TODO remove and replace by some more meaningful methods
*
* Creates a render URL that decrements the sample integer
*
* @return the render URL
*
* @throws PortletException
* @throws IOException
*/
public PortletURL getDecSampleIntURL() throws PortletException, IOException {
// clone the model
final TemplateModel clone = cloneModel();
// modify the cloned model
clone.decSampleInt();
// represent the cloned model via a URL
return createRenderURL(clone);
}
/**
* TODO remove and replace by some more meaningful methods
*
* Creates a render URL that increments the sample integer
*
* @return the render URL
*
* @throws PortletException
* @throws IOException
*/
public PortletURL getIncSampleIntURL() throws PortletException, IOException {
// clone the model
final TemplateModel clone = cloneModel();
// modify the cloned model
clone.incSampleInt();
// represent the cloned model via a URL
return createRenderURL(clone);
}
/**
* Returns the value of the form field that encodes the cancel action
*
* @return form field value
*/
public String getValueActionCancel() {
return privateMarshaller.marshalEnum(ACTION.SAMPLE_FORM_CANCEL);
}
/**
* Returns the value of the form field that encodes the save action
*
* @return form field value
*/
public String getValueActionSave() {
return privateMarshaller.marshalEnum(ACTION.SAMPLE_FORM_SAVE);
}
/**
* Returns the name of the form field that encodes the action
*
* @return form field name
*/
public String getKeyAction() {
return privateMarshaller.marshalEnum(KEY.ACTION);
}
/**
* Returns the name of the form field that encodes the sample text
*
* @return form field name
*/
public String getKeySampleText() {
return privateMarshaller.marshalEnum(KEY.SAMPLE_TEXT);
}
}
| |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.10.12 at 12:10:10 PM CEST
//
package org.xlcloud.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for anonymous complex type.
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://bull.com/xlcloud/vcms}Referenceable">
* <sequence>
* <element name="tag" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://bull.com/xlcloud/vcms}category" minOccurs="0" maxOccurs="unbounded"/>
* <element ref="{http://bull.com/xlcloud/vcms}cookbook" minOccurs="0" maxOccurs="unbounded"/>
* </sequence>
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="vendor" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="description" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="license" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="referencePath" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="catalogScope" type="{http://bull.com/xlcloud/vcms}CatalogScopeType" />
* <attribute name="accountId" type="{http://www.w3.org/2001/XMLSchema}long" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType( XmlAccessType.FIELD )
@XmlType( name = "", propOrder = { "tag", "cookbooks" } )
@XmlRootElement( name = "application" )
public class Application extends Referenceable implements Serializable {
private static final long serialVersionUID = -7119626714137847850L;
private static final String RESOURCE_PREFIX = "applications";
protected List<String> tag;
private Cookbooks cookbooks;
@XmlAttribute
private String category;
@XmlAttribute
protected String name;
@XmlAttribute
protected String vendor;
@XmlAttribute
protected String version;
@XmlAttribute
protected String description;
@XmlAttribute
protected String license;
@XmlAttribute
protected String type;
@XmlAttribute
private CatalogScopeType catalogScope;
@XmlAttribute
private Long accountId;
/**
* Gets the value of the tag property.
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the tag property.
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getTag().add(newItem);
* </pre>
* <p>
* Objects of the following type(s) are allowed in the list {@link String }
*/
public List<String> getTag() {
if (tag == null) {
tag = new ArrayList<String>();
}
return this.tag;
}
/**
* <p>
* getTag() method returns a reference to the live list, not a snapshot.
* Therefore any modification you make to the list returned by getTag() will
* be present inside the JAXB object. This is why a <CODE>set</CODE> method
* is deprecated for the tag property. setter was created to avoid warnings
* in dozer logs, more details in: http://jira.ow2.org/browse/XLCLOUD-336
*
* @param tag
*/
@Deprecated
public void setTag(List<String> tag) {
getTag().clear();
getTag().addAll(tag);
}
/**
* Gets the value of the name property.
*
* @return possible object is {@link String }
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is {@link String }
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the vendor property.
*
* @return possible object is {@link String }
*/
public String getVendor() {
return vendor;
}
/**
* Sets the value of the vendor property.
*
* @param value
* allowed object is {@link String }
*/
public void setVendor(String value) {
this.vendor = value;
}
/**
* Gets the value of the version property.
*
* @return possible object is {@link String }
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is {@link String }
*/
public void setVersion(String value) {
this.version = value;
}
/**
* Gets the value of the description property.
*
* @return possible object is {@link String }
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is {@link String }
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the license property.
*
* @return possible object is {@link String }
*/
public String getLicense() {
return license;
}
/**
* Sets the value of the license property.
*
* @param value
* allowed object is {@link String }
*/
public void setLicense(String value) {
this.license = value;
}
/**
* Gets the value of the type property.
*
* @return possible object is {@link String }
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is {@link String }
*/
public void setType(String value) {
this.type = value;
}
/** {@inheritDoc} */
@Override
protected String getResourcePrefix() {
return RESOURCE_PREFIX;
}
/**
* Gets the value of {@link #category}.
*
* @return value of {@link #category}
*/
public String getCategory() {
return category;
}
/**
* Sets the value of {@link #category}.
*
* @param category
* - value
*/
public void setCategory(String category) {
this.category = category;
}
/**
* Gets the value of {@link #catalogScope}.
*
* @return value of {@link #catalogScope}
*/
public CatalogScopeType getCatalogScope() {
return catalogScope;
}
/**
* Sets the value of {@link #catalogScope}.
*
* @param catalogScope
* - value
*/
public void setCatalogScope(CatalogScopeType catalogScope) {
this.catalogScope = catalogScope;
}
/**
* Gets the value of {@link #accountId}.
*
* @return value of {@link #accountId}
*/
public Long getAccountId() {
return accountId;
}
/**
* Sets the value of {@link #accountId}.
*
* @param accountId
* - value
*/
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
/**
* Gets the value of {@link #cookbooks}.
*
* @return value of {@link #cookbooks}
*/
public Cookbooks getCookbooks() {
if(cookbooks == null) {
cookbooks = new Cookbooks();
}
return cookbooks;
}
/**
* Sets the value of {@link #cookbooks}.
*
* @param cookbook
* - value
*/
public void setCookbooks(Cookbooks cookbooks) {
this.cookbooks = cookbooks;
}
}
| |
/*
* Copyright 2014 The British Library / The SCAPE Project Consortium
* Authors: Alecs Geuder (alecs.geuder@bl.uk),
* William Palmer (William.Palmer@bl.uk)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.bl.dpt.utils.schematron;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPathExpressionException;
import java.io.*;
import java.util.*;
/**
* Creates XSLT Processors from schematron files that can validate xml documents.
* (left side of http://www.xml.com/2003/11/12/graphics/Processor.jpg)
*/
public class ValidatorFactory {
private static final Logger logger = LoggerFactory.getLogger(ValidatorFactory.class);
private byte[] schXSLT = null;
private File schXSLTFile = null;
private DOMSource doc = null;
private LinkedHashMap<String, String> assertPatternMap = new LinkedHashMap<String,String>();
/**
* The namespace for Schematron schemas
*/
private static final String namespace = "http://purl.oclc.org/dsdl/schematron";
/**
* Use this constructor if the XSLT resulting from the merge of the
* generic skeleton files and a domain-specific .sch schematron file
* shall be calculated on the fly and not saved to a file.
*/
public ValidatorFactory() {}
/**
* Constructor for the case where a file-path to the XSLT file from the merge of the
* generic skeleton files and a domain-specific .sch schematron file is
* provided.
*
* In case the file content already exists it is directly used.
* In case of an empty file the translated XSLT is written to the file.
*
* @param schematronSXLTFilePath The path to the XSLT file.
* @throws java.io.IOException
*/
public ValidatorFactory(String schematronSXLTFilePath) throws IOException {
this.schXSLTFile = new File(schematronSXLTFilePath);
if (schXSLTFile.exists()) {
this.schXSLT = Files.toByteArray(schXSLTFile);
}
}
/**
* The collection of iso-schematron files used to create the XSLT processor.
* (http://www.schematron.com/tmp/iso-schematron-xslt1.zip)
* TODO: make this configurable?
*/
private final static class ISOFiles {
// (1) ISO_DSDL:
// "This is a macro processor to assemble the schema from various parts.
// If your schema is not in separate parts, you can skip this stage.
// This stage also generates error messages for some common XPath syntax problems."
final static String ISO_DSDL="/iso-schematron/iso_dsdl_include.xsl";
// (2) ISO_ABSTRACT:
// "This is a macro processor to convert abstract patterns to real patterns.
// If your schema does not use abstract patterns, you can skip this
// stage."
final static String ISO_ABSTRACT="/iso-schematron/iso_abstract_expand.xsl";
// (3) ISO_SVRL:
// compiles the Schematron schema into an XSLT script
final static String ISO_SVRL="/iso-schematron/iso_svrl_for_xslt1.xsl";
}
//see here: http://stackoverflow.com/a/12453881
/**
* Implement a URIResolver so that XSL files can be found in the jar resources
* @author wpalmer
*/
private static class ResourceResolver implements URIResolver {
public StreamSource resolve(String pRef, String pBase) {
return new StreamSource(ResourceResolver.class.getClassLoader().getResourceAsStream("iso-schematron/"+pRef));
}
}
/**
* Returns a XSLT OutputStream converted from a Schematron .sch
*
* If the internal byte[] buffer is already populated it just returns that one.
* If a file-path was specified in the constructor, the results are also written there.
*
* @param schSource The source of the schematron file.
* @return a byte[] representation of the XSLT OutputStream
* @throws javax.xml.transform.TransformerException
* @throws java.io.IOException
* @throws javax.xml.parsers.ParserConfigurationException
* @throws org.xml.sax.SAXException
* @throws javax.xml.xpath.XPathExpressionException
*/
private byte[] schToXSLT(Source schSource) throws TransformerException, IOException, SAXException, ParserConfigurationException, XPathExpressionException {
if (schXSLT == null) {
ByteArrayOutputStream streamedSchematronSXLT = new ByteArrayOutputStream();
TransformerFactory factory = TransformerFactory.newInstance();
factory.setURIResolver(new ResourceResolver());
logger.debug("Building schematronSXLT: assembling the schema from possibly various parts..");
logger.trace("..using as input: {})", schSource);
Transformer assemble = factory.newTransformer(new StreamSource(this.getClass().getResourceAsStream(ISOFiles.ISO_DSDL)));
ByteArrayOutputStream assembleOutput = new ByteArrayOutputStream();
assemble.transform(schSource, new StreamResult(assembleOutput));
logger.debug("Building schematronSXLT: converting abstract patterns to real patterns..");
Transformer abstract2real = factory.newTransformer(new StreamSource(this.getClass().getResourceAsStream(ISOFiles.ISO_ABSTRACT)));
ByteArrayOutputStream abstract2realOutput = new ByteArrayOutputStream();
logger.trace("..using as input: {}", abstract2realOutput);
abstract2real.transform(new StreamSource(new ByteArrayInputStream(assembleOutput.toByteArray())),
new StreamResult(abstract2realOutput));
logger.debug("Building schematronSXLT: compiling the .sch into an XSLT script..");
Transformer toXSLT = factory.newTransformer(new StreamSource(this.getClass().getResourceAsStream(ISOFiles.ISO_SVRL)));
toXSLT.setParameter("terminate", "false"); //don't halt on errors
logger.trace("..using as input: {}", abstract2realOutput);
toXSLT.transform(new StreamSource(new ByteArrayInputStream(abstract2realOutput.toByteArray())),
new StreamResult(streamedSchematronSXLT));
// in case the constructor was provided with a path to an empty (not yet existing) file,
// write this now.
if (this.schXSLTFile != null && !this.schXSLTFile.exists()) {
streamedSchematronSXLT.writeTo(new FileOutputStream(this.schXSLTFile));
}
schXSLT = streamedSchematronSXLT.toByteArray();
}
return schXSLT;
}
/**
* Removes all pattern elements from a DOM whose names are not specified in the given patternFilter.
*
* (for an example see also the tests.
*
* @param doc the original schema as Document
* @param patternFilter a set of strings representing the names of pattern elements in a schematron schema file
* @return the filtered DOM as {@link javax.xml.transform.dom.DOMSource}
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws javax.xml.parsers.ParserConfigurationException
* @throws javax.xml.xpath.XPathExpressionException
*/
private DOMSource filterPatterns(Document doc, Set<String> patternFilter) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
if (this.doc != null) {
return this.doc;
}
NodeList patterns = doc.getElementsByTagNameNS(namespace, "pattern");
for (int p=0;p<patterns.getLength();p++) {
Element pattern = (Element) patterns.item(p);
if (patternFilter != null && !patternFilter.contains(pattern.getAttribute("name").trim())) {
pattern.getParentNode().removeChild(pattern);
p--; // prevent off-by-one error
} else {
NodeList rules = pattern.getElementsByTagNameNS(namespace, "rule");
for (int r=0;r<rules.getLength();r++) {
Element rule = (Element) rules.item(r);
NodeList tests = rule.getElementsByTagNameNS(namespace, "assert");
// add pattern to each assert it contains
for (int i=0;i<tests.getLength();i++) {
Element test = (Element) tests.item(i);
logger.debug("Adding (grand-)parent pattern {} to assert {}", pattern.getAttribute("name"), test.getTextContent());
assertPatternMap.put(test.getTextContent(), pattern.getAttribute("name"));
}
}
}
}
this.doc = new DOMSource(doc);
return this.doc;
}
/**
* Parses the original StreamSource into {@link Document} form .
* @param original
* @return the dom Document
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
private Document toDoc(StreamSource original) throws IOException, SAXException, ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true); // need this in order to call doc.getElementsByTagNameNS later
DocumentBuilder dB = dbf.newDocumentBuilder();
return dB.parse(original.getInputStream());
}
/**
* Create a new {@link Validator} based on the path to the schematron schema
*
* @param schemaPath the path to the schematron schema file
*
* @return a new Validator instance
* @throws javax.xml.transform.TransformerException
* @throws java.io.IOException
* @throws org.xml.sax.SAXException
* @throws javax.xml.parsers.ParserConfigurationException
* @throws javax.xml.xpath.XPathExpressionException
*/ public Validator newValidator(String schemaPath) throws TransformerException, IOException, SAXException, ParserConfigurationException, XPathExpressionException {
return newValidator(new StreamSource(new FileInputStream(schemaPath)));
}
/**
* Create a new {@link Validator} providing a schematron schema input source
*
* @param schemaInput the input containing the schematron schema (the
* 'policy')
* @return a new Validator instance
* @throws javax.xml.transform.TransformerException
* @throws java.io.IOException
* @throws org.xml.sax.SAXException
* @throws javax.xml.parsers.ParserConfigurationException
* @throws javax.xml.xpath.XPathExpressionException
*/ public Validator newValidator(StreamSource schemaInput) throws TransformerException, IOException, SAXException, ParserConfigurationException, XPathExpressionException {
return newValidator(schemaInput, null);
}
/**
* Create a new {@link Validator} providing a schematron schema input and a
* pattern filter.
*
* @param schemaPath the path to the schematron schema file
* @param patternFilter contains a set of strings, each representing a
* pattern element in the schematron schema; all patterns of which the
* name is not mentioned will be ignored. <br>
* NOTE: patternFilter can be null, in this case all patterns will be
* taken into account
* @return a new Validator instance
* @throws javax.xml.transform.TransformerException
* @throws java.io.IOException
* @throws org.xml.sax.SAXException
* @throws javax.xml.parsers.ParserConfigurationException
* @throws javax.xml.xpath.XPathExpressionException
*/ public Validator newValidator(String schemaPath, Set<String> patternFilter) throws TransformerException, IOException, SAXException, ParserConfigurationException, XPathExpressionException {
return newValidator(new StreamSource(new FileInputStream(schemaPath)), patternFilter);
}
/**
* Create a new {@link Validator} providing a schematron schema input and a
* pattern filter.
*
* @param schemaInput the input containing the schematron schema (the
* 'policy')
* @param patternFilter contains a set of strings, each representing a
* pattern element in the schematron schema; all patterns of which the
* name is not mentioned will be ignored. <br>
* NOTE: patternFilter can be null, in this case all patterns will be
* taken into account
* @return a new Validator instance
* @throws javax.xml.transform.TransformerException
* @throws java.io.IOException
* @throws org.xml.sax.SAXException
* @throws javax.xml.parsers.ParserConfigurationException
* @throws javax.xml.xpath.XPathExpressionException
*/
public Validator newValidator(StreamSource schemaInput, Set<String> patternFilter) throws TransformerException, IOException, SAXException, ParserConfigurationException, XPathExpressionException {
return new Validator(schToXSLT(filterPatterns(toDoc(schemaInput), patternFilter)), assertPatternMap);
}
/**
* Gets a collection of pattern names for a given schematron schema.
*
* @param schemaInput the source of the schematron schema
* @param patternFilter contains a set of strings, each representing a
* pattern element in the schematron schema; all patterns of which the
* name is not mentioned will be ignored. <br>
* NOTE: patternFilter can be null, in this case all patterns will be
* taken into account
* @return a Collection of String containing the pattern names
*
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws XPathExpressionException
*/
public Collection<String> getPatternNames(StreamSource schemaInput, Set<String> patternFilter) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
filterPatterns(toDoc(schemaInput), patternFilter);
return new LinkedHashSet<String>(assertPatternMap.values());
}
/**
* Gets the {@link #assertPatternMap}, a reversed dictionary linking schematron tests
* to schematron patterns (categories)
*
* @param schemaInput the source of the schematron schema
* @param patternFilter contains a set of strings, each representing a
* pattern element in the schematron schema; all patterns of which the
* name is not mentioned will be ignored. <br>
* NOTE: patternFilter can be null, in this case all patterns will be
* taken into account
* @return A HashMap linking the test names (Strings) to the category names (Strings)
*
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws XPathExpressionException
* @throws TransformerException
*/
public Map<String,String> getAssertPatternMap(StreamSource schemaInput, Set<String> patternFilter) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformerException {
if (assertPatternMap.size() == 0) {
schToXSLT(filterPatterns(toDoc(schemaInput), patternFilter));
}
return Collections.unmodifiableMap(assertPatternMap);
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.painless;
import org.apache.lucene.index.LeafReaderContext;
import org.elasticsearch.SpecialPermission;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.painless.Compiler.Loader;
import org.elasticsearch.painless.lookup.PainlessLookupBuilder;
import org.elasticsearch.painless.spi.Whitelist;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptException;
import org.elasticsearch.script.SearchScript;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.painless.WriterConstants.OBJECT_TYPE;
import static org.elasticsearch.painless.node.SSource.MainMethodReserved;
/**
* Implementation of a ScriptEngine for the Painless language.
*/
public final class PainlessScriptEngine extends AbstractComponent implements ScriptEngine {
/**
* Standard name of the Painless language.
*/
public static final String NAME = "painless";
/**
* Permissions context used during compilation.
*/
private static final AccessControlContext COMPILATION_CONTEXT;
/**
* Setup the allowed permissions.
*/
static {
final Permissions none = new Permissions();
none.setReadOnly();
COMPILATION_CONTEXT = new AccessControlContext(new ProtectionDomain[] {
new ProtectionDomain(null, none)
});
}
/**
* Default compiler settings to be used. Note that {@link CompilerSettings} is mutable but this instance shouldn't be mutated outside
* of {@link PainlessScriptEngine#PainlessScriptEngine(Settings, Map)}.
*/
private final CompilerSettings defaultCompilerSettings = new CompilerSettings();
private final Map<ScriptContext<?>, Compiler> contextsToCompilers;
/**
* Constructor.
* @param settings The settings to initialize the engine with.
*/
public PainlessScriptEngine(Settings settings, Map<ScriptContext<?>, List<Whitelist>> contexts) {
super(settings);
defaultCompilerSettings.setRegexesEnabled(CompilerSettings.REGEX_ENABLED.get(settings));
Map<ScriptContext<?>, Compiler> contextsToCompilers = new HashMap<>();
for (Map.Entry<ScriptContext<?>, List<Whitelist>> entry : contexts.entrySet()) {
ScriptContext<?> context = entry.getKey();
if (context.instanceClazz.equals(SearchScript.class)) {
contextsToCompilers.put(context, new Compiler(GenericElasticsearchScript.class, null, null,
PainlessLookupBuilder.buildFromWhitelists(entry.getValue())));
} else {
contextsToCompilers.put(context, new Compiler(context.instanceClazz, context.factoryClazz, context.statefulFactoryClazz,
PainlessLookupBuilder.buildFromWhitelists(entry.getValue())));
}
}
this.contextsToCompilers = Collections.unmodifiableMap(contextsToCompilers);
}
/**
* Get the type name(s) for the language.
* @return Always contains only the single name of the language.
*/
@Override
public String getType() {
return NAME;
}
@Override
public <T> T compile(String scriptName, String scriptSource, ScriptContext<T> context, Map<String, String> params) {
Compiler compiler = contextsToCompilers.get(context);
if (context.instanceClazz.equals(SearchScript.class)) {
Constructor<?> constructor = compile(compiler, scriptName, scriptSource, params);
boolean needsScore;
try {
GenericElasticsearchScript newInstance = (GenericElasticsearchScript)constructor.newInstance();
needsScore = newInstance.needs_score();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("internal error");
}
SearchScript.Factory factory = (p, lookup) -> new SearchScript.LeafFactory() {
@Override
public SearchScript newInstance(final LeafReaderContext context) {
try {
// a new instance is required for the class bindings model to work correctly
GenericElasticsearchScript newInstance = (GenericElasticsearchScript)constructor.newInstance();
return new ScriptImpl(newInstance, p, lookup, context);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("internal error");
}
}
@Override
public boolean needs_score() {
return needsScore;
}
};
return context.factoryClazz.cast(factory);
} else {
// Check we ourselves are not being called by unprivileged code.
SpecialPermission.check();
// Create our loader (which loads compiled code with no permissions).
final Loader loader = AccessController.doPrivileged(new PrivilegedAction<Loader>() {
@Override
public Loader run() {
return compiler.createLoader(getClass().getClassLoader());
}
});
MainMethodReserved reserved = new MainMethodReserved();
compile(contextsToCompilers.get(context), loader, reserved, scriptName, scriptSource, params);
if (context.statefulFactoryClazz != null) {
return generateFactory(loader, context, reserved, generateStatefulFactory(loader, context, reserved));
} else {
return generateFactory(loader, context, reserved, WriterConstants.CLASS_TYPE);
}
}
}
/**
* Generates a stateful factory class that will return script instances. Acts as a middle man between
* the {@link ScriptContext#factoryClazz} and the {@link ScriptContext#instanceClazz} when used so that
* the stateless factory can be used for caching and the stateful factory can act as a cache for new
* script instances. Uses the newInstance method from a {@link ScriptContext#statefulFactoryClazz} to
* define the factory method to create new instances of the {@link ScriptContext#instanceClazz}.
* @param loader The {@link ClassLoader} that is used to define the factory class and script class.
* @param context The {@link ScriptContext}'s semantics are used to define the factory class.
* @param <T> The factory class.
* @return A factory class that will return script instances.
*/
private <T> Type generateStatefulFactory(Loader loader, ScriptContext<T> context, MainMethodReserved reserved) {
int classFrames = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS;
int classAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL;
String interfaceBase = Type.getType(context.statefulFactoryClazz).getInternalName();
String className = interfaceBase + "$StatefulFactory";
String classInterfaces[] = new String[] { interfaceBase };
ClassWriter writer = new ClassWriter(classFrames);
writer.visit(WriterConstants.CLASS_VERSION, classAccess, className, null, OBJECT_TYPE.getInternalName(), classInterfaces);
Method newFactory = null;
for (Method method : context.factoryClazz.getMethods()) {
if ("newFactory".equals(method.getName())) {
newFactory = method;
break;
}
}
for (int count = 0; count < newFactory.getParameterTypes().length; ++count) {
writer.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "$arg" + count,
Type.getType(newFactory.getParameterTypes()[count]).getDescriptor(), null, null).visitEnd();
}
org.objectweb.asm.commons.Method base =
new org.objectweb.asm.commons.Method("<init>", MethodType.methodType(void.class).toMethodDescriptorString());
org.objectweb.asm.commons.Method init = new org.objectweb.asm.commons.Method("<init>",
MethodType.methodType(void.class, newFactory.getParameterTypes()).toMethodDescriptorString());
GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ASM5, init,
writer.visitMethod(Opcodes.ACC_PUBLIC, init.getName(), init.getDescriptor(), null, null));
constructor.visitCode();
constructor.loadThis();
constructor.invokeConstructor(OBJECT_TYPE, base);
for (int count = 0; count < newFactory.getParameterTypes().length; ++count) {
constructor.loadThis();
constructor.loadArg(count);
constructor.putField(Type.getType(className), "$arg" + count, Type.getType(newFactory.getParameterTypes()[count]));
}
constructor.returnValue();
constructor.endMethod();
Method newInstance = null;
for (Method method : context.statefulFactoryClazz.getMethods()) {
if ("newInstance".equals(method.getName())) {
newInstance = method;
break;
}
}
org.objectweb.asm.commons.Method instance = new org.objectweb.asm.commons.Method(newInstance.getName(),
MethodType.methodType(newInstance.getReturnType(), newInstance.getParameterTypes()).toMethodDescriptorString());
List<Class<?>> parameters = new ArrayList<>(Arrays.asList(newFactory.getParameterTypes()));
parameters.addAll(Arrays.asList(newInstance.getParameterTypes()));
org.objectweb.asm.commons.Method constru = new org.objectweb.asm.commons.Method("<init>",
MethodType.methodType(void.class, parameters.toArray(new Class<?>[] {})).toMethodDescriptorString());
GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ASM5, instance,
writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL,
instance.getName(), instance.getDescriptor(), null, null));
adapter.visitCode();
adapter.newInstance(WriterConstants.CLASS_TYPE);
adapter.dup();
for (int count = 0; count < newFactory.getParameterTypes().length; ++count) {
adapter.loadThis();
adapter.getField(Type.getType(className), "$arg" + count, Type.getType(newFactory.getParameterTypes()[count]));
}
adapter.loadArgs();
adapter.invokeConstructor(WriterConstants.CLASS_TYPE, constru);
adapter.returnValue();
adapter.endMethod();
writeNeedsMethods(context.statefulFactoryClazz, writer, reserved);
writer.visitEnd();
loader.defineFactory(className.replace('/', '.'), writer.toByteArray());
return Type.getType(className);
}
/**
* Generates a factory class that will return script instances or stateful factories.
* Uses the newInstance method from a {@link ScriptContext#factoryClazz} to define the factory method
* to create new instances of the {@link ScriptContext#instanceClazz} or uses the newFactory method
* to create new factories of the {@link ScriptContext#statefulFactoryClazz}.
* @param loader The {@link ClassLoader} that is used to define the factory class and script class.
* @param context The {@link ScriptContext}'s semantics are used to define the factory class.
* @param classType The type to be instaniated in the newFactory or newInstance method. Depends
* on whether a {@link ScriptContext#statefulFactoryClazz} is specified.
* @param <T> The factory class.
* @return A factory class that will return script instances.
*/
private <T> T generateFactory(Loader loader, ScriptContext<T> context, MainMethodReserved reserved, Type classType) {
int classFrames = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS;
int classAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER| Opcodes.ACC_FINAL;
String interfaceBase = Type.getType(context.factoryClazz).getInternalName();
String className = interfaceBase + "$Factory";
String classInterfaces[] = new String[] { interfaceBase };
ClassWriter writer = new ClassWriter(classFrames);
writer.visit(WriterConstants.CLASS_VERSION, classAccess, className, null, OBJECT_TYPE.getInternalName(), classInterfaces);
org.objectweb.asm.commons.Method init =
new org.objectweb.asm.commons.Method("<init>", MethodType.methodType(void.class).toMethodDescriptorString());
GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ASM5, init,
writer.visitMethod(Opcodes.ACC_PUBLIC, init.getName(), init.getDescriptor(), null, null));
constructor.visitCode();
constructor.loadThis();
constructor.invokeConstructor(OBJECT_TYPE, init);
constructor.returnValue();
constructor.endMethod();
Method reflect = null;
for (Method method : context.factoryClazz.getMethods()) {
if ("newInstance".equals(method.getName())) {
reflect = method;
break;
} else if ("newFactory".equals(method.getName())) {
reflect = method;
break;
}
}
org.objectweb.asm.commons.Method instance = new org.objectweb.asm.commons.Method(reflect.getName(),
MethodType.methodType(reflect.getReturnType(), reflect.getParameterTypes()).toMethodDescriptorString());
org.objectweb.asm.commons.Method constru = new org.objectweb.asm.commons.Method("<init>",
MethodType.methodType(void.class, reflect.getParameterTypes()).toMethodDescriptorString());
GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ASM5, instance,
writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL,
instance.getName(), instance.getDescriptor(), null, null));
adapter.visitCode();
adapter.newInstance(classType);
adapter.dup();
adapter.loadArgs();
adapter.invokeConstructor(classType, constru);
adapter.returnValue();
adapter.endMethod();
writeNeedsMethods(context.factoryClazz, writer, reserved);
writer.visitEnd();
Class<?> factory = loader.defineFactory(className.replace('/', '.'), writer.toByteArray());
try {
return context.factoryClazz.cast(factory.getConstructor().newInstance());
} catch (Exception exception) { // Catch everything to let the user know this is something caused internally.
throw new IllegalStateException(
"An internal error occurred attempting to define the factory class [" + className + "].", exception);
}
}
private void writeNeedsMethods(Class<?> clazz, ClassWriter writer, MainMethodReserved reserved) {
for (Method method : clazz.getMethods()) {
if (method.getName().startsWith("needs") &&
method.getReturnType().equals(boolean.class) && method.getParameterTypes().length == 0) {
String name = method.getName();
name = name.substring(5);
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
org.objectweb.asm.commons.Method needs = new org.objectweb.asm.commons.Method(method.getName(),
MethodType.methodType(boolean.class).toMethodDescriptorString());
GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ASM5, needs,
writer.visitMethod(Opcodes.ACC_PUBLIC, needs.getName(), needs.getDescriptor(), null, null));
adapter.visitCode();
adapter.push(reserved.getUsedVariables().contains(name));
adapter.returnValue();
adapter.endMethod();
}
}
}
Constructor<?> compile(Compiler compiler, String scriptName, String source, Map<String, String> params) {
final CompilerSettings compilerSettings = buildCompilerSettings(params);
// Check we ourselves are not being called by unprivileged code.
SpecialPermission.check();
// Create our loader (which loads compiled code with no permissions).
final Loader loader = AccessController.doPrivileged(new PrivilegedAction<Loader>() {
@Override
public Loader run() {
return compiler.createLoader(getClass().getClassLoader());
}
});
try {
// Drop all permissions to actually compile the code itself.
return AccessController.doPrivileged(new PrivilegedAction<Constructor<?>>() {
@Override
public Constructor<?> run() {
String name = scriptName == null ? source : scriptName;
Constructor<?> constructor = compiler.compile(loader, new MainMethodReserved(), name, source, compilerSettings);
try {
return constructor;
} catch (Exception exception) { // Catch everything to let the user know this is something caused internally.
throw new IllegalStateException(
"An internal error occurred attempting to define the script [" + name + "].", exception);
}
}
}, COMPILATION_CONTEXT);
// Note that it is safe to catch any of the following errors since Painless is stateless.
} catch (OutOfMemoryError | StackOverflowError | VerifyError | Exception e) {
throw convertToScriptException(source, e);
}
}
void compile(Compiler compiler, Loader loader, MainMethodReserved reserved,
String scriptName, String source, Map<String, String> params) {
final CompilerSettings compilerSettings = buildCompilerSettings(params);
try {
// Drop all permissions to actually compile the code itself.
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
String name = scriptName == null ? source : scriptName;
compiler.compile(loader, reserved, name, source, compilerSettings);
return null;
}
}, COMPILATION_CONTEXT);
// Note that it is safe to catch any of the following errors since Painless is stateless.
} catch (OutOfMemoryError | StackOverflowError | VerifyError | Exception e) {
throw convertToScriptException(source, e);
}
}
private CompilerSettings buildCompilerSettings(Map<String, String> params) {
CompilerSettings compilerSettings;
if (params.isEmpty()) {
// Use the default settings.
compilerSettings = defaultCompilerSettings;
} else {
// Use custom settings specified by params.
compilerSettings = new CompilerSettings();
// Except regexes enabled - this is a node level setting and can't be changed in the request.
compilerSettings.setRegexesEnabled(defaultCompilerSettings.areRegexesEnabled());
Map<String, String> copy = new HashMap<>(params);
String value = copy.remove(CompilerSettings.MAX_LOOP_COUNTER);
if (value != null) {
compilerSettings.setMaxLoopCounter(Integer.parseInt(value));
}
value = copy.remove(CompilerSettings.PICKY);
if (value != null) {
compilerSettings.setPicky(Boolean.parseBoolean(value));
}
value = copy.remove(CompilerSettings.INITIAL_CALL_SITE_DEPTH);
if (value != null) {
compilerSettings.setInitialCallSiteDepth(Integer.parseInt(value));
}
value = copy.remove(CompilerSettings.REGEX_ENABLED.getKey());
if (value != null) {
throw new IllegalArgumentException("[painless.regex.enabled] can only be set on node startup.");
}
if (!copy.isEmpty()) {
throw new IllegalArgumentException("Unrecognized compile-time parameter(s): " + copy);
}
}
return compilerSettings;
}
private ScriptException convertToScriptException(String scriptSource, Throwable t) {
// create a script stack: this is just the script portion
List<String> scriptStack = new ArrayList<>();
for (StackTraceElement element : t.getStackTrace()) {
if (WriterConstants.CLASS_NAME.equals(element.getClassName())) {
// found the script portion
int offset = element.getLineNumber();
if (offset == -1) {
scriptStack.add("<<< unknown portion of script >>>");
} else {
offset--; // offset is 1 based, line numbers must be!
int startOffset = getPreviousStatement(offset);
int endOffset = getNextStatement(scriptSource, offset);
StringBuilder snippet = new StringBuilder();
if (startOffset > 0) {
snippet.append("... ");
}
snippet.append(scriptSource.substring(startOffset, endOffset));
if (endOffset < scriptSource.length()) {
snippet.append(" ...");
}
scriptStack.add(snippet.toString());
StringBuilder pointer = new StringBuilder();
if (startOffset > 0) {
pointer.append(" ");
}
for (int i = startOffset; i < offset; i++) {
pointer.append(' ');
}
pointer.append("^---- HERE");
scriptStack.add(pointer.toString());
}
break;
}
}
throw new ScriptException("compile error", t, scriptStack, scriptSource, PainlessScriptEngine.NAME);
}
// very simple heuristic: +/- 25 chars. can be improved later.
private int getPreviousStatement(int offset) {
return Math.max(0, offset - 25);
}
private int getNextStatement(String scriptSource, int offset) {
return Math.min(scriptSource.length(), offset + 25);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright 2009 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.gora.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.reflect.ReflectData;
import org.apache.avro.util.Utf8;
import org.apache.gora.avro.PersistentDatumReader;
import org.apache.gora.avro.PersistentDatumWriter;
import org.apache.hadoop.io.WritableUtils;
// This code is copied almost directly from HBase project's Bytes class.
/**
* Utility class that handles byte arrays, conversions to/from other types.
*
*/
public class ByteUtils {
/**
* Size of boolean in bytes
*/
public static final int SIZEOF_BOOLEAN = Byte.SIZE/Byte.SIZE;
/**
* Size of byte in bytes
*/
public static final int SIZEOF_BYTE = SIZEOF_BOOLEAN;
/**
* Size of char in bytes
*/
public static final int SIZEOF_CHAR = Character.SIZE/Byte.SIZE;
/**
* Size of double in bytes
*/
public static final int SIZEOF_DOUBLE = Double.SIZE/Byte.SIZE;
/**
* Size of float in bytes
*/
public static final int SIZEOF_FLOAT = Float.SIZE/Byte.SIZE;
/**
* Size of int in bytes
*/
public static final int SIZEOF_INT = Integer.SIZE/Byte.SIZE;
/**
* Size of long in bytes
*/
public static final int SIZEOF_LONG = Long.SIZE/Byte.SIZE;
/**
* Size of short in bytes
*/
public static final int SIZEOF_SHORT = Short.SIZE/Byte.SIZE;
/**
* Put bytes at the specified byte array position.
* @param tgtBytes the byte array
* @param tgtOffset position in the array
* @param srcBytes byte to write out
* @param srcOffset
* @param srcLength
* @return incremented offset
*/
public static int putBytes(byte[] tgtBytes, int tgtOffset, byte[] srcBytes,
int srcOffset, int srcLength) {
System.arraycopy(srcBytes, srcOffset, tgtBytes, tgtOffset, srcLength);
return tgtOffset + srcLength;
}
/**
* Write a single byte out to the specified byte array position.
* @param bytes the byte array
* @param offset position in the array
* @param b byte to write out
* @return incremented offset
*/
public static int putByte(byte[] bytes, int offset, byte b) {
bytes[offset] = b;
return offset + 1;
}
/**
* Returns a new byte array, copied from the passed ByteBuffer.
* @param bb A ByteBuffer
* @return the byte array
*/
public static byte[] toBytes(ByteBuffer bb) {
int length = bb.limit();
byte [] result = new byte[length];
System.arraycopy(bb.array(), bb.arrayOffset(), result, 0, length);
return result;
}
/**
* @param b Presumed UTF-8 encoded byte array.
* @return String made from <code>b</code>
*/
public static String toString(final byte [] b) {
if (b == null) {
return null;
}
return toString(b, 0, b.length);
}
public static String toString(final byte [] b1,
String sep,
final byte [] b2) {
return toString(b1, 0, b1.length) + sep + toString(b2, 0, b2.length);
}
/**
* @param b Presumed UTF-8 encoded byte array.
* @param off
* @param len
* @return String made from <code>b</code>
*/
public static String toString(final byte [] b, int off, int len) {
if(b == null) {
return null;
}
if(len == 0) {
return "";
}
String result = null;
try {
result = new String(b, off, len, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* Converts a string to a UTF-8 byte array.
* @param s
* @return the byte array
*/
public static byte[] toBytes(String s) {
if (s == null) {
throw new IllegalArgumentException("string cannot be null");
}
byte [] result = null;
try {
result = s.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* Convert a boolean to a byte array.
* @param b
* @return <code>b</code> encoded in a byte array.
*/
public static byte [] toBytes(final boolean b) {
byte [] bb = new byte[1];
bb[0] = b? (byte)-1: (byte)0;
return bb;
}
/**
* @param b
* @return True or false.
*/
public static boolean toBoolean(final byte [] b) {
if (b == null || b.length > 1) {
throw new IllegalArgumentException("Array is wrong size");
}
return b[0] != (byte)0;
}
/**
* Convert a long value to a byte array
* @param val
* @return the byte array
*/
public static byte[] toBytes(long val) {
byte [] b = new byte[8];
for(int i=7;i>0;i--) {
b[i] = (byte)(val);
val >>>= 8;
}
b[0] = (byte)(val);
return b;
}
/**
* Converts a byte array to a long value
* @param bytes
* @return the long value
*/
public static long toLong(byte[] bytes) {
return toLong(bytes, 0);
}
/**
* Converts a byte array to a long value
* @param bytes
* @param offset
* @return the long value
*/
public static long toLong(byte[] bytes, int offset) {
return toLong(bytes, offset, SIZEOF_LONG);
}
/**
* Converts a byte array to a long value
* @param bytes
* @param offset
* @param length
* @return the long value
*/
public static long toLong(byte[] bytes, int offset, final int length) {
if (bytes == null || length != SIZEOF_LONG ||
(offset + length > bytes.length)) {
return -1L;
}
long l = 0;
for(int i = offset; i < (offset + length); i++) {
l <<= 8;
l ^= (long)bytes[i] & 0xFF;
}
return l;
}
/**
* Presumes float encoded as IEEE 754 floating-point "single format"
* @param bytes
* @return Float made from passed byte array.
*/
public static float toFloat(byte [] bytes) {
return toFloat(bytes, 0);
}
/**
* Presumes float encoded as IEEE 754 floating-point "single format"
* @param bytes
* @param offset
* @return Float made from passed byte array.
*/
public static float toFloat(byte [] bytes, int offset) {
int i = toInt(bytes, offset);
return Float.intBitsToFloat(i);
}
/**
* @param f
* @return the float represented as byte []
*/
public static byte [] toBytes(final float f) {
// Encode it as int
int i = Float.floatToRawIntBits(f);
return toBytes(i);
}
/**
* @param bytes
* @return Return double made from passed bytes.
*/
public static double toDouble(final byte [] bytes) {
return toDouble(bytes, 0);
}
/**
* @param bytes
* @param offset
* @return Return double made from passed bytes.
*/
public static double toDouble(final byte [] bytes, final int offset) {
long l = toLong(bytes, offset);
return Double.longBitsToDouble(l);
}
/**
* @param d
* @return the double represented as byte []
*/
public static byte [] toBytes(final double d) {
// Encode it as a long
long l = Double.doubleToRawLongBits(d);
return toBytes(l);
}
/**
* Convert an int value to a byte array
* @param val
* @return the byte array
*/
public static byte[] toBytes(int val) {
byte [] b = new byte[4];
for(int i = 3; i > 0; i--) {
b[i] = (byte)(val);
val >>>= 8;
}
b[0] = (byte)(val);
return b;
}
/**
* Converts a byte array to an int value
* @param bytes
* @return the int value
*/
public static int toInt(byte[] bytes) {
return toInt(bytes, 0);
}
/**
* Converts a byte array to an int value
* @param bytes
* @param offset
* @return the int value
*/
public static int toInt(byte[] bytes, int offset) {
return toInt(bytes, offset, SIZEOF_INT);
}
/**
* Converts a byte array to an int value
* @param bytes
* @param offset
* @param length
* @return the int value
*/
public static int toInt(byte[] bytes, int offset, final int length) {
if (bytes == null || length != SIZEOF_INT ||
(offset + length > bytes.length)) {
return -1;
}
int n = 0;
for(int i = offset; i < (offset + length); i++) {
n <<= 8;
n ^= bytes[i] & 0xFF;
}
return n;
}
/**
* Convert a short value to a byte array
* @param val
* @return the byte array
*/
public static byte[] toBytes(short val) {
byte[] b = new byte[SIZEOF_SHORT];
b[1] = (byte)(val);
val >>= 8;
b[0] = (byte)(val);
return b;
}
/**
* Converts a byte array to a short value
* @param bytes
* @return the short value
*/
public static short toShort(byte[] bytes) {
return toShort(bytes, 0);
}
/**
* Converts a byte array to a short value
* @param bytes
* @param offset
* @return the short value
*/
public static short toShort(byte[] bytes, int offset) {
return toShort(bytes, offset, SIZEOF_SHORT);
}
/**
* Converts a byte array to a short value
* @param bytes
* @param offset
* @param length
* @return the short value
*/
public static short toShort(byte[] bytes, int offset, final int length) {
if (bytes == null || length != SIZEOF_SHORT ||
(offset + length > bytes.length)) {
return -1;
}
short n = 0;
n ^= bytes[offset] & 0xFF;
n <<= 8;
n ^= bytes[offset+1] & 0xFF;
return n;
}
/**
* Convert a char value to a byte array
*
* @param val
* @return the byte array
*/
public static byte[] toBytes(char val) {
byte[] b = new byte[SIZEOF_CHAR];
b[1] = (byte) (val);
val >>= 8;
b[0] = (byte) (val);
return b;
}
/**
* Converts a byte array to a char value
*
* @param bytes
* @return the char value
*/
public static char toChar(byte[] bytes) {
return toChar(bytes, 0);
}
/**
* Converts a byte array to a char value
*
* @param bytes
* @param offset
* @return the char value
*/
public static char toChar(byte[] bytes, int offset) {
return toChar(bytes, offset, SIZEOF_CHAR);
}
/**
* Converts a byte array to a char value
*
* @param bytes
* @param offset
* @param length
* @return the char value
*/
public static char toChar(byte[] bytes, int offset, final int length) {
if (bytes == null || length != SIZEOF_CHAR ||
(offset + length > bytes.length)) {
return (char)-1;
}
char n = 0;
n ^= bytes[offset] & 0xFF;
n <<= 8;
n ^= bytes[offset + 1] & 0xFF;
return n;
}
/**
* Converts a byte array to a char array value
*
* @param bytes
* @return the char value
*/
public static char[] toChars(byte[] bytes) {
return toChars(bytes, 0, bytes.length);
}
/**
* Converts a byte array to a char array value
*
* @param bytes
* @param offset
* @return the char value
*/
public static char[] toChars(byte[] bytes, int offset) {
return toChars(bytes, offset, bytes.length-offset);
}
/**
* Converts a byte array to a char array value
*
* @param bytes
* @param offset
* @param length
* @return the char value
*/
public static char[] toChars(byte[] bytes, int offset, final int length) {
int max = offset + length;
if (bytes == null || (max > bytes.length) || length %2 ==1) {
return null;
}
char[] chars = new char[length / 2];
for (int i = 0, j = offset; i < chars.length && j < max; i++, j += 2) {
char c = 0;
c ^= bytes[j] & 0xFF;
c <<= 8;
c ^= bytes[j + 1] & 0xFF;
chars[i] = c;
}
return chars;
}
/**
* @param vint Integer to make a vint of.
* @return Vint as bytes array.
*/
public static byte [] vintToBytes(final long vint) {
long i = vint;
int size = WritableUtils.getVIntSize(i);
byte [] result = new byte[size];
int offset = 0;
if (i >= -112 && i <= 127) {
result[offset] = ((byte)i);
return result;
}
int len = -112;
if (i < 0) {
i ^= -1L; // take one's complement'
len = -120;
}
long tmp = i;
while (tmp != 0) {
tmp = tmp >> 8;
len--;
}
result[offset++] = (byte)len;
len = (len < -120) ? -(len + 120) : -(len + 112);
for (int idx = len; idx != 0; idx--) {
int shiftbits = (idx - 1) * 8;
long mask = 0xFFL << shiftbits;
result[offset++] = (byte)((i & mask) >> shiftbits);
}
return result;
}
/**
* @param buffer
* @return vint bytes as an integer.
*/
public static long bytesToVlong(final byte [] buffer) {
int offset = 0;
byte firstByte = buffer[offset++];
int len = WritableUtils.decodeVIntSize(firstByte);
if (len == 1) {
return firstByte;
}
long i = 0;
for (int idx = 0; idx < len-1; idx++) {
byte b = buffer[offset++];
i = i << 8;
i = i | (b & 0xFF);
}
return (WritableUtils.isNegativeVInt(firstByte) ? (i ^ -1L) : i);
}
/**
* @param buffer
* @return vint bytes as an integer.
*/
public static int bytesToVint(final byte [] buffer) {
int offset = 0;
byte firstByte = buffer[offset++];
int len = WritableUtils.decodeVIntSize(firstByte);
if (len == 1) {
return firstByte;
}
long i = 0;
for (int idx = 0; idx < len-1; idx++) {
byte b = buffer[offset++];
i = i << 8;
i = i | (b & 0xFF);
}
return (int)(WritableUtils.isNegativeVInt(firstByte) ? (i ^ -1L) : i);
}
/**
* Reads a zero-compressed encoded long from input stream and returns it.
* @param buffer Binary array
* @param offset Offset into array at which vint begins.
* @throws java.io.IOException
* @return deserialized long from stream.
*/
public static long readVLong(final byte [] buffer, final int offset)
throws IOException {
byte firstByte = buffer[offset];
int len = WritableUtils.decodeVIntSize(firstByte);
if (len == 1) {
return firstByte;
}
long i = 0;
for (int idx = 0; idx < len-1; idx++) {
byte b = buffer[offset + 1 + idx];
i = i << 8;
i = i | (b & 0xFF);
}
return (WritableUtils.isNegativeVInt(firstByte) ? (i ^ -1L) : i);
}
/**
* @param left
* @param right
* @return 0 if equal, < 0 if left is less than right, etc.
*/
public static int compareTo(final byte [] left, final byte [] right) {
return compareTo(left, 0, left.length, right, 0, right.length);
}
/**
* @param b1
* @param b2
* @param s1 Where to start comparing in the left buffer
* @param s2 Where to start comparing in the right buffer
* @param l1 How much to compare from the left buffer
* @param l2 How much to compare from the right buffer
* @return 0 if equal, < 0 if left is less than right, etc.
*/
public static int compareTo(byte[] b1, int s1, int l1,
byte[] b2, int s2, int l2) {
// Bring WritableComparator code local
int end1 = s1 + l1;
int end2 = s2 + l2;
for (int i = s1, j = s2; i < end1 && j < end2; i++, j++) {
int a = (b1[i] & 0xff);
int b = (b2[j] & 0xff);
if (a != b) {
return a - b;
}
}
return l1 - l2;
}
/**
* @param left
* @param right
* @return True if equal
*/
public static boolean equals(final byte [] left, final byte [] right) {
// Could use Arrays.equals?
return left == null && right == null? true:
(left == null || right == null || (left.length != right.length))? false:
compareTo(left, right) == 0;
}
@SuppressWarnings("unchecked")
public static Object fromBytes( byte[] val, Schema schema
, PersistentDatumReader<?> datumReader, Object object)
throws IOException {
Type type = schema.getType();
switch (type) {
case ENUM:
String symbol = schema.getEnumSymbols().get(val[0]);
return Enum.valueOf(ReflectData.get().getClass(schema), symbol);
case STRING: return new Utf8(toString(val));
case BYTES: return ByteBuffer.wrap(val);
case INT: return bytesToVint(val);
case LONG: return bytesToVlong(val);
case FLOAT: return toFloat(val);
case DOUBLE: return toDouble(val);
case BOOLEAN: return val[0] != 0;
case RECORD: //fall
case MAP:
case ARRAY: return IOUtils.deserialize(val, datumReader, schema, object);
default: throw new RuntimeException("Unknown type: "+type);
}
}
public static byte[] toBytes(Object o, Schema schema
, PersistentDatumWriter<?> datumWriter)
throws IOException {
Type type = schema.getType();
switch (type) {
case STRING: return toBytes(((Utf8)o).toString()); // TODO: maybe ((Utf8)o).getBytes(); ?
case BYTES: return ((ByteBuffer)o).array();
case INT: return vintToBytes((Integer)o);
case LONG: return vintToBytes((Long)o);
case FLOAT: return toBytes((Float)o);
case DOUBLE: return toBytes((Double)o);
case BOOLEAN: return (Boolean)o ? new byte[] {1} : new byte[] {0};
case ENUM: return new byte[] { (byte)((Enum<?>) o).ordinal() };
case RECORD: //fall
case MAP:
case ARRAY: return IOUtils.serialize(datumWriter, schema, o);
default: throw new RuntimeException("Unknown type: "+type);
}
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.compiler.util;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInsight.daemon.impl.AnnotationHolderImpl;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.compiler.options.ValidationConfiguration;
import com.intellij.lang.ExternalLanguageAnnotators;
import com.intellij.lang.StdLanguages;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.AnnotationSession;
import com.intellij.lang.annotation.ExternalAnnotator;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.compiler.options.ExcludesConfiguration;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.xml.XmlFile;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.hash.LinkedHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.DataInput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @author peter
*/
public class InspectionValidatorWrapper implements Validator {
private final InspectionValidator myValidator;
private final PsiManager myPsiManager;
private final CompilerManager myCompilerManager;
private final InspectionManager myInspectionManager;
private final InspectionProjectProfileManager myProfileManager;
private final PsiDocumentManager myPsiDocumentManager;
private static final ThreadLocal<Boolean> ourCompilationThreads = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return Boolean.FALSE;
}
};
public InspectionValidatorWrapper(final CompilerManager compilerManager, final InspectionManager inspectionManager,
final InspectionProjectProfileManager profileManager, final PsiDocumentManager psiDocumentManager,
final PsiManager psiManager, final InspectionValidator validator) {
myCompilerManager = compilerManager;
myInspectionManager = inspectionManager;
myProfileManager = profileManager;
myPsiDocumentManager = psiDocumentManager;
myPsiManager = psiManager;
myValidator = validator;
}
public static boolean isCompilationThread() {
return ourCompilationThreads.get().booleanValue();
}
private static List<ProblemDescriptor> runInspectionOnFile(@NotNull PsiFile file,
@NotNull LocalInspectionTool inspectionTool) {
InspectionManager inspectionManager = InspectionManager.getInstance(file.getProject());
GlobalInspectionContext context = inspectionManager.createNewGlobalContext(false);
return InspectionEngine.runInspectionOnFile(file, new LocalInspectionToolWrapper(inspectionTool), context);
}
private class MyValidatorProcessingItem implements ProcessingItem {
private final VirtualFile myVirtualFile;
private final PsiManager myPsiManager;
private PsiElementsValidityState myValidityState;
public MyValidatorProcessingItem(@NotNull final PsiFile psiFile) {
myVirtualFile = psiFile.getVirtualFile();
myPsiManager = psiFile.getManager();
}
@Override
@NotNull
public VirtualFile getFile() {
return myVirtualFile;
}
@Override
@Nullable
public ValidityState getValidityState() {
if (myValidityState == null) {
myValidityState = computeValidityState();
}
return myValidityState;
}
private PsiElementsValidityState computeValidityState() {
final PsiElementsValidityState state = new PsiElementsValidityState();
final PsiFile psiFile = getPsiFile();
if (psiFile != null) {
for (PsiElement psiElement : myValidator.getDependencies(psiFile)) {
state.addDependency(psiElement);
}
}
return state;
}
@Nullable
public PsiFile getPsiFile() {
return myVirtualFile.isValid() ? myPsiManager.findFile(myVirtualFile) : null;
}
}
@Override
@NotNull
public ProcessingItem[] getProcessingItems(final CompileContext context) {
final Project project = context.getProject();
if (project.isDefault() || !ValidationConfiguration.shouldValidate(this, context)) {
return ProcessingItem.EMPTY_ARRAY;
}
final ExcludesConfiguration excludesConfiguration = ValidationConfiguration.getExcludedEntriesConfiguration(project);
final List<ProcessingItem> items =
DumbService.getInstance(project).runReadActionInSmartMode(new Computable<List<ProcessingItem>>() {
@Override
public List<ProcessingItem> compute() {
final CompileScope compileScope = context.getCompileScope();
if (!myValidator.isAvailableOnScope(compileScope)) return null;
final ArrayList<ProcessingItem> items = new ArrayList<ProcessingItem>();
final Processor<VirtualFile> processor = new Processor<VirtualFile>() {
@Override
public boolean process(VirtualFile file) {
if (!file.isValid()) {
return true;
}
if (myCompilerManager.isExcludedFromCompilation(file) ||
excludesConfiguration.isExcluded(file)) {
return true;
}
final Module module = context.getModuleByFile(file);
if (module != null) {
final PsiFile psiFile = myPsiManager.findFile(file);
if (psiFile != null) {
items.add(new MyValidatorProcessingItem(psiFile));
}
}
return true;
}
};
ContainerUtil.process(myValidator.getFilesToProcess(myPsiManager.getProject(), context), processor);
return items;
}
});
if (items == null) return ProcessingItem.EMPTY_ARRAY;
return items.toArray(new ProcessingItem[items.size()]);
}
@Override
public ProcessingItem[] process(final CompileContext context, final ProcessingItem[] items) {
context.getProgressIndicator().setText(myValidator.getProgressIndicatorText());
final List<ProcessingItem> processedItems = new ArrayList<ProcessingItem>();
final List<LocalInspectionTool> inspections = new ArrayList<LocalInspectionTool>();
for (final Class aClass : myValidator.getInspectionToolClasses(context)) {
try {
inspections.add((LocalInspectionTool)aClass.newInstance());
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new Error(e);
}
}
for (int i = 0; i < items.length; i++) {
final MyValidatorProcessingItem item = (MyValidatorProcessingItem)items[i];
context.getProgressIndicator().checkCanceled();
context.getProgressIndicator().setFraction((double)i / items.length);
try {
ourCompilationThreads.set(Boolean.TRUE);
if (checkFile(inspections, item, context)) {
processedItems.add(item);
}
}
finally {
ourCompilationThreads.set(Boolean.FALSE);
}
}
return processedItems.toArray(new ProcessingItem[processedItems.size()]);
}
private boolean checkFile(List<LocalInspectionTool> inspections, final MyValidatorProcessingItem item, final CompileContext context) {
boolean hasErrors = false;
if (!checkUnderReadAction(item, context, new Computable<Map<ProblemDescriptor, HighlightDisplayLevel>>() {
@Override
public Map<ProblemDescriptor, HighlightDisplayLevel> compute() {
return myValidator.checkAdditionally(item.getPsiFile());
}
})) {
hasErrors = true;
}
if (!checkUnderReadAction(item, context, new Computable<Map<ProblemDescriptor, HighlightDisplayLevel>>() {
@Override
public Map<ProblemDescriptor, HighlightDisplayLevel> compute() {
final PsiFile file = item.getPsiFile();
if (file instanceof XmlFile) {
return runXmlFileSchemaValidation((XmlFile)file);
}
return Collections.emptyMap();
}
})) {
hasErrors = true;
}
final InspectionProfile inspectionProfile = myProfileManager.getInspectionProfile();
for (final LocalInspectionTool inspectionTool : inspections) {
if (!checkUnderReadAction(item, context, new Computable<Map<ProblemDescriptor, HighlightDisplayLevel>>() {
@Override
public Map<ProblemDescriptor, HighlightDisplayLevel> compute() {
final PsiFile file = item.getPsiFile();
if (file != null && getHighlightDisplayLevel(inspectionTool, inspectionProfile, file) != HighlightDisplayLevel.DO_NOT_SHOW) {
return runInspectionTool(file, inspectionTool, getHighlightDisplayLevel(inspectionTool, inspectionProfile, file)
);
}
return Collections.emptyMap();
}
})) {
hasErrors = true;
}
}
return !hasErrors;
}
private boolean checkUnderReadAction(final MyValidatorProcessingItem item, final CompileContext context, final Computable<Map<ProblemDescriptor, HighlightDisplayLevel>> runnable) {
return DumbService.getInstance(context.getProject()).runReadActionInSmartMode(new Computable<Boolean>() {
@Override
public Boolean compute() {
final PsiFile file = item.getPsiFile();
if (file == null) return false;
final Document document = myPsiDocumentManager.getCachedDocument(file);
if (document != null && myPsiDocumentManager.isUncommited(document)) {
final String url = file.getViewProvider().getVirtualFile().getUrl();
context.addMessage(CompilerMessageCategory.WARNING, CompilerBundle.message("warning.text.file.has.been.changed"), url, -1, -1);
return false;
}
if (reportProblems(context, runnable.compute())) return false;
return true;
}
});
}
private boolean reportProblems(CompileContext context, Map<ProblemDescriptor, HighlightDisplayLevel> problemsMap) {
if (problemsMap.isEmpty()) {
return false;
}
boolean errorsReported = false;
for (Map.Entry<ProblemDescriptor, HighlightDisplayLevel> entry : problemsMap.entrySet()) {
ProblemDescriptor problemDescriptor = entry.getKey();
final PsiElement element = problemDescriptor.getPsiElement();
final PsiFile psiFile = element.getContainingFile();
if (psiFile == null) continue;
final VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null) continue;
final CompilerMessageCategory category = myValidator.getCategoryByHighlightDisplayLevel(entry.getValue(), virtualFile, context);
final Document document = myPsiDocumentManager.getDocument(psiFile);
final int offset = problemDescriptor.getStartElement().getTextOffset();
assert document != null;
final int line = document.getLineNumber(offset);
final int column = offset - document.getLineStartOffset(line);
context.addMessage(category, problemDescriptor.getDescriptionTemplate(), virtualFile.getUrl(), line + 1, column + 1);
if (CompilerMessageCategory.ERROR == category) {
errorsReported = true;
}
}
return errorsReported;
}
private static Map<ProblemDescriptor, HighlightDisplayLevel> runInspectionTool(final PsiFile file,
final LocalInspectionTool inspectionTool,
final HighlightDisplayLevel level) {
Map<ProblemDescriptor, HighlightDisplayLevel> problemsMap = new LinkedHashMap<ProblemDescriptor, HighlightDisplayLevel>();
for (ProblemDescriptor descriptor : runInspectionOnFile(file, inspectionTool)) {
final ProblemHighlightType highlightType = descriptor.getHighlightType();
final HighlightDisplayLevel highlightDisplayLevel;
if (highlightType == ProblemHighlightType.WEAK_WARNING) {
highlightDisplayLevel = HighlightDisplayLevel.WEAK_WARNING;
}
else if (highlightType == ProblemHighlightType.INFORMATION) {
highlightDisplayLevel = HighlightDisplayLevel.DO_NOT_SHOW;
}
else {
highlightDisplayLevel = level;
}
problemsMap.put(descriptor, highlightDisplayLevel);
}
return problemsMap;
}
private static HighlightDisplayLevel getHighlightDisplayLevel(final LocalInspectionTool inspectionTool,
final InspectionProfile inspectionProfile, PsiElement file) {
final HighlightDisplayKey key = HighlightDisplayKey.find(inspectionTool.getShortName());
return inspectionProfile.isToolEnabled(key, file) ? inspectionProfile.getErrorLevel(key, file) : HighlightDisplayLevel.DO_NOT_SHOW;
}
private Map<ProblemDescriptor, HighlightDisplayLevel> runXmlFileSchemaValidation(@NotNull XmlFile xmlFile) {
final AnnotationHolderImpl holder = new AnnotationHolderImpl(new AnnotationSession(xmlFile));
final List<ExternalAnnotator> annotators = ExternalLanguageAnnotators.allForFile(StdLanguages.XML, xmlFile);
for (ExternalAnnotator<?, ?> annotator : annotators) {
processAnnotator(xmlFile, holder, annotator);
}
if (!holder.hasAnnotations()) return Collections.emptyMap();
Map<ProblemDescriptor, HighlightDisplayLevel> problemsMap = new LinkedHashMap<ProblemDescriptor, HighlightDisplayLevel>();
for (final Annotation annotation : holder) {
final HighlightInfo info = HighlightInfo.fromAnnotation(annotation);
if (info.getSeverity() == HighlightSeverity.INFORMATION) continue;
final PsiElement startElement = xmlFile.findElementAt(info.startOffset);
final PsiElement endElement = info.startOffset == info.endOffset ? startElement : xmlFile.findElementAt(info.endOffset - 1);
if (startElement == null || endElement == null) continue;
final ProblemDescriptor descriptor =
myInspectionManager.createProblemDescriptor(startElement, endElement, info.getDescription(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
false);
final HighlightDisplayLevel level = info.getSeverity() == HighlightSeverity.ERROR? HighlightDisplayLevel.ERROR: HighlightDisplayLevel.WARNING;
problemsMap.put(descriptor, level);
}
return problemsMap;
}
private static <X, Y> void processAnnotator(@NotNull XmlFile xmlFile, AnnotationHolderImpl holder, ExternalAnnotator<X, Y> annotator) {
X initial = annotator.collectInformation(xmlFile);
if (initial != null) {
Y result = annotator.doAnnotate(initial);
if (result != null) {
annotator.apply(xmlFile, result, holder);
}
}
}
@Override
@NotNull
public String getDescription() {
return myValidator.getDescription();
}
@Override
public boolean validateConfiguration(final CompileScope scope) {
return true;
}
@Override
public ValidityState createValidityState(final DataInput in) throws IOException {
return PsiElementsValidityState.load(in);
}
}
| |
package org.ncbo.resource_access_tools.resource.ncbi.pubchem;
import gov.nih.nlm.ncbi.www.soap.eutils.esummary.DocSumType;
import gov.nih.nlm.ncbi.www.soap.eutils.esummary.ESummaryRequest;
import gov.nih.nlm.ncbi.www.soap.eutils.esummary.ESummaryResult;
import gov.nih.nlm.ncbi.www.soap.eutils.esummary.ItemType;
import org.ncbo.resource_access_tools.enumeration.ResourceType;
import org.ncbo.resource_access_tools.populate.Element;
import org.ncbo.resource_access_tools.populate.Element.BadElementStructureException;
import org.ncbo.resource_access_tools.populate.Structure;
import org.ncbo.resource_access_tools.resource.ncbi.AbstractNcbiResourceAccessTool;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
/**
* PubChemAccessTool is responsible for getting data elements for
* PubChem Compound database.
* It process records with associated MeSH terms using term "has_mesh[filter]"
* using E-Utils.
*
* @author kyadav
* @version $$
*/
public class PubChemAccessTool extends AbstractNcbiResourceAccessTool {
// Home URL of the resource
private static final String PCM_URL = "http://pubchem.ncbi.nlm.nih.gov/";
// Name of the resource
private static final String PCM_NAME = "PubChem";
// Short name of the resource
private static final String PCM_RESOURCEID = "PCM";
// Text description of the resource
private static final String PCM_DESCRIPTION = "PubChem provides information on the biological activities of small molecules. It is a component of NIH's Molecular Libraries Roadmap Initiative.";
// URL that points to the logo of the resource
private static final String PCM_LOGO = "http://pubchem.ncbi.nlm.nih.gov/images/pubchemlogob.gif";
// Basic URL that points to an element when concatenated with an local element ID
private static final String PCM_ELT_URL = "http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=";
//PubChem Compound Database name for E-Utils.
private static final String PCM_EUTILS_DB = "pccompound";
//Query terms for E-Utils.This term get records with associated MeSH terms.
private static final String PCM_EUTILS_TERM = "has_mesh[filter]";
// The set of context names
private static final String[] PCM_ITEMKEYS = {"MeSHHeadingList", "MeSHTermList", "PharmActionList", "SynonymList"};
// Weight associated to a context
private static final Double[] PCM_WEIGHTS = {1.0, 1.0, 0.8, 0.9};
// OntoID associated for reported annotations(MSH ontology : 1351)
private static final String[] PCM_ONTOIDS = {"1351", "1351", Structure.FOR_CONCEPT_RECOGNITION, Structure.FOR_CONCEPT_RECOGNITION};
// Structure for GEO Access tool
private static final Structure PCM_STRUCTURE = new Structure(PCM_ITEMKEYS, PCM_RESOURCEID, PCM_WEIGHTS, PCM_ONTOIDS);
// A context name used to describe the associated element
private static final String PCM_MAIN_ITEMKEY = "MeSHHeadingList";
/**
* Construct PubChemAccessTool using database connection property
* It set properties for tool Resource
*/
public PubChemAccessTool() {
super(PCM_NAME, PCM_RESOURCEID, PCM_STRUCTURE);
try {
this.getToolResource().setResourceURL(new URL(PCM_URL));
this.getToolResource().setResourceLogo(new URL(PCM_LOGO));
this.getToolResource().setResourceElementURL(PCM_ELT_URL);
} catch (MalformedURLException e) {
logger.error("Malformed URL Exception", e);
}
this.getToolResource().setResourceDescription(PCM_DESCRIPTION);
}
@Override
public ResourceType getResourceType() {
return ResourceType.SMALL;
}
@Override
protected String getEutilsDB() {
return PCM_EUTILS_DB;
}
@Override
protected String getEutilsTerm() {
return PCM_EUTILS_TERM;
}
@Override
public void updateResourceInformation() {
// TODO See if it can be implemented for this resource.
}
@Override
public int updateResourceContent() {
return super.eutilsUpdateAll(null);
}
/**
* This method extract data from PubChem Compound
* and populate the Element Table () with data elements for GSE and GDS data
*
* @param UIDs - Set of uid strings
* @return number of elements processed
*/
@Override
protected int updateElementTableWithUIDs(HashSet<String> UIDs) throws BadElementStructureException {
int nbElement = 0;
// Create summary request for e-utils
ESummaryRequest esummaryRequest = new ESummaryRequest();
esummaryRequest.setEmail(EUTILS_EMAIL);
esummaryRequest.setTool(EUTILS_TOOL);
esummaryRequest.setDb(this.getEutilsDB());
ESummaryResult esummaryResult;
StringBuffer UIDlist;
DocSumType[] resultDocSums;
ItemType[] docSumItems;
ArrayList<String> contextNames = this.getToolResource().getResourceStructure().getContextNames();
Element element;
Structure eltStructure = new Structure(contextNames);
String[] UIDsTab = new String[UIDs.size()];
UIDsTab = UIDs.toArray(UIDsTab);
int max;
String concepts;
List<String> itemKeys = Arrays.asList(PCM_ITEMKEYS);
String meSHHeadingList;
// Process UIDs
for (int step = 0; step < UIDsTab.length; step += EUTILS_MAX) {
max = step + EUTILS_MAX;
UIDlist = new StringBuffer();
if (max > UIDsTab.length) {
max = UIDsTab.length;
}
for (int u = step; u < max; u++) {
UIDlist.append(UIDsTab[u]);
if (u < max - 1) {
UIDlist.append(COMMA_STRING);
}
}
esummaryRequest.setId(UIDlist.toString());
try {
// Fire request to E-utils tool
esummaryResult = this.getToolEutils().run_eSummary(esummaryRequest);
resultDocSums = esummaryResult.getDocSum();
// Process each item
for (int i = 0; i < resultDocSums.length; i++) {
docSumItems = resultDocSums[i].getItem();
// This section depends of the structure and the type of content we want to get back
// UID as localElementID (same as CID)
String localElementID = resultDocSums[i].getId();
for (int j = 0; j < docSumItems.length; j++) {
if (!itemKeys.contains(docSumItems[j].getName())) {
continue;
}
// Extract MeSHHeadingList and map to as MESH ontology concepts
if (PCM_ITEMKEYS[0].equals(docSumItems[j].getName())) {
meSHHeadingList = getItemTypeContent(docSumItems[j], GT_SEPARATOR_STRING);
// Map terms to MESH concepts.
concepts = resourceUpdateService.mapTermsToVirtualLocalConceptIDs(meSHHeadingList, PCM_ONTOIDS[0], GT_SEPARATOR_STRING);
if (!EMPTY_STRING.equals(meSHHeadingList)
&& (concepts == null || concepts.trim().length() == 0)) {
logger.error("Cannot map MESH term " + meSHHeadingList + " to local concept id for element with ID " + localElementID + ".");
}
eltStructure.putContext(Structure.generateContextName(PCM_RESOURCEID, PCM_ITEMKEYS[0]), concepts);
}
// Extract MeSHTermList and map to as MESH ontology concepts
else if (PCM_ITEMKEYS[1].equals(docSumItems[j].getName())) {
meSHHeadingList = getItemTypeContent(docSumItems[j], GT_SEPARATOR_STRING);
// Map terms to MESH concepts.
concepts = resourceUpdateService.mapTermsToVirtualLocalConceptIDs(meSHHeadingList, PCM_ONTOIDS[1], GT_SEPARATOR_STRING);
if (!EMPTY_STRING.equals(meSHHeadingList)
&& (concepts == null || concepts.trim().length() == 0)) {
logger.error("Cannot map MESH term " + meSHHeadingList + " to local concept id for element with ID " + localElementID + ".");
}
eltStructure.putContext(Structure.generateContextName(PCM_RESOURCEID, PCM_ITEMKEYS[1]), concepts);
}
// Extract PharmActionList
else if (PCM_ITEMKEYS[2].equals(docSumItems[j].getName())) {
eltStructure.putContext(Structure.generateContextName(PCM_RESOURCEID, PCM_ITEMKEYS[2]), getItemTypeContent(docSumItems[j], COMMA_SEPARATOR));
}
// Extract SynonymList
else if (PCM_ITEMKEYS[3].equals(docSumItems[j].getName())) {
eltStructure.putContext(Structure.generateContextName(PCM_RESOURCEID, PCM_ITEMKEYS[3]), getItemTypeContent(docSumItems[j], COMMA_SEPARATOR));
}
}
if (localElementID != null) {
element = new Element(localElementID, eltStructure);
// Insert element into database.
if (resourceUpdateService.addElement(element)) {
nbElement++;
}
} else {
logger.error("** PROBLEM ** In getting Element with null localElementID .");
}
}
} catch (RemoteException e) {
logger.error("** PROBLEM ** Cannot get information using ESummary.", e);
}
}
return nbElement;
}
@Override
public String elementURLString(String elementLocalID) {
return PCM_ELT_URL + elementLocalID;
}
@Override
public String mainContextDescriptor() {
return PCM_MAIN_ITEMKEY;
}
@Override
protected String stringToNCBITerm(String query) {
return super.stringToNCBITerm(query) + "+AND+has_mesh[filter]";
}
}
| |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net;
import android.os.Parcelable;
import android.os.Parcel;
import android.util.Log;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* A class representing the capabilities of a link
*
* @hide
*/
public class LinkCapabilities implements Parcelable {
private static final String TAG = "LinkCapabilities";
private static final boolean DBG = false;
/** The Map of Keys to Values */
private HashMap<Integer, String> mCapabilities;
/**
* The set of keys defined for a links capabilities.
*
* Keys starting with RW are read + write, i.e. the application
* can request for a certain requirement corresponding to that key.
* Keys starting with RO are read only, i.e. the the application
* can read the value of that key from the socket but cannot request
* a corresponding requirement.
*
* TODO: Provide a documentation technique for concisely and precisely
* define the syntax for each value string associated with a key.
*/
public static final class Key {
/** No constructor */
private Key() {}
/**
* An integer representing the network type.
* @see ConnectivityManager
*/
public final static int RO_NETWORK_TYPE = 1;
/**
* Desired minimum forward link (download) bandwidth for the
* in kilobits per second (kbps). Values should be strings such
* "50", "100", "1500", etc.
*/
public final static int RW_DESIRED_FWD_BW = 2;
/**
* Required minimum forward link (download) bandwidth, in
* per second (kbps), below which the socket cannot function.
* Values should be strings such as "50", "100", "1500", etc.
*/
public final static int RW_REQUIRED_FWD_BW = 3;
/**
* Available forward link (download) bandwidth for the socket.
* This value is in kilobits per second (kbps).
* Values will be strings such as "50", "100", "1500", etc.
*/
public final static int RO_AVAILABLE_FWD_BW = 4;
/**
* Desired minimum reverse link (upload) bandwidth for the socket
* in kilobits per second (kbps).
* Values should be strings such as "50", "100", "1500", etc.
* <p>
* This key is set via the needs map.
*/
public final static int RW_DESIRED_REV_BW = 5;
/**
* Required minimum reverse link (upload) bandwidth, in kilobits
* per second (kbps), below which the socket cannot function.
* If a rate is not specified, the default rate of kbps will be
* Values should be strings such as "50", "100", "1500", etc.
*/
public final static int RW_REQUIRED_REV_BW = 6;
/**
* Available reverse link (upload) bandwidth for the socket.
* This value is in kilobits per second (kbps).
* Values will be strings such as "50", "100", "1500", etc.
*/
public final static int RO_AVAILABLE_REV_BW = 7;
/**
* Maximum latency for the socket, in milliseconds, above which
* socket cannot function.
* Values should be strings such as "50", "300", "500", etc.
*/
public final static int RW_MAX_ALLOWED_LATENCY = 8;
/**
* Interface that the socket is bound to. This can be a virtual
* interface (e.g. VPN or Mobile IP) or a physical interface
* (e.g. wlan0 or rmnet0).
* Values will be strings such as "wlan0", "rmnet0"
*/
public final static int RO_BOUND_INTERFACE = 9;
/**
* Physical interface that the socket is routed on.
* This can be different from BOUND_INTERFACE in cases such as
* VPN or Mobile IP. The physical interface may change over time
* if seamless mobility is supported.
* Values will be strings such as "wlan0", "rmnet0"
*/
public final static int RO_PHYSICAL_INTERFACE = 10;
}
/**
* Role informs the LinkSocket about the data usage patterns of your
* application.
* <P>
* {@code Role.DEFAULT} is the default role, and is used whenever
* a role isn't set.
*/
public static final class Role {
/** No constructor */
private Role() {}
// examples only, discuss which roles should be defined, and then
// code these to match
/** Default Role */
public static final String DEFAULT = "default";
/** Bulk down load */
public static final String BULK_DOWNLOAD = "bulk.download";
/** Bulk upload */
public static final String BULK_UPLOAD = "bulk.upload";
/** VoIP Application at 24kbps */
public static final String VOIP_24KBPS = "voip.24k";
/** VoIP Application at 32kbps */
public static final String VOIP_32KBPS = "voip.32k";
/** Video Streaming at 480p */
public static final String VIDEO_STREAMING_480P = "video.streaming.480p";
/** Video Streaming at 720p */
public static final String VIDEO_STREAMING_720I = "video.streaming.720i";
/** Video Chat Application at 360p */
public static final String VIDEO_CHAT_360P = "video.chat.360p";
/** Video Chat Application at 480p */
public static final String VIDEO_CHAT_480P = "video.chat.480i";
}
/**
* Constructor
*/
public LinkCapabilities() {
mCapabilities = new HashMap<Integer, String>();
}
/**
* Copy constructor.
*
* @param source
*/
public LinkCapabilities(LinkCapabilities source) {
if (source != null) {
mCapabilities = new HashMap<Integer, String>(source.mCapabilities);
} else {
mCapabilities = new HashMap<Integer, String>();
}
}
/**
* Create the {@code LinkCapabilities} with values depending on role type.
* @param applicationRole a {@code LinkSocket.Role}
* @return the {@code LinkCapabilities} associated with the applicationRole, empty if none
*/
public static LinkCapabilities createNeedsMap(String applicationRole) {
if (DBG) log("createNeededCapabilities(applicationRole) EX");
return new LinkCapabilities();
}
/**
* Remove all capabilities
*/
public void clear() {
mCapabilities.clear();
}
/**
* Returns whether this map is empty.
*/
public boolean isEmpty() {
return mCapabilities.isEmpty();
}
/**
* Returns the number of elements in this map.
*
* @return the number of elements in this map.
*/
public int size() {
return mCapabilities.size();
}
/**
* Given the key return the capability string
*
* @param key
* @return the capability string
*/
public String get(int key) {
return mCapabilities.get(key);
}
/**
* Store the key/value capability pair
*
* @param key
* @param value
*/
public void put(int key, String value) {
mCapabilities.put(key, value);
}
/**
* Returns whether this map contains the specified key.
*
* @param key to search for.
* @return {@code true} if this map contains the specified key,
* {@code false} otherwise.
*/
public boolean containsKey(int key) {
return mCapabilities.containsKey(key);
}
/**
* Returns whether this map contains the specified value.
*
* @param value to search for.
* @return {@code true} if this map contains the specified value,
* {@code false} otherwise.
*/
public boolean containsValue(String value) {
return mCapabilities.containsValue(value);
}
/**
* Returns a set containing all of the mappings in this map. Each mapping is
* an instance of {@link Map.Entry}. As the set is backed by this map,
* changes in one will be reflected in the other.
*
* @return a set of the mappings.
*/
public Set<Entry<Integer, String>> entrySet() {
return mCapabilities.entrySet();
}
/**
* @return the set of the keys.
*/
public Set<Integer> keySet() {
return mCapabilities.keySet();
}
/**
* @return the set of values
*/
public Collection<String> values() {
return mCapabilities.values();
}
/**
* Implement the Parcelable interface
* @hide
*/
public int describeContents() {
return 0;
}
/**
* Convert to string for debugging
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
boolean firstTime = true;
for (Entry<Integer, String> entry : mCapabilities.entrySet()) {
if (firstTime) {
firstTime = false;
} else {
sb.append(",");
}
sb.append(entry.getKey());
sb.append(":\"");
sb.append(entry.getValue());
sb.append("\"");
return mCapabilities.toString();
}
return sb.toString();
}
/**
* Implement the Parcelable interface.
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mCapabilities.size());
for (Entry<Integer, String> entry : mCapabilities.entrySet()) {
dest.writeInt(entry.getKey().intValue());
dest.writeString(entry.getValue());
}
}
/**
* Implement the Parcelable interface.
* @hide
*/
public static final Creator<LinkCapabilities> CREATOR =
new Creator<LinkCapabilities>() {
public LinkCapabilities createFromParcel(Parcel in) {
LinkCapabilities capabilities = new LinkCapabilities();
int size = in.readInt();
while (size-- != 0) {
int key = in.readInt();
String value = in.readString();
capabilities.mCapabilities.put(key, value);
}
return capabilities;
}
public LinkCapabilities[] newArray(int size) {
return new LinkCapabilities[size];
}
};
/**
* Debug logging
*/
protected static void log(String s) {
Log.d(TAG, s);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.compute.ComputeJob;
import org.apache.ignite.compute.ComputeJobAdapter;
import org.apache.ignite.compute.ComputeJobContext;
import org.apache.ignite.compute.ComputeJobResult;
import org.apache.ignite.compute.ComputeJobResultPolicy;
import org.apache.ignite.compute.ComputeTask;
import org.apache.ignite.compute.ComputeTaskAdapter;
import org.apache.ignite.compute.ComputeTaskContinuousMapper;
import org.apache.ignite.compute.ComputeTaskFuture;
import org.apache.ignite.compute.ComputeTaskSession;
import org.apache.ignite.compute.ComputeTaskSessionAttributeListener;
import org.apache.ignite.compute.ComputeTaskSessionFullSupport;
import org.apache.ignite.compute.ComputeTaskSplitAdapter;
import org.apache.ignite.internal.processors.task.GridInternal;
import org.apache.ignite.lang.IgniteClosure;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.resources.JobContextResource;
import org.apache.ignite.resources.LoggerResource;
import org.apache.ignite.resources.TaskContinuousMapperResource;
import org.apache.ignite.resources.TaskSessionResource;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.testframework.junits.common.GridCommonTest;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
/**
* Continuous task test.
*/
@GridCommonTest(group = "Kernal Self")
public class GridContinuousTaskSelfTest extends GridCommonAbstractTest {
/** */
private static final int JOB_COUNT = 10;
/** */
private static final int THREAD_COUNT = 10;
/**
* @throws Exception If test failed.
*/
@Test
public void testContinuousJobsChain() throws Exception {
try {
Ignite ignite = startGrid(0);
ComputeTaskFuture<Integer> fut1 = ignite.compute().executeAsync(TestJobsChainTask.class, true);
ComputeTaskFuture<Integer> fut2 = ignite.compute().executeAsync(TestJobsChainTask.class, false);
assert fut1.get() == 55;
assert fut2.get() == 55;
}
finally {
stopGrid(0);
}
}
/**
* @throws Exception If test failed.
*/
@Test
public void testContinuousJobsChainMultiThreaded() throws Exception {
try {
final Ignite ignite = startGrid(0);
startGrid(1);
GridTestUtils.runMultiThreaded(new Runnable() {
/** {@inheritDoc} */
@Override public void run() {
try {
ComputeTaskFuture<Integer> fut1 = ignite.compute().executeAsync(TestJobsChainTask.class, true);
ComputeTaskFuture<Integer> fut2 = ignite.compute().executeAsync(TestJobsChainTask.class, false);
assert fut1.get() == 55;
assert fut2.get() == 55;
}
catch (IgniteException e) {
assert false : "Test task failed: " + e;
}
}
}, THREAD_COUNT, "continuous-jobs-chain");
}
finally {
stopGrid(0);
stopGrid(1);
}
}
/**
* @throws Exception If test failed.
*/
@Test
public void testContinuousJobsSessionChain() throws Exception {
try {
Ignite ignite = startGrid(0);
startGrid(1);
ignite.compute().execute(SessionChainTestTask.class, false);
}
finally {
stopGrid(0);
stopGrid(1);
}
}
/**
* @throws Exception If test failed.
*/
@Test
public void testContinuousSlowMap() throws Exception {
try {
Ignite ignite = startGrid(0);
Integer cnt = ignite.compute().execute(SlowMapTestTask.class, null);
assert cnt != null;
assert cnt == 2 : "Unexpected result: " + cnt;
}
finally {
stopGrid(0);
}
}
/**
* @throws Exception If test failed.
*/
@Test
public void testClearTimeouts() throws Exception {
int holdccTimeout = 4000;
try {
Ignite grid = startGrid(0);
TestClearTimeoutsClosure closure = new TestClearTimeoutsClosure();
grid.compute().apply(closure, holdccTimeout);
Thread.sleep(holdccTimeout * 2);
assert closure.counter == 2;
}
finally {
stopGrid(0);
}
}
/**
* @throws Exception If test failed.
*/
@Test
public void testMultipleHoldccCalls() throws Exception {
try {
Ignite grid = startGrid(0);
assertTrue(grid.compute().apply(new TestMultipleHoldccCallsClosure(), (Object)null));
}
finally {
stopGrid(0);
}
}
/**
* @throws Exception If test failed.
*/
@Test
public void testClosureWithNestedInternalTask() throws Exception {
try {
IgniteEx ignite = startGrid(0);
ComputeTaskInternalFuture<String> fut = ignite.context().closure().callAsync(GridClosureCallMode.BALANCE, new Callable<String>() {
/** */
@IgniteInstanceResource
private IgniteEx g;
@Override public String call() throws Exception {
return g.compute(g.cluster()).execute(NestedHoldccTask.class, null);
}
}, ignite.cluster().nodes());
assertEquals("DONE", fut.get(3000));
}
finally {
stopGrid(0, true);
}
}
/** Test task with continuation. */
@GridInternal
public static class NestedHoldccTask extends ComputeTaskAdapter<String, String> {
/** {@inheritDoc} */
@NotNull @Override public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid,
@Nullable String arg) throws IgniteException {
Map<ComputeJob, ClusterNode> map = new HashMap<>();
for (ClusterNode node : subgrid)
map.put(new NestedHoldccJob(), node);
return map;
}
/** {@inheritDoc} */
@Nullable @Override public String reduce(List<ComputeJobResult> results) throws IgniteException {
return results.get(0).getData();
}
}
/** Test job. */
public static class NestedHoldccJob extends ComputeJobAdapter {
/** */
@JobContextResource
private ComputeJobContext jobCtx;
/** */
private int cnt = 0;
/** {@inheritDoc} */
@Override public Object execute() throws IgniteException {
if (cnt < 1) {
cnt++;
jobCtx.holdcc();
new Timer().schedule(new TimerTask() {
@Override public void run() {
jobCtx.callcc();
}
}, 500);
return "NOT DONE";
}
return "DONE";
}
}
/** */
@SuppressWarnings({"PublicInnerClass"})
public static class TestMultipleHoldccCallsClosure implements IgniteClosure<Object, Boolean> {
/** */
private int counter;
/** */
private volatile boolean success;
/** Auto-inject job context. */
@JobContextResource
private ComputeJobContext jobCtx;
/** */
@LoggerResource
private IgniteLogger log;
@Override public Boolean apply(Object param) {
counter++;
if (counter == 2)
return success;
jobCtx.holdcc(4000);
try {
jobCtx.holdcc();
}
catch (IllegalStateException ignored) {
success = true;
log.info("Second holdcc() threw IllegalStateException as expected.");
}
finally {
new Timer().schedule(new TimerTask() {
@Override public void run() {
jobCtx.callcc();
}
}, 1000);
}
return false;
}
}
/** */
@SuppressWarnings({"PublicInnerClass"})
public static class TestClearTimeoutsClosure implements IgniteClosure<Integer, Object> {
/** */
private int counter;
/** Auto-inject job context. */
@JobContextResource
private ComputeJobContext jobCtx;
@Override public Object apply(Integer holdccTimeout) {
assert holdccTimeout >= 2000;
counter++;
if (counter == 1) {
new Timer().schedule(new TimerTask() {
@Override public void run() {
jobCtx.callcc();
}
}, 1000);
jobCtx.holdcc(holdccTimeout);
}
if (counter == 2)
// Job returned from the suspended state.
return null;
return null;
}
}
/** */
@SuppressWarnings({"PublicInnerClass"})
public static class TestJobsChainTask implements ComputeTask<Boolean, Integer> {
/** */
@TaskContinuousMapperResource
private ComputeTaskContinuousMapper mapper;
/** */
@LoggerResource
private IgniteLogger log;
/** */
private int cnt;
/** {@inheritDoc} */
@NotNull @Override public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid, Boolean arg) {
assert mapper != null;
assert arg != null;
ComputeJob job = new TestJob(++cnt);
if (arg) {
mapper.send(job, subgrid.get(0));
log.info("Sent test task by continuous mapper: " + job);
}
else {
log.info("Will return job as map() result: " + job);
return Collections.singletonMap(job, subgrid.get(0));
}
return null;
}
/** {@inheritDoc} */
@Override public ComputeJobResultPolicy result(ComputeJobResult res, List<ComputeJobResult> received) {
assert mapper != null;
assert res.getException() == null : "Unexpected exception: " + res.getException();
log.info("Received job result [result=" + res + ", count=" + cnt + ']');
int tmp = ++cnt;
if (tmp <= JOB_COUNT) {
mapper.send(new TestJob(tmp));
log.info("Sent test task by continuous mapper (from result() method).");
}
return ComputeJobResultPolicy.WAIT;
}
/** {@inheritDoc} */
@Override public Integer reduce(List<ComputeJobResult> results) {
assert results.size() == 10 : "Unexpected result count: " + results.size();
log.info("Called reduce() method [results=" + results + ']');
int res = 0;
for (ComputeJobResult result : results) {
assert result.getData() != null : "Unexpected result data (null): " + result;
res += (Integer)result.getData();
}
return res;
}
}
/** */
@SuppressWarnings({"PublicInnerClass"})
public static class TestJob extends ComputeJobAdapter {
/** */
public TestJob() { /* No-op. */ }
/**
* @param arg Job argument.
*/
public TestJob(Integer arg) {
super(arg);
}
/** {@inheritDoc} */
@Override public Serializable execute() {
Integer i = argument(0);
return i != null ? i : 0;
}
}
/** */
@SuppressWarnings({"PublicInnerClass"})
@ComputeTaskSessionFullSupport
public static class SessionChainTestTask extends ComputeTaskSplitAdapter<Object, Object> {
/** */
@TaskSessionResource
private ComputeTaskSession ses;
/** */
@TaskContinuousMapperResource
private ComputeTaskContinuousMapper mapper;
/** */
@LoggerResource
private IgniteLogger log;
/** {@inheritDoc} */
@Override protected Collection<? extends ComputeJob> split(int gridSize, Object arg) {
ses.addAttributeListener(new ComputeTaskSessionAttributeListener() {
@Override public void onAttributeSet(Object key, Object val) {
if (key instanceof String) {
if (((String)key).startsWith("sendJob")) {
assert val instanceof Integer;
int cnt = (Integer)val;
if (cnt < JOB_COUNT) {
try {
mapper.send(new SessionChainTestJob(cnt));
}
catch (IgniteException e) {
log.error("Failed to send new job.", e);
}
}
}
}
}
}, true);
Collection<ComputeJob> jobs = new ArrayList<>();
for (int i = 0; i < JOB_COUNT; i++)
jobs.add(new SessionChainTestJob(0));
return jobs;
}
/** {@inheritDoc} */
@Override public Object reduce(List<ComputeJobResult> results) {
assertEquals(JOB_COUNT * JOB_COUNT, results.size());
return null;
}
}
/** */
@SuppressWarnings({"PublicInnerClass"})
public static class SessionChainTestJob extends ComputeJobAdapter {
/** */
@TaskSessionResource
private ComputeTaskSession ses;
/** */
@JobContextResource
private ComputeJobContext ctx;
/** */
public SessionChainTestJob() { /* No-op. */}
/**
* @param arg Job argument.
*/
public SessionChainTestJob(Integer arg) {
super(arg);
}
/** {@inheritDoc} */
@Override public Serializable execute() {
Integer i = argument(0);
int arg = i != null ? i : 0;
ses.setAttribute("sendJob" + ctx.getJobId(), 1 + arg);
return arg;
}
}
/** */
@SuppressWarnings({"PublicInnerClass"})
public static class SlowMapTestTask extends ComputeTaskAdapter<Object, Integer> {
/** */
@TaskContinuousMapperResource
private ComputeTaskContinuousMapper mapper;
/** */
private int cnt;
/** {@inheritDoc} */
@NotNull @Override public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid, Object arg) {
mapper.send(new TestJob(++cnt));
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
throw new IgniteException("Job has been interrupted.", e);
}
mapper.send(new TestJob(++cnt));
return null;
}
/** {@inheritDoc} */
@Override public Integer reduce(List<ComputeJobResult> results) throws IgniteException {
return results == null ? 0 : results.size();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.service;
import java.net.InetAddress;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Iterables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.Stage;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.ReadCommand;
import org.apache.cassandra.db.SinglePartitionReadCommand;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.partitions.PartitionIterator;
import org.apache.cassandra.exceptions.ReadFailureException;
import org.apache.cassandra.exceptions.ReadTimeoutException;
import org.apache.cassandra.exceptions.UnavailableException;
import org.apache.cassandra.metrics.ReadRepairMetrics;
import org.apache.cassandra.net.MessageOut;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.schema.SpeculativeRetryParam;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.service.StorageProxy.LocalReadRunnable;
import org.apache.cassandra.tracing.TraceState;
import org.apache.cassandra.tracing.Tracing;
/**
* Sends a read request to the replicas needed to satisfy a given ConsistencyLevel.
*
* Optionally, may perform additional requests to provide redundancy against replica failure:
* AlwaysSpeculatingReadExecutor will always send a request to one extra replica, while
* SpeculatingReadExecutor will wait until it looks like the original request is in danger
* of timing out before performing extra reads.
*/
public abstract class AbstractReadExecutor
{
private static final Logger logger = LoggerFactory.getLogger(AbstractReadExecutor.class);
protected final ReadCommand command;
protected final List<InetAddress> targetReplicas;
protected final ReadCallback handler;
protected final TraceState traceState;
AbstractReadExecutor(Keyspace keyspace, ReadCommand command, ConsistencyLevel consistencyLevel, List<InetAddress> targetReplicas, long queryStartNanoTime)
{
this.command = command;
this.targetReplicas = targetReplicas;
this.handler = new ReadCallback(new DigestResolver(keyspace, command, consistencyLevel, targetReplicas.size()), consistencyLevel, command, targetReplicas, queryStartNanoTime);
this.traceState = Tracing.instance.get();
// Set the digest version (if we request some digests). This is the smallest version amongst all our target replicas since new nodes
// knows how to produce older digest but the reverse is not true.
// TODO: we need this when talking with pre-3.0 nodes. So if we preserve the digest format moving forward, we can get rid of this once
// we stop being compatible with pre-3.0 nodes.
int digestVersion = MessagingService.current_version;
for (InetAddress replica : targetReplicas)
digestVersion = Math.min(digestVersion, MessagingService.instance().getVersion(replica));
command.setDigestVersion(digestVersion);
}
protected void makeDataRequests(Iterable<InetAddress> endpoints)
{
makeRequests(command, endpoints);
}
protected void makeDigestRequests(Iterable<InetAddress> endpoints)
{
makeRequests(command.copy().setIsDigestQuery(true), endpoints);
}
private void makeRequests(ReadCommand readCommand, Iterable<InetAddress> endpoints)
{
boolean hasLocalEndpoint = false;
for (InetAddress endpoint : endpoints)
{
if (StorageProxy.canDoLocalRequest(endpoint))
{
hasLocalEndpoint = true;
continue;
}
if (traceState != null)
traceState.trace("reading {} from {}", readCommand.isDigestQuery() ? "digest" : "data", endpoint);
logger.trace("reading {} from {}", readCommand.isDigestQuery() ? "digest" : "data", endpoint);
MessageOut<ReadCommand> message = readCommand.createMessage();
MessagingService.instance().sendRRWithFailure(message, endpoint, handler);
}
// We delay the local (potentially blocking) read till the end to avoid stalling remote requests.
if (hasLocalEndpoint)
{
logger.trace("reading {} locally", readCommand.isDigestQuery() ? "digest" : "data");
StageManager.getStage(Stage.READ).maybeExecuteImmediately(new LocalReadRunnable(command, handler));
}
}
/**
* Perform additional requests if it looks like the original will time out. May block while it waits
* to see if the original requests are answered first.
*/
public abstract void maybeTryAdditionalReplicas();
/**
* Get the replicas involved in the [finished] request.
*
* @return target replicas + the extra replica, *IF* we speculated.
*/
public abstract Collection<InetAddress> getContactedReplicas();
/**
* send the initial set of requests
*/
public abstract void executeAsync();
/**
* wait for an answer. Blocks until success or timeout, so it is caller's
* responsibility to call maybeTryAdditionalReplicas first.
*/
public PartitionIterator get() throws ReadFailureException, ReadTimeoutException, DigestMismatchException
{
return handler.get();
}
private static ReadRepairDecision newReadRepairDecision(TableMetadata metadata)
{
if (metadata.params.readRepairChance > 0d ||
metadata.params.dcLocalReadRepairChance > 0)
{
double chance = ThreadLocalRandom.current().nextDouble();
if (metadata.params.readRepairChance > chance)
return ReadRepairDecision.GLOBAL;
if (metadata.params.dcLocalReadRepairChance > chance)
return ReadRepairDecision.DC_LOCAL;
}
return ReadRepairDecision.NONE;
}
/**
* @return an executor appropriate for the configured speculative read policy
*/
public static AbstractReadExecutor getReadExecutor(SinglePartitionReadCommand command, ConsistencyLevel consistencyLevel, long queryStartNanoTime) throws UnavailableException
{
Keyspace keyspace = Keyspace.open(command.metadata().keyspace);
List<InetAddress> allReplicas = StorageProxy.getLiveSortedEndpoints(keyspace, command.partitionKey());
// 11980: Excluding EACH_QUORUM reads from potential RR, so that we do not miscount DC responses
ReadRepairDecision repairDecision = consistencyLevel == ConsistencyLevel.EACH_QUORUM
? ReadRepairDecision.NONE
: newReadRepairDecision(command.metadata());
List<InetAddress> targetReplicas = consistencyLevel.filterForQuery(keyspace, allReplicas, repairDecision);
// Throw UAE early if we don't have enough replicas.
consistencyLevel.assureSufficientLiveNodes(keyspace, targetReplicas);
if (repairDecision != ReadRepairDecision.NONE)
{
Tracing.trace("Read-repair {}", repairDecision);
ReadRepairMetrics.attempted.mark();
}
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(command.metadata().id);
SpeculativeRetryParam retry = cfs.metadata().params.speculativeRetry;
// Speculative retry is disabled *OR* there are simply no extra replicas to speculate.
// 11980: Disable speculative retry if using EACH_QUORUM in order to prevent miscounting DC responses
if (retry.equals(SpeculativeRetryParam.NONE)
|| consistencyLevel == ConsistencyLevel.EACH_QUORUM
|| consistencyLevel.blockFor(keyspace) == allReplicas.size())
return new NeverSpeculatingReadExecutor(keyspace, command, consistencyLevel, targetReplicas, queryStartNanoTime);
if (targetReplicas.size() == allReplicas.size())
{
// CL.ALL, RRD.GLOBAL or RRD.DC_LOCAL and a single-DC.
// We are going to contact every node anyway, so ask for 2 full data requests instead of 1, for redundancy
// (same amount of requests in total, but we turn 1 digest request into a full blown data request).
return new AlwaysSpeculatingReadExecutor(keyspace, cfs, command, consistencyLevel, targetReplicas, queryStartNanoTime);
}
// RRD.NONE or RRD.DC_LOCAL w/ multiple DCs.
InetAddress extraReplica = allReplicas.get(targetReplicas.size());
// With repair decision DC_LOCAL all replicas/target replicas may be in different order, so
// we might have to find a replacement that's not already in targetReplicas.
if (repairDecision == ReadRepairDecision.DC_LOCAL && targetReplicas.contains(extraReplica))
{
for (InetAddress address : allReplicas)
{
if (!targetReplicas.contains(address))
{
extraReplica = address;
break;
}
}
}
targetReplicas.add(extraReplica);
if (retry.equals(SpeculativeRetryParam.ALWAYS))
return new AlwaysSpeculatingReadExecutor(keyspace, cfs, command, consistencyLevel, targetReplicas, queryStartNanoTime);
else // PERCENTILE or CUSTOM.
return new SpeculatingReadExecutor(keyspace, cfs, command, consistencyLevel, targetReplicas, queryStartNanoTime);
}
public static class NeverSpeculatingReadExecutor extends AbstractReadExecutor
{
public NeverSpeculatingReadExecutor(Keyspace keyspace, ReadCommand command, ConsistencyLevel consistencyLevel, List<InetAddress> targetReplicas, long queryStartNanoTime)
{
super(keyspace, command, consistencyLevel, targetReplicas, queryStartNanoTime);
}
public void executeAsync()
{
makeDataRequests(targetReplicas.subList(0, 1));
if (targetReplicas.size() > 1)
makeDigestRequests(targetReplicas.subList(1, targetReplicas.size()));
}
public void maybeTryAdditionalReplicas()
{
// no-op
}
public Collection<InetAddress> getContactedReplicas()
{
return targetReplicas;
}
}
private static class SpeculatingReadExecutor extends AbstractReadExecutor
{
private final ColumnFamilyStore cfs;
private volatile boolean speculated = false;
public SpeculatingReadExecutor(Keyspace keyspace,
ColumnFamilyStore cfs,
ReadCommand command,
ConsistencyLevel consistencyLevel,
List<InetAddress> targetReplicas,
long queryStartNanoTime)
{
super(keyspace, command, consistencyLevel, targetReplicas, queryStartNanoTime);
this.cfs = cfs;
}
public void executeAsync()
{
// if CL + RR result in covering all replicas, getReadExecutor forces AlwaysSpeculating. So we know
// that the last replica in our list is "extra."
List<InetAddress> initialReplicas = targetReplicas.subList(0, targetReplicas.size() - 1);
if (handler.blockfor < initialReplicas.size())
{
// We're hitting additional targets for read repair. Since our "extra" replica is the least-
// preferred by the snitch, we do an extra data read to start with against a replica more
// likely to reply; better to let RR fail than the entire query.
makeDataRequests(initialReplicas.subList(0, 2));
if (initialReplicas.size() > 2)
makeDigestRequests(initialReplicas.subList(2, initialReplicas.size()));
}
else
{
// not doing read repair; all replies are important, so it doesn't matter which nodes we
// perform data reads against vs digest.
makeDataRequests(initialReplicas.subList(0, 1));
if (initialReplicas.size() > 1)
makeDigestRequests(initialReplicas.subList(1, initialReplicas.size()));
}
}
public void maybeTryAdditionalReplicas()
{
// no latency information, or we're overloaded
if (cfs.sampleLatencyNanos > TimeUnit.MILLISECONDS.toNanos(command.getTimeout()))
return;
if (!handler.await(cfs.sampleLatencyNanos, TimeUnit.NANOSECONDS))
{
// Could be waiting on the data, or on enough digests.
ReadCommand retryCommand = command;
if (handler.resolver.isDataPresent())
retryCommand = command.copy().setIsDigestQuery(true);
InetAddress extraReplica = Iterables.getLast(targetReplicas);
if (traceState != null)
traceState.trace("speculating read retry on {}", extraReplica);
logger.trace("speculating read retry on {}", extraReplica);
MessagingService.instance().sendRRWithFailure(retryCommand.createMessage(), extraReplica, handler);
speculated = true;
cfs.metric.speculativeRetries.inc();
}
}
public Collection<InetAddress> getContactedReplicas()
{
return speculated
? targetReplicas
: targetReplicas.subList(0, targetReplicas.size() - 1);
}
}
private static class AlwaysSpeculatingReadExecutor extends AbstractReadExecutor
{
private final ColumnFamilyStore cfs;
public AlwaysSpeculatingReadExecutor(Keyspace keyspace,
ColumnFamilyStore cfs,
ReadCommand command,
ConsistencyLevel consistencyLevel,
List<InetAddress> targetReplicas,
long queryStartNanoTime)
{
super(keyspace, command, consistencyLevel, targetReplicas, queryStartNanoTime);
this.cfs = cfs;
}
public void maybeTryAdditionalReplicas()
{
// no-op
}
public Collection<InetAddress> getContactedReplicas()
{
return targetReplicas;
}
@Override
public void executeAsync()
{
makeDataRequests(targetReplicas.subList(0, targetReplicas.size() > 1 ? 2 : 1));
if (targetReplicas.size() > 2)
makeDigestRequests(targetReplicas.subList(2, targetReplicas.size()));
cfs.metric.speculativeRetries.inc();
}
}
}
| |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.exposurenotification.nearby;
import androidx.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.samples.Hex;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* A scanned packet coming from other device's EN advertising.
*
* @hide
*/
public class ScannedPacket {
byte[] id;
byte[] encryptedMetadata;
ScannedPacketContent[] scannedPacketContents;
ScannedPacket(
byte[] id,
byte[] encryptedMetadata,
ScannedPacketContent[] scannedPacketContents) {
this.id = id;
this.encryptedMetadata = encryptedMetadata;
this.scannedPacketContents = scannedPacketContents;
}
/**
* Returns the rolling proximity ID.
*/
public byte[] getId() {
return Arrays.copyOf(id, id.length);
}
/**
* Returns the encrypted metadata.
*/
public byte[] getEncryptedMetadata() {
return Arrays.copyOf(encryptedMetadata, encryptedMetadata.length);
}
/**
* Returns the scanned packet contents.
*/
public ScannedPacketContent[] getScannedPacketContents() {
return Arrays.copyOf(scannedPacketContents, scannedPacketContents.length);
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof ScannedPacket) {
ScannedPacket that = (ScannedPacket) obj;
return Arrays.equals(id, that.id)
&& Arrays.equals(encryptedMetadata, that.encryptedMetadata)
&& Arrays.equals(scannedPacketContents, that.scannedPacketContents);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(id, encryptedMetadata, scannedPacketContents);
}
@Override
public String toString() {
StringBuilder scannedPacketContentsString = new StringBuilder();
for (ScannedPacketContent scannedPacketContent : scannedPacketContents) {
scannedPacketContentsString.append(scannedPacketContent.toString()).append(",");
}
return String.format(
Locale.US,
"ScannedPacket<id: %s, encryptedMetadata: %s, scannedPacketContents: %s>",
Hex.bytesToStringLowercase(id),
Hex.bytesToStringLowercase(encryptedMetadata),
scannedPacketContentsString);
}
/**
* A builder for {@link ScannedPacket}.
*/
public static final class ScannedPacketBuilder {
private byte[] id = new byte[0];
private byte[] encryptedMetadata = new byte[0];
private ScannedPacketContent[] scannedPacketContents = new ScannedPacketContent[0];
public ScannedPacketBuilder setId(byte[] id) {
this.id = Arrays.copyOf(id, id.length);
return this;
}
public ScannedPacketBuilder setEncryptedMetadata(byte[] encryptedMetadata) {
this.encryptedMetadata = Arrays.copyOf(encryptedMetadata, encryptedMetadata.length);
return this;
}
public ScannedPacketBuilder setScannedPacketContents(
ScannedPacketContent[] scannedPacketContents) {
checkArgument(
scannedPacketContents != null && scannedPacketContents.length > 0,
"scannedPacketContents's size must be > 0");
this.scannedPacketContents =
Arrays.copyOf(scannedPacketContents, scannedPacketContents.length);
return this;
}
public ScannedPacket build() {
return new ScannedPacket(id, encryptedMetadata, scannedPacketContents);
}
}
/**
* A scanned packet content coming from other device's EN advertising.
*
* @hide
*/
public static class ScannedPacketContent {
int epochSeconds;
int rssi;
int previousScanEpochSeconds;
ScannedPacketContent(
int epochSeconds,
int rssi,
int previousScanEpochSeconds) {
this.epochSeconds = epochSeconds;
this.rssi = rssi;
this.previousScanEpochSeconds = previousScanEpochSeconds;
}
public int getEpochSeconds() {
return epochSeconds;
}
public int getRssi() {
return rssi;
}
public int getPreviousScanEpochSeconds() {
return previousScanEpochSeconds;
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof ScannedPacketContent) {
ScannedPacketContent that = (ScannedPacketContent) obj;
return Objects.equal(epochSeconds, that.epochSeconds)
&& Objects.equal(rssi, that.rssi)
&& Objects.equal(previousScanEpochSeconds, that.previousScanEpochSeconds);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(epochSeconds, rssi, previousScanEpochSeconds);
}
@Override
public String toString() {
return String.format(
Locale.US,
"ScannedPacketContent<"
+ "epochSeconds: %s, "
+ "rssi: %d, "
+ "previousScanEpochSeconds: %s>",
new Date(SECONDS.toMillis(epochSeconds)),
rssi,
new Date(SECONDS.toMillis(previousScanEpochSeconds)));
}
/**
* A builder for {@link ScannedPacketContent}.
*/
public static final class ScannedPacketContentBuilder {
private int epochSeconds = 0;
private int rssi = 0;
private int previousScanEpochSeconds = 0;
public ScannedPacketContentBuilder setEpochSeconds(int epochSeconds) {
this.epochSeconds = epochSeconds;
return this;
}
public ScannedPacketContentBuilder setRssi(int rssi) {
this.rssi = rssi;
return this;
}
public ScannedPacketContentBuilder setPreviousScanEpochSeconds(int previousScanEpochSeconds) {
this.previousScanEpochSeconds = previousScanEpochSeconds;
return this;
}
public ScannedPacketContent build() {
return new ScannedPacketContent(epochSeconds, rssi, previousScanEpochSeconds);
}
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar.annotations;
import com.facebook.presto.metadata.BoundVariables;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.LongVariableConstraint;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.metadata.TypeVariableConstraint;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.function.FunctionDependency;
import com.facebook.presto.spi.function.IsNull;
import com.facebook.presto.spi.function.LiteralParameters;
import com.facebook.presto.spi.function.OperatorDependency;
import com.facebook.presto.spi.function.OperatorType;
import com.facebook.presto.spi.function.SqlNullable;
import com.facebook.presto.spi.function.SqlType;
import com.facebook.presto.spi.function.TypeParameter;
import com.facebook.presto.spi.function.TypeParameterSpecialization;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.spi.type.TypeSignature;
import com.facebook.presto.spi.type.TypeSignatureParameter;
import com.facebook.presto.type.Constraint;
import com.facebook.presto.type.LiteralParameter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import static com.facebook.presto.metadata.FunctionKind.SCALAR;
import static com.facebook.presto.metadata.Signature.comparableTypeParameter;
import static com.facebook.presto.metadata.Signature.internalOperator;
import static com.facebook.presto.metadata.Signature.internalScalarFunction;
import static com.facebook.presto.metadata.Signature.orderableTypeParameter;
import static com.facebook.presto.metadata.Signature.typeVariable;
import static com.facebook.presto.metadata.SignatureBinder.applyBoundVariables;
import static com.facebook.presto.spi.StandardErrorCode.FUNCTION_IMPLEMENTATION_ERROR;
import static com.facebook.presto.spi.function.OperatorType.BETWEEN;
import static com.facebook.presto.spi.function.OperatorType.CAST;
import static com.facebook.presto.spi.function.OperatorType.EQUAL;
import static com.facebook.presto.spi.function.OperatorType.GREATER_THAN;
import static com.facebook.presto.spi.function.OperatorType.GREATER_THAN_OR_EQUAL;
import static com.facebook.presto.spi.function.OperatorType.HASH_CODE;
import static com.facebook.presto.spi.function.OperatorType.LESS_THAN;
import static com.facebook.presto.spi.function.OperatorType.LESS_THAN_OR_EQUAL;
import static com.facebook.presto.spi.function.OperatorType.NOT_EQUAL;
import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static java.lang.String.format;
import static java.lang.invoke.MethodHandles.lookup;
import static java.lang.invoke.MethodHandles.permuteArguments;
import static java.lang.reflect.Modifier.isStatic;
import static java.util.Arrays.asList;
import static java.util.Objects.requireNonNull;
public class ScalarImplementation
{
private final Signature signature;
private final boolean nullable;
private final List<Boolean> nullableArguments;
private final List<Boolean> nullFlags;
private final MethodHandle methodHandle;
private final List<ImplementationDependency> dependencies;
private final Optional<MethodHandle> constructor;
private final List<ImplementationDependency> constructorDependencies;
private final List<Class<?>> argumentNativeContainerTypes;
private final Map<String, Class<?>> specializedTypeParameters;
public ScalarImplementation(
Signature signature,
boolean nullable,
List<Boolean> nullableArguments,
List<Boolean> nullFlags,
MethodHandle methodHandle,
List<ImplementationDependency> dependencies,
Optional<MethodHandle> constructor,
List<ImplementationDependency> constructorDependencies,
List<Class<?>> argumentNativeContainerTypes,
Map<String, Class<?>> specializedTypeParameters)
{
this.signature = requireNonNull(signature, "signature is null");
this.nullable = nullable;
this.nullableArguments = ImmutableList.copyOf(requireNonNull(nullableArguments, "nullableArguments is null"));
this.nullFlags = ImmutableList.copyOf(requireNonNull(nullFlags, "nullFlags is null"));
this.methodHandle = requireNonNull(methodHandle, "methodHandle is null");
this.dependencies = ImmutableList.copyOf(requireNonNull(dependencies, "dependencies is null"));
this.constructor = requireNonNull(constructor, "constructor is null");
this.constructorDependencies = ImmutableList.copyOf(requireNonNull(constructorDependencies, "constructorDependencies is null"));
this.argumentNativeContainerTypes = ImmutableList.copyOf(requireNonNull(argumentNativeContainerTypes, "argumentNativeContainerTypes is null"));
this.specializedTypeParameters = ImmutableMap.copyOf(requireNonNull(specializedTypeParameters, "specializedTypeParameters is null"));
}
public Optional<MethodHandleAndConstructor> specialize(Signature boundSignature, BoundVariables boundVariables, TypeManager typeManager, FunctionRegistry functionRegistry)
{
for (Map.Entry<String, Class<?>> entry : specializedTypeParameters.entrySet()) {
if (!entry.getValue().isAssignableFrom(boundVariables.getTypeVariable(entry.getKey()).getJavaType())) {
return Optional.empty();
}
}
Class<?> returnContainerType = getNullAwareReturnType(typeManager.getType(boundSignature.getReturnType()).getJavaType(), nullable);
if (!returnContainerType.equals(methodHandle.type().returnType())) {
return Optional.empty();
}
for (int i = 0; i < boundSignature.getArgumentTypes().size(); i++) {
Class<?> argumentType = typeManager.getType(boundSignature.getArgumentTypes().get(i)).getJavaType();
boolean nullableParameter = isParameterNullable(argumentType, nullableArguments.get(i), nullFlags.get(i));
Class<?> argumentContainerType = getNullAwareContainerType(argumentType, nullableParameter);
if (!argumentNativeContainerTypes.get(i).isAssignableFrom(argumentContainerType)) {
return Optional.empty();
}
}
MethodHandle methodHandle = this.methodHandle;
for (ImplementationDependency dependency : dependencies) {
methodHandle = MethodHandles.insertArguments(methodHandle, 0, dependency.resolve(boundVariables, typeManager, functionRegistry));
}
MethodHandle constructor = null;
if (this.constructor.isPresent()) {
constructor = this.constructor.get();
for (ImplementationDependency dependency : constructorDependencies) {
constructor = MethodHandles.insertArguments(constructor, 0, dependency.resolve(boundVariables, typeManager, functionRegistry));
}
}
return Optional.of(new MethodHandleAndConstructor(methodHandle, Optional.ofNullable(constructor)));
}
private static Class<?> getNullAwareReturnType(Class<?> clazz, boolean nullable)
{
if (nullable) {
return Primitives.wrap(clazz);
}
return clazz;
}
private static Class<?> getNullAwareContainerType(Class<?> clazz, boolean nullable)
{
if (clazz == void.class) {
return Primitives.wrap(clazz);
}
if (nullable) {
return Primitives.wrap(clazz);
}
return clazz;
}
private static boolean isParameterNullable(Class<?> type, boolean nullableArgument, boolean nullFlag)
{
if (!nullableArgument) {
return false;
}
// void must be nullable even if the null flag is present
if (type == void.class) {
return true;
}
if (nullFlag) {
return !type.isPrimitive();
}
return true;
}
public boolean hasSpecializedTypeParameters()
{
return !specializedTypeParameters.isEmpty();
}
public Signature getSignature()
{
return signature;
}
public boolean isNullable()
{
return nullable;
}
public List<Boolean> getNullableArguments()
{
return nullableArguments;
}
public List<Boolean> getNullFlags()
{
return nullFlags;
}
public MethodHandle getMethodHandle()
{
return methodHandle;
}
public List<ImplementationDependency> getDependencies()
{
return dependencies;
}
public static final class MethodHandleAndConstructor
{
private final MethodHandle methodHandle;
private final Optional<MethodHandle> constructor;
public MethodHandleAndConstructor(MethodHandle methodHandle, Optional<MethodHandle> constructor)
{
this.methodHandle = requireNonNull(methodHandle, "methodHandle is null");
this.constructor = requireNonNull(constructor, "constructor is null");
}
public MethodHandle getMethodHandle()
{
return methodHandle;
}
public Optional<MethodHandle> getConstructor()
{
return constructor;
}
}
private interface ImplementationDependency
{
Object resolve(BoundVariables boundVariables, TypeManager typeManager, FunctionRegistry functionRegistry);
}
private static final class FunctionImplementationDependency
extends ScalarImplementationDependency
{
private FunctionImplementationDependency(String name, TypeSignature returnType, List<TypeSignature> argumentTypes)
{
super(internalScalarFunction(name, returnType, argumentTypes));
}
}
private static final class OperatorImplementationDependency
extends ScalarImplementationDependency
{
private final OperatorType operator;
private OperatorImplementationDependency(OperatorType operator, TypeSignature returnType, List<TypeSignature> argumentTypes)
{
super(internalOperator(operator, returnType, argumentTypes));
this.operator = requireNonNull(operator, "operator is null");
}
public OperatorType getOperator()
{
return operator;
}
}
private abstract static class ScalarImplementationDependency
implements ImplementationDependency
{
private final Signature signature;
private ScalarImplementationDependency(Signature signature)
{
this.signature = requireNonNull(signature, "signature is null");
}
public Signature getSignature()
{
return signature;
}
@Override
public MethodHandle resolve(BoundVariables boundVariables, TypeManager typeManager, FunctionRegistry functionRegistry)
{
Signature signature = applyBoundVariables(this.signature, boundVariables, this.signature.getArgumentTypes().size());
return functionRegistry.getScalarFunctionImplementation(signature).getMethodHandle();
}
}
private static final class TypeImplementationDependency
implements ImplementationDependency
{
private final TypeSignature signature;
private TypeImplementationDependency(String signature)
{
this.signature = parseTypeSignature(requireNonNull(signature, "signature is null"));
}
@Override
public Type resolve(BoundVariables boundVariables, TypeManager typeManager, FunctionRegistry functionRegistry)
{
return typeManager.getType(applyBoundVariables(signature, boundVariables));
}
}
private static final class LiteralImplementationDependency
implements ImplementationDependency
{
private final String literalName;
private LiteralImplementationDependency(String literalName)
{
this.literalName = requireNonNull(literalName, "literalName is null");
}
@Override
public Long resolve(BoundVariables boundVariables, TypeManager typeManager, FunctionRegistry functionRegistry)
{
return boundVariables.getLongVariable(literalName);
}
}
public static final class Parser
{
private static final Set<OperatorType> COMPARABLE_TYPE_OPERATORS = ImmutableSet.of(EQUAL, NOT_EQUAL, HASH_CODE);
private static final Set<OperatorType> ORDERABLE_TYPE_OPERATORS = ImmutableSet.of(LESS_THAN, LESS_THAN_OR_EQUAL, GREATER_THAN, GREATER_THAN_OR_EQUAL, BETWEEN);
private final String functionName;
private final boolean nullable;
private final List<Boolean> nullableArguments = new ArrayList<>();
private final List<Boolean> nullFlags = new ArrayList<>();
private final TypeSignature returnType;
private final List<TypeSignature> argumentTypes = new ArrayList<>();
private final List<Class<?>> argumentNativeContainerTypes = new ArrayList<>();
private final MethodHandle methodHandle;
private final List<ImplementationDependency> dependencies = new ArrayList<>();
private final LinkedHashSet<TypeParameter> typeParameters = new LinkedHashSet<>();
private final ImmutableSet<String> typeParameterNames;
private final Set<String> literalParameters = new HashSet<>();
private final Map<String, Class<?>> specializedTypeParameters;
private final Optional<MethodHandle> constructorMethodHandle;
private final List<ImplementationDependency> constructorDependencies = new ArrayList<>();
private final List<LongVariableConstraint> longVariableConstraints = new ArrayList<>();
private Parser(String functionName, Method method, Map<Set<TypeParameter>, Constructor<?>> constructors)
{
this.functionName = requireNonNull(functionName, "functionName is null");
this.nullable = method.getAnnotation(SqlNullable.class) != null;
checkArgument(nullable || !containsLegacyNullable(method.getAnnotations()), "Method [%s] is annotated with @Nullable but not @SqlNullable", method);
Stream.of(method.getAnnotationsByType(TypeParameter.class))
.forEach(typeParameters::add);
typeParameterNames = typeParameters.stream()
.map(TypeParameter::value)
.collect(toImmutableSet());
LiteralParameters literalParametersAnnotation = method.getAnnotation(LiteralParameters.class);
if (literalParametersAnnotation != null) {
literalParameters.addAll(asList(literalParametersAnnotation.value()));
}
SqlType returnType = method.getAnnotation(SqlType.class);
checkArgument(returnType != null, format("Method [%s] is missing @SqlType annotation", method));
this.returnType = parseTypeSignature(returnType.value(), literalParameters);
Class<?> actualReturnType = method.getReturnType();
if (Primitives.isWrapperType(actualReturnType)) {
checkArgument(nullable, "Method [%s] has wrapper return type %s but is missing @SqlNullable", method, actualReturnType.getSimpleName());
}
else if (actualReturnType.isPrimitive()) {
checkArgument(!nullable, "Method [%s] annotated with @SqlNullable has primitive return type %s", method, actualReturnType.getSimpleName());
}
Stream.of(method.getAnnotationsByType(Constraint.class))
.map(annotation -> new LongVariableConstraint(annotation.variable(), annotation.expression()))
.forEach(longVariableConstraints::add);
this.specializedTypeParameters = getDeclaredSpecializedTypeParameters(method);
for (TypeParameter typeParameter : typeParameters) {
checkArgument(
typeParameter.value().matches("[A-Z][A-Z0-9]*"),
"Expected type parameter to only contain A-Z and 0-9 (starting with A-Z), but got %s on method [%s]", typeParameter.value(), method);
}
parseArguments(method);
this.constructorMethodHandle = getConstructor(method, constructors);
this.methodHandle = getMethodHandle(method);
}
private void parseArguments(Method method)
{
for (int i = 0; i < method.getParameterCount(); i++) {
Annotation[] annotations = method.getParameterAnnotations()[i];
Class<?> parameterType = method.getParameterTypes()[i];
// Skip injected parameters
if (parameterType == ConnectorSession.class) {
continue;
}
if (containsMetaParameter(annotations)) {
checkArgument(annotations.length == 1, "Meta parameters may only have a single annotation [%s]", method);
checkArgument(argumentTypes.isEmpty(), "Meta parameter must come before parameters [%s]", method);
Annotation annotation = annotations[0];
if (annotation instanceof TypeParameter) {
checkTypeParameters(parseTypeSignature(((TypeParameter) annotation).value()), method, typeParameterNames);
}
if (annotation instanceof LiteralParameter) {
checkArgument(literalParameters.contains(((LiteralParameter) annotation).value()), "Parameter injected by @LiteralParameter must be declared with @LiteralParameters on the method [%s]", method);
}
dependencies.add(parseDependency(annotation));
}
else {
checkArgument(!Stream.of(annotations).anyMatch(IsNull.class::isInstance), "Method [%s] has @IsNull parameter that does not follow a @SqlType parameter", method);
SqlType type = Stream.of(annotations)
.filter(SqlType.class::isInstance)
.map(SqlType.class::cast)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException(format("Method [%s] is missing @SqlType annotation for parameter", method)));
boolean nullableArgument = Stream.of(annotations).anyMatch(SqlNullable.class::isInstance);
checkArgument(nullableArgument || !containsLegacyNullable(annotations), "Method [%s] has parameter annotated with @Nullable but not @SqlNullable", method);
boolean hasNullFlag = false;
if (method.getParameterCount() > (i + 1)) {
Annotation[] parameterAnnotations = method.getParameterAnnotations()[i + 1];
if (Stream.of(parameterAnnotations).anyMatch(IsNull.class::isInstance)) {
Class<?> isNullType = method.getParameterTypes()[i + 1];
checkArgument(Stream.of(parameterAnnotations).filter(Parser::isPrestoAnnotation).allMatch(IsNull.class::isInstance), "Method [%s] has @IsNull parameter that has other annotations", method);
checkArgument(isNullType == boolean.class, "Method [%s] has non-boolean parameter with @IsNull", method);
checkArgument((parameterType == Void.class) || !Primitives.isWrapperType(parameterType), "Method [%s] uses @IsNull following a parameter with boxed primitive type: %s", method, parameterType.getSimpleName());
nullableArgument = true;
hasNullFlag = true;
}
}
if (Primitives.isWrapperType(parameterType)) {
checkArgument(nullableArgument, "Method [%s] has parameter with wrapper type %s that is missing @SqlNullable", method, parameterType.getSimpleName());
}
else if (parameterType.isPrimitive() && !hasNullFlag) {
checkArgument(!nullableArgument, "Method [%s] has parameter with primitive type %s annotated with @SqlNullable", method, parameterType.getSimpleName());
}
if (typeParameterNames.contains(type.value()) && !(parameterType == Object.class && nullableArgument)) {
// Infer specialization on this type parameter. We don't do this for @SqlNullable Object because it could match a type like BIGINT
Class<?> specialization = specializedTypeParameters.get(type.value());
Class<?> nativeParameterType = Primitives.unwrap(parameterType);
checkArgument(specialization == null || specialization.equals(nativeParameterType), "Method [%s] type %s has conflicting specializations %s and %s", method, type.value(), specialization, nativeParameterType);
specializedTypeParameters.put(type.value(), nativeParameterType);
}
argumentNativeContainerTypes.add(parameterType);
argumentTypes.add(parseTypeSignature(type.value(), literalParameters));
if (hasNullFlag) {
// skip @IsNull parameter
i++;
}
nullableArguments.add(nullableArgument);
nullFlags.add(hasNullFlag);
}
}
}
private void checkTypeParameters(TypeSignature typeSignature, Method method, Set<String> typeParameterNames)
{
// Check recursively if `typeSignature` contains something like `T<bigint>`
if (typeParameterNames.contains(typeSignature.getBase())) {
checkArgument(typeSignature.getParameters().isEmpty(), "Expected type parameter not to take parameters, but got %s on method [%s]", typeSignature.getBase(), method);
return;
}
for (TypeSignatureParameter parameter : typeSignature.getParameters()) {
Optional<TypeSignature> childTypeSignature = parameter.getTypeSignatureOrNamedTypeSignature();
if (childTypeSignature.isPresent()) {
checkTypeParameters(childTypeSignature.get(), method, typeParameterNames);
}
}
}
// Find matching constructor, if this is an instance method, and populate constructorDependencies
private Optional<MethodHandle> getConstructor(Method method, Map<Set<TypeParameter>, Constructor<?>> constructors)
{
if (isStatic(method.getModifiers())) {
return Optional.empty();
}
Constructor<?> constructor = constructors.get(typeParameters);
checkArgument(constructor != null, "Method [%s] is an instance method and requires a public constructor to be declared with %s type parameters", method, typeParameters);
for (int i = 0; i < constructor.getParameterCount(); i++) {
Annotation[] annotations = constructor.getParameterAnnotations()[i];
checkArgument(containsMetaParameter(annotations), "Constructors may only have meta parameters [%s]", constructor);
checkArgument(annotations.length == 1, "Meta parameters may only have a single annotation [%s]", constructor);
Annotation annotation = annotations[0];
if (annotation instanceof TypeParameter) {
checkTypeParameters(parseTypeSignature(((TypeParameter) annotation).value()), method, typeParameterNames);
}
constructorDependencies.add(parseDependency(annotation));
}
try {
return Optional.of(lookup().unreflectConstructor(constructor));
}
catch (IllegalAccessException e) {
throw new PrestoException(FUNCTION_IMPLEMENTATION_ERROR, e);
}
}
private Map<String, Class<?>> getDeclaredSpecializedTypeParameters(Method method)
{
Map<String, Class<?>> specializedTypeParameters = new HashMap<>();
TypeParameterSpecialization[] typeParameterSpecializations = method.getAnnotationsByType(TypeParameterSpecialization.class);
ImmutableSet<String> typeParameterNames = typeParameters.stream()
.map(TypeParameter::value)
.collect(toImmutableSet());
for (TypeParameterSpecialization specialization : typeParameterSpecializations) {
checkArgument(typeParameterNames.contains(specialization.name()), "%s does not match any declared type parameters (%s) [%s]", specialization.name(), typeParameters, method);
Class<?> existingSpecialization = specializedTypeParameters.get(specialization.name());
checkArgument(existingSpecialization == null || existingSpecialization.equals(specialization.nativeContainerType()),
"%s has conflicting specializations %s and %s [%s]", specialization.name(), existingSpecialization, specialization.nativeContainerType(), method);
specializedTypeParameters.put(specialization.name(), specialization.nativeContainerType());
}
return specializedTypeParameters;
}
private MethodHandle getMethodHandle(Method method)
{
MethodHandle methodHandle;
try {
methodHandle = lookup().unreflect(method);
}
catch (IllegalAccessException e) {
throw new PrestoException(FUNCTION_IMPLEMENTATION_ERROR, e);
}
if (!isStatic(method.getModifiers())) {
// Re-arrange the parameters, so that the "this" parameter is after the meta parameters
int[] permutedIndices = new int[methodHandle.type().parameterCount()];
permutedIndices[0] = dependencies.size();
MethodType newType = methodHandle.type().changeParameterType(dependencies.size(), methodHandle.type().parameterType(0));
for (int i = 0; i < dependencies.size(); i++) {
permutedIndices[i + 1] = i;
newType = newType.changeParameterType(i, methodHandle.type().parameterType(i + 1));
}
for (int i = dependencies.size() + 1; i < permutedIndices.length; i++) {
permutedIndices[i] = i;
}
methodHandle = permuteArguments(methodHandle, newType, permutedIndices);
}
return methodHandle;
}
private static List<TypeVariableConstraint> createTypeVariableConstraints(Iterable<TypeParameter> typeParameters, List<ImplementationDependency> dependencies)
{
Set<String> orderableRequired = new HashSet<>();
Set<String> comparableRequired = new HashSet<>();
for (ImplementationDependency dependency : dependencies) {
if (dependency instanceof OperatorImplementationDependency) {
OperatorType operator = ((OperatorImplementationDependency) dependency).getOperator();
if (operator == CAST) {
continue;
}
Set<String> argumentTypes = ((OperatorImplementationDependency) dependency).getSignature().getArgumentTypes().stream()
.map(TypeSignature::getBase)
.collect(toImmutableSet());
checkArgument(argumentTypes.size() == 1, "Operator dependency must only have arguments of a single type");
String argumentType = Iterables.getOnlyElement(argumentTypes);
if (COMPARABLE_TYPE_OPERATORS.contains(operator)) {
comparableRequired.add(argumentType);
}
if (ORDERABLE_TYPE_OPERATORS.contains(operator)) {
orderableRequired.add(argumentType);
}
}
}
ImmutableList.Builder<TypeVariableConstraint> typeVariableConstraints = ImmutableList.builder();
for (TypeParameter typeParameter : typeParameters) {
String name = typeParameter.value();
if (orderableRequired.contains(name)) {
typeVariableConstraints.add(orderableTypeParameter(name));
}
else if (comparableRequired.contains(name)) {
typeVariableConstraints.add(comparableTypeParameter(name));
}
else {
typeVariableConstraints.add(typeVariable(name));
}
}
return typeVariableConstraints.build();
}
private ImplementationDependency parseDependency(Annotation annotation)
{
if (annotation instanceof TypeParameter) {
return new TypeImplementationDependency(((TypeParameter) annotation).value());
}
if (annotation instanceof LiteralParameter) {
return new LiteralImplementationDependency(((LiteralParameter) annotation).value());
}
if (annotation instanceof FunctionDependency) {
FunctionDependency function = (FunctionDependency) annotation;
return new FunctionImplementationDependency(
function.name(),
parseTypeSignature(function.returnType(), literalParameters),
Arrays.stream(function.argumentTypes())
.map(signature -> parseTypeSignature(signature, literalParameters))
.collect(toImmutableList()));
}
if (annotation instanceof OperatorDependency) {
OperatorDependency operator = (OperatorDependency) annotation;
return new OperatorImplementationDependency(
operator.operator(),
parseTypeSignature(operator.returnType(), literalParameters),
Arrays.stream(operator.argumentTypes())
.map(signature -> parseTypeSignature(signature, literalParameters))
.collect(toImmutableList()));
}
throw new IllegalArgumentException("Unsupported annotation " + annotation.getClass().getSimpleName());
}
private static boolean containsMetaParameter(Annotation[] annotations)
{
for (Annotation annotation : annotations) {
if (isMetaParameter(annotation)) {
return true;
}
}
return false;
}
private static boolean isMetaParameter(Annotation annotation)
{
return annotation instanceof TypeParameter ||
annotation instanceof LiteralParameter ||
annotation instanceof FunctionDependency ||
annotation instanceof OperatorDependency;
}
public ScalarImplementation get()
{
Signature signature = new Signature(
functionName,
SCALAR,
createTypeVariableConstraints(typeParameters, dependencies),
longVariableConstraints,
returnType,
argumentTypes,
false);
return new ScalarImplementation(
signature,
nullable,
nullableArguments,
nullFlags,
methodHandle,
dependencies,
constructorMethodHandle,
constructorDependencies,
argumentNativeContainerTypes,
specializedTypeParameters);
}
public static ScalarImplementation parseImplementation(String functionName, Method method, Map<Set<TypeParameter>, Constructor<?>> constructors)
{
return new Parser(functionName, method, constructors).get();
}
private static boolean containsLegacyNullable(Annotation[] annotations)
{
return Arrays.stream(annotations)
.map(Annotation::annotationType)
.map(Class::getName)
.anyMatch(name -> name.equals(Nullable.class.getName()));
}
private static boolean isPrestoAnnotation(Annotation annotation)
{
return isMetaParameter(annotation) ||
annotation instanceof SqlType ||
annotation instanceof SqlNullable ||
annotation instanceof IsNull;
}
}
}
| |
/* -------------------------------------------------------------------------- *
* OpenSim: SingleModelGuiElements.java *
* -------------------------------------------------------------------------- *
* OpenSim is a toolkit for musculoskeletal modeling and simulation, *
* developed as an open source project by a worldwide community. Development *
* and support is coordinated from Stanford University, with funding from the *
* U.S. NIH and DARPA. See http://opensim.stanford.edu and the README file *
* for more information including specific grant numbers. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ayman Habib *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
/*
* SingleModelVisuals.java
*
* Created on November 14, 2006, 5:46 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.opensim.view;
import java.util.ArrayList;
import java.util.Vector;
import org.opensim.modeling.ArrayConstObjPtr;
import org.opensim.modeling.Force;
import org.opensim.modeling.Muscle;
import org.opensim.modeling.ForceSet;
import org.opensim.modeling.ArrayStr;
import org.opensim.modeling.BodyIterator;
import org.opensim.modeling.BodyList;
import org.opensim.modeling.Model;
import org.opensim.modeling.Coordinate;
import org.opensim.modeling.CoordinateSet;
import org.opensim.modeling.FrameIterator;
import org.opensim.modeling.FrameList;
import org.opensim.modeling.MarkerSet;
import org.opensim.modeling.ObjectGroup;
import org.opensim.modeling.OpenSimContext;
import org.opensim.modeling.PhysicalFrame;
import org.opensim.view.pub.OpenSimDB;
/**
*
* @author Pete Loan & Ayman Habib
*/
public class SingleModelGuiElements {
String preferredUnits; // Place holder for model specific Gui pref.
Model model; // model that Gui elements are created for
private String[] bodyNames=null;
private String[] frameNames=null;
private String[] physicalFrameNames=null;
private String[] coordinateNames=null;
private String[] unconstrainedCoordinateNames=null;
private String[] actuatorClassNames=null;
private String[] actuatorNames=null;
private String[] markerNames=null;
private boolean unsavedChanges = false;
// Not a semaphore, just a flag to disallow the closing (and possibly editing)
// of a model while in use.
private boolean locked = false;
private String lockOwner = null;
OpenSimContext context;
NavigatorByTypeModel navigatorByTypeModel;
public SingleModelGuiElements(Model model)
{
this.model=model;
context = OpenSimDB.getInstance().getContext(model);
}
/**
* Turn on/off the flag for marking changes to the model.
*/
public void setUnsavedChangesFlag(boolean state)
{
unsavedChanges = state;
}
/**
* Get the flag for marking changes to the model.
*/
public boolean getUnsavedChangesFlag()
{
return unsavedChanges;
}
/**
* Get the flag for marking the model as locked.
*/
public boolean isLocked()
{
return locked;
}
/**
* Get the owner of the lock.
*/
public String getLockOwner()
{
return lockOwner;
}
/**
* Mark the model as locked. If it's already locked, return false.
*/
public boolean lockModel(String owner)
{
if (locked == false) {
locked = true;
lockOwner = owner;
return true;
} else {
return false;
}
}
/**
* Unlock the model.
*/
public void unlockModel()
{
locked = false;
lockOwner = "";
}
/**
* Get a list of names for model frames
*/
public String[] getBodyNames()
{
if (bodyNames == null) {
BodyList bodies = model.getBodyList();
BodyIterator bi = bodies.begin();
ArrayList<String> bNames = new ArrayList<String>();
while (!bi.equals(bodies.end())) {
bNames.add(bi.getName());
bi.next();
}
bodyNames = new String[bNames.size()];
bNames.toArray(bodyNames);
}
return bodyNames;
}
// This method populates frameNames and physicalFrameNames for later use
public String[] getFrameNames()
{
if (frameNames == null) {
FrameList frames = model.getFrameList();
FrameIterator bi = frames.begin();
ArrayList<String> bNames = new ArrayList<String>();
ArrayList<String> phFrameNames = new ArrayList<String>();
while (!bi.equals(frames.end())) {
bNames.add(bi.getAbsolutePathString());
if (PhysicalFrame.safeDownCast(bi.__deref__())!= null)
phFrameNames.add(bi.getAbsolutePathString());
bi.next();
}
frameNames = new String[bNames.size()];
bNames.toArray(frameNames);
physicalFrameNames = new String[phFrameNames.size()];
phFrameNames.toArray(getPhysicalFrameNames());
}
return frameNames;
}
/**
* Get a list of names for model coordinates
*/
public String[] getCoordinateNames()
{
if (coordinateNames==null){
CoordinateSet coordinates = model.getCoordinateSet();
coordinateNames = new String[coordinates.getSize()];
for (int i = 0; i < coordinates.getSize(); i++)
coordinateNames[i] = new String(coordinates.get(i).getName());
}
return coordinateNames;
}
/**
* Get a list of names for model coordinates
*/
public String[] getUnconstrainedCoordinateNames()
{
if (unconstrainedCoordinateNames==null){
CoordinateSet coordinates = model.getCoordinateSet();
Vector<String> coordinateNamesVec = new Vector<String>();
for (int i = 0; i < coordinates.getSize(); i++){
Coordinate coord = coordinates.get(i);
boolean constrained = context.isConstrained(coord);
if (!constrained)
coordinateNamesVec.add(coord.getName());
}
unconstrainedCoordinateNames= new String[coordinateNamesVec.size()];
coordinateNamesVec.toArray(unconstrainedCoordinateNames);
}
return unconstrainedCoordinateNames;
}
/**
* Get a list of names for actuator groups in model
*/
public Vector<String> getActuatorGroupNames()
{
Vector<String> ret=new Vector<String>(4);
ForceSet actuators = model.getForceSet();
if (actuators !=null){
ArrayStr muscleGroupNames = new ArrayStr();
actuators.getGroupNames(muscleGroupNames);
for(int i=0; i<muscleGroupNames.getSize();i++){
ret.add(muscleGroupNames.getitem(i));
Force act = actuators.get(i);
}
}
return ret;
}
/**
* Get Actuators that belong to the passed in muscle group
*/
public Vector<String> getActuatorNamesForGroup(String groupName)
{
Vector<String> ret = new Vector<String>(20);
ForceSet actuators = model.getForceSet();
if (actuators !=null){
ObjectGroup group=actuators.getGroup(groupName);
assert(group!=null);
ArrayConstObjPtr objects = group.getMembers();
for(int i=0; i<objects.getSize();i++){
ret.add(objects.getitem(i).getName());
}
}
return ret;
}
/**
* Get a list of names for model actuators that are muscles
*/
public Vector<String> getMuscleNames()
{
Vector<String> ret=new Vector<String>(20);
ForceSet actuators = model.getForceSet();
if (actuators !=null){
for(int i=0; i<actuators.getSize();i++){
if (Muscle.safeDownCast(actuators.get(i)) != null)
ret.add(actuators.get(i).getName());
}
}
return ret;
}
/**
* Get a list of names for the model's markers
*/
public String[] getMarkerNames()
{
if (markerNames == null)
updateMarkerNames();
return markerNames;
}
public void updateMarkerNames()
{
ArrayList<String> namesList = new ArrayList<String>(4);
MarkerSet markers = model.getMarkerSet();
if (markers != null) {
for (int i=0; i<markers.getSize(); i++)
namesList.add(markers.get(i).getName());
}
markerNames = new String[namesList.size()];
System.arraycopy(namesList.toArray(), 0, markerNames, 0, namesList.size());
java.util.Arrays.sort(markerNames);
}
/**
* Get names of actuators
*/
public String[] getActuatorNames()
{
if (actuatorNames == null)
updateActuatorNames();
return actuatorNames;
}
public void updateActuatorNames()
{
ArrayList<String> namesList = new ArrayList<String>(4);
ForceSet actuators = model.getForceSet();
if (actuators != null) {
for (int i=0; i<actuators.getSize(); i++) {
Force act =actuators.get(i);
Muscle muscle = Muscle.safeDownCast(act);
if (muscle != null) {
namesList.add(muscle.getName());
}
}
}
actuatorNames = new String[namesList.size()];
System.arraycopy(namesList.toArray(), 0, actuatorNames, 0, namesList.size());
java.util.Arrays.sort(actuatorNames);
}
/**
* @return the physicalFrameNames
*/
public String[] getPhysicalFrameNames() {
if (frameNames == null) {
getFrameNames(); // For the side effect of populating both frameNames and physicalFrameNames
}
return physicalFrameNames;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.physical.impl.filter;
import java.io.IOException;
import java.util.List;
import org.apache.drill.common.expression.ErrorCollector;
import org.apache.drill.common.expression.ErrorCollectorImpl;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.exec.exception.ClassTransformationException;
import org.apache.drill.exec.exception.OutOfMemoryException;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.expr.ClassGenerator;
import org.apache.drill.exec.expr.CodeGenerator;
import org.apache.drill.exec.expr.ExpressionTreeMaterializer;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.physical.config.Filter;
import org.apache.drill.exec.record.AbstractSingleRecordBatch;
import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.exec.record.TransferPair;
import org.apache.drill.exec.record.VectorWrapper;
import org.apache.drill.exec.record.selection.SelectionVector2;
import org.apache.drill.exec.record.selection.SelectionVector4;
import org.apache.drill.exec.vector.ValueVector;
import com.google.common.collect.Lists;
public class FilterRecordBatch extends AbstractSingleRecordBatch<Filter>{
//private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FilterRecordBatch.class);
private SelectionVector2 sv2;
private SelectionVector4 sv4;
private Filterer filter;
public FilterRecordBatch(Filter pop, RecordBatch incoming, FragmentContext context) throws OutOfMemoryException {
super(pop, context, incoming);
}
@Override
public FragmentContext getContext() {
return context;
}
@Override
public int getRecordCount() {
return sv2 != null ? sv2.getCount() : sv4.getCount();
}
@Override
public SelectionVector2 getSelectionVector2() {
return sv2;
}
@Override
public SelectionVector4 getSelectionVector4() {
return sv4;
}
@Override
protected IterOutcome doWork() {
container.zeroVectors();
int recordCount = incoming.getRecordCount();
filter.filterBatch(recordCount);
return IterOutcome.OK;
}
@Override
public void close() {
if (sv2 != null) {
sv2.clear();
}
if (sv4 != null) {
sv4.clear();
}
super.close();
}
@Override
protected boolean setupNewSchema() throws SchemaChangeException {
if (sv2 != null) {
sv2.clear();
}
switch (incoming.getSchema().getSelectionVectorMode()) {
case NONE:
if (sv2 == null) {
sv2 = new SelectionVector2(oContext.getAllocator());
}
this.filter = generateSV2Filterer();
break;
case TWO_BYTE:
sv2 = new SelectionVector2(oContext.getAllocator());
this.filter = generateSV2Filterer();
break;
case FOUR_BYTE:
/*
* Filter does not support SV4 handling. There are couple of minor issues in the
* logic that handles SV4 + filter should always be pushed beyond sort so disabling
* it in FilterPrel.
*
// set up the multi-batch selection vector
this.svAllocator = oContext.getAllocator().getNewPreAllocator();
if (!svAllocator.preAllocate(incoming.getRecordCount()*4))
throw new SchemaChangeException("Attempted to filter an SV4 which exceeds allowed memory (" +
incoming.getRecordCount() * 4 + " bytes)");
sv4 = new SelectionVector4(svAllocator.getAllocation(), incoming.getRecordCount(), Character.MAX_VALUE);
this.filter = generateSV4Filterer();
break;
*/
default:
throw new UnsupportedOperationException();
}
if (container.isSchemaChanged()) {
container.buildSchema(SelectionVectorMode.TWO_BYTE);
return true;
}
return false;
}
protected Filterer generateSV4Filterer() throws SchemaChangeException {
final ErrorCollector collector = new ErrorCollectorImpl();
final List<TransferPair> transfers = Lists.newArrayList();
final ClassGenerator<Filterer> cg = CodeGenerator.getRoot(Filterer.TEMPLATE_DEFINITION4, context.getFunctionRegistry(), context.getOptions());
final LogicalExpression expr = ExpressionTreeMaterializer.materialize(popConfig.getExpr(), incoming, collector, context.getFunctionRegistry());
if (collector.hasErrors()) {
throw new SchemaChangeException(String.format("Failure while trying to materialize incoming schema. Errors:\n %s.", collector.toErrorString()));
}
cg.addExpr(new ReturnValueExpression(expr), ClassGenerator.BlkCreateMode.FALSE);
for (final VectorWrapper<?> vw : incoming) {
for (final ValueVector vv : vw.getValueVectors()) {
final TransferPair pair = vv.getTransferPair(oContext.getAllocator());
container.add(pair.getTo());
transfers.add(pair);
}
}
// allocate outgoing sv4
container.buildSchema(SelectionVectorMode.FOUR_BYTE);
try {
final TransferPair[] tx = transfers.toArray(new TransferPair[transfers.size()]);
final Filterer filter = context.getImplementationClass(cg);
filter.setup(context, incoming, this, tx);
return filter;
} catch (ClassTransformationException | IOException e) {
throw new SchemaChangeException("Failure while attempting to load generated class", e);
}
}
protected Filterer generateSV2Filterer() throws SchemaChangeException {
final ErrorCollector collector = new ErrorCollectorImpl();
final List<TransferPair> transfers = Lists.newArrayList();
final ClassGenerator<Filterer> cg = CodeGenerator.getRoot(Filterer.TEMPLATE_DEFINITION2, context.getFunctionRegistry(), context.getOptions());
final LogicalExpression expr = ExpressionTreeMaterializer.materialize(popConfig.getExpr(), incoming, collector,
context.getFunctionRegistry(), false, unionTypeEnabled);
if (collector.hasErrors()) {
throw new SchemaChangeException(String.format("Failure while trying to materialize incoming schema. Errors:\n %s.", collector.toErrorString()));
}
cg.addExpr(new ReturnValueExpression(expr), ClassGenerator.BlkCreateMode.FALSE);
for (final VectorWrapper<?> v : incoming) {
final TransferPair pair = v.getValueVector().makeTransferPair(container.addOrGet(v.getField(), callBack));
transfers.add(pair);
}
try {
final TransferPair[] tx = transfers.toArray(new TransferPair[transfers.size()]);
final Filterer filter = context.getImplementationClass(cg);
filter.setup(context, incoming, this, tx);
return filter;
} catch (ClassTransformationException | IOException e) {
throw new SchemaChangeException("Failure while attempting to load generated class", e);
}
}
}
| |
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.context.properties;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Utility that can be used to map values from a supplied source to a destination.
* Primarily intended to be help when mapping from
* {@link ConfigurationProperties @ConfigurationProperties} to third-party classes.
* <p>
* Can filter values based on predicates and adapt values if needed. For example:
* <pre class="code">
* PropertyMapper map = PropertyMapper.get();
* map.from(source::getName)
* .to(destination::setName);
* map.from(source::getTimeout)
* .whenNonNull()
* .asInt(Duration::getSeconds)
* .to(destination::setTimeoutSecs);
* map.from(source::isEnabled)
* .whenFalse().
* .toCall(destination::disable);
* </pre>
* <p>
* Mappings can ultimately be applied to a {@link Source#to(Consumer) setter}, trigger a
* {@link Source#toCall(Runnable) method call} or create a
* {@link Source#toInstance(Function) new instance}.
*
* @author Phillip Webb
* @since 2.0.0
*/
public final class PropertyMapper {
private static final Predicate<?> ALWAYS = (t) -> true;
private static final PropertyMapper INSTANCE = new PropertyMapper(null, null);
private final PropertyMapper parent;
private final SourceOperator sourceOperator;
private PropertyMapper(PropertyMapper parent, SourceOperator sourceOperator) {
this.parent = parent;
this.sourceOperator = sourceOperator;
}
/**
* Return a new {@link PropertyMapper} instance that applies
* {@link Source#whenNonNull() whenNonNull} to every source.
* @return a new property mapper instance
*/
public PropertyMapper alwaysApplyingWhenNonNull() {
return alwaysApplying(this::whenNonNull);
}
private <T> Source<T> whenNonNull(Source<T> source) {
return source.whenNonNull();
}
/**
* Return a new {@link PropertyMapper} instance that applies the given
* {@link SourceOperator} to every source.
* @param operator the source operator to apply
* @return a new property mapper instance
*/
public PropertyMapper alwaysApplying(SourceOperator operator) {
Assert.notNull(operator, "Operator must not be null");
return new PropertyMapper(this, operator);
}
/**
* Return a new {@link Source} from the specified value supplier that can be used to
* perform the mapping.
* @param <T> the source type
* @param supplier the value supplier
* @return a {@link Source} that can be used to complete the mapping
*/
public <T> Source<T> from(Supplier<T> supplier) {
Assert.notNull(supplier, "Supplier must not be null");
Source<T> source = getSource(supplier);
if (this.sourceOperator != null) {
source = this.sourceOperator.apply(source);
}
return source;
}
@SuppressWarnings("unchecked")
private <T> Source<T> getSource(Supplier<T> supplier) {
if (this.parent != null) {
return this.parent.from(supplier);
}
return new Source<>(new CachingSupplier<>(supplier), (Predicate<T>) ALWAYS);
}
/**
* Return the property mapper.
* @return the property mapper
*/
public static PropertyMapper get() {
return INSTANCE;
}
/**
* Supplier that caches the value to prevent multiple calls.
*/
private static class CachingSupplier<T> implements Supplier<T> {
private final Supplier<T> supplier;
private boolean hasResult;
private T result;
CachingSupplier(Supplier<T> supplier) {
this.supplier = supplier;
}
@Override
public T get() {
if (!this.hasResult) {
this.result = this.supplier.get();
this.hasResult = true;
}
return this.result;
}
}
/**
* An operation that can be applied to a {@link Source}.
*/
@FunctionalInterface
public interface SourceOperator {
/**
* Apply the operation to the given source.
* @param <T> the source type
* @param source the source to operate on
* @return the updated source
*/
<T> Source<T> apply(Source<T> source);
}
/**
* A source that is in the process of being mapped.
* @param <T> the source type
*/
public final static class Source<T> {
private final Supplier<T> supplier;
private final Predicate<T> predicate;
private Source(Supplier<T> supplier, Predicate<T> predicate) {
Assert.notNull(predicate, "Predicate must not be null");
this.supplier = supplier;
this.predicate = predicate;
}
/**
* Return an adapted version of the source with {@link Integer} type.
* @param <R> the resulting type
* @param adapter an adapter to convert the current value to a number.
* @return a new adapted source instance
*/
public <R extends Number> Source<Integer> asInt(Function<T, R> adapter) {
return as(adapter).as(Number::intValue);
}
/**
* Return an adapted version of the source changed via the given adapter function.
* @param <R> the resulting type
* @param adapter the adapter to apply
* @return a new adapted source instance
*/
public <R> Source<R> as(Function<T, R> adapter) {
Assert.notNull(adapter, "Adapter must not be null");
Supplier<Boolean> test = () -> this.predicate.test(this.supplier.get());
Predicate<R> predicate = (t) -> test.get();
Supplier<R> supplier = () -> {
if (test.get()) {
return adapter.apply(this.supplier.get());
}
return null;
};
return new Source<>(supplier, predicate);
}
/**
* Return a filtered version of the source that won't map non-null values or
* suppliers that throw a {@link NullPointerException}.
* @return a new filtered source instance
*/
public Source<T> whenNonNull() {
return new Source<>(new NullPointerExceptionSafeSupplier<>(this.supplier),
Objects::nonNull);
}
/**
* Return a filtered version of the source that will only map values that
* {@code true}.
* @return a new filtered source instance
*/
public Source<T> whenTrue() {
return when(Boolean.TRUE::equals);
}
/**
* Return a filtered version of the source that will only map values that
* {@code false}.
* @return a new filtered source instance
*/
public Source<T> whenFalse() {
return when(Boolean.FALSE::equals);
}
/**
* Return a filtered version of the source that will only map values that have a
* {@code toString()} containing actual text.
* @return a new filtered source instance
*/
public Source<T> whenHasText() {
return when((value) -> StringUtils.hasText(Objects.toString(value, null)));
}
/**
* Return a filtered version of the source that will only map values equal to the
* specified {@code object}.
* @param object the object to match
* @return a new filtered source instance
*/
public Source<T> whenEqualTo(Object object) {
return when(object::equals);
}
/**
* Return a filtered version of the source that won't map values that match the
* given predicate.
* @param predicate the predicate used to filter values
* @return a new filtered source instance
*/
public Source<T> whenNot(Predicate<T> predicate) {
Assert.notNull(predicate, "Predicate must not be null");
return new Source<>(this.supplier, predicate.negate());
}
/**
* Return a filtered version of the source that won't map values that don't match
* the given predicate.
* @param predicate the predicate used to filter values
* @return a new filtered source instance
*/
public Source<T> when(Predicate<T> predicate) {
Assert.notNull(predicate, "Predicate must not be null");
return new Source<>(this.supplier, predicate);
}
/**
* Complete the mapping by passing any non-filtered value to the specified
* consumer.
* @param consumer the consumer that should accept the value if it's not been
* filtered
*/
public void to(Consumer<T> consumer) {
Assert.notNull(consumer, "Consumer must not be null");
T value = this.supplier.get();
if (this.predicate.test(value)) {
consumer.accept(value);
}
}
/**
* Complete the mapping by creating a new instance from the non-filtered value.
* @param <R> the resulting type
* @param factory the factory used to create the instance
* @return the instance
* @throws NoSuchElementException if the value has been filtered
*/
public <R> R toInstance(Function<T, R> factory) {
Assert.notNull(factory, "Factory must not be null");
T value = this.supplier.get();
if (!this.predicate.test(value)) {
throw new NoSuchElementException("No value present");
}
return factory.apply(value);
}
/**
* Complete the mapping by calling the specified method when the value has not
* been filtered.
* @param runnable the method to call if the value has not been filtered
*/
public void toCall(Runnable runnable) {
Assert.notNull(runnable, "Runnable must not be null");
T value = this.supplier.get();
if (this.predicate.test(value)) {
runnable.run();
}
}
}
/**
* Supplier that will catch and ignore any {@link NullPointerException}.
*/
private static class NullPointerExceptionSafeSupplier<T> implements Supplier<T> {
private final Supplier<T> supplier;
NullPointerExceptionSafeSupplier(Supplier<T> supplier) {
this.supplier = supplier;
}
@Override
public T get() {
try {
return this.supplier.get();
}
catch (NullPointerException ex) {
return null;
}
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations;
import org.apache.lucene.index.AtomicReaderContext;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.util.ObjectArray;
import org.elasticsearch.search.aggregations.Aggregator.BucketAggregationMode;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
*/
public class AggregatorFactories {
public static final AggregatorFactories EMPTY = new Empty();
private AggregatorFactory[] factories;
public static Builder builder() {
return new Builder();
}
private AggregatorFactories(AggregatorFactory[] factories) {
this.factories = factories;
}
private static Aggregator createAndRegisterContextAware(AggregationContext context, AggregatorFactory factory, Aggregator parent, long estimatedBucketsCount) {
final Aggregator aggregator = factory.create(context, parent, estimatedBucketsCount);
if (aggregator.shouldCollect()) {
context.registerReaderContextAware(aggregator);
}
return aggregator;
}
/**
* Create all aggregators so that they can be consumed with multiple buckets.
*/
public Aggregator[] createSubAggregators(Aggregator parent, final long estimatedBucketsCount) {
Aggregator[] aggregators = new Aggregator[count()];
for (int i = 0; i < factories.length; ++i) {
final AggregatorFactory factory = factories[i];
final Aggregator first = createAndRegisterContextAware(parent.context(), factory, parent, estimatedBucketsCount);
if (first.bucketAggregationMode() == BucketAggregationMode.MULTI_BUCKETS) {
// This aggregator already supports multiple bucket ordinals, can be used directly
aggregators[i] = first;
continue;
}
// the aggregator doesn't support multiple ordinals, let's wrap it so that it does.
aggregators[i] = new Aggregator(first.name(), BucketAggregationMode.MULTI_BUCKETS, AggregatorFactories.EMPTY, 1, first.context(), first.parent()) {
ObjectArray<Aggregator> aggregators;
{
// if estimated count is zero, we at least create a single aggregator.
// The estimated count is just an estimation and we can't rely on how it's estimated (that is, an
// estimation of 0 should not imply that we'll end up without any buckets)
long arraySize = estimatedBucketsCount > 0 ? estimatedBucketsCount : 1;
aggregators = bigArrays.newObjectArray(arraySize);
aggregators.set(0, first);
}
@Override
public boolean shouldCollect() {
return first.shouldCollect();
}
@Override
protected void doPostCollection() throws IOException {
for (long i = 0; i < aggregators.size(); ++i) {
final Aggregator aggregator = aggregators.get(i);
if (aggregator != null) {
aggregator.postCollection();
}
}
}
@Override
public void collect(int doc, long owningBucketOrdinal) throws IOException {
aggregators = bigArrays.grow(aggregators, owningBucketOrdinal + 1);
Aggregator aggregator = aggregators.get(owningBucketOrdinal);
if (aggregator == null) {
aggregator = createAndRegisterContextAware(parent.context(), factory, parent, estimatedBucketsCount);
aggregators.set(owningBucketOrdinal, aggregator);
}
aggregator.collect(doc, 0);
}
@Override
public void setNextReader(AtomicReaderContext reader) {
}
@Override
public InternalAggregation buildAggregation(long owningBucketOrdinal) {
// The bucket ordinal may be out of range in case of eg. a terms/filter/terms where
// the filter matches no document in the highest buckets of the first terms agg
if (owningBucketOrdinal >= aggregators.size() || aggregators.get(owningBucketOrdinal) == null) {
return first.buildEmptyAggregation();
} else {
return aggregators.get(owningBucketOrdinal).buildAggregation(0);
}
}
@Override
public InternalAggregation buildEmptyAggregation() {
return first.buildEmptyAggregation();
}
@Override
public void doClose() {
Releasables.close(aggregators);
}
};
}
return aggregators;
}
public Aggregator[] createTopLevelAggregators(AggregationContext ctx) {
// These aggregators are going to be used with a single bucket ordinal, no need to wrap the PER_BUCKET ones
Aggregator[] aggregators = new Aggregator[factories.length];
for (int i = 0; i < factories.length; i++) {
aggregators[i] = createAndRegisterContextAware(ctx, factories[i], null, 0);
}
return aggregators;
}
public int count() {
return factories.length;
}
void setParent(AggregatorFactory parent) {
for (AggregatorFactory factory : factories) {
factory.parent = parent;
}
}
public void validate() {
for (AggregatorFactory factory : factories) {
factory.validate();
}
}
private final static class Empty extends AggregatorFactories {
private static final AggregatorFactory[] EMPTY_FACTORIES = new AggregatorFactory[0];
private static final Aggregator[] EMPTY_AGGREGATORS = new Aggregator[0];
private Empty() {
super(EMPTY_FACTORIES);
}
@Override
public Aggregator[] createSubAggregators(Aggregator parent, long estimatedBucketsCount) {
return EMPTY_AGGREGATORS;
}
@Override
public Aggregator[] createTopLevelAggregators(AggregationContext ctx) {
return EMPTY_AGGREGATORS;
}
}
public static class Builder {
private final Set<String> names = new HashSet<>();
private final List<AggregatorFactory> factories = new ArrayList<>();
public Builder add(AggregatorFactory factory) {
if (!names.add(factory.name)) {
throw new ElasticsearchIllegalArgumentException("Two sibling aggregations cannot have the same name: [" + factory.name + "]");
}
factories.add(factory);
return this;
}
public AggregatorFactories build() {
if (factories.isEmpty()) {
return EMPTY;
}
return new AggregatorFactories(factories.toArray(new AggregatorFactory[factories.size()]));
}
}
}
| |
/*
* Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.planner.consumer;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import io.crate.Constants;
import io.crate.analyze.HavingClause;
import io.crate.analyze.QuerySpec;
import io.crate.analyze.relations.AnalyzedRelation;
import io.crate.analyze.relations.PlannedAnalyzedRelation;
import io.crate.analyze.relations.QueriedDocTable;
import io.crate.analyze.symbol.Aggregation;
import io.crate.analyze.symbol.Symbol;
import io.crate.exceptions.VersionInvalidException;
import io.crate.metadata.Functions;
import io.crate.metadata.Routing;
import io.crate.metadata.RowGranularity;
import io.crate.metadata.doc.DocTableInfo;
import io.crate.planner.Planner;
import io.crate.planner.distribution.DistributionInfo;
import io.crate.planner.node.NoopPlannedAnalyzedRelation;
import io.crate.planner.node.dql.CollectPhase;
import io.crate.planner.node.dql.DistributedGroupBy;
import io.crate.planner.node.dql.GroupByConsumer;
import io.crate.planner.node.dql.MergePhase;
import io.crate.planner.projection.GroupProjection;
import io.crate.planner.projection.Projection;
import io.crate.planner.projection.TopNProjection;
import io.crate.planner.projection.builder.ProjectionBuilder;
import io.crate.planner.projection.builder.SplitPoints;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Singleton;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@Singleton
public class DistributedGroupByConsumer implements Consumer {
private final Visitor visitor;
@Inject
public DistributedGroupByConsumer(Functions functions) {
visitor = new Visitor(functions);
}
@Override
public PlannedAnalyzedRelation consume(AnalyzedRelation relation, ConsumerContext context) {
return visitor.process(relation, context);
}
private static class Visitor extends RelationPlanningVisitor {
private final Functions functions;
public Visitor(Functions functions) {
this.functions = functions;
}
@Override
public PlannedAnalyzedRelation visitQueriedDocTable(QueriedDocTable table, ConsumerContext context) {
if (!table.querySpec().groupBy().isPresent()) {
return null;
}
QuerySpec querySpec = table.querySpec();
List<Symbol> groupBy = querySpec.groupBy().get();
DocTableInfo tableInfo = table.tableRelation().tableInfo();
if(querySpec.where().hasVersions()){
context.validationException(new VersionInvalidException());
return null;
}
GroupByConsumer.validateGroupBySymbols(table.tableRelation(), groupBy);
ProjectionBuilder projectionBuilder = new ProjectionBuilder(functions, querySpec);
SplitPoints splitPoints = projectionBuilder.getSplitPoints();
// start: Map/Collect side
GroupProjection groupProjection = projectionBuilder.groupProjection(
splitPoints.leaves(),
groupBy,
splitPoints.aggregates(),
Aggregation.Step.ITER,
Aggregation.Step.PARTIAL);
groupProjection.setRequiredGranularity(RowGranularity.SHARD);
Planner.Context plannerContext = context.plannerContext();
Routing routing = plannerContext.allocateRouting(tableInfo, querySpec.where(), null);
CollectPhase collectNode = new CollectPhase(
plannerContext.jobId(),
plannerContext.nextExecutionPhaseId(),
"distributing collect",
routing,
tableInfo.rowGranularity(),
splitPoints.leaves(),
ImmutableList.<Projection>of(groupProjection),
querySpec.where(),
DistributionInfo.DEFAULT_MODULO
);
// end: Map/Collect side
// start: Reducer
List<Symbol> collectOutputs = new ArrayList<>(
groupBy.size() +
splitPoints.aggregates().size());
collectOutputs.addAll(groupBy);
collectOutputs.addAll(splitPoints.aggregates());
List<Projection> reducerProjections = new LinkedList<>();
reducerProjections.add(projectionBuilder.groupProjection(
collectOutputs,
groupBy,
splitPoints.aggregates(),
Aggregation.Step.PARTIAL,
Aggregation.Step.FINAL)
);
table.tableRelation().validateOrderBy(querySpec.orderBy());
Optional<HavingClause> havingClause = querySpec.having();
if (havingClause.isPresent()) {
if (havingClause.get().noMatch()) {
return new NoopPlannedAnalyzedRelation(table, plannerContext.jobId());
} else if (havingClause.get().hasQuery()) {
reducerProjections.add(ProjectionBuilder.filterProjection(
collectOutputs,
havingClause.get().query()
));
}
}
boolean isRootRelation = context.rootRelation() == table;
if (isRootRelation) {
reducerProjections.add(ProjectionBuilder.topNProjection(
collectOutputs,
querySpec.orderBy().orNull(),
0,
querySpec.limit().or(Constants.DEFAULT_SELECT_LIMIT) + querySpec.offset(),
querySpec.outputs()));
}
MergePhase mergePhase = new MergePhase(
plannerContext.jobId(),
plannerContext.nextExecutionPhaseId(),
"distributed merge",
collectNode.executionNodes().size(),
collectNode.outputTypes(),
reducerProjections,
DistributionInfo.DEFAULT_BROADCAST
);
mergePhase.executionNodes(ImmutableSet.copyOf(collectNode.executionNodes()));
// end: Reducer
MergePhase localMergeNode = null;
String localNodeId = plannerContext.clusterService().state().nodes().localNodeId();
if(isRootRelation) {
TopNProjection topN = ProjectionBuilder.topNProjection(
querySpec.outputs(),
querySpec.orderBy().orNull(),
querySpec.offset(),
querySpec.limit().or(Constants.DEFAULT_SELECT_LIMIT),
null);
localMergeNode = MergePhase.localMerge(
plannerContext.jobId(),
plannerContext.nextExecutionPhaseId(),
ImmutableList.<Projection>of(topN),
mergePhase.executionNodes().size(),
mergePhase.outputTypes());
localMergeNode.executionNodes(Sets.newHashSet(localNodeId));
}
return new DistributedGroupBy(
collectNode,
mergePhase,
localMergeNode,
plannerContext.jobId()
);
}
}
}
| |
package org.apache.lucene.analysis;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import java.util.List;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
import org.apache.lucene.queryParser.QueryParser; // for javadoc
import org.apache.lucene.util.Version;
/**
* Removes stop words from a token stream.
*/
public final class StopFilter extends TokenFilter {
// deprecated
private static boolean ENABLE_POSITION_INCREMENTS_DEFAULT = false;
private final CharArraySet stopWords;
private boolean enablePositionIncrements = ENABLE_POSITION_INCREMENTS_DEFAULT;
private TermAttribute termAtt;
private PositionIncrementAttribute posIncrAtt;
/**
* Construct a token stream filtering the given input.
* @deprecated Use {@link #StopFilter(boolean, TokenStream, String[])} instead
*/
public StopFilter(TokenStream input, String [] stopWords)
{
this(ENABLE_POSITION_INCREMENTS_DEFAULT, input, stopWords, false);
}
/**
* Construct a token stream filtering the given input.
* @param enablePositionIncrements true if token positions should record the removed stop words
* @param input input TokenStream
* @param stopWords array of stop words
* @deprecated Use {@link #StopFilter(boolean, TokenStream, Set)} instead.
*/
public StopFilter(boolean enablePositionIncrements, TokenStream input, String [] stopWords)
{
this(enablePositionIncrements, input, stopWords, false);
}
/**
* Constructs a filter which removes words from the input
* TokenStream that are named in the array of words.
* @deprecated Use {@link #StopFilter(boolean, TokenStream, String[], boolean)} instead
*/
public StopFilter(TokenStream in, String[] stopWords, boolean ignoreCase) {
this(ENABLE_POSITION_INCREMENTS_DEFAULT, in, stopWords, ignoreCase);
}
/**
* Constructs a filter which removes words from the input
* TokenStream that are named in the array of words.
* @param enablePositionIncrements true if token positions should record the removed stop words
* @param in input TokenStream
* @param stopWords array of stop words
* @param ignoreCase true if case is ignored
* @deprecated Use {@link #StopFilter(boolean, TokenStream, Set, boolean)} instead.
*/
public StopFilter(boolean enablePositionIncrements, TokenStream in, String[] stopWords, boolean ignoreCase) {
super(in);
this.stopWords = (CharArraySet)makeStopSet(stopWords, ignoreCase);
this.enablePositionIncrements = enablePositionIncrements;
init();
}
/**
* Construct a token stream filtering the given input.
* If <code>stopWords</code> is an instance of {@link CharArraySet} (true if
* <code>makeStopSet()</code> was used to construct the set) it will be directly used
* and <code>ignoreCase</code> will be ignored since <code>CharArraySet</code>
* directly controls case sensitivity.
* <p/>
* If <code>stopWords</code> is not an instance of {@link CharArraySet},
* a new CharArraySet will be constructed and <code>ignoreCase</code> will be
* used to specify the case sensitivity of that set.
*
* @param input
* @param stopWords The set of Stop Words.
* @param ignoreCase -Ignore case when stopping.
* @deprecated Use {@link #StopFilter(boolean, TokenStream, Set, boolean)} instead
*/
public StopFilter(TokenStream input, Set stopWords, boolean ignoreCase)
{
this(ENABLE_POSITION_INCREMENTS_DEFAULT, input, stopWords, ignoreCase);
}
/**
* Construct a token stream filtering the given input.
* If <code>stopWords</code> is an instance of {@link CharArraySet} (true if
* <code>makeStopSet()</code> was used to construct the set) it will be directly used
* and <code>ignoreCase</code> will be ignored since <code>CharArraySet</code>
* directly controls case sensitivity.
* <p/>
* If <code>stopWords</code> is not an instance of {@link CharArraySet},
* a new CharArraySet will be constructed and <code>ignoreCase</code> will be
* used to specify the case sensitivity of that set.
*
* @param enablePositionIncrements true if token positions should record the removed stop words
* @param input Input TokenStream
* @param stopWords The set of Stop Words.
* @param ignoreCase -Ignore case when stopping.
*/
public StopFilter(boolean enablePositionIncrements, TokenStream input, Set stopWords, boolean ignoreCase)
{
super(input);
if (stopWords instanceof CharArraySet) {
this.stopWords = (CharArraySet)stopWords;
} else {
this.stopWords = new CharArraySet(stopWords.size(), ignoreCase);
this.stopWords.addAll(stopWords);
}
this.enablePositionIncrements = enablePositionIncrements;
init();
}
/**
* Constructs a filter which removes words from the input
* TokenStream that are named in the Set.
*
* @see #makeStopSet(java.lang.String[])
* @deprecated Use {@link #StopFilter(boolean, TokenStream, Set)} instead
*/
public StopFilter(TokenStream in, Set stopWords) {
this(ENABLE_POSITION_INCREMENTS_DEFAULT, in, stopWords, false);
}
/**
* Constructs a filter which removes words from the input
* TokenStream that are named in the Set.
*
* @param enablePositionIncrements true if token positions should record the removed stop words
* @param in Input stream
* @param stopWords The set of Stop Words.
* @see #makeStopSet(java.lang.String[])
*/
public StopFilter(boolean enablePositionIncrements, TokenStream in, Set stopWords) {
this(enablePositionIncrements, in, stopWords, false);
}
public void init() {
termAtt = (TermAttribute) addAttribute(TermAttribute.class);
posIncrAtt = (PositionIncrementAttribute) addAttribute(PositionIncrementAttribute.class);
}
/**
* Builds a Set from an array of stop words,
* appropriate for passing into the StopFilter constructor.
* This permits this stopWords construction to be cached once when
* an Analyzer is constructed.
*
* @see #makeStopSet(java.lang.String[], boolean) passing false to ignoreCase
*/
public static final Set makeStopSet(String[] stopWords) {
return makeStopSet(stopWords, false);
}
/**
* Builds a Set from an array of stop words,
* appropriate for passing into the StopFilter constructor.
* This permits this stopWords construction to be cached once when
* an Analyzer is constructed.
*
* @see #makeStopSet(java.lang.String[], boolean) passing false to ignoreCase
*/
public static final Set makeStopSet(List/*<String>*/ stopWords) {
return makeStopSet(stopWords, false);
}
/**
*
* @param stopWords An array of stopwords
* @param ignoreCase If true, all words are lower cased first.
* @return a Set containing the words
*/
public static final Set makeStopSet(String[] stopWords, boolean ignoreCase) {
CharArraySet stopSet = new CharArraySet(stopWords.length, ignoreCase);
stopSet.addAll(Arrays.asList(stopWords));
return stopSet;
}
/**
*
* @param stopWords A List of Strings representing the stopwords
* @param ignoreCase if true, all words are lower cased first
* @return A Set containing the words
*/
public static final Set makeStopSet(List/*<String>*/ stopWords, boolean ignoreCase){
CharArraySet stopSet = new CharArraySet(stopWords.size(), ignoreCase);
stopSet.addAll(stopWords);
return stopSet;
}
/**
* Returns the next input Token whose term() is not a stop word.
*/
public final boolean incrementToken() throws IOException {
// return the first non-stop word found
int skippedPositions = 0;
while (input.incrementToken()) {
if (!stopWords.contains(termAtt.termBuffer(), 0, termAtt.termLength())) {
if (enablePositionIncrements) {
posIncrAtt.setPositionIncrement(posIncrAtt.getPositionIncrement() + skippedPositions);
}
return true;
}
skippedPositions += posIncrAtt.getPositionIncrement();
}
// reached EOS -- return null
return false;
}
/**
* @see #setEnablePositionIncrementsDefault(boolean).
* @deprecated Please specify this when you create the StopFilter
*/
public static boolean getEnablePositionIncrementsDefault() {
return ENABLE_POSITION_INCREMENTS_DEFAULT;
}
/**
* Returns version-dependent default for
* enablePositionIncrements. Analyzers that embed
* StopFilter use this method when creating the
* StopFilter. Prior to 2.9, this returns {@link #getEnablePositionIncrementsDefault}.
* On 2.9 or later, it returns true.
*/
public static boolean getEnablePositionIncrementsVersionDefault(Version matchVersion) {
if (matchVersion.onOrAfter(Version.LUCENE_29)) {
return true;
} else {
return ENABLE_POSITION_INCREMENTS_DEFAULT;
}
}
/**
* Set the default position increments behavior of every StopFilter created from now on.
* <p>
* Note: behavior of a single StopFilter instance can be modified
* with {@link #setEnablePositionIncrements(boolean)}.
* This static method allows control over behavior of classes using StopFilters internally,
* for example {@link org.apache.lucene.analysis.standard.StandardAnalyzer StandardAnalyzer}
* if used with the no-arg ctor.
* <p>
* Default : false.
* @see #setEnablePositionIncrements(boolean).
* @deprecated Please specify this when you create the StopFilter
*/
public static void setEnablePositionIncrementsDefault(boolean defaultValue) {
ENABLE_POSITION_INCREMENTS_DEFAULT = defaultValue;
}
/**
* @see #setEnablePositionIncrements(boolean).
*/
public boolean getEnablePositionIncrements() {
return enablePositionIncrements;
}
/**
* If <code>true</code>, this StopFilter will preserve
* positions of the incoming tokens (ie, accumulate and
* set position increments of the removed stop tokens).
* Generally, <code>true</code> is best as it does not
* lose information (positions of the original tokens)
* during indexing.
*
* <p> When set, when a token is stopped
* (omitted), the position increment of the following
* token is incremented.
*
* <p> <b>NOTE</b>: be sure to also
* set {@link QueryParser#setEnablePositionIncrements} if
* you use QueryParser to create queries.
*/
public void setEnablePositionIncrements(boolean enable) {
this.enablePositionIncrements = enable;
}
}
| |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.app.rest.editor;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.flowable.app.domain.editor.AbstractModel;
import org.flowable.app.domain.editor.AppDefinition;
import org.flowable.app.domain.editor.Model;
import org.flowable.app.model.common.ResultListDataRepresentation;
import org.flowable.app.model.editor.ModelKeyRepresentation;
import org.flowable.app.model.editor.ModelRepresentation;
import org.flowable.app.model.editor.decisiontable.DecisionTableDefinitionRepresentation;
import org.flowable.app.security.SecurityUtils;
import org.flowable.app.service.api.ModelService;
import org.flowable.app.service.editor.FlowableModelQueryService;
import org.flowable.app.service.exception.BadRequestException;
import org.flowable.app.service.exception.InternalServerErrorException;
import org.flowable.form.model.FormModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@RestController
public class ModelsResource {
private final Logger logger = LoggerFactory.getLogger(ModelsResource.class);
@Autowired
protected FlowableModelQueryService modelQueryService;
@Autowired
protected ModelService modelService;
@Autowired
protected ObjectMapper objectMapper;
@RequestMapping(value = "/rest/models", method = RequestMethod.GET, produces = "application/json")
public ResultListDataRepresentation getModels(@RequestParam(required = false) String filter, @RequestParam(required = false) String sort, @RequestParam(required = false) Integer modelType,
HttpServletRequest request) {
return modelQueryService.getModels(filter, sort, modelType, request);
}
@RequestMapping(value = "/rest/models-for-app-definition", method = RequestMethod.GET, produces = "application/json")
public ResultListDataRepresentation getModelsToIncludeInAppDefinition() {
return modelQueryService.getModelsToIncludeInAppDefinition();
}
@RequestMapping(value = "/rest/import-process-model", method = RequestMethod.POST, produces = "application/json")
public ModelRepresentation importProcessModel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
return modelQueryService.importProcessModel(request, file);
}
/*
* specific endpoint for IE9 flash upload component
*/
@RequestMapping(value = "/rest/import-process-model/text", method = RequestMethod.POST)
public String importProcessModelText(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
ModelRepresentation modelRepresentation = modelQueryService.importProcessModel(request, file);
String modelRepresentationJson = null;
try {
modelRepresentationJson = objectMapper.writeValueAsString(modelRepresentation);
} catch (Exception e) {
logger.error("Error while processing Model representation json", e);
throw new InternalServerErrorException("Model Representation could not be saved");
}
return modelRepresentationJson;
}
@RequestMapping(value = "/rest/models", method = RequestMethod.POST, produces = "application/json")
public ModelRepresentation createModel(@RequestBody ModelRepresentation modelRepresentation) {
modelRepresentation.setKey(modelRepresentation.getKey().replaceAll(" ", ""));
ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(null, modelRepresentation.getModelType(), modelRepresentation.getKey());
if (modelKeyInfo.isKeyAlreadyExists()) {
throw new BadRequestException("Provided model key already exists: " + modelRepresentation.getKey());
}
String json = null;
if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_FORM)) {
try {
json = objectMapper.writeValueAsString(new FormModel());
} catch (Exception e) {
logger.error("Error creating form model", e);
throw new InternalServerErrorException("Error creating form");
}
} else if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_DECISION_TABLE)) {
try {
DecisionTableDefinitionRepresentation decisionTableDefinition = new DecisionTableDefinitionRepresentation();
String decisionTableDefinitionKey = modelRepresentation.getName().replaceAll(" ", "");
decisionTableDefinition.setKey(decisionTableDefinitionKey);
json = objectMapper.writeValueAsString(decisionTableDefinition);
} catch (Exception e) {
logger.error("Error creating decision table model", e);
throw new InternalServerErrorException("Error creating decision table");
}
} else if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_APP)) {
try {
json = objectMapper.writeValueAsString(new AppDefinition());
} catch (Exception e) {
logger.error("Error creating app definition", e);
throw new InternalServerErrorException("Error creating app definition");
}
} else {
ObjectNode editorNode = objectMapper.createObjectNode();
editorNode.put("id", "canvas");
editorNode.put("resourceId", "canvas");
ObjectNode stencilSetNode = objectMapper.createObjectNode();
stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
editorNode.set("stencilset", stencilSetNode);
ObjectNode propertiesNode = objectMapper.createObjectNode();
propertiesNode.put("process_id", modelRepresentation.getKey());
propertiesNode.put("name", modelRepresentation.getName());
if (StringUtils.isNotEmpty(modelRepresentation.getDescription())) {
propertiesNode.put("documentation", modelRepresentation.getDescription());
}
editorNode.set("properties", propertiesNode);
ArrayNode childShapeArray = objectMapper.createArrayNode();
editorNode.set("childShapes", childShapeArray);
ObjectNode childNode = objectMapper.createObjectNode();
childShapeArray.add(childNode);
ObjectNode boundsNode = objectMapper.createObjectNode();
childNode.set("bounds", boundsNode);
ObjectNode lowerRightNode = objectMapper.createObjectNode();
boundsNode.set("lowerRight", lowerRightNode);
lowerRightNode.put("x", 130);
lowerRightNode.put("y", 193);
ObjectNode upperLeftNode = objectMapper.createObjectNode();
boundsNode.set("upperLeft", upperLeftNode);
upperLeftNode.put("x", 100);
upperLeftNode.put("y", 163);
childNode.set("childShapes", objectMapper.createArrayNode());
childNode.set("dockers", objectMapper.createArrayNode());
childNode.set("outgoing", objectMapper.createArrayNode());
childNode.put("resourceId", "startEvent1");
ObjectNode stencilNode = objectMapper.createObjectNode();
childNode.set("stencil", stencilNode);
stencilNode.put("id", "StartNoneEvent");
json = editorNode.toString();
}
Model newModel = modelService.createModel(modelRepresentation, json, SecurityUtils.getCurrentUserObject());
return new ModelRepresentation(newModel);
}
@RequestMapping(value = "/rest/models/{modelId}/clone", method = RequestMethod.POST, produces = "application/json")
public ModelRepresentation duplicateModel(@PathVariable String modelId, @RequestBody ModelRepresentation modelRepresentation) {
String json = null;
Model model = null;
if (modelId != null) {
model = modelService.getModel(modelId);
json = model.getModelEditorJson();
}
if (model == null) {
throw new InternalServerErrorException("Error duplicating model : Unknown original model");
}
if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_FORM)) {
// noting to do special for forms (just clone the json)
} else if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_APP)) {
// noting to do special for applications (just clone the json)
} else {
// BPMN model
ObjectNode editorNode = null;
try {
ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(json);
editorNode = deleteEmbededReferencesFromBPMNModel(editorJsonNode);
ObjectNode propertiesNode = (ObjectNode) editorNode.get("properties");
String processId = model.getName().replaceAll(" ", "");
propertiesNode.put("process_id", processId);
propertiesNode.put("name", model.getName());
if (StringUtils.isNotEmpty(model.getDescription())) {
propertiesNode.put("documentation", model.getDescription());
}
editorNode.set("properties", propertiesNode);
} catch (IOException e) {
e.printStackTrace();
}
if (editorNode != null) {
json = editorNode.toString();
}
}
// create the new model
Model newModel = modelService.createModel(modelRepresentation, json, SecurityUtils.getCurrentUserObject());
// copy also the thumbnail
byte[] imageBytes = model.getThumbnail();
newModel = modelService.saveModel(newModel, newModel.getModelEditorJson(), imageBytes, false, newModel.getComment(), SecurityUtils.getCurrentUserObject());
return new ModelRepresentation(newModel);
}
protected ObjectNode deleteEmbededReferencesFromBPMNModel(ObjectNode editorJsonNode) {
try {
internalDeleteNodeByNameFromBPMNModel(editorJsonNode, "formreference");
internalDeleteNodeByNameFromBPMNModel(editorJsonNode, "subprocessreference");
return editorJsonNode;
} catch (Exception e) {
throw new InternalServerErrorException("Cannot delete the external references");
}
}
protected ObjectNode deleteEmbededReferencesFromStepModel(ObjectNode editorJsonNode) {
try {
JsonNode startFormNode = editorJsonNode.get("startForm");
if (startFormNode != null) {
editorJsonNode.remove("startForm");
}
internalDeleteNodeByNameFromStepModel(editorJsonNode.get("steps"), "formDefinition");
internalDeleteNodeByNameFromStepModel(editorJsonNode.get("steps"), "subProcessDefinition");
return editorJsonNode;
} catch (Exception e) {
throw new InternalServerErrorException("Cannot delete the external references");
}
}
protected void internalDeleteNodeByNameFromBPMNModel(JsonNode editorJsonNode, String propertyName) {
JsonNode childShapesNode = editorJsonNode.get("childShapes");
if (childShapesNode != null && childShapesNode.isArray()) {
ArrayNode childShapesArrayNode = (ArrayNode) childShapesNode;
for (JsonNode childShapeNode : childShapesArrayNode) {
// Properties
ObjectNode properties = (ObjectNode) childShapeNode.get("properties");
if (properties != null && properties.has(propertyName)) {
JsonNode propertyNode = properties.get(propertyName);
if (propertyNode != null) {
properties.remove(propertyName);
}
}
// Potential nested child shapes
if (childShapeNode.has("childShapes")) {
internalDeleteNodeByNameFromBPMNModel(childShapeNode, propertyName);
}
}
}
}
private void internalDeleteNodeByNameFromStepModel(JsonNode stepsNode, String propertyName) {
if (stepsNode == null || !stepsNode.isArray()) {
return;
}
for (JsonNode jsonNode : stepsNode) {
ObjectNode stepNode = (ObjectNode) jsonNode;
if (stepNode.has(propertyName)) {
JsonNode propertyNode = stepNode.get(propertyName);
if (propertyNode != null) {
stepNode.remove(propertyName);
}
}
// Nested steps
if (stepNode.has("steps")) {
internalDeleteNodeByNameFromStepModel(stepNode.get("steps"), propertyName);
}
// Overdue steps
if (stepNode.has("overdueSteps")) {
internalDeleteNodeByNameFromStepModel(stepNode.get("overdueSteps"), propertyName);
}
// Choices is special, can have nested steps inside
if (stepNode.has("choices")) {
ArrayNode choicesArrayNode = (ArrayNode) stepNode.get("choices");
for (JsonNode choiceNode : choicesArrayNode) {
if (choiceNode.has("steps")) {
internalDeleteNodeByNameFromStepModel(choiceNode.get("steps"), propertyName);
}
}
}
}
}
}
| |
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.objc;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.ASSET_CATALOG;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.BREAKPAD_FILE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.BUNDLE_FILE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.BUNDLE_IMPORT_DIR;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.CC_LIBRARY;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DEBUG_SYMBOLS;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DEBUG_SYMBOLS_PLIST;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DEFINE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.FLAG;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.FORCE_LOAD_FOR_XCODEGEN;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.FORCE_LOAD_LIBRARY;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.FRAMEWORK_DIR;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.FRAMEWORK_FILE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.Flag.USES_CPP;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.Flag.USES_SWIFT;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.GENERAL_RESOURCE_DIR;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.GENERAL_RESOURCE_FILE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.HEADER;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.IMPORTED_LIBRARY;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.INCLUDE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.INCLUDE_SYSTEM;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.J2OBJC_LIBRARY;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.LIBRARY;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.LINKED_BINARY;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.LINKMAP_FILE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.LINKOPT;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.MODULE_MAP;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.SDK_DYLIB;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.SDK_FRAMEWORK;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.SOURCE;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.STORYBOARD;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.STRINGS;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.TOP_LEVEL_MODULE_MAP;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.WEAK_SDK_FRAMEWORK;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.XCASSETS_DIR;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.XCDATAMODEL;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.XIB;
import static com.google.devtools.build.lib.vfs.PathFragment.TO_PATH_FRAGMENT;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.UnmodifiableIterator;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.rules.apple.AppleToolchain;
import com.google.devtools.build.lib.rules.cpp.CcCommon;
import com.google.devtools.build.lib.rules.cpp.CcLinkParams;
import com.google.devtools.build.lib.rules.cpp.CcLinkParamsProvider;
import com.google.devtools.build.lib.rules.cpp.CppCompilationContext;
import com.google.devtools.build.lib.rules.cpp.CppModuleMap;
import com.google.devtools.build.lib.rules.cpp.CppRunfilesProvider;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.FileType;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Contains information common to multiple objc_* rules, and provides a unified API for extracting
* and accessing it.
*/
// TODO(bazel-team): Decompose and subsume area-specific logic and data into the various *Support
// classes. Make sure to distinguish rule output (providers, runfiles, ...) from intermediate,
// rule-internal information. Any provider created by a rule should not be read, only published.
public final class ObjcCommon {
/**
* Provides a way to access attributes that are common to all compilation rules.
*/
// TODO(bazel-team): Delete and move into support-specific attributes classes once ObjcCommon is
// gone.
static final class CompilationAttributes {
private final RuleContext ruleContext;
private final ObjcSdkFrameworks.Attributes sdkFrameworkAttributes;
CompilationAttributes(RuleContext ruleContext) {
this.ruleContext = Preconditions.checkNotNull(ruleContext);
this.sdkFrameworkAttributes = new ObjcSdkFrameworks.Attributes(ruleContext);
}
ImmutableList<Artifact> hdrs() {
// Some rules may compile but not have the "hdrs" attribute.
if (!ruleContext.attributes().has("hdrs", BuildType.LABEL_LIST)) {
return ImmutableList.of();
}
ImmutableList.Builder<Artifact> headers = ImmutableList.builder();
for (Pair<Artifact, Label> header : CcCommon.getHeaders(ruleContext)) {
headers.add(header.first);
}
return headers.build();
}
/**
* Returns headers that cannot be compiled individually.
*/
ImmutableList<Artifact> textualHdrs() {
// Some rules may compile but not have the "textual_hdrs" attribute.
if (!ruleContext.attributes().has("textual_hdrs", BuildType.LABEL_LIST)) {
return ImmutableList.of();
}
return ruleContext.getPrerequisiteArtifacts("textual_hdrs", Mode.TARGET).list();
}
Optional<Artifact> bridgingHeader() {
Artifact header = ruleContext.getPrerequisiteArtifact("bridging_header", Mode.TARGET);
return Optional.fromNullable(header);
}
Iterable<PathFragment> includes() {
return Iterables.transform(
ruleContext.attributes().get("includes", Type.STRING_LIST),
PathFragment.TO_PATH_FRAGMENT);
}
Iterable<PathFragment> sdkIncludes() {
return Iterables.transform(
ruleContext.attributes().get("sdk_includes", Type.STRING_LIST),
PathFragment.TO_PATH_FRAGMENT);
}
/**
* Returns the value of the sdk_frameworks attribute plus frameworks that are included
* automatically.
*/
ImmutableSet<SdkFramework> sdkFrameworks() {
return sdkFrameworkAttributes.sdkFrameworks();
}
/**
* Returns the value of the weak_sdk_frameworks attribute.
*/
ImmutableSet<SdkFramework> weakSdkFrameworks() {
return sdkFrameworkAttributes.weakSdkFrameworks();
}
/**
* Returns the value of the sdk_dylibs attribute.
*/
ImmutableSet<String> sdkDylibs() {
return sdkFrameworkAttributes.sdkDylibs();
}
/**
* Returns the exec paths of all header search paths that should be added to this target and
* dependers on this target, obtained from the {@code includes} attribute.
*/
ImmutableList<PathFragment> headerSearchPaths(PathFragment genfilesFragment) {
ImmutableList.Builder<PathFragment> paths = new ImmutableList.Builder<>();
PathFragment packageFragment =
ruleContext.getLabel().getPackageIdentifier().getPathFragment();
List<PathFragment> rootFragments = ImmutableList.of(
packageFragment,
genfilesFragment.getRelative(packageFragment));
Iterable<PathFragment> relativeIncludes =
Iterables.filter(includes(), Predicates.not(PathFragment.IS_ABSOLUTE));
for (PathFragment include : relativeIncludes) {
for (PathFragment rootFragment : rootFragments) {
paths.add(rootFragment.getRelative(include).normalize());
}
}
return paths.build();
}
/**
* Returns any values specified in this rule's {@code copts} attribute or an empty list if the
* attribute does not exist or no values are specified.
*/
public Iterable<String> copts() {
return ruleContext.getTokenizedStringListAttr("copts");
}
/**
* Returns any values specified in this rule's {@code linkopts} attribute or an empty list if
* the attribute does not exist or no values are specified.
*/
public Iterable<String> linkopts() {
return ruleContext.getTokenizedStringListAttr("linkopts");
}
/**
* The clang module maps of direct dependencies of this rule. These are needed to generate
* this rule's module map.
*/
public List<CppModuleMap> moduleMapsForDirectDeps() {
// Make sure all dependencies that have headers are included here. If a module map is missing,
// its private headers will be treated as public!
ArrayList<CppModuleMap> moduleMaps = new ArrayList<>();
collectModuleMapsFromAttributeIfExists(moduleMaps, "deps");
collectModuleMapsFromAttributeIfExists(moduleMaps, "non_propagated_deps");
return moduleMaps;
}
/**
* Collects all module maps from the targets in a certain attribute and adds them into
* {@code moduleMaps}.
*
* @param moduleMaps an {@link ArrayList} to collect the module maps into
* @param attribute the name of a label list attribute to collect module maps from
*/
private void collectModuleMapsFromAttributeIfExists(
ArrayList<CppModuleMap> moduleMaps, String attribute) {
if (ruleContext.attributes().has(attribute, BuildType.LABEL_LIST)) {
Iterable<ObjcProvider> providers =
ruleContext.getPrerequisites(attribute, Mode.TARGET, ObjcProvider.class);
for (ObjcProvider provider : providers) {
moduleMaps.addAll(provider.get(TOP_LEVEL_MODULE_MAP).toCollection());
}
}
}
/**
* Returns whether this target uses language features that require clang modules, such as
* {@literal @}import.
*/
public boolean enableModules() {
return ruleContext.attributes().has("enable_modules", Type.BOOLEAN)
&& ruleContext.attributes().get("enable_modules", Type.BOOLEAN);
}
}
/**
* Provides a way to access attributes that are common to all resources rules.
*/
// TODO(bazel-team): Delete and move into support-specific attributes classes once ObjcCommon is
// gone.
static final class ResourceAttributes {
private final RuleContext ruleContext;
ResourceAttributes(RuleContext ruleContext) {
this.ruleContext = ruleContext;
}
ImmutableList<Artifact> strings() {
return ruleContext.getPrerequisiteArtifacts("strings", Mode.TARGET).list();
}
ImmutableList<Artifact> xibs() {
return ruleContext.getPrerequisiteArtifacts("xibs", Mode.TARGET).list();
}
ImmutableList<Artifact> storyboards() {
return ruleContext.getPrerequisiteArtifacts("storyboards", Mode.TARGET).list();
}
ImmutableList<Artifact> resources() {
return ruleContext.getPrerequisiteArtifacts("resources", Mode.TARGET).list();
}
ImmutableList<Artifact> structuredResources() {
return ruleContext.getPrerequisiteArtifacts("structured_resources", Mode.TARGET).list();
}
ImmutableList<Artifact> datamodels() {
return ruleContext.getPrerequisiteArtifacts("datamodels", Mode.TARGET).list();
}
ImmutableList<Artifact> assetCatalogs() {
return ruleContext.getPrerequisiteArtifacts("asset_catalogs", Mode.TARGET).list();
}
}
static class Builder {
private RuleContext context;
private BuildConfiguration buildConfiguration;
private Optional<CompilationAttributes> compilationAttributes = Optional.absent();
private Optional<ResourceAttributes> resourceAttributes = Optional.absent();
private Iterable<SdkFramework> extraSdkFrameworks = ImmutableList.of();
private Iterable<SdkFramework> extraWeakSdkFrameworks = ImmutableList.of();
private Iterable<String> extraSdkDylibs = ImmutableList.of();
private Iterable<Artifact> frameworkImports = ImmutableList.of();
private Optional<CompilationArtifacts> compilationArtifacts = Optional.absent();
private Iterable<ObjcProvider> depObjcProviders = ImmutableList.of();
private Iterable<ObjcProvider> directDepObjcProviders = ImmutableList.of();
private Iterable<String> defines = ImmutableList.of();
private Iterable<PathFragment> userHeaderSearchPaths = ImmutableList.of();
private Iterable<PathFragment> directDependencyHeaderSearchPaths = ImmutableList.of();
private IntermediateArtifacts intermediateArtifacts;
private boolean alwayslink;
private boolean hasModuleMap;
private Iterable<Artifact> extraImportLibraries = ImmutableList.of();
private DsymOutputType dsymOutputType;
private Optional<Artifact> linkedBinary = Optional.absent();
private Optional<Artifact> linkmapFile = Optional.absent();
private Iterable<CppCompilationContext> depCcHeaderProviders = ImmutableList.of();
private Iterable<CcLinkParamsProvider> depCcLinkProviders = ImmutableList.of();
/**
* Builder for {@link ObjcCommon} obtaining both attribute data and configuration data from
* the given rule context.
*/
Builder(RuleContext context) {
this(context, context.getConfiguration());
}
/**
* Builder for {@link ObjcCommon} obtaining attribute data from the rule context and
* configuration data from the given configuration object for use in situations where a single
* target's outputs are under multiple configurations.
*/
Builder(RuleContext context, BuildConfiguration buildConfiguration) {
this.context = Preconditions.checkNotNull(context);
this.buildConfiguration = Preconditions.checkNotNull(buildConfiguration);
}
public Builder setCompilationAttributes(CompilationAttributes baseCompilationAttributes) {
Preconditions.checkState(!this.compilationAttributes.isPresent(),
"compilationAttributes is already set to: %s", this.compilationAttributes);
this.compilationAttributes = Optional.of(baseCompilationAttributes);
return this;
}
public Builder setResourceAttributes(ResourceAttributes baseResourceAttributes) {
Preconditions.checkState(!this.resourceAttributes.isPresent(),
"resourceAttributes is already set to: %s", this.resourceAttributes);
this.resourceAttributes = Optional.of(baseResourceAttributes);
return this;
}
Builder addExtraSdkFrameworks(Iterable<SdkFramework> extraSdkFrameworks) {
this.extraSdkFrameworks = Iterables.concat(this.extraSdkFrameworks, extraSdkFrameworks);
return this;
}
Builder addExtraWeakSdkFrameworks(Iterable<SdkFramework> extraWeakSdkFrameworks) {
this.extraWeakSdkFrameworks =
Iterables.concat(this.extraWeakSdkFrameworks, extraWeakSdkFrameworks);
return this;
}
Builder addExtraSdkDylibs(Iterable<String> extraSdkDylibs) {
this.extraSdkDylibs = Iterables.concat(this.extraSdkDylibs, extraSdkDylibs);
return this;
}
Builder addFrameworkImports(Iterable<Artifact> frameworkImports) {
this.frameworkImports = Iterables.concat(this.frameworkImports, frameworkImports);
return this;
}
Builder setCompilationArtifacts(CompilationArtifacts compilationArtifacts) {
Preconditions.checkState(!this.compilationArtifacts.isPresent(),
"compilationArtifacts is already set to: %s", this.compilationArtifacts);
this.compilationArtifacts = Optional.of(compilationArtifacts);
return this;
}
/**
* Add providers which will be exposed both to the declaring rule and to any dependers on the
* declaring rule.
*/
Builder addDepObjcProviders(Iterable<ObjcProvider> depObjcProviders) {
this.depObjcProviders = Iterables.concat(this.depObjcProviders, depObjcProviders);
return this;
}
/**
* Add providers which will only be used by the declaring rule, and won't be propagated to any
* dependers on the declaring rule.
*/
Builder addNonPropagatedDepObjcProviders(Iterable<ObjcProvider> directDepObjcProviders) {
this.directDepObjcProviders = Iterables.concat(
this.directDepObjcProviders, directDepObjcProviders);
return this;
}
public Builder addUserHeaderSearchPaths(Iterable<PathFragment> userHeaderSearchPaths) {
this.userHeaderSearchPaths =
Iterables.concat(this.userHeaderSearchPaths, userHeaderSearchPaths);
return this;
}
/**
* Adds header search paths that will only be visible by strict dependents of the provider.
*/
public Builder addDirectDependencyHeaderSearchPaths(
Iterable<PathFragment> directDependencyHeaderSearchPaths) {
this.directDependencyHeaderSearchPaths =
Iterables.concat(
this.directDependencyHeaderSearchPaths, directDependencyHeaderSearchPaths);
return this;
}
public Builder addDefines(Iterable<String> defines) {
this.defines = Iterables.concat(this.defines, defines);
return this;
}
Builder setIntermediateArtifacts(IntermediateArtifacts intermediateArtifacts) {
this.intermediateArtifacts = intermediateArtifacts;
return this;
}
Builder setAlwayslink(boolean alwayslink) {
this.alwayslink = alwayslink;
return this;
}
/**
* Specifies that this target has a clang module map. This should be called if this target
* compiles sources or exposes headers for other targets to use. Note that this does not add
* the action to generate the module map. It simply indicates that it should be added to the
* provider.
*/
Builder setHasModuleMap() {
this.hasModuleMap = true;
return this;
}
/**
* Adds additional static libraries to be linked into the final ObjC application bundle.
*/
Builder addExtraImportLibraries(Iterable<Artifact> extraImportLibraries) {
this.extraImportLibraries = Iterables.concat(this.extraImportLibraries, extraImportLibraries);
return this;
}
/**
* Sets a linked binary generated by this rule to be propagated to dependers.
*/
Builder setLinkedBinary(Artifact linkedBinary) {
this.linkedBinary = Optional.of(linkedBinary);
return this;
}
/**
* Sets which type of dsym output this rule generated to be propagated to dependers.
*/
Builder addDebugArtifacts(DsymOutputType dsymOutputType) {
this.dsymOutputType = dsymOutputType;
return this;
}
/**
* Sets a linkmap file generated by this rule to be propagated to dependers.
*/
Builder setLinkmapFile(Artifact linkmapFile) {
this.linkmapFile = Optional.of(linkmapFile);
return this;
}
/**
* Sets information from {@code cc_library} dependencies to be used during compilation.
*/
public Builder addDepCcHeaderProviders(Iterable<CppCompilationContext> depCcHeaderProviders) {
this.depCcHeaderProviders = Iterables.concat(this.depCcHeaderProviders, depCcHeaderProviders);
return this;
}
/**
* Sets information from {@code cc_library} dependencies to be used during linking.
*/
public Builder addDepCcLinkProviders(RuleContext ruleContext) {
for (TransitiveInfoCollection dep : ruleContext.getPrerequisites("deps", Mode.TARGET)) {
// Hack to determine if dep is a cc target. Required so objc_library archives packed in
// CcLinkParamsProvider do not get consumed as cc targets.
if (dep.getProvider(CppRunfilesProvider.class) != null) {
CcLinkParamsProvider ccLinkParamsProvider = dep.getProvider(CcLinkParamsProvider.class);
this.depCcLinkProviders =
Iterables.concat(
this.depCcLinkProviders,
ImmutableList.<CcLinkParamsProvider>of(ccLinkParamsProvider));
}
}
return this;
}
ObjcCommon build() {
Iterable<BundleableFile> bundleImports = BundleableFile.bundleImportsFromRule(context);
ObjcProvider.Builder objcProvider =
new ObjcProvider.Builder()
.addAll(IMPORTED_LIBRARY, extraImportLibraries)
.addAll(BUNDLE_FILE, bundleImports)
.addAll(
BUNDLE_IMPORT_DIR,
uniqueContainers(
BundleableFile.toArtifacts(bundleImports), BUNDLE_CONTAINER_TYPE))
.addAll(SDK_FRAMEWORK, extraSdkFrameworks)
.addAll(WEAK_SDK_FRAMEWORK, extraWeakSdkFrameworks)
.addAll(SDK_DYLIB, extraSdkDylibs)
.addAll(FRAMEWORK_FILE, frameworkImports)
.addAll(FRAMEWORK_DIR, uniqueContainers(frameworkImports, FRAMEWORK_CONTAINER_TYPE))
.addAll(INCLUDE, userHeaderSearchPaths)
.addAllForDirectDependents(INCLUDE, directDependencyHeaderSearchPaths)
.addAll(DEFINE, defines)
.addTransitiveAndPropagate(depObjcProviders)
.addTransitiveWithoutPropagating(directDepObjcProviders);
for (CppCompilationContext headerProvider : depCcHeaderProviders) {
objcProvider.addTransitiveAndPropagate(HEADER, headerProvider.getDeclaredIncludeSrcs());
objcProvider.addAll(INCLUDE, headerProvider.getIncludeDirs());
// TODO(bazel-team): This pulls in stl via CppHelper.mergeToolchainDependentContext but
// probably shouldn't.
objcProvider.addAll(INCLUDE_SYSTEM, headerProvider.getSystemIncludeDirs());
objcProvider.addAll(DEFINE, headerProvider.getDefines());
}
for (CcLinkParamsProvider linkProvider : depCcLinkProviders) {
CcLinkParams params = linkProvider.getCcLinkParams(true, false);
ImmutableList<String> linkOpts = params.flattenedLinkopts();
ImmutableSet.Builder<SdkFramework> frameworkLinkOpts = new ImmutableSet.Builder<>();
ImmutableList.Builder<String> nonFrameworkLinkOpts = new ImmutableList.Builder<>();
// Add any framework flags as frameworks directly, rather than as linkopts.
for (UnmodifiableIterator<String> iterator = linkOpts.iterator(); iterator.hasNext(); ) {
String arg = iterator.next();
if (arg.equals("-framework") && iterator.hasNext()) {
String framework = iterator.next();
frameworkLinkOpts.add(new SdkFramework(framework));
} else {
nonFrameworkLinkOpts.add(arg);
}
}
objcProvider
.addAll(SDK_FRAMEWORK, frameworkLinkOpts.build())
.addAll(LINKOPT, nonFrameworkLinkOpts.build())
.addTransitiveAndPropagate(CC_LIBRARY, params.getLibraries());
}
if (compilationAttributes.isPresent()) {
CompilationAttributes attributes = compilationAttributes.get();
Iterable<PathFragment> sdkIncludes = Iterables.transform(
Interspersing.prependEach(
AppleToolchain.sdkDir() + "/usr/include/",
PathFragment.safePathStrings(attributes.sdkIncludes())),
TO_PATH_FRAGMENT);
objcProvider
.addAll(HEADER, attributes.hdrs())
.addAll(HEADER, attributes.textualHdrs())
.addAll(INCLUDE, attributes.headerSearchPaths(buildConfiguration.getGenfilesFragment()))
.addAll(INCLUDE, sdkIncludes)
.addAll(SDK_FRAMEWORK, attributes.sdkFrameworks())
.addAll(WEAK_SDK_FRAMEWORK, attributes.weakSdkFrameworks())
.addAll(SDK_DYLIB, attributes.sdkDylibs());
}
if (resourceAttributes.isPresent()) {
ResourceAttributes attributes = resourceAttributes.get();
objcProvider
.addAll(GENERAL_RESOURCE_FILE, attributes.storyboards())
.addAll(GENERAL_RESOURCE_FILE, attributes.resources())
.addAll(GENERAL_RESOURCE_FILE, attributes.strings())
.addAll(GENERAL_RESOURCE_FILE, attributes.xibs())
.addAll(
GENERAL_RESOURCE_DIR, xcodeStructuredResourceDirs(attributes.structuredResources()))
.addAll(BUNDLE_FILE, BundleableFile.flattenedRawResourceFiles(attributes.resources()))
.addAll(
BUNDLE_FILE,
BundleableFile.structuredRawResourceFiles(attributes.structuredResources()))
.addAll(
XCASSETS_DIR,
uniqueContainers(attributes.assetCatalogs(), ASSET_CATALOG_CONTAINER_TYPE))
.addAll(ASSET_CATALOG, attributes.assetCatalogs())
.addAll(XCDATAMODEL, attributes.datamodels())
.addAll(XIB, attributes.xibs())
.addAll(STRINGS, attributes.strings())
.addAll(STORYBOARD, attributes.storyboards());
}
if (useLaunchStoryboard(context)) {
Artifact launchStoryboard =
context.getPrerequisiteArtifact("launch_storyboard", Mode.TARGET);
objcProvider.add(GENERAL_RESOURCE_FILE, launchStoryboard);
if (ObjcRuleClasses.STORYBOARD_TYPE.matches(launchStoryboard.getPath())) {
objcProvider.add(STORYBOARD, launchStoryboard);
} else {
objcProvider.add(XIB, launchStoryboard);
}
}
for (CompilationArtifacts artifacts : compilationArtifacts.asSet()) {
Iterable<Artifact> allSources =
Iterables.concat(artifacts.getSrcs(), artifacts.getNonArcSrcs());
// TODO(bazel-team): Add private headers to the provider when we have module maps to enforce
// them.
objcProvider
.addAll(HEADER, artifacts.getAdditionalHdrs())
.addAll(LIBRARY, artifacts.getArchive().asSet())
.addAll(SOURCE, allSources);
if (artifacts.getArchive().isPresent()
&& J2ObjcLibrary.J2OBJC_SUPPORTED_RULES.contains(context.getRule().getRuleClass())) {
objcProvider.addAll(J2OBJC_LIBRARY, artifacts.getArchive().asSet());
}
boolean usesCpp = false;
boolean usesSwift = false;
for (Artifact sourceFile :
Iterables.concat(artifacts.getSrcs(), artifacts.getNonArcSrcs())) {
usesCpp = usesCpp || ObjcRuleClasses.CPP_SOURCES.matches(sourceFile.getExecPath());
usesSwift = usesSwift || ObjcRuleClasses.SWIFT_SOURCES.matches(sourceFile.getExecPath());
}
if (usesCpp) {
objcProvider.add(FLAG, USES_CPP);
}
if (usesSwift) {
objcProvider.add(FLAG, USES_SWIFT);
}
}
if (alwayslink) {
for (CompilationArtifacts artifacts : compilationArtifacts.asSet()) {
for (Artifact archive : artifacts.getArchive().asSet()) {
objcProvider.add(FORCE_LOAD_LIBRARY, archive);
objcProvider.add(FORCE_LOAD_FOR_XCODEGEN, String.format(
"$(BUILT_PRODUCTS_DIR)/lib%s.a",
XcodeProvider.xcodeTargetName(context.getLabel())));
}
}
for (Artifact archive : extraImportLibraries) {
objcProvider.add(FORCE_LOAD_LIBRARY, archive);
objcProvider.add(FORCE_LOAD_FOR_XCODEGEN,
"$(WORKSPACE_ROOT)/" + archive.getExecPath().getSafePathString());
}
}
if (hasModuleMap
&& buildConfiguration.getFragment(ObjcConfiguration.class).moduleMapsEnabled()) {
CppModuleMap moduleMap = intermediateArtifacts.moduleMap();
objcProvider.add(MODULE_MAP, moduleMap.getArtifact());
objcProvider.add(TOP_LEVEL_MODULE_MAP, moduleMap);
}
objcProvider.addAll(LINKED_BINARY, linkedBinary.asSet())
.addAll(LINKMAP_FILE, linkmapFile.asSet());
if (dsymOutputType != null) {
objcProvider
.add(BREAKPAD_FILE, intermediateArtifacts.breakpadSym())
.add(DEBUG_SYMBOLS, intermediateArtifacts.dsymSymbol(dsymOutputType))
.add(DEBUG_SYMBOLS_PLIST, intermediateArtifacts.dsymPlist(dsymOutputType));
}
return new ObjcCommon(objcProvider.build(), compilationArtifacts);
}
/**
* Returns {@code true} if the given rule context has a launch storyboard set.
*/
private static boolean useLaunchStoryboard(RuleContext ruleContext) {
if (!ruleContext.attributes().has("launch_storyboard", LABEL)) {
return false;
}
Artifact launchStoryboard =
ruleContext.getPrerequisiteArtifact("launch_storyboard", Mode.TARGET);
return launchStoryboard != null;
}
}
static final FileType BUNDLE_CONTAINER_TYPE = FileType.of(".bundle");
static final FileType ASSET_CATALOG_CONTAINER_TYPE = FileType.of(".xcassets");
public static final FileType FRAMEWORK_CONTAINER_TYPE = FileType.of(".framework");
private final ObjcProvider objcProvider;
private final Optional<CompilationArtifacts> compilationArtifacts;
private ObjcCommon(
ObjcProvider objcProvider,
Optional<CompilationArtifacts> compilationArtifacts) {
this.objcProvider = Preconditions.checkNotNull(objcProvider);
this.compilationArtifacts = Preconditions.checkNotNull(compilationArtifacts);
}
public ObjcProvider getObjcProvider() {
return objcProvider;
}
public Optional<CompilationArtifacts> getCompilationArtifacts() {
return compilationArtifacts;
}
/**
* Returns an {@link Optional} containing the compiled {@code .a} file, or
* {@link Optional#absent()} if this object contains no {@link CompilationArtifacts} or the
* compilation information has no sources.
*/
public Optional<Artifact> getCompiledArchive() {
if (compilationArtifacts.isPresent()) {
return compilationArtifacts.get().getArchive();
}
return Optional.absent();
}
static ImmutableList<PathFragment> userHeaderSearchPaths(BuildConfiguration configuration) {
return ImmutableList.of(
new PathFragment("."),
configuration.getGenfilesFragment());
}
/**
* Returns the first directory in the sequence of parents of the exec path of the given artifact
* that matches {@code type}. For instance, if {@code type} is FileType.of(".foo") and the exec
* path of {@code artifact} is {@code a/b/c/bar.foo/d/e}, then the return value is
* {@code a/b/c/bar.foo}.
*/
static Optional<PathFragment> nearestContainerMatching(FileType type, Artifact artifact) {
PathFragment container = artifact.getExecPath();
do {
if (type.matches(container)) {
return Optional.of(container);
}
container = container.getParentDirectory();
} while (container != null);
return Optional.absent();
}
/**
* Similar to {@link #nearestContainerMatching(FileType, Artifact)}, but tries matching several
* file types in {@code types}, and returns a path for the first match in the sequence.
*/
static Optional<PathFragment> nearestContainerMatching(
Iterable<FileType> types, Artifact artifact) {
for (FileType type : types) {
for (PathFragment container : nearestContainerMatching(type, artifact).asSet()) {
return Optional.of(container);
}
}
return Optional.absent();
}
/**
* Returns all directories matching {@code containerType} that contain the items in
* {@code artifacts}. This function ignores artifacts that are not in any directory matching
* {@code containerType}.
*/
static Iterable<PathFragment> uniqueContainers(
Iterable<Artifact> artifacts, FileType containerType) {
ImmutableSet.Builder<PathFragment> containers = new ImmutableSet.Builder<>();
for (Artifact artifact : artifacts) {
containers.addAll(ObjcCommon.nearestContainerMatching(containerType, artifact).asSet());
}
return containers.build();
}
/**
* Returns the Xcode structured resource directory paths.
*
* <p>For a checked-in source artifact "//a/b/res/sub_dir/d" included by objc rule "//a/b:c",
* "a/b/res" will be returned. For a generated source artifact "res/sub_dir/d" owned by genrule
* "//a/b:c", "bazel-out/.../genfiles/a/b/res" will be returned.
*
* <p>When XCode sees a included resource directory of "a/b/res", the entire directory structure
* up to "res" will be copied into the app bundle.
*/
static Iterable<PathFragment> xcodeStructuredResourceDirs(Iterable<Artifact> artifacts) {
ImmutableSet.Builder<PathFragment> containers = new ImmutableSet.Builder<>();
for (Artifact artifact : artifacts) {
PathFragment ownerRuleDirectory = artifact.getArtifactOwner().getLabel().getPackageFragment();
String containerName =
artifact.getRootRelativePath().relativeTo(ownerRuleDirectory).getSegment(0);
PathFragment rootExecPath = artifact.getRoot().getExecPath();
containers.add(rootExecPath.getRelative(ownerRuleDirectory.getRelative(containerName)));
}
return containers.build();
}
/**
* Similar to {@link #nearestContainerMatching(FileType, Artifact)}, but returns the container
* closest to the root that matches the given type.
*/
static Optional<PathFragment> farthestContainerMatching(FileType type, Artifact artifact) {
PathFragment container = artifact.getExecPath();
Optional<PathFragment> lastMatch = Optional.absent();
do {
if (type.matches(container)) {
lastMatch = Optional.of(container);
}
container = container.getParentDirectory();
} while (container != null);
return lastMatch;
}
static Iterable<String> notInContainerErrors(
Iterable<Artifact> artifacts, FileType containerType) {
return notInContainerErrors(artifacts, ImmutableList.of(containerType));
}
@VisibleForTesting
static final String NOT_IN_CONTAINER_ERROR_FORMAT =
"File '%s' is not in a directory of one of these type(s): %s";
static Iterable<String> notInContainerErrors(
Iterable<Artifact> artifacts, Iterable<FileType> containerTypes) {
Set<String> errors = new HashSet<>();
for (Artifact artifact : artifacts) {
boolean inContainer = nearestContainerMatching(containerTypes, artifact).isPresent();
if (!inContainer) {
errors.add(String.format(NOT_IN_CONTAINER_ERROR_FORMAT,
artifact.getExecPath(), Iterables.toString(containerTypes)));
}
}
return errors;
}
}
| |
/*
* Copyright 2012-2013 E.Hooijmeijer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.javaswift.cloudie;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.commons.io.IOUtils;
import org.javaswift.cloudie.login.CloudieCallbackWrapper;
import org.javaswift.cloudie.login.CredentialsStore;
import org.javaswift.cloudie.login.CredentialsStore.Credentials;
import org.javaswift.cloudie.login.LoginPanel;
import org.javaswift.cloudie.login.LoginPanel.LoginCallback;
import org.javaswift.cloudie.ops.CloudieOperations;
import org.javaswift.cloudie.ops.CloudieOperations.CloudieCallback;
import org.javaswift.cloudie.ops.CloudieOperationsImpl;
import org.javaswift.cloudie.ops.ContainerSpecification;
import org.javaswift.cloudie.preview.PreviewPanel;
import org.javaswift.cloudie.util.AsyncWrapper;
import org.javaswift.cloudie.util.DoubleClickListener;
import org.javaswift.cloudie.util.GuiTreadingUtils;
import org.javaswift.cloudie.util.LabelComponentPanel;
import org.javaswift.cloudie.util.PopupTrigger;
import org.javaswift.cloudie.util.ReflectionAction;
import org.javaswift.joss.client.factory.AccountConfig;
import org.javaswift.joss.client.factory.AuthenticationMethod;
import org.javaswift.joss.exception.CommandException;
import org.javaswift.joss.model.Container;
import org.javaswift.joss.model.StoredObject;
import com.beust.jcommander.ParameterException;
/**
* CloudiePanel.
*
* @author E.Hooijmeijer
*
*/
public class CloudiePanel extends JPanel implements CloudieOperations.CloudieCallback {
private static final Border LR_PADDING = BorderFactory.createEmptyBorder(0, 2, 0, 2);
private DefaultListModel containers = new DefaultListModel();
private JList containersList = new JList(containers);
private DefaultListModel storedObjects = new DefaultListModel();
private JList storedObjectsList = new JList(storedObjects);
private List<StoredObject> allStoredObjects = new ArrayList<StoredObject>();
private JTextField searchTextField = new JTextField(16);
private Action accountLoginAction = new ReflectionAction<CloudiePanel>("Login..", getIcon("server_connect.png"), this, "onLogin");
private Action accountLogoutAction = new ReflectionAction<CloudiePanel>("Logout", getIcon("disconnect.png"), this, "onLogout");
private Action accountQuitAction = new ReflectionAction<CloudiePanel>("Quit", getIcon("weather_rain.png"), this, "onQuit");
private Action containerRefreshAction = new ReflectionAction<CloudiePanel>("Refresh", getIcon("arrow_refresh.png"), this, "onRefreshContainers");
private Action containerCreateAction = new ReflectionAction<CloudiePanel>("Create...", getIcon("folder_add.png"), this, "onCreateContainer");
private Action containerDeleteAction = new ReflectionAction<CloudiePanel>("Delete...", getIcon("folder_delete.png"), this, "onDeleteContainer");
private Action containerPurgeAction = new ReflectionAction<CloudiePanel>("Purge...", getIcon("delete.png"), this, "onPurgeContainer");
private Action containerEmptyAction = new ReflectionAction<CloudiePanel>("Empty...", getIcon("bin_empty.png"), this, "onEmptyContainer");
private Action containerViewMetaData = new ReflectionAction<CloudiePanel>("View Metadata...", getIcon("page_gear.png"), this, "onViewMetaDataContainer");
private Action storedObjectOpenAction = new ReflectionAction<CloudiePanel>("Open in Browser", getIcon("application_view_icons.png"), this,
"onOpenInBrowserStoredObject");
private Action storedObjectPreviewAction = new ReflectionAction<CloudiePanel>("Preview", getIcon("images.png"), this, "onPreviewStoredObject");
private Action storedObjectCreateAction = new ReflectionAction<CloudiePanel>("Create...", getIcon("page_add.png"), this, "onCreateStoredObject");
private Action storedObjectDownloadAction = new ReflectionAction<CloudiePanel>("Download...", getIcon("page_go.png"), this, "onDownloadStoredObject");
private Action storedObjectDeleteAction = new ReflectionAction<CloudiePanel>("Delete...", getIcon("page_delete.png"), this, "onDeleteStoredObject");
private Action storedObjectViewMetaData = new ReflectionAction<CloudiePanel>("View Metadata...", getIcon("page_gear.png"), this,
"onViewMetaDataStoredObject");
private Action aboutAction = new ReflectionAction<CloudiePanel>("About", getIcon("information.png"), this, "onAbout");
private Action searchAction = new ReflectionAction<CloudiePanel>("Search", null, this, "onSearch");
private JFrame owner;
private CloudieOperations ops;
private CloudieOperations.CloudieCallback callback;
private PreviewPanel previewPanel = new PreviewPanel();
private StatusPanel statusPanel;
private boolean loggedIn;
private int busyCnt;
private CredentialsStore credentialsStore = new CredentialsStore();
private File lastFolder = null;
/**
* creates Cloudie and immediately logs in using the given credentials.
* @param login the login credentials.
*/
public CloudiePanel(AuthenticationMethod method, List<String> args) {
this();
ops.login(toAccountConfig(method, args), callback);
}
private AccountConfig toAccountConfig(AuthenticationMethod method, List<String> args) {
AccountConfig cfg = new AccountConfig();
cfg.setAuthenticationMethod(method);
switch (method) {
case KEYSTONE:
cfg.setTenantId(args.get(4));
// passthrough
default:
cfg.setAuthUrl(args.get(0));
cfg.setTenantName(args.get(1));
cfg.setUsername(args.get(2));
cfg.setPassword(args.get(3));
}
return cfg;
}
/**
* creates Cloudie and immediately logs in using the given previously stored
* profile.
* @param profile the profile.
*/
public CloudiePanel(String profile) {
this();
CredentialsStore store = new CredentialsStore();
Credentials found = null;
for (Credentials cr : store.getAvailableCredentials()) {
if (cr.toString().equals(profile)) {
found = cr;
}
}
if (found == null) {
throw new ParameterException("Unknown profile '" + profile + "'.");
} else {
ops.login(found.toAccountConfig(), callback);
}
}
/**
* creates Cloudie and does not login.
*/
public CloudiePanel() {
super(new BorderLayout());
//
ops = createCloudieOperations();
callback = GuiTreadingUtils.guiThreadSafe(CloudieCallback.class, this);
//
statusPanel = new StatusPanel(ops, callback);
//
JScrollPane left = new JScrollPane(containersList);
//
storedObjectsList.setMinimumSize(new Dimension(420, 320));
JSplitPane center = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(storedObjectsList), new JScrollPane(previewPanel));
center.setDividerLocation(450);
//
JSplitPane main = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, center);
main.setDividerLocation(272);
add(main, BorderLayout.CENTER);
//
add(statusPanel, BorderLayout.SOUTH);
//
searchTextField.setAction(searchAction);
//
createLists();
//
storedObjectsList.addMouseListener(new PopupTrigger<CloudiePanel>(createStoredObjectPopupMenu(), this, "enableDisableStoredObjectMenu"));
storedObjectsList.addMouseListener(new DoubleClickListener(storedObjectPreviewAction));
containersList.addMouseListener(new PopupTrigger<CloudiePanel>(createContainerPopupMenu(), this, "enableDisableContainerMenu"));
//
bind();
//
enableDisable();
}
public void setOwner(JFrame owner) {
this.owner = owner;
}
private void createLists() {
containersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
containersList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel lbl = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
lbl.setBorder(LR_PADDING);
Container c = (Container) value;
lbl.setText(c.getName());
lbl.setToolTipText(lbl.getText());
return lbl;
}
});
containersList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
enableDisableContainerMenu();
updateStatusPanelForContainer();
}
});
//
storedObjectsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
storedObjectsList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel lbl = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
lbl.setBorder(LR_PADDING);
StoredObject so = (StoredObject) value;
lbl.setText(so.getName());
lbl.setToolTipText(lbl.getText());
return lbl;
}
});
storedObjectsList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
enableDisableStoredObjectMenu();
updateStatusPanelForStoredObject();
}
});
}
private CloudieOperations createCloudieOperations() {
CloudieOperationsImpl lops = new CloudieOperationsImpl();
return AsyncWrapper.async(lops);
}
public static Icon getIcon(String string) {
return new ImageIcon(CloudiePanel.class.getResource("/icons/" + string));
}
public boolean isContainerSelected() {
return containersList.getSelectedIndex() >= 0;
}
public Container getSelectedContainer() {
return isContainerSelected() ? (Container) containers.get(containersList.getSelectedIndex()) : null;
}
public boolean isSingleStoredObjectSelected() {
return storedObjectsList.getSelectedIndices().length == 1;
}
public boolean isStoredObjectsSelected() {
return storedObjectsList.getSelectedIndices().length > 0;
}
public List<StoredObject> getSelectedStoredObjects() {
List<StoredObject> results = new ArrayList<StoredObject>();
for (int idx : storedObjectsList.getSelectedIndices()) {
results.add((StoredObject) storedObjects.get(idx));
}
return results;
}
public <A> A single(List<A> list) {
return list.isEmpty() ? null : list.get(0);
}
public void enableDisable() {
enableDisableAccountMenu();
enableDisableContainerMenu();
enableDisableStoredObjectMenu();
}
public void enableDisableAccountMenu() {
accountLoginAction.setEnabled(!loggedIn);
accountLogoutAction.setEnabled(loggedIn);
accountQuitAction.setEnabled(true);
}
public void enableDisableContainerMenu() {
boolean containerSelected = isContainerSelected();
Container selected = getSelectedContainer();
//
containerRefreshAction.setEnabled(loggedIn);
containerCreateAction.setEnabled(loggedIn);
containerDeleteAction.setEnabled(containerSelected);
containerPurgeAction.setEnabled(containerSelected);
containerEmptyAction.setEnabled(containerSelected);
containerViewMetaData.setEnabled(containerSelected && selected.isInfoRetrieved() && !selected.getMetadata().isEmpty());
}
public void enableDisableStoredObjectMenu() {
boolean singleObjectSelected = isSingleStoredObjectSelected();
boolean objectsSelected = isStoredObjectsSelected();
boolean containerSelected = isContainerSelected();
StoredObject selected = single(getSelectedStoredObjects());
Container selectedContainer = getSelectedContainer();
//
storedObjectPreviewAction.setEnabled(singleObjectSelected && selected.isInfoRetrieved());
storedObjectCreateAction.setEnabled(containerSelected);
storedObjectDownloadAction.setEnabled(containerSelected && objectsSelected);
storedObjectViewMetaData.setEnabled(containerSelected && singleObjectSelected && selected.isInfoRetrieved() && !selected.getMetadata().isEmpty());
//
storedObjectOpenAction.setEnabled(objectsSelected && containerSelected && selectedContainer.isPublic());
storedObjectDeleteAction.setEnabled(containerSelected && objectsSelected);
}
protected void updateStatusPanelForStoredObject() {
if (isStoredObjectsSelected()) {
statusPanel.onSelectStoredObjects(getSelectedStoredObjects());
}
}
protected void updateStatusPanelForContainer() {
if (isContainerSelected()) {
statusPanel.onSelectContainer(getSelectedContainer());
}
}
@Override
public void onNumberOfCalls(int nrOfCalls) {
statusPanel.onNumberOfCalls(nrOfCalls);
}
public void onLogin() {
final JDialog loginDialog = new JDialog(owner, "Login");
final LoginPanel loginPanel = new LoginPanel(new LoginCallback() {
@Override
public void doLogin(AccountConfig accountConfig) {
CloudieCallback cb = GuiTreadingUtils.guiThreadSafe(CloudieCallback.class, new CloudieCallbackWrapper(callback) {
@Override
public void onLoginSuccess() {
loginDialog.setVisible(false);
super.onLoginSuccess();
}
@Override
public void onError(CommandException ex) {
JOptionPane.showMessageDialog(loginDialog, "Login Failed\n" + ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
});
ops.login(accountConfig, cb);
}
}, credentialsStore);
try {
loginPanel.setOwner(loginDialog);
loginDialog.getContentPane().add(loginPanel);
loginDialog.setModal(true);
loginDialog.setSize(480, 340);
loginDialog.setResizable(false);
loginDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
center(loginDialog);
loginDialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
loginPanel.onCancel();
}
@Override
public void windowOpened(WindowEvent e) {
loginPanel.onShow();
}
});
loginDialog.setVisible(true);
} finally {
loginDialog.dispose();
}
}
private void center(JDialog dialog) {
int x = owner.getLocation().x + (owner.getWidth() - dialog.getWidth()) / 2;
int y = owner.getLocation().y + (owner.getHeight() - dialog.getHeight()) / 2;
dialog.setLocation(x, y);
}
@Override
public void onLoginSuccess() {
this.onNewStoredObjects();
ops.refreshContainers(callback);
loggedIn = true;
enableDisable();
}
public void onAbout() {
StringBuilder sb = loadResource("/about.html");
JLabel label = new JLabel(sb.toString());
JOptionPane.showMessageDialog(this, label, "About Cloudie", JOptionPane.INFORMATION_MESSAGE, getIcon("weather_cloudy.png"));
}
private StringBuilder loadResource(String resource) {
StringBuilder sb = new StringBuilder();
InputStream input = CloudiePanel.class.getResourceAsStream(resource);
try {
try {
List<String> lines = IOUtils.readLines(input);
for (String line : lines) {
sb.append(line);
}
} finally {
input.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return sb;
}
public void onLogout() {
ops.logout(callback);
}
@Override
public void onLogoutSuccess() {
this.onUpdateContainers(Collections.<Container> emptyList());
this.onNewStoredObjects();
statusPanel.onDeselect();
loggedIn = false;
enableDisable();
}
public void onQuit() {
if (onClose()) {
System.exit(0);
}
}
private JPopupMenu createContainerPopupMenu() {
JPopupMenu pop = new JPopupMenu("Container");
pop.add(new JMenuItem(containerRefreshAction));
pop.add(new JMenuItem(containerViewMetaData));
pop.addSeparator();
pop.add(new JMenuItem(containerCreateAction));
pop.add(new JMenuItem(containerDeleteAction));
pop.addSeparator();
pop.add(new JMenuItem(containerEmptyAction));
pop.addSeparator();
pop.add(new JMenuItem(containerPurgeAction));
return pop;
}
protected void onPurgeContainer() {
Container c = getSelectedContainer();
if (confirm("Are you sure you want to PURGE container '" + c.getName()
+ "'? This will remove the container and ALL ITS CONTENTS.\n You cannot get back what you delete!")) {
ops.purgeContainer(c, callback);
}
}
protected void onEmptyContainer() {
Container c = getSelectedContainer();
if (confirm("Are you sure you want to EMPTY container '" + c.getName() + "'? This will remove ALL ITS CONTENTS.\n You cannot get back what you delete!")) {
ops.emptyContainer(c, callback);
}
}
protected void onRefreshContainers() {
int idx = containersList.getSelectedIndex();
refreshContainers();
containersList.setSelectedIndex(idx);
}
protected void onDeleteContainer() {
Container c = getSelectedContainer();
if (confirm("Are you sure you want to delete container '" + c.getName() + "'? You cannot get back what you delete.")) {
ops.deleteContainer(c, callback);
}
}
protected void onCreateContainer() {
ContainerSpecification spec = doGetContainerSpec();
ops.createContainer(spec, callback);
}
private ContainerSpecification doGetContainerSpec() {
JTextField name = new JTextField();
JCheckBox priv = new JCheckBox("private container");
if (JOptionPane.showConfirmDialog(this, new Object[] { "Name", name, priv }, "Create Container", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
return new ContainerSpecification(name.getText(), priv.isSelected());
}
return null;
}
/**
* @return
*/
private JPopupMenu createStoredObjectPopupMenu() {
JPopupMenu pop = new JPopupMenu("StoredObject");
pop.add(new JMenuItem(storedObjectPreviewAction));
pop.add(new JMenuItem(storedObjectOpenAction));
pop.add(new JMenuItem(storedObjectViewMetaData));
pop.addSeparator();
pop.add(new JMenuItem(storedObjectCreateAction));
pop.add(new JMenuItem(storedObjectDownloadAction));
pop.addSeparator();
pop.add(new JMenuItem(storedObjectDeleteAction));
return pop;
}
public JMenuBar createMenuBar() {
JMenuBar bar = new JMenuBar();
JMenu accountMenu = new JMenu("Account");
JMenu containerMenu = new JMenu("Container");
JMenu storedObjectMenu = new JMenu("StoredObject");
JMenu helpMenu = new JMenu("Help");
accountMenu.setMnemonic('A');
containerMenu.setMnemonic('C');
storedObjectMenu.setMnemonic('O');
helpMenu.setMnemonic('H');
bar.add(accountMenu);
bar.add(containerMenu);
bar.add(storedObjectMenu);
bar.add(helpMenu);
JPanel panel = new JPanel(new FlowLayout(SwingConstants.RIGHT, 0, 0));
JLabel label = new JLabel(getIcon("zoom.png"));
label.setLabelFor(searchTextField);
label.setDisplayedMnemonic('f');
panel.add(label);
panel.add(searchTextField);
bar.add(panel);
//
accountMenu.add(new JMenuItem(accountLoginAction));
accountMenu.add(new JMenuItem(accountLogoutAction));
accountMenu.addSeparator();
accountMenu.add(new JMenuItem(accountQuitAction));
//
containerMenu.add(new JMenuItem(containerRefreshAction));
containerMenu.add(new JMenuItem(containerViewMetaData));
containerMenu.addSeparator();
containerMenu.add(new JMenuItem(containerCreateAction));
containerMenu.add(new JMenuItem(containerDeleteAction));
containerMenu.addSeparator();
containerMenu.add(new JMenuItem(containerEmptyAction));
containerMenu.addSeparator();
containerMenu.add(new JMenuItem(containerPurgeAction));
//
storedObjectMenu.add(new JMenuItem(storedObjectPreviewAction));
storedObjectMenu.add(new JMenuItem(storedObjectOpenAction));
storedObjectMenu.add(new JMenuItem(storedObjectViewMetaData));
storedObjectMenu.addSeparator();
storedObjectMenu.add(new JMenuItem(storedObjectCreateAction));
storedObjectMenu.add(new JMenuItem(storedObjectDownloadAction));
storedObjectMenu.addSeparator();
storedObjectMenu.add(new JMenuItem(storedObjectDeleteAction));
//
helpMenu.add(new JMenuItem(aboutAction));
//
return bar;
}
protected void onOpenInBrowserStoredObject() {
Container container = getSelectedContainer();
List<StoredObject> objects = getSelectedStoredObjects();
if (container.isPublic()) {
for (StoredObject obj : objects) {
String publicURL = obj.getPublicURL();
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(new URI(publicURL));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
protected void onPreviewStoredObject() {
StoredObject obj = single(getSelectedStoredObjects());
if (obj.getContentLength() < 16 * 1024 * 1024) {
previewPanel.preview(obj.getContentType(), obj.downloadObject());
}
}
protected void onViewMetaDataStoredObject() {
StoredObject obj = single(getSelectedStoredObjects());
Map<String, Object> metadata = obj.getMetadata();
List<LabelComponentPanel> panels = buildMetaDataPanels(metadata);
JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " metadata.", JOptionPane.INFORMATION_MESSAGE);
}
private List<LabelComponentPanel> buildMetaDataPanels(Map<String, Object> metadata) {
List<LabelComponentPanel> panels = new ArrayList<LabelComponentPanel>();
for (Map.Entry<String, Object> entry : metadata.entrySet()) {
JLabel comp = new JLabel(String.valueOf(entry.getValue()));
comp.setFont(comp.getFont().deriveFont(Font.PLAIN));
panels.add(new LabelComponentPanel(entry.getKey(), comp));
}
return panels;
}
protected void onViewMetaDataContainer() {
Container obj = getSelectedContainer();
Map<String, Object> metadata = obj.getMetadata();
List<LabelComponentPanel> panels = buildMetaDataPanels(metadata);
JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " metadata.", JOptionPane.INFORMATION_MESSAGE);
}
protected void onDownloadStoredObject() {
Container container = getSelectedContainer();
List<StoredObject> obj = getSelectedStoredObjects();
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(lastFolder);
if (obj.size() == 1) {
chooser.setSelectedFile(new File(obj.get(0).getName()));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
} else {
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File selected = chooser.getSelectedFile();
for (StoredObject so : obj) {
File target = selected;
if (target.isDirectory()) {
target = new File(selected, so.getName());
}
if (target.exists()) {
if (confirm("File '" + target.getName() + "' already exists. Overwrite?")) {
doSaveStoredObject(target, container, so);
}
} else {
doSaveStoredObject(target, container, so);
}
}
lastFolder = selected.isFile() ? selected.getParentFile() : selected;
}
}
private void doSaveStoredObject(File target, Container container, StoredObject obj) {
ops.downloadStoredObject(container, obj, target, callback);
}
protected void onDeleteStoredObject() {
Container container = getSelectedContainer();
List<StoredObject> objects = getSelectedStoredObjects();
if (objects.size() == 1) {
doDeleteSingleObject(container, single(objects));
} else {
doDeleteMultipleObjects(container, objects);
}
}
protected void doDeleteSingleObject(Container container, StoredObject obj) {
if (confirm("Are you sure you want to delete '" + obj.getName() + "' from '" + container.getName() + "'? You cannot get back what you delete.")) {
ops.deleteStoredObjects(container, Collections.singletonList(obj), callback);
}
}
protected void doDeleteMultipleObjects(Container container, List<StoredObject> obj) {
if (confirm("Are you sure you want to delete " + obj.size() + " objects from '" + container.getName() + "'? You cannot get back what you delete.")) {
ops.deleteStoredObjects(container, obj, callback);
}
}
protected void onCreateStoredObject() {
Container container = getSelectedContainer();
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.setCurrentDirectory(lastFolder);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File[] selectedFiles = chooser.getSelectedFiles();
ops.createStoredObjects(container, selectedFiles, callback);
lastFolder = chooser.getCurrentDirectory();
}
}
public void bind() {
containersList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
} else {
int idx = containersList.getSelectedIndex();
if (idx >= 0) {
refreshFiles((Container) containers.get(idx));
}
}
}
});
//
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable ex) {
if (ex instanceof CommandException) {
showError((CommandException) ex);
} else {
ex.printStackTrace();
}
}
});
//
containersList.getInputMap().put(KeyStroke.getKeyStroke("F5"), "refresh");
containersList.getActionMap().put("refresh", containerRefreshAction);
//
storedObjectsList.getInputMap().put(KeyStroke.getKeyStroke("F5"), "refresh");
storedObjectsList.getActionMap().put("refresh", containerRefreshAction);
//
}
public void refreshContainers() {
containers.clear();
storedObjects.clear();
ops.refreshContainers(callback);
}
public void refreshFiles(Container selected) {
storedObjects.clear();
ops.refreshStoredObjects(selected, callback);
}
//
// Callback
//
@Override
public void onStart() {
if (busyCnt == 0) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
statusPanel.onStart();
}
busyCnt++;
}
@Override
public void onDone() {
busyCnt--;
if (busyCnt == 0) {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
statusPanel.onEnd();
}
enableDisable();
}
@Override
public void onError(CommandException ex) {
ex.printStackTrace();
showError(ex);
}
/**
* {@inheritDoc}.
*/
@Override
public void onUpdateContainers(Collection<Container> cs) {
containers.clear();
for (Container container : cs) {
containers.addElement(container);
}
statusPanel.onDeselectContainer();
}
/**
* {@inheritDoc}.
*/
@Override
public void onStoredObjectDeleted(Container container, StoredObject storedObject) {
if (isContainerSelected() && getSelectedContainer().equals(container)) {
int idx = storedObjects.indexOf(storedObject);
if (idx >= 0) {
storedObjectsList.getSelectionModel().removeIndexInterval(idx, idx);
}
storedObjects.removeElement(storedObject);
allStoredObjects.remove(storedObject);
}
}
public void onSearch() {
storedObjects.clear();
for (StoredObject storedObject : allStoredObjects) {
if (isFilterIncluded(storedObject)) {
storedObjects.addElement(storedObject);
}
}
}
/**
* {@inheritDoc}.
*/
@Override
public void onNewStoredObjects() {
searchTextField.setText("");
storedObjects.clear();
allStoredObjects.clear();
statusPanel.onDeselectStoredObject();
}
/**
* {@inheritDoc}.
*/
@Override
public void onAppendStoredObjects(Container container, int page, Collection<StoredObject> sos) {
if (isContainerSelected() && getSelectedContainer().equals(container)) {
allStoredObjects.addAll(sos);
for (StoredObject storedObject : sos) {
if (isFilterIncluded(storedObject)) {
storedObjects.addElement(storedObject);
}
}
}
}
private boolean isFilterIncluded(StoredObject obj) {
String filter = searchTextField.getText();
if (filter.isEmpty()) {
return true;
} else {
return obj.getName().contains(filter);
}
}
@Override
public void onContainerUpdate(Container container) {
statusPanel.onSelectContainer(container);
}
@Override
public void onStoredObjectUpdate(StoredObject obj) {
statusPanel.onSelectStoredObjects(Collections.singletonList(obj));
}
//
//
//
/**
* @return true if the window can close.
*/
public boolean onClose() {
return (loggedIn && confirm("Are you sure you want to Quit this application?")) || (!loggedIn);
}
public boolean confirm(String message) {
return JOptionPane.showConfirmDialog(this, message, "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION;
}
protected void showError(CommandException ex) {
JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.OK_OPTION);
}
}
| |
package com.ctrip.zeus.dao.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CertCertificateExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
protected Integer offset;
protected Integer rows;
public CertCertificateExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public CertCertificateExample orderBy(String orderByClause) {
this.setOrderByClause(orderByClause);
return this;
}
public CertCertificateExample orderBy(String ... orderByClauses) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < orderByClauses.length; i++) {
sb.append(orderByClauses[i]);
if (i < orderByClauses.length - 1) {
sb.append(" , ");
}
}
this.setOrderByClause(sb.toString());
return this;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria(this);
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
rows = null;
offset = null;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Integer getOffset() {
return this.offset;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public Integer getRows() {
return this.rows;
}
public CertCertificateExample limit(Integer rows) {
this.rows = rows;
return this;
}
public CertCertificateExample limit(Integer offset, Integer rows) {
this.offset = offset;
this.rows = rows;
return this;
}
public CertCertificateExample page(Integer page, Integer pageSize) {
this.offset = page * pageSize;
this.rows = pageSize;
return this;
}
public static Criteria newAndCreateCriteria() {
CertCertificateExample example = new CertCertificateExample();
return example.createCriteria();
}
public CertCertificateExample when(boolean condition, IExampleWhen then) {
if (condition) {
then.example(this);
}
return this;
}
public CertCertificateExample when(boolean condition, IExampleWhen then, IExampleWhen otherwise) {
if (condition) {
then.example(this);
} else {
otherwise.example(this);
}
return this;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("id = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("id <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("id > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("id >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("id < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("id <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andDomainIsNull() {
addCriterion("`domain` is null");
return (Criteria) this;
}
public Criteria andDomainIsNotNull() {
addCriterion("`domain` is not null");
return (Criteria) this;
}
public Criteria andDomainEqualTo(String value) {
addCriterion("`domain` =", value, "domain");
return (Criteria) this;
}
public Criteria andDomainEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`domain` = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDomainNotEqualTo(String value) {
addCriterion("`domain` <>", value, "domain");
return (Criteria) this;
}
public Criteria andDomainNotEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`domain` <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDomainGreaterThan(String value) {
addCriterion("`domain` >", value, "domain");
return (Criteria) this;
}
public Criteria andDomainGreaterThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`domain` > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDomainGreaterThanOrEqualTo(String value) {
addCriterion("`domain` >=", value, "domain");
return (Criteria) this;
}
public Criteria andDomainGreaterThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`domain` >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDomainLessThan(String value) {
addCriterion("`domain` <", value, "domain");
return (Criteria) this;
}
public Criteria andDomainLessThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`domain` < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDomainLessThanOrEqualTo(String value) {
addCriterion("`domain` <=", value, "domain");
return (Criteria) this;
}
public Criteria andDomainLessThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`domain` <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDomainLike(String value) {
addCriterion("`domain` like", value, "domain");
return (Criteria) this;
}
public Criteria andDomainNotLike(String value) {
addCriterion("`domain` not like", value, "domain");
return (Criteria) this;
}
public Criteria andDomainIn(List<String> values) {
addCriterion("`domain` in", values, "domain");
return (Criteria) this;
}
public Criteria andDomainNotIn(List<String> values) {
addCriterion("`domain` not in", values, "domain");
return (Criteria) this;
}
public Criteria andDomainBetween(String value1, String value2) {
addCriterion("`domain` between", value1, value2, "domain");
return (Criteria) this;
}
public Criteria andDomainNotBetween(String value1, String value2) {
addCriterion("`domain` not between", value1, value2, "domain");
return (Criteria) this;
}
public Criteria andStateIsNull() {
addCriterion("`state` is null");
return (Criteria) this;
}
public Criteria andStateIsNotNull() {
addCriterion("`state` is not null");
return (Criteria) this;
}
public Criteria andStateEqualTo(Boolean value) {
addCriterion("`state` =", value, "state");
return (Criteria) this;
}
public Criteria andStateEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`state` = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andStateNotEqualTo(Boolean value) {
addCriterion("`state` <>", value, "state");
return (Criteria) this;
}
public Criteria andStateNotEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`state` <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andStateGreaterThan(Boolean value) {
addCriterion("`state` >", value, "state");
return (Criteria) this;
}
public Criteria andStateGreaterThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`state` > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andStateGreaterThanOrEqualTo(Boolean value) {
addCriterion("`state` >=", value, "state");
return (Criteria) this;
}
public Criteria andStateGreaterThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`state` >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andStateLessThan(Boolean value) {
addCriterion("`state` <", value, "state");
return (Criteria) this;
}
public Criteria andStateLessThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`state` < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andStateLessThanOrEqualTo(Boolean value) {
addCriterion("`state` <=", value, "state");
return (Criteria) this;
}
public Criteria andStateLessThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("`state` <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andStateIn(List<Boolean> values) {
addCriterion("`state` in", values, "state");
return (Criteria) this;
}
public Criteria andStateNotIn(List<Boolean> values) {
addCriterion("`state` not in", values, "state");
return (Criteria) this;
}
public Criteria andStateBetween(Boolean value1, Boolean value2) {
addCriterion("`state` between", value1, value2, "state");
return (Criteria) this;
}
public Criteria andStateNotBetween(Boolean value1, Boolean value2) {
addCriterion("`state` not between", value1, value2, "state");
return (Criteria) this;
}
public Criteria andVersionIsNull() {
addCriterion("version is null");
return (Criteria) this;
}
public Criteria andVersionIsNotNull() {
addCriterion("version is not null");
return (Criteria) this;
}
public Criteria andVersionEqualTo(Integer value) {
addCriterion("version =", value, "version");
return (Criteria) this;
}
public Criteria andVersionEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("version = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andVersionNotEqualTo(Integer value) {
addCriterion("version <>", value, "version");
return (Criteria) this;
}
public Criteria andVersionNotEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("version <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andVersionGreaterThan(Integer value) {
addCriterion("version >", value, "version");
return (Criteria) this;
}
public Criteria andVersionGreaterThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("version > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andVersionGreaterThanOrEqualTo(Integer value) {
addCriterion("version >=", value, "version");
return (Criteria) this;
}
public Criteria andVersionGreaterThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("version >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andVersionLessThan(Integer value) {
addCriterion("version <", value, "version");
return (Criteria) this;
}
public Criteria andVersionLessThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("version < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andVersionLessThanOrEqualTo(Integer value) {
addCriterion("version <=", value, "version");
return (Criteria) this;
}
public Criteria andVersionLessThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("version <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andVersionIn(List<Integer> values) {
addCriterion("version in", values, "version");
return (Criteria) this;
}
public Criteria andVersionNotIn(List<Integer> values) {
addCriterion("version not in", values, "version");
return (Criteria) this;
}
public Criteria andVersionBetween(Integer value1, Integer value2) {
addCriterion("version between", value1, value2, "version");
return (Criteria) this;
}
public Criteria andVersionNotBetween(Integer value1, Integer value2) {
addCriterion("version not between", value1, value2, "version");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeIsNull() {
addCriterion("DataChange_LastTime is null");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeIsNotNull() {
addCriterion("DataChange_LastTime is not null");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeEqualTo(Date value) {
addCriterion("DataChange_LastTime =", value, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("DataChange_LastTime = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDatachangeLasttimeNotEqualTo(Date value) {
addCriterion("DataChange_LastTime <>", value, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeNotEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("DataChange_LastTime <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDatachangeLasttimeGreaterThan(Date value) {
addCriterion("DataChange_LastTime >", value, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeGreaterThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("DataChange_LastTime > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDatachangeLasttimeGreaterThanOrEqualTo(Date value) {
addCriterion("DataChange_LastTime >=", value, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeGreaterThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("DataChange_LastTime >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDatachangeLasttimeLessThan(Date value) {
addCriterion("DataChange_LastTime <", value, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeLessThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("DataChange_LastTime < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDatachangeLasttimeLessThanOrEqualTo(Date value) {
addCriterion("DataChange_LastTime <=", value, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeLessThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("DataChange_LastTime <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDatachangeLasttimeIn(List<Date> values) {
addCriterion("DataChange_LastTime in", values, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeNotIn(List<Date> values) {
addCriterion("DataChange_LastTime not in", values, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeBetween(Date value1, Date value2) {
addCriterion("DataChange_LastTime between", value1, value2, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andDatachangeLasttimeNotBetween(Date value1, Date value2) {
addCriterion("DataChange_LastTime not between", value1, value2, "datachangeLasttime");
return (Criteria) this;
}
public Criteria andCidIsNull() {
addCriterion("cid is null");
return (Criteria) this;
}
public Criteria andCidIsNotNull() {
addCriterion("cid is not null");
return (Criteria) this;
}
public Criteria andCidEqualTo(String value) {
addCriterion("cid =", value, "cid");
return (Criteria) this;
}
public Criteria andCidEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("cid = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCidNotEqualTo(String value) {
addCriterion("cid <>", value, "cid");
return (Criteria) this;
}
public Criteria andCidNotEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("cid <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCidGreaterThan(String value) {
addCriterion("cid >", value, "cid");
return (Criteria) this;
}
public Criteria andCidGreaterThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("cid > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCidGreaterThanOrEqualTo(String value) {
addCriterion("cid >=", value, "cid");
return (Criteria) this;
}
public Criteria andCidGreaterThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("cid >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCidLessThan(String value) {
addCriterion("cid <", value, "cid");
return (Criteria) this;
}
public Criteria andCidLessThanColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("cid < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCidLessThanOrEqualTo(String value) {
addCriterion("cid <=", value, "cid");
return (Criteria) this;
}
public Criteria andCidLessThanOrEqualToColumn(CertCertificateWithBLOBs.Column column) {
addCriterion(new StringBuilder("cid <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCidLike(String value) {
addCriterion("cid like", value, "cid");
return (Criteria) this;
}
public Criteria andCidNotLike(String value) {
addCriterion("cid not like", value, "cid");
return (Criteria) this;
}
public Criteria andCidIn(List<String> values) {
addCriterion("cid in", values, "cid");
return (Criteria) this;
}
public Criteria andCidNotIn(List<String> values) {
addCriterion("cid not in", values, "cid");
return (Criteria) this;
}
public Criteria andCidBetween(String value1, String value2) {
addCriterion("cid between", value1, value2, "cid");
return (Criteria) this;
}
public Criteria andCidNotBetween(String value1, String value2) {
addCriterion("cid not between", value1, value2, "cid");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
private CertCertificateExample example;
protected Criteria(CertCertificateExample example) {
super();
this.example = example;
}
public CertCertificateExample example() {
return this.example;
}
@Deprecated
public Criteria andIf(boolean ifAdd, ICriteriaAdd add) {
if (ifAdd) {
add.add(this);
}
return this;
}
public Criteria when(boolean condition, ICriteriaWhen then) {
if (condition) {
then.criteria(this);
}
return this;
}
public Criteria when(boolean condition, ICriteriaWhen then, ICriteriaWhen otherwise) {
if (condition) {
then.criteria(this);
} else {
otherwise.criteria(this);
}
return this;
}
@Deprecated
public interface ICriteriaAdd {
Criteria add(Criteria add);
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
public interface ICriteriaWhen {
void criteria(Criteria criteria);
}
public interface IExampleWhen {
void example(com.ctrip.zeus.dao.entity.CertCertificateExample example);
}
}
| |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.annotate;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.CommittedChangesProvider;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FilePathImpl;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.annotate.*;
import com.intellij.openapi.vcs.history.*;
import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.*;
import org.jetbrains.idea.svn.checkin.CommitInfo;
import org.jetbrains.idea.svn.diff.DiffOptions;
import org.jetbrains.idea.svn.history.*;
import org.jetbrains.idea.svn.info.Info;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc2.SvnTarget;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAnnotationProvider {
private static final Object MERGED_KEY = new Object();
private final SvnVcs myVcs;
public SvnAnnotationProvider(final SvnVcs vcs) {
myVcs = vcs;
}
public FileAnnotation annotate(final VirtualFile file) throws VcsException {
final SvnDiffProvider provider = (SvnDiffProvider)myVcs.getDiffProvider();
final SVNRevision currentRevision = ((SvnRevisionNumber)provider.getCurrentRevision(file)).getRevision();
final VcsRevisionDescription lastChangedRevision = provider.getCurrentRevisionDescription(file);
if (lastChangedRevision == null) {
throw new VcsException("Can not get current revision for file " + file.getPath());
}
final SVNRevision svnRevision = ((SvnRevisionNumber)lastChangedRevision.getRevisionNumber()).getRevision();
if (! svnRevision.isValid()) {
throw new VcsException("Can not get last changed revision for file: " + file.getPath() + "\nPlease run svn info for this file and file an issue.");
}
return annotate(file, new SvnFileRevision(myVcs, currentRevision, currentRevision, null, null, null, null, null),
lastChangedRevision.getRevisionNumber(), true);
}
public FileAnnotation annotate(final VirtualFile file, final VcsFileRevision revision) throws VcsException {
return annotate(file, revision, revision.getRevisionNumber(), false);
}
private FileAnnotation annotate(final VirtualFile file, final VcsFileRevision revision, final VcsRevisionNumber lastChangedRevision,
final boolean loadExternally) throws VcsException {
if (file.isDirectory()) {
throw new VcsException(SvnBundle.message("exception.text.cannot.annotate.directory"));
}
final FileAnnotation[] annotation = new FileAnnotation[1];
final VcsException[] exception = new VcsException[1];
Runnable command = new Runnable() {
public void run() {
final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
final File ioFile = new File(file.getPath()).getAbsoluteFile();
Info info = null;
try {
final String contents;
if (loadExternally) {
byte[] data = SvnUtil.getFileContents(myVcs, SvnTarget.fromFile(ioFile), SVNRevision.BASE, SVNRevision.UNDEFINED);
contents = LoadTextUtil.getTextByBinaryPresentation(data, file, false, false).toString();
} else {
final byte[] bytes = VcsHistoryUtil.loadRevisionContent(revision);
contents = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false).toString();
}
final SvnFileAnnotation result = new SvnFileAnnotation(myVcs, file, contents, lastChangedRevision);
info = myVcs.getInfo(ioFile);
if (info == null) {
exception[0] = new VcsException(new SVNException(SVNErrorMessage.create(SVNErrorCode.UNKNOWN, "File ''{0}'' is not under version control", ioFile)));
return;
}
final String url = info.getURL() == null ? null : info.getURL().toString();
SVNRevision endRevision = ((SvnFileRevision) revision).getRevision();
if (SVNRevision.WORKING.equals(endRevision)) {
endRevision = info.getRevision();
}
if (progress != null) {
progress.setText(SvnBundle.message("progress.text.computing.annotation", file.getName()));
}
// ignore mime type=true : IDEA-19562
final AnnotationConsumer annotateHandler = createAnnotationHandler(progress, result);
final boolean calculateMergeinfo = SvnConfiguration.getInstance(myVcs.getProject()).isShowMergeSourcesInAnnotate() &&
SvnUtil.checkRepositoryVersion15(myVcs, url);
final MySteppedLogGetter logGetter = new MySteppedLogGetter(
myVcs, ioFile, progress,
myVcs.getFactory(ioFile).createHistoryClient(), endRevision, result,
url, calculateMergeinfo, file.getCharset());
logGetter.go();
final LinkedList<SVNRevision> rp = logGetter.getRevisionPoints();
// TODO: only 2 elements will be in rp and for loop will be executed only once - probably rewrite with Pair
AnnotateClient annotateClient = myVcs.getFactory(ioFile).createAnnotateClient();
for (int i = 0; i < rp.size() - 1; i++) {
annotateClient.annotate(SvnTarget.fromFile(ioFile), rp.get(i + 1), rp.get(i), calculateMergeinfo, getLogClientOptions(myVcs),
annotateHandler);
}
if (rp.get(1).getNumber() > 0) {
result.setFirstRevision(rp.get(1));
}
annotation[0] = result;
}
catch (IOException e) {
exception[0] = new VcsException(e);
} catch (VcsException e) {
if (e.getCause() instanceof SVNException) {
handleSvnException(ioFile, info, (SVNException)e.getCause(), file, revision, annotation, exception);
}
else {
exception[0] = e;
}
}
}
};
if (ApplicationManager.getApplication().isDispatchThread()) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(command, SvnBundle.message("action.text.annotate"), false, myVcs.getProject());
}
else {
command.run();
}
if (exception[0] != null) {
throw new VcsException(exception[0]);
}
return annotation[0];
}
private void handleSvnException(File ioFile,
Info info,
SVNException e,
VirtualFile file,
VcsFileRevision revision,
FileAnnotation[] annotation, VcsException[] exception) {
// TODO: Check how this scenario could be reproduced by user and what changes needs to be done for command line client
if (SVNErrorCode.FS_NOT_FOUND.equals(e.getErrorMessage().getErrorCode())) {
final CommittedChangesProvider<SvnChangeList,ChangeBrowserSettings> provider = myVcs.getCommittedChangesProvider();
try {
final Pair<SvnChangeList, FilePath> pair = provider.getOneList(file, revision.getRevisionNumber());
if (pair != null && info != null && pair.getSecond() != null && ! Comparing.equal(pair.getSecond().getIOFile(), ioFile)) {
annotation[0] = annotateNonExisting(pair, revision, info, file.getCharset(), file);
return;
}
}
catch (VcsException e1) {
exception[0] = e1;
}
catch (SVNException e1) {
exception[0] = new VcsException(e);
}
catch (IOException e1) {
exception[0] = new VcsException(e);
}
}
exception[0] = new VcsException(e);
}
public static File getCommonAncestor(final File file1, final File file2) throws IOException {
if (FileUtil.filesEqual(file1, file2)) return file1;
final File can1 = file1.getCanonicalFile();
final File can2 = file2.getCanonicalFile();
final List<String> parts1 = StringUtil.split(can1.getPath(), File.separator, true);
final List<String> parts2 = StringUtil.split(can2.getPath(), File.separator, true);
int cnt = 0;
while (parts1.size() > cnt && parts2.size() > cnt) {
if (! parts1.get(cnt).equals(parts2.get(cnt))) {
if (cnt > 0) {
return new File(StringUtil.join(parts1.subList(0, cnt), File.separator));
} else {
return null;
}
}
++ cnt;
}
//shorter one
if (parts1.size() > parts2.size()) {
return file2;
} else {
return file1;
}
}
private SvnRemoteFileAnnotation annotateNonExisting(Pair<SvnChangeList, FilePath> pair,
VcsFileRevision revision,
Info info,
Charset charset, final VirtualFile current) throws VcsException, SVNException, IOException {
final File wasFile = pair.getSecond().getIOFile();
final File root = getCommonAncestor(wasFile, info.getFile());
if (root == null) throw new VcsException("Can not find relative path for " + wasFile.getPath() + "@" + revision.getRevisionNumber().asString());
final String relativePath = FileUtil.getRelativePath(root.getPath(), wasFile.getPath(), File.separatorChar);
if (relativePath == null) throw new VcsException("Can not find relative path for " + wasFile.getPath() + "@" + revision.getRevisionNumber().asString());
Info wcRootInfo = myVcs.getInfo(root);
if (wcRootInfo == null || wcRootInfo.getURL() == null) {
throw new VcsException("Can not find relative path for " + wasFile.getPath() + "@" + revision.getRevisionNumber().asString());
}
SVNURL wasUrl = wcRootInfo.getURL();
final String[] strings = relativePath.replace('\\','/').split("/");
for (String string : strings) {
wasUrl = wasUrl.appendPath(string, true);
}
final SVNRevision svnRevision = ((SvnRevisionNumber)revision.getRevisionNumber()).getRevision();
byte[] data = SvnUtil.getFileContents(myVcs, SvnTarget.fromURL(wasUrl), svnRevision, svnRevision);
final String contents = LoadTextUtil.getTextByBinaryPresentation(data, charset == null ? CharsetToolkit.UTF8_CHARSET : charset).toString();
final SvnRemoteFileAnnotation result = new SvnRemoteFileAnnotation(myVcs, contents, revision.getRevisionNumber(), current);
final AnnotationConsumer annotateHandler = createAnnotationHandler(ProgressManager.getInstance().getProgressIndicator(), result);
final boolean calculateMergeinfo = SvnConfiguration.getInstance(myVcs.getProject()).isShowMergeSourcesInAnnotate() &&
SvnUtil.checkRepositoryVersion15(myVcs, wasUrl.toString());
AnnotateClient client = myVcs.getFactory().createAnnotateClient();
client
.annotate(SvnTarget.fromURL(wasUrl, svnRevision), SVNRevision.create(1), svnRevision, calculateMergeinfo, getLogClientOptions(myVcs),
annotateHandler);
return result;
}
@NotNull
private static AnnotationConsumer createAnnotationHandler(@Nullable final ProgressIndicator progress,
@NotNull final BaseSvnFileAnnotation result) {
return new AnnotationConsumer() {
@Override
public void consume(int lineNumber, @NotNull CommitInfo info, @Nullable CommitInfo mergeInfo) throws SVNException {
if (progress != null) {
progress.checkCanceled();
}
result.setLineInfo(lineNumber, info, mergeInfo != null && info.getRevision() > mergeInfo.getRevision() ? mergeInfo : null);
}
};
}
@Override
public VcsAnnotation createCacheable(FileAnnotation fileAnnotation) {
if (! (fileAnnotation instanceof SvnFileAnnotation)) return null;
final SvnFileAnnotation svnFileAnnotation = (SvnFileAnnotation) fileAnnotation;
final AnnotationSourceSwitcher annotationSourceSwitcher = svnFileAnnotation.getAnnotationSourceSwitcher();
if (annotationSourceSwitcher != null) {
annotationSourceSwitcher.switchTo(AnnotationSource.LOCAL);
}
final int size = svnFileAnnotation.getLineCount();
final VcsUsualLineAnnotationData lineAnnotationData = new VcsUsualLineAnnotationData(size);
for (int i = 0; i < size; i++) {
final VcsRevisionNumber revisionNumber = svnFileAnnotation.getLineRevisionNumber(i);
lineAnnotationData.put(i, revisionNumber);
}
final VcsAnnotation vcsAnnotation = new VcsAnnotation(VcsUtil.getFilePath(svnFileAnnotation.getFile()), lineAnnotationData,
svnFileAnnotation.getFirstRevisionNumber());
if (annotationSourceSwitcher != null) {
final VcsRareLineAnnotationData merged = new VcsRareLineAnnotationData(size);
final Map<VcsRevisionNumber, VcsFileRevision> addMap = new HashMap<VcsRevisionNumber, VcsFileRevision>();
annotationSourceSwitcher.switchTo(AnnotationSource.MERGE);
for (int i = 0; i < size; i++) {
if (annotationSourceSwitcher.mergeSourceAvailable(i)) {
final VcsRevisionNumber number = svnFileAnnotation.getLineRevisionNumber(i);
if (number == null) continue;
merged.put(i, number);
addMap.put(number, svnFileAnnotation.getRevision(((SvnRevisionNumber) number).getRevision().getNumber()));
}
}
if (! merged.isEmpty()) {
vcsAnnotation.addAnnotation(MERGED_KEY, merged);
vcsAnnotation.addCachedOtherRevisions(addMap);
}
}
return vcsAnnotation;
}
@Nullable
@Override
public FileAnnotation restore(VcsAnnotation vcsAnnotation,
VcsAbstractHistorySession session,
String annotatedContent,
boolean forCurrentRevision, VcsRevisionNumber revisionNumber) {
final SvnFileAnnotation annotation =
new SvnFileAnnotation(myVcs, vcsAnnotation.getFilePath().getVirtualFile(), annotatedContent, revisionNumber);
final VcsLineAnnotationData basicAnnotation = vcsAnnotation.getBasicAnnotation();
final VcsLineAnnotationData data = vcsAnnotation.getAdditionalAnnotations().get(MERGED_KEY);
final Map<VcsRevisionNumber,VcsFileRevision> historyAsMap = session.getHistoryAsMap();
final Map<VcsRevisionNumber, VcsFileRevision> cachedOtherRevisions = vcsAnnotation.getCachedOtherRevisions();
for (int i = 0; i < basicAnnotation.getNumLines(); i++) {
final VcsRevisionNumber revision = basicAnnotation.getRevision(i);
final VcsRevisionNumber mergedData = data == null ? null : data.getRevision(i);
final SvnFileRevision fileRevision = (SvnFileRevision)historyAsMap.get(revision);
if (fileRevision == null) return null;
if (mergedData == null) {
annotation.setLineInfo(i, fileRevision.getCommitInfo(), null);
} else {
final SvnFileRevision mergedRevision = (SvnFileRevision)cachedOtherRevisions.get(mergedData);
if (mergedRevision == null) return null;
annotation.setLineInfo(i, fileRevision.getCommitInfo(), mergedRevision.getCommitInfo());
}
}
if (vcsAnnotation.getFirstRevision() != null) {
annotation.setFirstRevision(((SvnRevisionNumber) vcsAnnotation.getFirstRevision()).getRevision());
}
for (VcsFileRevision revision : session.getRevisionList()) {
annotation.setRevision(((SvnRevisionNumber) revision.getRevisionNumber()).getRevision().getNumber(), (SvnFileRevision)revision);
}
return annotation;
}
private static class MySteppedLogGetter {
private final LinkedList<SVNRevision> myRevisionPoints;
private final SvnVcs myVcs;
private final File myIoFile;
private final ProgressIndicator myProgress;
private final HistoryClient myClient;
private final SVNRevision myEndRevision;
private final boolean myCalculateMergeinfo;
private final SvnFileAnnotation myResult;
private final String myUrl;
private final Charset myCharset;
private MySteppedLogGetter(final SvnVcs vcs, final File ioFile, final ProgressIndicator progress, final HistoryClient client,
final SVNRevision endRevision,
final SvnFileAnnotation result,
final String url,
final boolean calculateMergeinfo,
Charset charset) {
myVcs = vcs;
myIoFile = ioFile;
myProgress = progress;
myClient = client;
myEndRevision = endRevision;
myCalculateMergeinfo = calculateMergeinfo;
myResult = result;
myUrl = url;
myCharset = charset;
myRevisionPoints = new LinkedList<SVNRevision>();
}
public void go() throws VcsException {
final int maxAnnotateRevisions = SvnConfiguration.getInstance(myVcs.getProject()).getMaxAnnotateRevisions();
boolean longHistory = true;
if (maxAnnotateRevisions == -1) {
longHistory = false;
} else {
if (myEndRevision.getNumber() < maxAnnotateRevisions) {
longHistory = false;
}
}
if (! longHistory) {
doLog(myCalculateMergeinfo, null, 0);
putDefaultBounds();
} else {
doLog(false, null, 0);
final List<VcsFileRevision> fileRevisionList = myResult.getRevisions();
if (fileRevisionList.size() < maxAnnotateRevisions) {
putDefaultBounds();
if (myCalculateMergeinfo) {
doLog(true, null, 0);
}
return;
}
myRevisionPoints.add(((SvnRevisionNumber) fileRevisionList.get(0).getRevisionNumber()).getRevision());
final SVNRevision truncateTo =
((SvnRevisionNumber)fileRevisionList.get(maxAnnotateRevisions - 1).getRevisionNumber()).getRevision();
myRevisionPoints.add(truncateTo);
// todo file history can be asked in parallel
if (myCalculateMergeinfo) {
doLog(true, truncateTo, maxAnnotateRevisions);
}
}
}
private void putDefaultBounds() {
myRevisionPoints.add(myEndRevision);
myRevisionPoints.add(SVNRevision.create(0));
}
private void doLog(final boolean includeMerged, final SVNRevision truncateTo, final int max) throws VcsException {
myClient.doLog(SvnTarget.fromFile(myIoFile), myEndRevision, truncateTo == null ? SVNRevision.create(1L) : truncateTo,
false, false, includeMerged, max, null,
new LogEntryConsumer() {
@Override
public void consume(LogEntry logEntry) {
if (SVNRevision.UNDEFINED.getNumber() == logEntry.getRevision()) {
return;
}
if (myProgress != null) {
myProgress.checkCanceled();
myProgress.setText2(SvnBundle.message("progress.text2.revision.processed", logEntry.getRevision()));
}
myResult.setRevision(logEntry.getRevision(), new SvnFileRevision(myVcs, SVNRevision.UNDEFINED, logEntry, myUrl, ""));
}
});
}
public LinkedList<SVNRevision> getRevisionPoints() {
return myRevisionPoints;
}
}
public boolean isAnnotationValid( VcsFileRevision rev ){
return true;
}
@Nullable
private static DiffOptions getLogClientOptions(@NotNull SvnVcs vcs) {
return SvnConfiguration.getInstance(vcs.getProject()).isIgnoreSpacesInAnnotate() ? new DiffOptions(true, true, true) : null;
}
}
| |
/*
* Generated by the Jasper component of Apache Tomcat
* Version: JspC/ApacheTomcat8
* Generated at: 2016-11-04 01:18:37 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.jivesoftware.openfire.admin.decorators;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.jivesoftware.util.StringUtils;
import org.jivesoftware.admin.AdminConsole;
import org.jivesoftware.util.LocaleUtils;
import org.xmpp.packet.JID;
public final class main_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
static {
_jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(3);
_jspx_dependants.put("jar:file:/E:/workspace/openfire/build/lib/merge/sitemesh.jar!/META-INF/sitemesh-decorator.tld", Long.valueOf(1086663512000L));
_jspx_dependants.put("file:/E:/workspace/openfire/build/lib/merge/sitemesh.jar", Long.valueOf(1471419904000L));
_jspx_dependants.put("jar:file:/E:/workspace/openfire/build/lib/merge/sitemesh.jar!/META-INF/sitemesh-page.tld", Long.valueOf(1086663512000L));
}
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fdecorator_005fusePage_0026_005fid_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fsetBundle_0026_005fbasename_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fdecorator_005ftitle_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fdecorator_005fhead_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fcurrentcss_005fcss;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fadmin_005fsubnavbar_0026_005fcurrentcss_005fcss;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fadmin_005fsidebar_0026_005fheadercss_005fcurrentcss_005fcss;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fadmin_005fsubsidebar_0026_005fcurrentcss_005fcss;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fdecorator_005ftitle_0026_005fdefault_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fdecorator_005fbody_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fjustlinks_005fcurrentcss_005fcss;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fdecorator_005fusePage_0026_005fid_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005ffmt_005fsetBundle_0026_005fbasename_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fdecorator_005ftitle_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fdecorator_005fhead_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fcurrentcss_005fcss = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fadmin_005fsubnavbar_0026_005fcurrentcss_005fcss = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fadmin_005fsidebar_0026_005fheadercss_005fcurrentcss_005fcss = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fadmin_005fsubsidebar_0026_005fcurrentcss_005fcss = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fdecorator_005ftitle_0026_005fdefault_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fdecorator_005fbody_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fjustlinks_005fcurrentcss_005fcss = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fdecorator_005fusePage_0026_005fid_005fnobody.release();
_005fjspx_005ftagPool_005ffmt_005fsetBundle_0026_005fbasename_005fnobody.release();
_005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.release();
_005fjspx_005ftagPool_005fdecorator_005ftitle_005fnobody.release();
_005fjspx_005ftagPool_005fdecorator_005fhead_005fnobody.release();
_005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.release();
_005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.release();
_005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fcurrentcss_005fcss.release();
_005fjspx_005ftagPool_005fadmin_005fsubnavbar_0026_005fcurrentcss_005fcss.release();
_005fjspx_005ftagPool_005fadmin_005fsidebar_0026_005fheadercss_005fcurrentcss_005fcss.release();
_005fjspx_005ftagPool_005fadmin_005fsubsidebar_0026_005fcurrentcss_005fcss.release();
_005fjspx_005ftagPool_005fdecorator_005ftitle_0026_005fdefault_005fnobody.release();
_005fjspx_005ftagPool_005fdecorator_005fbody_005fnobody.release();
_005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fjustlinks_005fcurrentcss_005fcss.release();
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
"../error.jsp", true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
org.jivesoftware.admin.AdminPageBean info = null;
info = (org.jivesoftware.admin.AdminPageBean) _jspx_page_context.getAttribute("info", javax.servlet.jsp.PageContext.REQUEST_SCOPE);
if (info == null){
info = new org.jivesoftware.admin.AdminPageBean();
_jspx_page_context.setAttribute("info", info, javax.servlet.jsp.PageContext.REQUEST_SCOPE);
}
out.write("\r\n\r\n");
org.jivesoftware.util.WebManager webManager = null;
webManager = (org.jivesoftware.util.WebManager) _jspx_page_context.getAttribute("webManager", javax.servlet.jsp.PageContext.PAGE_SCOPE);
if (webManager == null){
webManager = new org.jivesoftware.util.WebManager();
_jspx_page_context.setAttribute("webManager", webManager, javax.servlet.jsp.PageContext.PAGE_SCOPE);
}
out.write('\r');
out.write('\n');
webManager.init(request, response, session, application, out);
out.write("\r\n\r\n");
// decorator:usePage
com.opensymphony.module.sitemesh.taglib.decorator.UsePageTag _jspx_th_decorator_005fusePage_005f0 = (com.opensymphony.module.sitemesh.taglib.decorator.UsePageTag) _005fjspx_005ftagPool_005fdecorator_005fusePage_0026_005fid_005fnobody.get(com.opensymphony.module.sitemesh.taglib.decorator.UsePageTag.class);
_jspx_th_decorator_005fusePage_005f0.setPageContext(_jspx_page_context);
_jspx_th_decorator_005fusePage_005f0.setParent(null);
// /decorators/main.jsp(36,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_decorator_005fusePage_005f0.setId("decoratedPage");
int _jspx_eval_decorator_005fusePage_005f0 = _jspx_th_decorator_005fusePage_005f0.doStartTag();
if (_jspx_th_decorator_005fusePage_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fdecorator_005fusePage_0026_005fid_005fnobody.reuse(_jspx_th_decorator_005fusePage_005f0);
return;
}
_005fjspx_005ftagPool_005fdecorator_005fusePage_0026_005fid_005fnobody.reuse(_jspx_th_decorator_005fusePage_005f0);
com.opensymphony.module.sitemesh.Page decoratedPage = null;
decoratedPage = (com.opensymphony.module.sitemesh.Page) _jspx_page_context.findAttribute("decoratedPage");
out.write("\r\n\r\n");
String path = request.getContextPath();
// Decorated pages will typically must set a pageID and optionally set a subPageID
// and extraParams. Store these values as request attributes so that the tab and sidebar
// handling tags can get at the data.
request.setAttribute("pageID", decoratedPage.getProperty("meta.pageID"));
request.setAttribute("subPageID", decoratedPage.getProperty("meta.subPageID"));
request.setAttribute("extraParams", decoratedPage.getProperty("meta.extraParams"));
// Message HTML can be passed in:
String message = decoratedPage.getProperty("page.message");
pageContext.setAttribute( "usernameHtmlEscaped", StringUtils.escapeHTMLTags(JID.unescapeNode(webManager.getUser().getUsername())) );
out.write("\r\n\r\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n\r\n");
if (_jspx_meth_fmt_005fsetBundle_005f0(_jspx_page_context))
return;
out.write("\r\n<html>\r\n<head>\r\n <title>");
out.print( AdminConsole.getAppName() );
out.write(' ');
if (_jspx_meth_fmt_005fmessage_005f0(_jspx_page_context))
return;
out.write(':');
out.write(' ');
if (_jspx_meth_decorator_005ftitle_005f0(_jspx_page_context))
return;
out.write("</title>\r\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\r\n <link rel=\"stylesheet\" type=\"text/css\" href=\"");
out.print( path );
out.write("/style/global.css\">\r\n <script language=\"JavaScript\" type=\"text/javascript\" src=\"");
out.print( path );
out.write("/js/prototype.js\"></script>\r\n <script language=\"JavaScript\" type=\"text/javascript\" src=\"");
out.print( path );
out.write("/js/scriptaculous.js\"></script>\r\n <script language=\"JavaScript\" type=\"text/javascript\" src=\"");
out.print( path );
out.write("/js/cookies.js\"></script>\r\n <script language=\"JavaScript\" type=\"text/javascript\">\r\n\r\n </script>\r\n <script type=\"text/javascript\" src=\"");
out.print( path );
out.write("/js/behaviour.js\"></script>\r\n <script type=\"text/javascript\">\r\n // Add a nice little rollover effect to any row in a jive-table object. This will help\r\n // visually link left and right columns.\r\n /*\r\n var myrules = {\r\n '.jive-table TBODY TR' : function(el) {\r\n el.onmouseover = function() {\r\n this.style.backgroundColor = '#ffffee';\r\n }\r\n el.onmouseout = function() {\r\n this.style.backgroundColor = '#ffffff';\r\n }\r\n }\r\n };\r\n Behaviour.register(myrules);\r\n */\r\n </script>\r\n ");
if (_jspx_meth_decorator_005fhead_005f0(_jspx_page_context))
return;
out.write("\r\n</head>\r\n\r\n<body id=\"jive-body\">\r\n\r\n<!-- BEGIN main -->\r\n<div id=\"main\">\r\n\r\n <div id=\"jive-header\">\r\n <div id=\"jive-logo\">\r\n <a href=\"/index.jsp\"><img src=\"/images/login_logo.gif\" alt=\"Openfire\" width=\"179\" height=\"53\" /></a>\r\n </div>\r\n <div id=\"jive-userstatus\">\r\n ");
out.print( AdminConsole.getAppName() );
out.write(' ');
out.print( AdminConsole.getVersionString() );
out.write("<br/>\r\n ");
if (_jspx_meth_fmt_005fmessage_005f1(_jspx_page_context))
return;
out.write(" - <a href=\"");
out.print( path );
out.write("/index.jsp?logout=true\">");
out.print( LocaleUtils.getLocalizedString("global.logout") );
out.write("</a>\r\n </div>\r\n <div id=\"jive-nav\">\r\n <div id=\"jive-nav-left\"></div>\r\n ");
if (_jspx_meth_admin_005ftabs_005f0(_jspx_page_context))
return;
out.write("\r\n <div id=\"jive-nav-right\"></div>\r\n </div>\r\n <div id=\"jive-subnav\">\r\n ");
if (_jspx_meth_admin_005fsubnavbar_005f0(_jspx_page_context))
return;
out.write("\r\n </div>\r\n </div>\r\n\r\n <div id=\"jive-main\">\r\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\">\r\n <tbody>\r\n <tr valign=\"top\">\r\n <td width=\"1%\">\r\n <div id=\"jive-sidebar-container\">\r\n <div id=\"jive-sidebar-box\">\r\n <div id=\"jive-sidebar\">\r\n ");
if (_jspx_meth_admin_005fsidebar_005f0(_jspx_page_context))
return;
out.write("\r\n <br>\r\n <img src=\"");
out.print( path );
out.write("/images/blank.gif\" width=\"150\" height=\"1\" border=\"0\" alt=\"\">\r\n </div>\r\n </div>\r\n </div>\r\n </td>\r\n <td width=\"99%\" id=\"jive-content\">\r\n\r\n\r\n ");
if (message != null) {
out.write("\r\n\r\n ");
out.print( message );
out.write("\r\n\r\n ");
}
out.write("\r\n\r\n <h1>\r\n ");
if (_jspx_meth_decorator_005ftitle_005f1(_jspx_page_context))
return;
out.write("\r\n </h1>\r\n\r\n <div id=\"jive-main-content\">\r\n ");
if (_jspx_meth_decorator_005fbody_005f0(_jspx_page_context))
return;
out.write("\r\n </div>\r\n </td>\r\n </tr>\r\n </tbody>\r\n </table>\r\n </div>\r\n\r\n</div>\r\n<!-- END main -->\r\n\r\n<!-- BEGIN footer -->\r\n\t<div id=\"jive-footer\">\r\n <div class=\"jive-footer-nav\">\r\n ");
if (_jspx_meth_admin_005ftabs_005f1(_jspx_page_context))
return;
out.write("\r\n </div>\r\n <div class=\"jive-footer-copyright\">\r\n Built by <a href=\"http://www.jivesoftware.com\">Jive Software</a> and the <a href=\"http://www.igniterealtime.org\">IgniteRealtime.org</a> community\r\n </div>\r\n </div>\r\n<!-- END footer -->\r\n\r\n</body>\r\n</html>\r\n");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_fmt_005fsetBundle_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// fmt:setBundle
org.apache.taglibs.standard.tag.rt.fmt.SetBundleTag _jspx_th_fmt_005fsetBundle_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.SetBundleTag) _005fjspx_005ftagPool_005ffmt_005fsetBundle_0026_005fbasename_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.SetBundleTag.class);
_jspx_th_fmt_005fsetBundle_005f0.setPageContext(_jspx_page_context);
_jspx_th_fmt_005fsetBundle_005f0.setParent(null);
// /decorators/main.jsp(55,0) name = basename type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_fmt_005fsetBundle_005f0.setBasename("openfire_i18n");
int _jspx_eval_fmt_005fsetBundle_005f0 = _jspx_th_fmt_005fsetBundle_005f0.doStartTag();
if (_jspx_th_fmt_005fsetBundle_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ffmt_005fsetBundle_0026_005fbasename_005fnobody.reuse(_jspx_th_fmt_005fsetBundle_005f0);
return true;
}
_005fjspx_005ftagPool_005ffmt_005fsetBundle_0026_005fbasename_005fnobody.reuse(_jspx_th_fmt_005fsetBundle_005f0);
return false;
}
private boolean _jspx_meth_fmt_005fmessage_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// fmt:message
org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
_jspx_th_fmt_005fmessage_005f0.setPageContext(_jspx_page_context);
_jspx_th_fmt_005fmessage_005f0.setParent(null);
// /decorators/main.jsp(58,44) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_fmt_005fmessage_005f0.setKey("login.title");
int _jspx_eval_fmt_005fmessage_005f0 = _jspx_th_fmt_005fmessage_005f0.doStartTag();
if (_jspx_th_fmt_005fmessage_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0);
return true;
}
_005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0);
return false;
}
private boolean _jspx_meth_decorator_005ftitle_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// decorator:title
com.opensymphony.module.sitemesh.taglib.decorator.TitleTag _jspx_th_decorator_005ftitle_005f0 = (com.opensymphony.module.sitemesh.taglib.decorator.TitleTag) _005fjspx_005ftagPool_005fdecorator_005ftitle_005fnobody.get(com.opensymphony.module.sitemesh.taglib.decorator.TitleTag.class);
_jspx_th_decorator_005ftitle_005f0.setPageContext(_jspx_page_context);
_jspx_th_decorator_005ftitle_005f0.setParent(null);
int _jspx_eval_decorator_005ftitle_005f0 = _jspx_th_decorator_005ftitle_005f0.doStartTag();
if (_jspx_th_decorator_005ftitle_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fdecorator_005ftitle_005fnobody.reuse(_jspx_th_decorator_005ftitle_005f0);
return true;
}
_005fjspx_005ftagPool_005fdecorator_005ftitle_005fnobody.reuse(_jspx_th_decorator_005ftitle_005f0);
return false;
}
private boolean _jspx_meth_decorator_005fhead_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// decorator:head
com.opensymphony.module.sitemesh.taglib.decorator.HeadTag _jspx_th_decorator_005fhead_005f0 = (com.opensymphony.module.sitemesh.taglib.decorator.HeadTag) _005fjspx_005ftagPool_005fdecorator_005fhead_005fnobody.get(com.opensymphony.module.sitemesh.taglib.decorator.HeadTag.class);
_jspx_th_decorator_005fhead_005f0.setPageContext(_jspx_page_context);
_jspx_th_decorator_005fhead_005f0.setParent(null);
int _jspx_eval_decorator_005fhead_005f0 = _jspx_th_decorator_005fhead_005f0.doStartTag();
if (_jspx_th_decorator_005fhead_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fdecorator_005fhead_005fnobody.reuse(_jspx_th_decorator_005fhead_005f0);
return true;
}
_005fjspx_005ftagPool_005fdecorator_005fhead_005fnobody.reuse(_jspx_th_decorator_005fhead_005f0);
return false;
}
private boolean _jspx_meth_fmt_005fmessage_005f1(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// fmt:message
org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f1 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
_jspx_th_fmt_005fmessage_005f1.setPageContext(_jspx_page_context);
_jspx_th_fmt_005fmessage_005f1.setParent(null);
// /decorators/main.jsp(99,12) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_fmt_005fmessage_005f1.setKey("admin.logged_in_as");
int _jspx_eval_fmt_005fmessage_005f1 = _jspx_th_fmt_005fmessage_005f1.doStartTag();
if (_jspx_eval_fmt_005fmessage_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
if (_jspx_eval_fmt_005fmessage_005f1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.pushBody();
_jspx_th_fmt_005fmessage_005f1.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
_jspx_th_fmt_005fmessage_005f1.doInitBody();
}
do {
if (_jspx_meth_fmt_005fparam_005f0(_jspx_th_fmt_005fmessage_005f1, _jspx_page_context))
return true;
int evalDoAfterBody = _jspx_th_fmt_005fmessage_005f1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
if (_jspx_eval_fmt_005fmessage_005f1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.popBody();
}
}
if (_jspx_th_fmt_005fmessage_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.reuse(_jspx_th_fmt_005fmessage_005f1);
return true;
}
_005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey.reuse(_jspx_th_fmt_005fmessage_005f1);
return false;
}
private boolean _jspx_meth_fmt_005fparam_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_fmt_005fmessage_005f1, javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// fmt:param
org.apache.taglibs.standard.tag.rt.fmt.ParamTag _jspx_th_fmt_005fparam_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.ParamTag) _005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.ParamTag.class);
_jspx_th_fmt_005fparam_005f0.setPageContext(_jspx_page_context);
_jspx_th_fmt_005fparam_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_fmt_005fmessage_005f1);
// /decorators/main.jsp(99,50) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_fmt_005fparam_005f0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("<strong>${usernameHtmlEscaped}</strong>", java.lang.Object.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
int _jspx_eval_fmt_005fparam_005f0 = _jspx_th_fmt_005fparam_005f0.doStartTag();
if (_jspx_th_fmt_005fparam_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.reuse(_jspx_th_fmt_005fparam_005f0);
return true;
}
_005fjspx_005ftagPool_005ffmt_005fparam_0026_005fvalue_005fnobody.reuse(_jspx_th_fmt_005fparam_005f0);
return false;
}
private boolean _jspx_meth_admin_005ftabs_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// admin:tabs
org.jivesoftware.admin.TabsTag _jspx_th_admin_005ftabs_005f0 = (org.jivesoftware.admin.TabsTag) _005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fcurrentcss_005fcss.get(org.jivesoftware.admin.TabsTag.class);
_jspx_th_admin_005ftabs_005f0.setPageContext(_jspx_page_context);
_jspx_th_admin_005ftabs_005f0.setParent(null);
// /decorators/main.jsp(103,12) name = css type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005ftabs_005f0.setCss("");
// /decorators/main.jsp(103,12) name = currentcss type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005ftabs_005f0.setCurrentcss("currentlink");
int _jspx_eval_admin_005ftabs_005f0 = _jspx_th_admin_005ftabs_005f0.doStartTag();
if (_jspx_eval_admin_005ftabs_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
if (_jspx_eval_admin_005ftabs_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.pushBody();
_jspx_th_admin_005ftabs_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
_jspx_th_admin_005ftabs_005f0.doInitBody();
}
do {
out.write("\r\n <a href=\"[url]\" title=\"[description]\" onmouseover=\"self.status='[description]';return true;\" onmouseout=\"self.status='';return true;\">[name]</a>\r\n ");
int evalDoAfterBody = _jspx_th_admin_005ftabs_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
if (_jspx_eval_admin_005ftabs_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.popBody();
}
}
if (_jspx_th_admin_005ftabs_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005ftabs_005f0);
return true;
}
_005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005ftabs_005f0);
return false;
}
private boolean _jspx_meth_admin_005fsubnavbar_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// admin:subnavbar
org.jivesoftware.admin.SubnavTag _jspx_th_admin_005fsubnavbar_005f0 = (org.jivesoftware.admin.SubnavTag) _005fjspx_005ftagPool_005fadmin_005fsubnavbar_0026_005fcurrentcss_005fcss.get(org.jivesoftware.admin.SubnavTag.class);
_jspx_th_admin_005fsubnavbar_005f0.setPageContext(_jspx_page_context);
_jspx_th_admin_005fsubnavbar_005f0.setParent(null);
// /decorators/main.jsp(109,12) name = css type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005fsubnavbar_005f0.setCss("");
// /decorators/main.jsp(109,12) name = currentcss type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005fsubnavbar_005f0.setCurrentcss("current");
int _jspx_eval_admin_005fsubnavbar_005f0 = _jspx_th_admin_005fsubnavbar_005f0.doStartTag();
if (_jspx_eval_admin_005fsubnavbar_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
if (_jspx_eval_admin_005fsubnavbar_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.pushBody();
_jspx_th_admin_005fsubnavbar_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
_jspx_th_admin_005fsubnavbar_005f0.doInitBody();
}
do {
out.write("\r\n <a href=\"[url]\" title=\"[description]\"\r\n onmouseover=\"self.status='[description]';return true;\" onmouseout=\"self.status='';return true;\"\r\n >[name]</a>\r\n ");
int evalDoAfterBody = _jspx_th_admin_005fsubnavbar_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
if (_jspx_eval_admin_005fsubnavbar_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.popBody();
}
}
if (_jspx_th_admin_005fsubnavbar_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fadmin_005fsubnavbar_0026_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005fsubnavbar_005f0);
return true;
}
_005fjspx_005ftagPool_005fadmin_005fsubnavbar_0026_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005fsubnavbar_005f0);
return false;
}
private boolean _jspx_meth_admin_005fsidebar_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// admin:sidebar
org.jivesoftware.admin.SidebarTag _jspx_th_admin_005fsidebar_005f0 = (org.jivesoftware.admin.SidebarTag) _005fjspx_005ftagPool_005fadmin_005fsidebar_0026_005fheadercss_005fcurrentcss_005fcss.get(org.jivesoftware.admin.SidebarTag.class);
_jspx_th_admin_005fsidebar_005f0.setPageContext(_jspx_page_context);
_jspx_th_admin_005fsidebar_005f0.setParent(null);
// /decorators/main.jsp(125,28) name = css type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005fsidebar_005f0.setCss("");
// /decorators/main.jsp(125,28) name = currentcss type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005fsidebar_005f0.setCurrentcss("currentlink");
// /decorators/main.jsp(125,28) name = headercss type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005fsidebar_005f0.setHeadercss("category");
int _jspx_eval_admin_005fsidebar_005f0 = _jspx_th_admin_005fsidebar_005f0.doStartTag();
if (_jspx_eval_admin_005fsidebar_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
if (_jspx_eval_admin_005fsidebar_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.pushBody();
_jspx_th_admin_005fsidebar_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
_jspx_th_admin_005fsidebar_005f0.doInitBody();
}
do {
out.write("\r\n <a href=\"[url]\" title=\"[description]\"\r\n onmouseover=\"self.status='[description]';return true;\" onmouseout=\"self.status='';return true;\"\r\n >[name]</a>\r\n ");
if (_jspx_meth_admin_005fsubsidebar_005f0(_jspx_th_admin_005fsidebar_005f0, _jspx_page_context))
return true;
out.write("\r\n ");
int evalDoAfterBody = _jspx_th_admin_005fsidebar_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
if (_jspx_eval_admin_005fsidebar_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.popBody();
}
}
if (_jspx_th_admin_005fsidebar_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fadmin_005fsidebar_0026_005fheadercss_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005fsidebar_005f0);
return true;
}
_005fjspx_005ftagPool_005fadmin_005fsidebar_0026_005fheadercss_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005fsidebar_005f0);
return false;
}
private boolean _jspx_meth_admin_005fsubsidebar_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_admin_005fsidebar_005f0, javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// admin:subsidebar
org.jivesoftware.admin.SubSidebarTag _jspx_th_admin_005fsubsidebar_005f0 = (org.jivesoftware.admin.SubSidebarTag) _005fjspx_005ftagPool_005fadmin_005fsubsidebar_0026_005fcurrentcss_005fcss.get(org.jivesoftware.admin.SubSidebarTag.class);
_jspx_th_admin_005fsubsidebar_005f0.setPageContext(_jspx_page_context);
_jspx_th_admin_005fsubsidebar_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_admin_005fsidebar_005f0);
// /decorators/main.jsp(129,33) name = css type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005fsubsidebar_005f0.setCss("");
// /decorators/main.jsp(129,33) name = currentcss type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005fsubsidebar_005f0.setCurrentcss("currentlink");
int _jspx_eval_admin_005fsubsidebar_005f0 = _jspx_th_admin_005fsubsidebar_005f0.doStartTag();
if (_jspx_eval_admin_005fsubsidebar_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
if (_jspx_eval_admin_005fsubsidebar_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.pushBody();
_jspx_th_admin_005fsubsidebar_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
_jspx_th_admin_005fsubsidebar_005f0.doInitBody();
}
do {
out.write("\r\n <a href=\"[url]\" title=\"[description]\"\r\n onmouseover=\"self.status='[description]';return true;\" onmouseout=\"self.status='';return true;\"\r\n >[name]</a>\r\n ");
int evalDoAfterBody = _jspx_th_admin_005fsubsidebar_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
if (_jspx_eval_admin_005fsubsidebar_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.popBody();
}
}
if (_jspx_th_admin_005fsubsidebar_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fadmin_005fsubsidebar_0026_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005fsubsidebar_005f0);
return true;
}
_005fjspx_005ftagPool_005fadmin_005fsubsidebar_0026_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005fsubsidebar_005f0);
return false;
}
private boolean _jspx_meth_decorator_005ftitle_005f1(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// decorator:title
com.opensymphony.module.sitemesh.taglib.decorator.TitleTag _jspx_th_decorator_005ftitle_005f1 = (com.opensymphony.module.sitemesh.taglib.decorator.TitleTag) _005fjspx_005ftagPool_005fdecorator_005ftitle_0026_005fdefault_005fnobody.get(com.opensymphony.module.sitemesh.taglib.decorator.TitleTag.class);
_jspx_th_decorator_005ftitle_005f1.setPageContext(_jspx_page_context);
_jspx_th_decorator_005ftitle_005f1.setParent(null);
// /decorators/main.jsp(151,20) name = default type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_decorator_005ftitle_005f1.setDefault(" ");
int _jspx_eval_decorator_005ftitle_005f1 = _jspx_th_decorator_005ftitle_005f1.doStartTag();
if (_jspx_th_decorator_005ftitle_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fdecorator_005ftitle_0026_005fdefault_005fnobody.reuse(_jspx_th_decorator_005ftitle_005f1);
return true;
}
_005fjspx_005ftagPool_005fdecorator_005ftitle_0026_005fdefault_005fnobody.reuse(_jspx_th_decorator_005ftitle_005f1);
return false;
}
private boolean _jspx_meth_decorator_005fbody_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// decorator:body
com.opensymphony.module.sitemesh.taglib.decorator.BodyTag _jspx_th_decorator_005fbody_005f0 = (com.opensymphony.module.sitemesh.taglib.decorator.BodyTag) _005fjspx_005ftagPool_005fdecorator_005fbody_005fnobody.get(com.opensymphony.module.sitemesh.taglib.decorator.BodyTag.class);
_jspx_th_decorator_005fbody_005f0.setPageContext(_jspx_page_context);
_jspx_th_decorator_005fbody_005f0.setParent(null);
int _jspx_eval_decorator_005fbody_005f0 = _jspx_th_decorator_005fbody_005f0.doStartTag();
if (_jspx_th_decorator_005fbody_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fdecorator_005fbody_005fnobody.reuse(_jspx_th_decorator_005fbody_005f0);
return true;
}
_005fjspx_005ftagPool_005fdecorator_005fbody_005fnobody.reuse(_jspx_th_decorator_005fbody_005f0);
return false;
}
private boolean _jspx_meth_admin_005ftabs_005f1(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// admin:tabs
org.jivesoftware.admin.TabsTag _jspx_th_admin_005ftabs_005f1 = (org.jivesoftware.admin.TabsTag) _005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fjustlinks_005fcurrentcss_005fcss.get(org.jivesoftware.admin.TabsTag.class);
_jspx_th_admin_005ftabs_005f1.setPageContext(_jspx_page_context);
_jspx_th_admin_005ftabs_005f1.setParent(null);
// /decorators/main.jsp(169,12) name = css type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005ftabs_005f1.setCss("");
// /decorators/main.jsp(169,12) name = currentcss type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005ftabs_005f1.setCurrentcss("currentlink");
// /decorators/main.jsp(169,12) name = justlinks type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_admin_005ftabs_005f1.setJustlinks(new java.lang.Boolean(true));
int _jspx_eval_admin_005ftabs_005f1 = _jspx_th_admin_005ftabs_005f1.doStartTag();
if (_jspx_eval_admin_005ftabs_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
if (_jspx_eval_admin_005ftabs_005f1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.pushBody();
_jspx_th_admin_005ftabs_005f1.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
_jspx_th_admin_005ftabs_005f1.doInitBody();
}
do {
out.write("\r\n <a href=\"[url]\" title=\"[description]\" onmouseover=\"self.status='[description]';return true;\" onmouseout=\"self.status='';return true;\">[name]</a>\r\n ");
int evalDoAfterBody = _jspx_th_admin_005ftabs_005f1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
if (_jspx_eval_admin_005ftabs_005f1 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.popBody();
}
}
if (_jspx_th_admin_005ftabs_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fjustlinks_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005ftabs_005f1);
return true;
}
_005fjspx_005ftagPool_005fadmin_005ftabs_0026_005fjustlinks_005fcurrentcss_005fcss.reuse(_jspx_th_admin_005ftabs_005f1);
return false;
}
}
| |
package distilledview.utils.qvdev.com.distilled;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import java.text.NumberFormat;
import java.util.EnumMap;
import java.util.Locale;
import java.util.Map;
/**
* A view which displays preferences for distilled pages. This allows users
* to change the theme, font size, etc. of distilled pages.
*/
public class DistilledPagePrefsView extends LinearLayout implements SeekBar.OnSeekBarChangeListener {
private enum STYLE {
LIGHT,
DARK,
SEPIA
}
// XML layout for View.
private static final int VIEW_LAYOUT = R.layout.distilled_page_prefs_view;
// RadioGroup for color mode buttons.
private RadioGroup mRadioGroup;
// Text field showing font scale percentage.
private TextView mFontScaleTextView;
// SeekBar for font scale. Has range of [0, 30].
private SeekBar mFontScaleSeekBar;
// Spinner for choosing a font family.
private Spinner mFontFamilySpinner;
private final NumberFormat mPercentageFormatter;
private Map<STYLE, RadioButton> mColorModeButtons;
private DistilledPagePrefs mDistilledPagePrefs;
/**
* Creates a DistilledPagePrefsView.
*
* @param context Context for acquiring resources.
* @param attrs Attributes from the XML layout inflation.
*/
public DistilledPagePrefsView(Context context, AttributeSet attrs) {
super(context, attrs);
mPercentageFormatter = NumberFormat.getPercentInstance(Locale.getDefault());
mColorModeButtons = new EnumMap<>(STYLE.class);
}
public static DistilledPagePrefsView create(Context context) {
return (DistilledPagePrefsView) LayoutInflater.from(context)
.inflate(VIEW_LAYOUT, null);
}
public static void showDialog(Activity context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.Base_Theme_AppCompat_Dialog_Alert);
builder.setView(DistilledPagePrefsView.create(context));
builder.show();
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
mDistilledPagePrefs = new DistilledPagePrefs(PreferenceManager.getDefaultSharedPreferences(getContext()));
mRadioGroup = (RadioGroup) findViewById(R.id.radio_button_group);
mColorModeButtons.put(STYLE.LIGHT, initializeAndGetButton(R.id.light_mode));
mColorModeButtons.put(STYLE.DARK, initializeAndGetButton(R.id.dark_mode));
mColorModeButtons.put(STYLE.SEPIA, initializeAndGetButton(R.id.sepia_mode));
mRadioGroup.check(mDistilledPagePrefs.getBackgroundMode());
mFontScaleSeekBar = (SeekBar) findViewById(R.id.font_size);
mFontScaleTextView = (TextView) findViewById(R.id.font_size_percentage);
mFontFamilySpinner = (Spinner) findViewById(R.id.font_family);
initFontFamilySpinner();
// Setting initial progress on font scale seekbar.
mFontScaleSeekBar.setOnSeekBarChangeListener(this);
setFontScaleProgress(mDistilledPagePrefs.getFontScale());
}
private void initFontFamilySpinner() {
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(),
android.R.layout.simple_spinner_item, getResources().getStringArray(
R.array.distiller_mode_font_family_values)) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
return overrideTypeFace(view, position);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
return overrideTypeFace(view, position);
}
private View overrideTypeFace(View view, int position) {
if (view instanceof TextView) {
TextView textView = (TextView) view;
Typeface typeface = getTypeFaceForPosition(position);
textView.setTypeface(typeface);
}
return view;
}
};
adapter.setDropDownViewResource(R.layout.distilled_page_font_family_spinner);
mFontFamilySpinner.setAdapter(adapter);
mFontFamilySpinner.setSelection(mDistilledPagePrefs.getTypeFace());
mFontFamilySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mFontFamilySpinner.setSelection(position);
mDistilledPagePrefs.setTypeFace(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Nothing to do.
}
});
}
public static Typeface getTypeFaceForPosition(int position) {
switch (position) {
case 1:
return Typeface.SERIF;
case 2:
return Typeface.SANS_SERIF;
default:
return Typeface.MONOSPACE;
}
}
public static int getBackgroundColorFromMode(int mode) {
if (mode == R.id.dark_mode) {
return R.color.dark;
} else if (mode == R.id.sepia_mode) {
return R.color.sepia;
} else {
return R.color.light;
}
}
public static int getTexColorFromMode(int mode) {
if (mode == R.id.dark_mode) {
return R.color.light;
} else if (mode == R.id.sepia_mode) {
return R.color.light;
} else {
return R.color.dark;
}
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mRadioGroup.setOrientation(HORIZONTAL);
for (RadioButton button : mColorModeButtons.values()) {
ViewGroup.LayoutParams layoutParams = button.getLayoutParams();
layoutParams.width = 0;
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// If text is wider than button, change layout so that buttons are stacked on
// top of each other.
for (RadioButton button : mColorModeButtons.values()) {
if (button.getLineCount() > 1) {
mRadioGroup.setOrientation(VERTICAL);
for (RadioButton innerLoopButton : mColorModeButtons.values()) {
ViewGroup.LayoutParams layoutParams = innerLoopButton.getLayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
}
break;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// progress = [0, 30]
// newValue = .50, .55, .60, ..., setFontScaleProgress1.95, 2.00 (supported font scales)
float newValue = (progress / 20f + .5f);
setFontScaleTextView(newValue);
mDistilledPagePrefs.setFontScale(newValue);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
/**
* Initiatializes a Button and selects it if it corresponds to the current
* theme.
*/
private RadioButton initializeAndGetButton(final int mode) {
final RadioButton button = (RadioButton) findViewById(mode);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDistilledPagePrefs.setFontMode(mode);
}
});
return button;
}
/**
* Sets the progress of mFontScaleSeekBar.
*/
private void setFontScaleProgress(float newValue) {
// newValue = .50, .55, .60, ..., 1.95, 2.00 (supported font scales)
// progress = [0, 30]
int progress = (int) ((newValue - .5) * 20);
mFontScaleSeekBar.setProgress(progress);
}
/**
* Sets the text for the font scale text view.
*/
private void setFontScaleTextView(float newValue) {
mFontScaleTextView.setText(mPercentageFormatter.format(newValue));
}
}
| |
package edu.pitt.math.hol_ssreflect.ocaml;
/**
* Describes a Caml type
*/
public abstract class CamlType {
/* Constants for simple types */
public static final CamlType STRING = new StringType();
public static final CamlType BOOL = new BoolType();
public static final CamlType INT = new IntType();
public static final CamlType HOL_TYPE = new HOLTypeType();
public static final CamlType TERM = new TermType();
public static final CamlType THM = new TheoremType();
public static final CamlType GOAL = new GoalType();
public static final CamlType GOAL_STATE = new GoalstateType();
public static final CamlType TACTIC = new TacticType();
/**
* Returns the number of arguments of an object of this type
*/
public int numberOfArguments() {
return 0;
}
/**
* Returns the type of the n-th argument (n is from 0 to numberOfArguments() - 1)
*/
public CamlType getArgType(int n) {
return null;
}
/**
* Returns the return type of a function
* @return
*/
public CamlType getLastType() {
return this;
}
/**
* Returns the command for printing a Caml object of this type
*/
public abstract String getPrintCommand();
/**
* Creates a function type
*/
public static FunctionType mk_function(CamlType argType, CamlType returnType) {
return new FunctionType(argType, returnType);
}
/**
* Function type
*/
public static class FunctionType extends CamlType {
private final CamlType argType;
private final CamlType returnType;
private FunctionType(CamlType argType, CamlType returnType) {
if (argType == null || returnType == null)
throw new RuntimeException("FunctionType: null arguments");
this.argType = argType;
this.returnType = returnType;
}
public CamlType getArgType() {
return argType;
}
public CamlType getReturnType() {
return returnType;
}
@Override
public String getPrintCommand() {
throw new RuntimeException("FuntionType: objects of this type are not allowed");
}
@Override
public int numberOfArguments() {
return 1 + returnType.numberOfArguments();
}
@Override
public CamlType getLastType() {
return returnType.getLastType();
}
@Override
public CamlType getArgType(int n) {
if (n == 0)
return argType;
return returnType.getArgType(n - 1);
}
@Override
public int hashCode() {
return argType.hashCode() + 31 * returnType.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof FunctionType))
return false;
FunctionType obj2 = (FunctionType) obj;
return argType.equals(obj2.argType) && returnType.equals(obj2.returnType);
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("Fun");
str.append('(');
str.append(argType);
str.append(',');
str.append(returnType);
str.append(')');
return str.toString();
}
}
/**
* String
*/
public static class StringType extends CamlType {
private StringType() {
}
@Override
public String getPrintCommand() {
return "raw_string_of_string";
}
@Override
public int hashCode() {
return 47;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof StringType))
return false;
return true;
}
@Override
public String toString() {
return "String";
}
}
/**
* Bool
*/
public static class BoolType extends CamlType {
private BoolType() {
}
@Override
public String getPrintCommand() {
return "raw_string_of_bool";
}
@Override
public int hashCode() {
return 179;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof BoolType))
return false;
return true;
}
@Override
public String toString() {
return "Bool";
}
}
/**
* Int
*/
public static class IntType extends CamlType {
private IntType() {
}
@Override
public String getPrintCommand() {
return "raw_string_of_int";
}
@Override
public int hashCode() {
return 79;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof IntType))
return false;
return true;
}
@Override
public String toString() {
return "Int";
}
}
/**
* Tactic
*/
public static class TacticType extends CamlType {
private TacticType() {
}
@Override
public String getPrintCommand() {
throw new RuntimeException("TacticType: objects of this type are not allowed");
}
@Override
public int hashCode() {
return 13;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof TacticType))
return false;
return true;
}
@Override
public String toString() {
return "Tactic";
}
}
/**
* Goal
*/
public static class GoalType extends CamlType {
private GoalType() {
}
@Override
public String getPrintCommand() {
return "raw_string_of_goal";
}
@Override
public int hashCode() {
return 71;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof GoalType))
return false;
return true;
}
@Override
public String toString() {
return "Goal";
}
}
/**
* Goal state
*/
public static class GoalstateType extends CamlType {
private GoalstateType() {
}
@Override
public String getPrintCommand() {
return "raw_string_of_goalstate";
}
@Override
public int hashCode() {
return 73;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof GoalstateType))
return false;
return true;
}
@Override
public String toString() {
return "Goalstate";
}
}
/**
* HOL type
*/
public static class HOLTypeType extends CamlType {
private HOLTypeType() {
}
@Override
public String getPrintCommand() {
return "raw_string_of_type";
}
@Override
public int hashCode() {
return 23;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof HOLTypeType))
return false;
return true;
}
@Override
public String toString() {
return "HOLType";
}
}
/**
* Term type
*/
public static class TermType extends CamlType {
private TermType() {
}
@Override
public String getPrintCommand() {
return "raw_string_of_term";
}
@Override
public int hashCode() {
return 11;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof TermType))
return false;
return true;
}
@Override
public String toString() {
return "Term";
}
}
/**
* Theorem type
*/
public static class TheoremType extends CamlType {
private TheoremType() {
}
@Override
public String getPrintCommand() {
return "raw_string_of_thm";
}
@Override
public int hashCode() {
return 13;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof TheoremType))
return false;
return true;
}
@Override
public String toString() {
return "Theorem";
}
}
/**
* List type
*/
public static class ListType extends CamlType {
private final CamlType elementType;
public ListType(CamlType elementType) {
if (elementType == null)
throw new RuntimeException("ListType: null argument");
this.elementType = elementType;
}
public CamlType getElementType() {
return elementType;
}
@Override
public String getPrintCommand() {
String type = '"' + elementType.toString() + '"';
String cmd = "(" + elementType.getPrintCommand() + ")";
return "raw_string_of_list " + type + " " + cmd;
}
@Override
public int hashCode() {
return elementType.hashCode() * 17;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ListType))
return false;
ListType obj2 = (ListType) obj;
return elementType.equals(obj2.elementType);
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("List");
str.append('(');
str.append(elementType);
str.append(')');
return str.toString();
}
}
/**
* Pair type
*/
public static class PairType extends CamlType {
private final CamlType a, b;
public PairType(CamlType a, CamlType b) {
if (a == null || b == null)
throw new RuntimeException("PairType: null argument");
this.a = a;
this.b = b;
}
public CamlType getFirstType() {
return a;
}
public CamlType getSecondType() {
return b;
}
@Override
public String getPrintCommand() {
String cmd1 = "(" + a.getPrintCommand() + ")";
String cmd2 = "(" + b.getPrintCommand() + ")";
return "raw_string_of_pair " + cmd1 + " " + cmd2;
}
@Override
public int hashCode() {
return a.hashCode() + b.hashCode() * 31;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof PairType))
return false;
PairType obj2 = (PairType) obj;
return a.equals(obj2.a) && b.equals(obj2.b);
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("Pair");
str.append('(');
str.append(a);
str.append(',');
str.append(b);
str.append(')');
return str.toString();
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved.
*
*/
package com.sleepycat.je.statcap;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.logging.Logger;
import com.sleepycat.je.CustomStats;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.EnvironmentMutableConfig;
import com.sleepycat.je.StatsConfig;
import com.sleepycat.je.config.EnvironmentParams;
import com.sleepycat.je.dbi.DbConfigManager;
import com.sleepycat.je.dbi.EnvConfigObserver;
import com.sleepycat.je.dbi.EnvironmentImpl;
import com.sleepycat.je.utilint.DaemonThread;
import com.sleepycat.je.utilint.LoggerUtils;
import com.sleepycat.je.utilint.Stat;
import com.sleepycat.je.utilint.StatDefinition;
import com.sleepycat.je.utilint.StatGroup;
import com.sleepycat.je.utilint.StringStat;
import com.sleepycat.utilint.StatLogger;
public class StatCapture extends DaemonThread implements EnvConfigObserver {
private EnvironmentImpl env;
private final StatsConfig clearingFastConfig;
private StatLogger stlog = null;
public static final String STATFILENAME = "je.stat";
public static final String STATFILEEXT = "csv";
private static final String CUSTOMGROUPNAME = "Custom";
private static final String DELIMITER = ",";
private static final String DELIMITERANDSPACE = ", ";
private final StringBuffer values = new StringBuffer();
private String currentHeader = null;
private Integer statKey = null;
private final SortedSet<String> statProjection;
/* BEGIN-NO-ANDROID */
private final JvmStats jvmstats = new JvmStats();
/* END-NO-ANDROID */
private final CustomStats customStats;
private String[] customStatHeader = null;
private boolean collectStats;
private final Logger logger;
private StatManager statMgr;
/*
* Exception of last outputStats() call or null if call was successful.
* Used to limit the number of errors logged.
*/
private Exception lastCallException = null;
public StatCapture(EnvironmentImpl environment,
String name,
long waitTime,
CustomStats customStats,
SortedSet<String> statProjection,
StatManager statMgr) {
super(waitTime, name, environment);
logger = LoggerUtils.getLogger(getClass());
environment.addConfigObserver(this);
File statdirf;
env = environment;
this.statMgr = statMgr;
statKey = statMgr.registerStatContext();
clearingFastConfig = new StatsConfig();
clearingFastConfig.setFast(true);
clearingFastConfig.setClear(true);
this.customStats = customStats;
this.statProjection = statProjection;
String statdir = env.getConfigManager().get(
EnvironmentParams.STATS_FILE_DIRECTORY);
collectStats = env.getConfigManager().getBoolean(
EnvironmentParams.STATS_COLLECT);
if (statdir == null || statdir.equals("")) {
statdirf = env.getEnvironmentHome();
} else {
statdirf = new File(statdir);
}
try {
stlog =
new StatLogger(statdirf,
STATFILENAME, STATFILEEXT,
env.getConfigManager().getInt(
EnvironmentParams.STATS_MAX_FILES),
env.getConfigManager().getInt(
EnvironmentParams.STATS_FILE_ROW_COUNT));
} catch (IOException e) {
throw new IllegalStateException(
" Error accessing statistics capture file "+
STATFILENAME + "." + STATFILEEXT +
" IO Exception: " + e.getMessage());
}
/* Add jvm and custom statistics to the projection list. */
/* BEGIN-NO-ANDROID */
jvmstats.addVMStatDefs(statProjection);
/* END-NO-ANDROID */
if (customStats != null) {
String[] customFldNames = customStats.getFieldNames();
customStatHeader = new String[customFldNames.length];
for (int i = 0; i < customFldNames.length; i++) {
customStatHeader[i] = CUSTOMGROUPNAME + ":" + customFldNames[i];
statProjection.add(customStatHeader[i]);
}
}
}
public synchronized void clearEnv() {
if (statKey != null && statMgr != null) {
statMgr.unregisterStatContext(statKey);
statKey = null;
}
statMgr = null;
if (env != null) {
env.removeConfigObserver(this);
}
env = null;
}
/**
* Called whenever the DaemonThread wakes up from a sleep.
*/
@Override
protected void onWakeup()
throws DatabaseException {
if (env.isClosed()) {
return;
}
if (!collectStats || env.isInvalid()) {
return;
}
outputStats();
}
@Override
public void requestShutdown() {
super.requestShutdown();
/*
* Check if env is valid outside of synchronized call to
* outputStats(). It is possible that a call to outputStats
* caused the invalidation and we would deadlock since that
* thread is holding the lock for this object and waiting for
* this thread to shutdown.
*/
if (!collectStats || env.isInvalid()) {
return;
}
outputStats();
}
private synchronized void outputStats() {
if (!collectStats || env.isInvalid()) {
return;
}
try {
SortedMap<String, String> stats = getStats();
if (stats != null) {
if (currentHeader == null) {
values.setLength(0);
values.append("time");
for (Iterator<String> nameit = statProjection.iterator();
nameit.hasNext();) {
String statname = nameit.next();
values.append(DELIMITER + statname);
}
stlog.setHeader(values.toString());
currentHeader = values.toString();
}
values.setLength(0);
values.append(StatUtils.getDate(System.currentTimeMillis()));
for (Iterator<String> nameit = statProjection.iterator();
nameit.hasNext();) {
String statname = nameit.next();
String val = stats.get(statname);
if (val != null) {
values.append(DELIMITER + val);
} else {
values.append(DELIMITERANDSPACE);
}
}
stlog.log(values.toString());
values.setLength(0);
lastCallException = null;
}
}
catch (IOException e) {
if (lastCallException == null) {
LoggerUtils.warning(logger, env,
"Error accessing statistics capture file " +
STATFILENAME + "." + STATFILEEXT +
" IO Exception: " + e.getMessage());
}
lastCallException = e;
}
}
private SortedMap<String, String> getStats() {
String mapName;
Object val;
final Collection<StatGroup> envStats = new ArrayList<StatGroup>(
statMgr.loadStats(clearingFastConfig, statKey).getStatGroups());
if (env.isReplicated()) {
Collection<StatGroup> rsg =
env.getRepStatGroups(clearingFastConfig, statKey);
if (rsg != null) {
envStats.addAll(rsg);
}
}
/* BEGIN-NO-ANDROID */
envStats.add(jvmstats.loadStats(clearingFastConfig));
/* END-NO-ANDROID */
SortedMap<String, String> statsMap = new TreeMap<String, String>();
for (StatGroup sg : envStats) {
for (Entry<StatDefinition, Stat<?>> e :
sg.getStats().entrySet()) {
mapName = (sg.getName() + ":" +
e.getKey().getName()).intern();
val = e.getValue().get();
/* get stats back as strings. */
if (val instanceof Number) {
statsMap.put(mapName,
Long.toString(((Number) val).longValue()));
} else if (e.getValue() instanceof StringStat) {
if (val != null){
statsMap.put(mapName, (String)val);
} else {
statsMap.put(mapName, " ");
}
}
}
}
if (customStats != null) {
String vals[] = customStats.getFieldValues();
for (int i = 0; i < vals.length; i++) {
statsMap.put(customStatHeader[i], vals[i]);
}
}
return statsMap;
}
public void envConfigUpdate(DbConfigManager configMgr,
EnvironmentMutableConfig newConfig)
throws DatabaseException {
stlog.setFileCount(configMgr.getInt(
EnvironmentParams.STATS_MAX_FILES));
stlog.setRowCount(configMgr.getInt(
EnvironmentParams.STATS_FILE_ROW_COUNT));
setWaitTime(configMgr.getDuration(
EnvironmentParams.STATS_COLLECT_INTERVAL));
collectStats =
configMgr.getBoolean(EnvironmentParams.STATS_COLLECT);
}
}
| |
/**
* Copyright 2010 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.util;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.migration.HRegionInfo090x;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.Writable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Utility class with methods for manipulating Writable objects
*/
public class Writables {
/**
* @param w writable
* @return The bytes of <code>w</code> gotten by running its
* {@link Writable#write(java.io.DataOutput)} method.
* @throws IOException e
* @see #getWritable(byte[], Writable)
*/
public static byte [] getBytes(final Writable w) throws IOException {
if (w == null) {
throw new IllegalArgumentException("Writable cannot be null");
}
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteStream);
try {
w.write(out);
out.close();
out = null;
return byteStream.toByteArray();
} finally {
if (out != null) {
out.close();
}
}
}
/**
* Put a bunch of Writables as bytes all into the one byte array.
* @param ws writable
* @return The bytes of <code>w</code> gotten by running its
* {@link Writable#write(java.io.DataOutput)} method.
* @throws IOException e
* @see #getHRegionInfos(byte[], int, int)
*/
public static byte [] getBytes(final Writable... ws) throws IOException {
List<byte []> bytes = new ArrayList<byte []>();
int size = 0;
for (Writable w: ws) {
byte [] b = getBytes(w);
size += b.length;
bytes.add(b);
}
byte [] result = new byte[size];
int offset = 0;
for (byte [] b: bytes) {
System.arraycopy(b, 0, result, offset, b.length);
offset += b.length;
}
return result;
}
/**
* Set bytes into the passed Writable by calling its
* {@link Writable#readFields(java.io.DataInput)}.
* @param bytes serialized bytes
* @param w An empty Writable (usually made by calling the null-arg
* constructor).
* @return The passed Writable after its readFields has been called fed
* by the passed <code>bytes</code> array or IllegalArgumentException
* if passed null or an empty <code>bytes</code> array.
* @throws IOException e
* @throws IllegalArgumentException
*/
public static Writable getWritable(final byte [] bytes, final Writable w)
throws IOException {
return getWritable(bytes, 0, bytes.length, w);
}
/**
* Set bytes into the passed Writable by calling its
* {@link Writable#readFields(java.io.DataInput)}.
* @param bytes serialized bytes
* @param offset offset into array
* @param length length of data
* @param w An empty Writable (usually made by calling the null-arg
* constructor).
* @return The passed Writable after its readFields has been called fed
* by the passed <code>bytes</code> array or IllegalArgumentException
* if passed null or an empty <code>bytes</code> array.
* @throws IOException e
* @throws IllegalArgumentException
*/
public static Writable getWritable(final byte [] bytes, final int offset,
final int length, final Writable w)
throws IOException {
if (bytes == null || length <=0) {
throw new IllegalArgumentException("Can't build a writable with empty " +
"bytes array");
}
if (w == null) {
throw new IllegalArgumentException("Writable cannot be null");
}
DataInputBuffer in = new DataInputBuffer();
try {
in.reset(bytes, offset, length);
w.readFields(in);
return w;
} finally {
in.close();
}
}
/**
* @param bytes serialized bytes
* @return A HRegionInfo instance built out of passed <code>bytes</code>.
* @throws IOException e
*/
public static HRegionInfo getHRegionInfo(final byte [] bytes)
throws IOException {
return (HRegionInfo)getWritable(bytes, new HRegionInfo());
}
/**
* @param bytes serialized bytes
* @return All the hregioninfos that are in the byte array. Keeps reading
* till we hit the end.
* @throws IOException e
*/
public static List<HRegionInfo> getHRegionInfos(final byte [] bytes,
final int offset, final int length)
throws IOException {
if (bytes == null) {
throw new IllegalArgumentException("Can't build a writable with empty " +
"bytes array");
}
DataInputBuffer in = new DataInputBuffer();
List<HRegionInfo> hris = new ArrayList<HRegionInfo>();
try {
in.reset(bytes, offset, length);
while (in.available() > 0) {
HRegionInfo hri = new HRegionInfo();
hri.readFields(in);
hris.add(hri);
}
} finally {
in.close();
}
return hris;
}
/**
* @param bytes serialized bytes
* @return A HRegionInfo instance built out of passed <code>bytes</code>
* or <code>null</code> if passed bytes are null or an empty array.
* @throws IOException e
*/
public static HRegionInfo getHRegionInfoOrNull(final byte [] bytes)
throws IOException {
return (bytes == null || bytes.length <= 0)?
null : getHRegionInfo(bytes);
}
/**
* Copy one Writable to another. Copies bytes using data streams.
* @param src Source Writable
* @param tgt Target Writable
* @return The target Writable.
* @throws IOException e
*/
public static Writable copyWritable(final Writable src, final Writable tgt)
throws IOException {
return copyWritable(getBytes(src), tgt);
}
/**
* Copy one Writable to another. Copies bytes using data streams.
* @param bytes Source Writable
* @param tgt Target Writable
* @return The target Writable.
* @throws IOException e
*/
public static Writable copyWritable(final byte [] bytes, final Writable tgt)
throws IOException {
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
try {
tgt.readFields(dis);
} finally {
dis.close();
}
return tgt;
}
/**
* Get HREgionInfoForMigration serialized from bytes.
* @param bytes serialized bytes
* @return HRegionInfoForMigration
* @throws IOException
*/
public static HRegionInfo090x getHRegionInfoForMigration(final byte [] bytes)
throws IOException {
return (HRegionInfo090x)getWritable(bytes, new HRegionInfo090x());
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.j2objc.ast;
import com.google.devtools.j2objc.util.ErrorUtil;
/**
* Base visitor class for the J2ObjC tree.
*/
public class TreeVisitor {
/**
* Executes this visitor on a specified node. This entry point should
* be used instead of visit(), so exception can be caught and reported.
*
* @param node the top-level node to visit.
*/
public void run(TreeNode node) {
node.accept(this);
// System.out.println("After running " + this.getClass().getSimpleName());
// System.out.println(node.toString());
}
public boolean preVisit(TreeNode node) {
return true;
}
public void postVisit(TreeNode node) {}
public boolean visit(AnnotationTypeDeclaration node) {
return true;
}
public void endVisit(AnnotationTypeDeclaration node) {}
public boolean visit(AnnotationTypeMemberDeclaration node) {
return true;
}
public void endVisit(AnnotationTypeMemberDeclaration node) {}
public boolean visit(AnonymousClassDeclaration node) {
return true;
}
public void endVisit(AnonymousClassDeclaration node) {
// System.out.println(node.getTypeBinding());
// System.out.println(node.getTypeBinding().getName());
// System.out.println(node.getTypeBinding().getPackage());
}
public boolean visit(ArrayAccess node) {
return true;
}
public void endVisit(ArrayAccess node) {}
public boolean visit(ArrayCreation node) {
return true;
}
public void endVisit(ArrayCreation node) {}
public boolean visit(ArrayInitializer node) {
return true;
}
public void endVisit(ArrayInitializer node) {}
public boolean visit(ArrayType node) {
return true;
}
public void endVisit(ArrayType node) {}
public boolean visit(AssertStatement node) {
return true;
}
public void endVisit(AssertStatement node) {}
public boolean visit(Assignment node) {
return true;
}
public void endVisit(Assignment node) {}
public boolean visit(Block node) {
return true;
}
public void endVisit(Block node) {}
public boolean visit(BlockComment node) {
return true;
}
public void endVisit(BlockComment node) {}
public boolean visit(BooleanLiteral node) {
return true;
}
public void endVisit(BooleanLiteral node) {}
public boolean visit(BreakStatement node) {
return true;
}
public void endVisit(BreakStatement node) {}
public boolean visit(CStringLiteral node) {
return true;
}
public void endVisit(CStringLiteral node) {}
public boolean visit(CastExpression node) {
return true;
}
public void endVisit(CastExpression node) {}
public boolean visit(CatchClause node) {
return true;
}
public void endVisit(CatchClause node) {}
public boolean visit(CharacterLiteral node) {
return true;
}
public void endVisit(CharacterLiteral node) {}
public boolean visit(ClassInstanceCreation node) {
return true;
}
public void endVisit(ClassInstanceCreation node) {}
public boolean visit(CompilationUnit node) {
return true;
}
public void endVisit(CompilationUnit node) {}
public boolean visit(ConditionalExpression node) {
return true;
}
public void endVisit(ConditionalExpression node) {}
public boolean visit(ConstructorInvocation node) {
return true;
}
public void endVisit(ConstructorInvocation node) {}
public boolean visit(ContinueStatement node) {
return true;
}
public void endVisit(ContinueStatement node) {}
public boolean visit(DoStatement node) {
return true;
}
public void endVisit(DoStatement node) {}
public boolean visit(EmptyStatement node) {
return true;
}
public void endVisit(EmptyStatement node) {}
public boolean visit(EnhancedForStatement node) {
return true;
}
public void endVisit(EnhancedForStatement node) {}
public boolean visit(EnumConstantDeclaration node) {
return true;
}
public void endVisit(EnumConstantDeclaration node) {}
public boolean visit(EnumDeclaration node) {
return true;
}
public void endVisit(EnumDeclaration node) {}
public boolean visit(ExpressionStatement node) {
return true;
}
public void endVisit(ExpressionStatement node) {}
public boolean visit(FieldAccess node) {
return true;
}
public void endVisit(FieldAccess node) {}
public boolean visit(FieldDeclaration node) {
return true;
}
public void endVisit(FieldDeclaration node) {}
public boolean visit(ForStatement node) {
return true;
}
public void endVisit(ForStatement node) {}
public boolean visit(FunctionDeclaration node) {
return true;
}
public void endVisit(FunctionDeclaration node) {}
public boolean visit(FunctionInvocation node) {
return true;
}
public void endVisit(FunctionInvocation node) {}
public boolean visit(IfStatement node) {
return true;
}
public void endVisit(IfStatement node) {}
public boolean visit(InfixExpression node) {
return true;
}
public void endVisit(InfixExpression node) {}
public boolean visit(Initializer node) {
return true;
}
public void endVisit(Initializer node) {}
public boolean visit(InstanceofExpression node) {
return true;
}
public void endVisit(InstanceofExpression node) {}
public boolean visit(Javadoc node) {
// By default don't visit javadoc nodes because they aren't code.
// This is consistent with JDT's base visitor class.
return false;
}
public void endVisit(Javadoc node) {}
public boolean visit(LabeledStatement node) {
return true;
}
public void endVisit(LabeledStatement node) {}
public boolean visit(LineComment node) {
return true;
}
public void endVisit(LineComment node) {}
public boolean visit(MarkerAnnotation node) {
return true;
}
public void endVisit(MarkerAnnotation node) {}
public boolean visit(MemberValuePair node) {
return true;
}
public void endVisit(MemberValuePair node) {}
public boolean visit(MethodDeclaration node) {
return true;
}
public void endVisit(MethodDeclaration node) {}
public boolean visit(MethodInvocation node) {
return true;
}
public void endVisit(MethodInvocation node) {}
public boolean visit(NativeDeclaration node) {
return true;
}
public void endVisit(NativeDeclaration node) {}
public boolean visit(NativeExpression node) {
return true;
}
public void endVisit(NativeExpression node) {}
public boolean visit(NativeStatement node) {
return true;
}
public void endVisit(NativeStatement node) {}
public boolean visit(NormalAnnotation node) {
return true;
}
public void endVisit(NormalAnnotation node) {}
public boolean visit(NullLiteral node) {
return true;
}
public void endVisit(NullLiteral node) {}
public boolean visit(NumberLiteral node) {
return true;
}
public void endVisit(NumberLiteral node) {}
public boolean visit(PackageDeclaration node) {
return true;
}
public void endVisit(PackageDeclaration node) {}
public boolean visit(ParameterizedType node) {
return true;
}
public void endVisit(ParameterizedType node) {}
public boolean visit(ParenthesizedExpression node) {
return true;
}
public void endVisit(ParenthesizedExpression node) {}
public boolean visit(PostfixExpression node) {
return true;
}
public void endVisit(PostfixExpression node) {}
public boolean visit(PrefixExpression node) {
return true;
}
public void endVisit(PrefixExpression node) {}
public boolean visit(PrimitiveType node) {
return true;
}
public void endVisit(PrimitiveType node) {}
public boolean visit(QualifiedName node) {
return true;
}
public void endVisit(QualifiedName node) {}
public boolean visit(QualifiedType node) {
return true;
}
public void endVisit(QualifiedType node) {}
public boolean visit(ReturnStatement node) {
return true;
}
public void endVisit(ReturnStatement node) {}
public boolean visit(SimpleName node) {
return true;
}
public void endVisit(SimpleName node) {}
public boolean visit(SimpleType node) {
return true;
}
public void endVisit(SimpleType node) {}
public boolean visit(SingleMemberAnnotation node) {
return true;
}
public void endVisit(SingleMemberAnnotation node) {}
public boolean visit(SingleVariableDeclaration node) {
return true;
}
public void endVisit(SingleVariableDeclaration node) {}
public boolean visit(StringLiteral node) {
return true;
}
public void endVisit(StringLiteral node) {}
public boolean visit(SuperConstructorInvocation node) {
return true;
}
public void endVisit(SuperConstructorInvocation node) {}
public boolean visit(SuperMethodInvocation node) {
return true;
}
public void endVisit(SuperMethodInvocation node) {}
public boolean visit(SuperFieldAccess node) {
return true;
}
public void endVisit(SuperFieldAccess node) {}
public boolean visit(SwitchCase node) {
return true;
}
public void endVisit(SwitchCase node) {}
public boolean visit(SwitchStatement node) {
return true;
}
public void endVisit(SwitchStatement node) {}
public boolean visit(SynchronizedStatement node) {
return true;
}
public void endVisit(SynchronizedStatement node) {}
public boolean visit(TagElement node) {
return true;
}
public void endVisit(TagElement node) {}
public boolean visit(TextElement node) {
return true;
}
public void endVisit(TextElement node) {}
public boolean visit(ThisExpression node) {
return true;
}
public void endVisit(ThisExpression node) {}
public boolean visit(ThrowStatement node) {
return true;
}
public void endVisit(ThrowStatement node) {}
public boolean visit(TryStatement node) {
return true;
}
public void endVisit(TryStatement node) {}
public boolean visit(TypeDeclaration node) {
return true;
}
public void endVisit(TypeDeclaration node) {}
public boolean visit(TypeDeclarationStatement node) {
return true;
}
public void endVisit(TypeDeclarationStatement node) {}
public boolean visit(TypeLiteral node) {
return true;
}
public void endVisit(TypeLiteral node) {}
public boolean visit(UnionType node) {
return true;
}
public void endVisit(UnionType node) {}
public boolean visit(VariableDeclarationExpression node) {
return true;
}
public void endVisit(VariableDeclarationExpression node) {}
public boolean visit(VariableDeclarationFragment node) {
return true;
}
public void endVisit(VariableDeclarationFragment node) {}
public boolean visit(VariableDeclarationStatement node) {
return true;
}
public void endVisit(VariableDeclarationStatement node) {}
public boolean visit(WhileStatement node) {
return true;
}
public void endVisit(WhileStatement node) {}
}
| |
/*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import org.h2.command.dml.Query;
import org.h2.engine.Session;
import org.h2.expression.Comparison;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.expression.ExpressionVisitor;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.util.StatementBuilder;
import org.h2.value.CompareMode;
import org.h2.value.Value;
/**
* A index condition object is made for each condition that can potentially use
* an index. This class does not extend expression, but in general there is one
* expression that maps to each index condition.
*
* @author Thomas Mueller
* @author Noel Grandin
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/
public class IndexCondition {
/**
* A bit of a search mask meaning 'equal'.
*/
public static final int EQUALITY = 1;
/**
* A bit of a search mask meaning 'larger or equal'.
*/
public static final int START = 2;
/**
* A bit of a search mask meaning 'smaller or equal'.
*/
public static final int END = 4;
/**
* A search mask meaning 'between'.
*/
public static final int RANGE = START | END;
/**
* A bit of a search mask meaning 'the condition is always false'.
*/
public static final int ALWAYS_FALSE = 8;
/**
* A bit of a search mask meaning 'spatial intersection'.
*/
public static final int SPATIAL_INTERSECTS = 16;
private final Column column;
/**
* see constants in {@link Comparison}
*/
private final int compareType;
private final Expression expression;
private List<Expression> expressionList;
private Query expressionQuery;
/**
* @param compareType the comparison type, see constants in
* {@link Comparison}
*/
private IndexCondition(int compareType, ExpressionColumn column,
Expression expression) {
this.compareType = compareType;
this.column = column == null ? null : column.getColumn();
this.expression = expression;
}
/**
* Create an index condition with the given parameters.
*
* @param compareType the comparison type, see constants in
* {@link Comparison}
* @param column the column
* @param expression the expression
* @return the index condition
*/
public static IndexCondition get(int compareType, ExpressionColumn column,
Expression expression) {
return new IndexCondition(compareType, column, expression);
}
/**
* Create an index condition with the compare type IN_LIST and with the
* given parameters.
*
* @param column the column
* @param list the expression list
* @return the index condition
*/
public static IndexCondition getInList(ExpressionColumn column,
List<Expression> list) {
IndexCondition cond = new IndexCondition(Comparison.IN_LIST, column,
null);
cond.expressionList = list;
return cond;
}
/**
* Create an index condition with the compare type IN_QUERY and with the
* given parameters.
*
* @param column the column
* @param query the select statement
* @return the index condition
*/
public static IndexCondition getInQuery(ExpressionColumn column, Query query) {
IndexCondition cond = new IndexCondition(Comparison.IN_QUERY, column,
null);
cond.expressionQuery = query;
return cond;
}
/**
* Get the current value of the expression.
*
* @param session the session
* @return the value
*/
public Value getCurrentValue(Session session) {
return expression.getValue(session);
}
/**
* Get the current value list of the expression. The value list is of the
* same type as the column, distinct, and sorted.
*
* @param session the session
* @return the value list
*/
public Value[] getCurrentValueList(Session session) {
HashSet<Value> valueSet = new HashSet<Value>();
for (Expression e : expressionList) {
Value v = e.getValue(session);
v = column.convert(v);
valueSet.add(v);
}
Value[] array = new Value[valueSet.size()];
valueSet.toArray(array);
final CompareMode mode = session.getDatabase().getCompareMode();
Arrays.sort(array, new Comparator<Value>() {
@Override
public int compare(Value o1, Value o2) {
return o1.compareTo(o2, mode);
}
});
return array;
}
/**
* Get the current result of the expression. The rows may not be of the same
* type, therefore the rows may not be unique.
*
* @return the result
*/
public ResultInterface getCurrentResult() {
return expressionQuery.query(0);
}
/**
* Get the SQL snippet of this comparison.
*
* @return the SQL snippet
*/
public String getSQL() {
if (compareType == Comparison.FALSE) {
return "FALSE";
}
StatementBuilder buff = new StatementBuilder();
buff.append(column.getSQL());
switch (compareType) {
case Comparison.EQUAL:
buff.append(" = ");
break;
case Comparison.EQUAL_NULL_SAFE:
buff.append(" IS ");
break;
case Comparison.BIGGER_EQUAL:
buff.append(" >= ");
break;
case Comparison.BIGGER:
buff.append(" > ");
break;
case Comparison.SMALLER_EQUAL:
buff.append(" <= ");
break;
case Comparison.SMALLER:
buff.append(" < ");
break;
case Comparison.IN_LIST:
buff.append(" IN(");
for (Expression e : expressionList) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
buff.append(')');
break;
case Comparison.IN_QUERY:
buff.append(" IN(");
buff.append(expressionQuery.getPlanSQL());
buff.append(')');
break;
case Comparison.SPATIAL_INTERSECTS:
buff.append(" && ");
break;
default:
DbException.throwInternalError("type=" + compareType);
}
if (expression != null) {
buff.append(expression.getSQL());
}
return buff.toString();
}
/**
* Get the comparison bit mask.
*
* @param indexConditions all index conditions
* @return the mask
*/
public int getMask(ArrayList<IndexCondition> indexConditions) {
switch (compareType) {
case Comparison.FALSE:
return ALWAYS_FALSE;
case Comparison.EQUAL:
case Comparison.EQUAL_NULL_SAFE:
return EQUALITY;
case Comparison.IN_LIST:
case Comparison.IN_QUERY:
if (indexConditions.size() > 1) {
if (!Table.TABLE.equals(column.getTable().getTableType())) {
// if combined with other conditions,
// IN(..) can only be used for regular tables
// test case:
// create table test(a int, b int, primary key(id, name));
// create unique index c on test(b, a);
// insert into test values(1, 10), (2, 20);
// select * from (select * from test)
// where a=1 and b in(10, 20);
return 0;
}
}
return EQUALITY;
case Comparison.BIGGER_EQUAL:
case Comparison.BIGGER:
return START;
case Comparison.SMALLER_EQUAL:
case Comparison.SMALLER:
return END;
case Comparison.SPATIAL_INTERSECTS:
return SPATIAL_INTERSECTS;
default:
throw DbException.throwInternalError("type=" + compareType);
}
}
/**
* Check if the result is always false.
*
* @return true if the result will always be false
*/
public boolean isAlwaysFalse() {
return compareType == Comparison.FALSE;
}
/**
* Check if this index condition is of the type column larger or equal to
* value.
*
* @return true if this is a start condition
*/
public boolean isStart() {
switch (compareType) {
case Comparison.EQUAL:
case Comparison.EQUAL_NULL_SAFE:
case Comparison.BIGGER_EQUAL:
case Comparison.BIGGER:
return true;
default:
return false;
}
}
/**
* Check if this index condition is of the type column smaller or equal to
* value.
*
* @return true if this is a end condition
*/
public boolean isEnd() {
switch (compareType) {
case Comparison.EQUAL:
case Comparison.EQUAL_NULL_SAFE:
case Comparison.SMALLER_EQUAL:
case Comparison.SMALLER:
return true;
default:
return false;
}
}
/**
* Check if this index condition is of the type spatial column intersects
* value.
*
* @return true if this is a spatial intersects condition
*/
public boolean isSpatialIntersects() {
switch (compareType) {
case Comparison.SPATIAL_INTERSECTS:
return true;
default:
return false;
}
}
/**
* Check if this index condition is of the type equality.
*
* @param constantExpression if the inner node is a constant expression
* @return true if this is a equality condition
*/
public boolean isEquality(boolean constantExpression) {
switch (compareType) {
case Comparison.EQUAL:
case Comparison.EQUAL_NULL_SAFE:
return !constantExpression || expression.isConstant();
default:
return false;
}
}
public int getCompareType() {
return compareType;
}
/**
* Get the referenced column.
*
* @return the column
*/
public Column getColumn() {
return column;
}
/**
* Check if the expression can be evaluated.
*
* @return true if it can be evaluated
*/
public boolean isEvaluatable() {
if (expression != null) {
return expression
.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR);
}
if (expressionList != null) {
for (Expression e : expressionList) {
if (!e.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR)) {
return false;
}
}
return true;
}
return expressionQuery
.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR);
}
@Override
public String toString() {
return "column=" + column +
", compareType=" + compareTypeToString(compareType) +
", expression=" + expression +
", expressionList=" + expressionList.toString() +
", expressionQuery=" + expressionQuery;
}
private static String compareTypeToString(int i) {
StatementBuilder s = new StatementBuilder();
if ((i & EQUALITY) == EQUALITY) {
s.appendExceptFirst("&");
s.append("EQUALITY");
}
if ((i & START) == START) {
s.appendExceptFirst("&");
s.append("START");
}
if ((i & END) == END) {
s.appendExceptFirst("&");
s.append("END");
}
if ((i & ALWAYS_FALSE) == ALWAYS_FALSE) {
s.appendExceptFirst("&");
s.append("ALWAYS_FALSE");
}
if ((i & SPATIAL_INTERSECTS) == SPATIAL_INTERSECTS) {
s.appendExceptFirst("&");
s.append("SPATIAL_INTERSECTS");
}
return s.toString();
}
}
| |
package org.jvnet.jaxb2_commons.lang;
import static org.jvnet.jaxb2_commons.locator.util.LocatorUtils.item;
import static org.jvnet.jaxb2_commons.locator.util.LocatorUtils.property;
import java.util.Collection;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
public class DefaultToStringStrategy implements ToStringStrategy2,
ToStringStrategy {
/**
* Whether to use the field names, the default is <code>true</code>.
*/
private boolean useFieldNames = true;
/**
* Whether to mark default field values, the default is <code>true</code>.
*/
private boolean useDefaultFieldValueMarkers = true;
/**
* Whether to use the class name, the default is <code>true</code>.
*/
private boolean useClassName = true;
/**
* Whether to use short class names, the default is <code>false</code>.
*/
private boolean useShortClassName = false;
/**
* Whether to use the identity hash code, the default is <code>true</code>.
*/
private boolean useIdentityHashCode = true;
/**
* The content start <code>'['</code>.
*/
private String contentStart = "[";
/**
* The content end <code>']'</code>.
*/
private String contentEnd = "]";
/**
* The field name value separator <code>'='</code>.
*/
private String fieldNameValueSeparator = "=";
/**
* Marker for the default field values (vs. explicitly set).
*/
private String defaultFieldValueMarker = "(default)";
/**
* Whether the field separator should be added before any other fields.
*/
private boolean fieldSeparatorAtStart = false;
/**
* Whether the field separator should be added after any other fields.
*/
private boolean fieldSeparatorAtEnd = false;
/**
* The field separator <code>','</code>.
*/
private String fieldSeparator = ", ";
/**
* The array start <code>'{'</code>.
*/
private String arrayStart = "{";
/**
* The array separator <code>','</code>.
*/
private String arraySeparator = ",";
/**
* The array end <code>'}'</code>.
*/
private String arrayEnd = "}";
/**
* The value to use when fullDetail is <code>null</code>, the default value
* is <code>true</code>.
*/
private boolean fullDetail = true;
/**
* The <code>null</code> text <code>'<null>'</code>.
*/
private String nullText = "<null>";
/**
* The summary size text start <code>'<size'</code>.
*/
private String sizeStartText = "<size=";
/**
* The summary size text start <code>'>'</code>.
*/
private String sizeEndText = ">";
public boolean isFullDetail() {
return fullDetail;
}
public boolean isUseIdentityHashCode() {
return useIdentityHashCode;
}
public boolean isUseDefaultFieldValueMarkers() {
return useDefaultFieldValueMarkers;
}
@SuppressWarnings("unchecked")
protected String getShortClassName(Class cls) {
return ClassUtils.getShortClassName(cls);
}
/**
* <p>
* Append to the <code>toString</code> the class name.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
* @param object
* the <code>Object</code> whose name to output
*/
protected void appendClassName(StringBuilder buffer, Object object) {
if (useClassName && object != null) {
if (useShortClassName) {
buffer.append(getShortClassName(object.getClass()));
} else {
buffer.append(object.getClass().getName());
}
}
}
/**
* <p>
* Append the {@link System#identityHashCode(java.lang.Object)}.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
* @param object
* the <code>Object</code> whose id to output
*/
protected void appendIdentityHashCode(StringBuilder buffer, Object object) {
if (this.isUseIdentityHashCode() && object != null) {
buffer.append('@');
buffer.append(Integer.toHexString(System.identityHashCode(object)));
}
}
/**
* <p>
* Append to the <code>toString</code> the content start.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
*/
protected void appendContentStart(StringBuilder buffer) {
buffer.append(contentStart);
}
/**
* <p>
* Append to the <code>toString</code> the content end.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
*/
protected void appendContentEnd(StringBuilder buffer) {
buffer.append(contentEnd);
}
protected void appendArrayStart(StringBuilder buffer) {
buffer.append(arrayStart);
}
protected void appendArrayEnd(StringBuilder buffer) {
buffer.append(arrayEnd);
}
protected void appendArraySeparator(StringBuilder buffer) {
buffer.append(arraySeparator);
}
/**
* <p>
* Append to the <code>toString</code> an indicator for <code>null</code>.
* </p>
*
* <p>
* The default indicator is <code>'<null>'</code>.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
*/
protected void appendNullText(StringBuilder buffer) {
buffer.append(nullText);
}
/**
* <p>
* Append to the <code>toString</code> the field start.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
* @param propertyName
* the field name
*/
protected void appendFieldStart(ObjectLocator parentLocator, Object parent,
String fieldName, StringBuilder buffer) {
if (useFieldNames && fieldName != null) {
buffer.append(fieldName);
buffer.append(fieldNameValueSeparator);
}
}
/**
* <p>
* Append to the <code>toString</code> the field start.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
* @param propertyName
* the field name
*/
protected void appendFieldStart(ObjectLocator parentLocator, Object parent,
String fieldName, StringBuilder buffer, boolean valueSet) {
if (useFieldNames && fieldName != null) {
buffer.append(fieldName);
buffer.append(fieldNameValueSeparator);
}
}
/**
* <p>
* Append to the <code>toString<code> the field end.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
* @param propertyName
* the field name, typically not used as already appended
*/
protected void appendFieldEnd(ObjectLocator parentLocator, Object parent,
String fieldName, StringBuilder buffer) {
appendFieldSeparator(buffer);
}
/**
* <p>
* Append to the <code>toString<code> the field end.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
* @param propertyName
* the field name, typically not used as already appended
*/
protected void appendFieldEnd(ObjectLocator parentLocator, Object parent,
String fieldName, StringBuilder buffer, boolean valueSet) {
if (!valueSet) {
if (isUseDefaultFieldValueMarkers()) {
appendDefaultFieldValueMarker(buffer);
}
}
appendFieldSeparator(buffer);
}
/**
* <p>
* Append to the <code>toString</code> the field separator.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
*/
protected void appendFieldSeparator(StringBuilder buffer) {
buffer.append(fieldSeparator);
}
protected void appendDefaultFieldValueMarker(StringBuilder buffer) {
buffer.append(defaultFieldValueMarker);
}
/**
* <p>
* Append to the <code>toString</code> a size summary.
* </p>
*
* <p>
* The size summary is used to summarize the contents of
* <code>Collections</code>, <code>Maps</code> and arrays.
* </p>
*
* <p>
* The output consists of a prefix, the passed in size and a suffix.
* </p>
*
* <p>
* The default format is <code>'<size=n>'<code>.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
* @param propertyName
* the field name, typically not used as already appended
* @param size
* the size to append
*/
protected void appendSummarySize(ObjectLocator locator,
StringBuilder buffer, int size) {
buffer.append(sizeStartText);
buffer.append(size);
buffer.append(sizeEndText);
}
public StringBuilder appendStart(ObjectLocator parentLocator,
Object object, StringBuilder buffer) {
if (object != null) {
appendClassName(buffer, object);
appendIdentityHashCode(buffer, object);
appendContentStart(buffer);
if (fieldSeparatorAtStart) {
appendFieldSeparator(buffer);
}
}
return buffer;
}
public StringBuilder appendEnd(ObjectLocator parentLocator, Object parent,
StringBuilder buffer) {
if (this.fieldSeparatorAtEnd == false) {
removeLastFieldSeparator(buffer);
}
appendContentEnd(buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, Object value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, boolean value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, byte value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, char value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, double value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, float value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, long value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, int value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, short value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer,
Object[] value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
@SuppressWarnings("unchecked")
public StringBuilder append(ObjectLocator parentLocator, Object parent,
String fieldName, StringBuilder buffer, Collection value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer,
boolean[] value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, byte[] value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, char[] value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer,
double[] value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, float[] value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, long[] value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, int[] value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder buffer, short[] value) {
appendFieldStart(parentLocator, parent, fieldName, buffer);
append(property(parentLocator, fieldName, value), buffer, value);
appendFieldEnd(parentLocator, parent, fieldName, buffer);
return buffer;
}
@SuppressWarnings("unchecked")
protected StringBuilder appendInternal(ObjectLocator locator,
StringBuilder buffer, Object value) {
if (value instanceof Collection) {
append(locator, buffer, (Collection) value);
} else if (value instanceof ToString2) {
((ToString2) value).append(locator, buffer, this);
} else if (value instanceof ToString) {
((ToString) value).append(locator, buffer, this);
} else {
buffer.append(value.toString());
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
Object value) {
if (value == null) {
appendNullText(buffer);
} else {
Class<?> theClass = value.getClass();
if (!theClass.isArray()) {
appendInternal(locator, buffer, value);
}
// 'Switch' on type of array, to dispatch to the correct handler
// This handles multi dimensional arrays of the same depth
else if (value instanceof long[]) {
append(locator, buffer, (long[]) value);
} else if (value instanceof int[]) {
append(locator, buffer, (int[]) value);
} else if (value instanceof short[]) {
append(locator, buffer, (short[]) value);
} else if (value instanceof char[]) {
append(locator, buffer, (char[]) value);
} else if (value instanceof byte[]) {
append(locator, buffer, (byte[]) value);
} else if (value instanceof double[]) {
append(locator, buffer, (double[]) value);
} else if (value instanceof float[]) {
append(locator, buffer, (float[]) value);
} else if (value instanceof boolean[]) {
append(locator, buffer, (boolean[]) value);
} else {
// Not an array of primitives
append(locator, buffer, (Object[]) value);
}
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
boolean value) {
buffer.append(value);
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
byte value) {
buffer.append(value);
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
char value) {
buffer.append(value);
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
double value) {
buffer.append(value);
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
float value) {
buffer.append(value);
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
int value) {
buffer.append(value);
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
long value) {
buffer.append(value);
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
short value) {
buffer.append(value);
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
Object[] array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
@SuppressWarnings("unchecked")
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
Collection array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
boolean[] array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
byte[] array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
char[] array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
double[] array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
float[] array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
int[] array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
long[] array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer,
short[] array) {
if (array == null) {
appendNullText(buffer);
} else if (isFullDetail()) {
appendDetail(locator, buffer, array);
} else {
appendSummary(locator, buffer, array);
}
return buffer;
}
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, boolean[] array) {
appendSummarySize(locator, buffer, array.length);
return buffer;
}
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, byte[] array) {
appendSummarySize(locator, buffer, array.length);
return buffer;
}
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, char[] array) {
appendSummarySize(locator, buffer, array.length);
return buffer;
}
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, double[] array) {
appendSummarySize(locator, buffer, array.length);
return buffer;
}
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, float[] array) {
appendSummarySize(locator, buffer, array.length);
return buffer;
}
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, int[] array) {
appendSummarySize(locator, buffer, array.length);
return buffer;
}
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, long[] array) {
appendSummarySize(locator, buffer, array.length);
return buffer;
}
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, short[] array) {
appendSummarySize(locator, buffer, array.length);
return buffer;
}
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, Object[] array) {
appendSummarySize(locator, buffer, array.length);
return buffer;
}
@SuppressWarnings("unchecked")
protected StringBuilder appendSummary(ObjectLocator locator,
StringBuilder buffer, Collection value) {
appendSummarySize(locator, buffer, value.size());
return buffer;
}
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, boolean[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
append(item(locator, i, array[i]), buffer, array[i]);
}
buffer.append(arrayEnd);
return buffer;
}
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, byte[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
append(item(locator, i, array[i]), buffer, array[i]);
}
buffer.append(arrayEnd);
return buffer;
}
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, char[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
append(item(locator, i, array[i]), buffer, array[i]);
}
buffer.append(arrayEnd);
return buffer;
}
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, double[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
append(item(locator, i, array[i]), buffer, array[i]);
}
buffer.append(arrayEnd);
return buffer;
}
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, float[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
append(item(locator, i, array[i]), buffer, array[i]);
}
buffer.append(arrayEnd);
return buffer;
}
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, int[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
append(item(locator, i, array[i]), buffer, array[i]);
}
buffer.append(arrayEnd);
return buffer;
}
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, long[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
append(item(locator, i, array[i]), buffer, array[i]);
}
buffer.append(arrayEnd);
return buffer;
}
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, short[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
append(item(locator, i, array[i]), buffer, array[i]);
}
buffer.append(arrayEnd);
return buffer;
}
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, Object[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
Object item = array[i];
if (i > 0) {
buffer.append(arraySeparator);
}
if (item == null) {
appendNullText(buffer);
} else {
append(item(locator, i, array[i]), buffer, array[i]);
}
}
buffer.append(arrayEnd);
return buffer;
}
@SuppressWarnings("unchecked")
protected StringBuilder appendDetail(ObjectLocator locator,
StringBuilder buffer, Collection array) {
appendArrayStart(buffer);
int i = 0;
for (Object item : array) {
if (i > 0) {
appendArraySeparator(buffer);
}
append(item(locator, i, item), buffer, item);
i = i + 1;
}
appendArrayEnd(buffer);
return buffer;
}
/**
* <p>
* Remove the last field separator from the buffer.
* </p>
*
* @param buffer
* the <code>StringBuilder</code> to populate
* @since 2.0
*/
protected void removeLastFieldSeparator(StringBuilder buffer) {
int len = buffer.length();
int sepLen = fieldSeparator.length();
if (len > 0 && sepLen > 0 && len >= sepLen) {
boolean match = true;
for (int i = 0; i < sepLen; i++) {
if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen
- 1 - i)) {
match = false;
break;
}
}
if (match) {
buffer.setLength(len - sepLen);
}
}
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
boolean value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
byte value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
char value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
double value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
float value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
int value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
long value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
short value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
Object value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
boolean[] value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
byte[] value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
char[] value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
double[] value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
float[] value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
int[] value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
long[] value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
short[] value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
@Override
public StringBuilder appendField(ObjectLocator parentLocator,
Object parent, String fieldName, StringBuilder stringBuilder,
Object[] value, boolean valueSet) {
appendFieldStart(parentLocator, parent, fieldName, stringBuilder,
valueSet);
append(property(parentLocator, fieldName, value), stringBuilder, value);
appendFieldEnd(parentLocator, parent, fieldName, stringBuilder,
valueSet);
return stringBuilder;
}
public static final DefaultToStringStrategy INSTANCE = new DefaultToStringStrategy();
}
| |
// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.daikon.di;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertArrayEquals;
import java.util.Arrays;
import java.util.List;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.talend.daikon.avro.SchemaConstants;
/**
* Unit-tests for {@link DynamicIndexMapperByIndex} class
*/
public class DynamicIndexMapperByIndexTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Checks {@link DynamicIndexMapperByIndex#DynamicIndexMapperByIndex(Schema)} throws {@link IllegalArgumentException}
* in case when incoming design schema doesn't contain dynamic field
* Case#1 INCLUDE_ALL_FIELDS is not present
*/
@Test
public void testConstructorDynamicNotPresent1() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Design schema doesn't contain dynamic field");
Schema designSchemaWithoutIncludeAllFields = SchemaBuilder.builder().record("Record") //
.prop(DiSchemaConstants.TALEND6_DYNAMIC_COLUMN_POSITION, "0").fields() //
.name("col1").type().intType().noDefault() //
.name("col2").type().stringType().noDefault() //
.name("col3").type().intType().noDefault() //
.endRecord(); //
DynamicIndexMapperByIndex indexMapper = new DynamicIndexMapperByIndex(designSchemaWithoutIncludeAllFields);
}
/**
* Checks {@link DynamicIndexMapperByIndex#DynamicIndexMapperByIndex(Schema)} throws {@link IllegalArgumentException}
* in case when incoming design schema doesn't contain dynamic field
* Case#2 TALEND6_DYNAMIC_COLUMN_POSITION is not present
*/
@Test
public void testConstructorDynamicNotPresent2() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Design schema doesn't contain dynamic field");
Schema designSchemaWithoutDynamicColumnPosition = SchemaBuilder.builder().record("Record") //
.prop(SchemaConstants.INCLUDE_ALL_FIELDS, "true").fields() //
.name("col1").type().intType().noDefault() //
.name("col2").type().stringType().noDefault() //
.name("col3").type().intType().noDefault() //
.endRecord(); //
DynamicIndexMapperByIndex indexMapper = new DynamicIndexMapperByIndex(designSchemaWithoutDynamicColumnPosition);
}
/**
* Checks {@link DynamicIndexMapperByIndex#DynamicIndexMapperByIndex(Schema)} throws {@link IllegalArgumentException}
* in case when incoming design schema doesn't contain dynamic field
* Case#3 both TALEND6_DYNAMIC_COLUMN_POSITION and INCLUDE_ALL_FIELDS are not present
*/
@Test
public void testConstructorDynamicNotPresent3() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Design schema doesn't contain dynamic field");
Schema designSchemaWithoutDynamic = SchemaBuilder.builder().record("Record").fields() //
.name("col1").type().intType().noDefault() //
.name("col2").type().stringType().noDefault() //
.name("col3").type().intType().noDefault() //
.endRecord(); //
DynamicIndexMapperByIndex indexMapper = new DynamicIndexMapperByIndex(designSchemaWithoutDynamic);
}
/**
* Checks {@link DynamicIndexMapperByIndex#computeIndexMap()} returns int array, which size equals n+1 and
* with values which equal indexes of corresponding fields in runtime schema, where n - number of fields in design schema
* and dynamic field position is at the start
*/
@Test
public void testComputeIndexMapStart() {
int[] expectedIndexMap = { -1, 2, 3, 4 };
Schema designSchema = SchemaBuilder.builder().record("Record") //
.prop(DiSchemaConstants.TALEND6_DYNAMIC_COLUMN_POSITION, "0").prop(SchemaConstants.INCLUDE_ALL_FIELDS, "true")
.fields() //
.name("col1").type().intType().noDefault() //
.name("col2").type().stringType().noDefault() //
.name("col3").type().intType().noDefault() //
.endRecord(); //
Schema runtimeSchema = SchemaBuilder.builder().record("Record").fields() //
.name("col0_1").type().intType().noDefault() //
.name("col0_2").type().intType().noDefault() //
.name("col1").type().intType().noDefault() //
.name("col2").type().stringType().noDefault() //
.name("col3").type().intType().noDefault() //
.endRecord(); //
DynamicIndexMapperByIndex indexMapper = new DynamicIndexMapperByIndex(designSchema);
int[] actualIndexMap = indexMapper.computeIndexMap(runtimeSchema);
assertArrayEquals(expectedIndexMap, actualIndexMap);
}
/**
* Checks {@link DynamicIndexMapperByIndex#computeIndexMap()} returns int array, which size equals n+1 and
* with values which equal indexes of corresponding fields in runtime schema, where n - number of fields in design schema
* and dynamic field position is in the middle
*/
@Test
public void testComputeIndexMapMiddle() {
int[] expectedIndexMap = { 0, -1, 3, 4 };
Schema designSchema = SchemaBuilder.builder().record("Record") //
.prop(DiSchemaConstants.TALEND6_DYNAMIC_COLUMN_POSITION, "1").prop(SchemaConstants.INCLUDE_ALL_FIELDS, "true")
.fields() //
.name("col0").type().intType().noDefault() //
.name("col2").type().stringType().noDefault() //
.name("col3").type().intType().noDefault() //
.endRecord(); //
Schema runtimeSchema = SchemaBuilder.builder().record("Record").fields() //
.name("col0").type().intType().noDefault() //
.name("col1_1").type().intType().noDefault() //
.name("col1_2").type().intType().noDefault() //
.name("col2").type().stringType().noDefault() //
.name("col3").type().intType().noDefault() //
.endRecord(); //
DynamicIndexMapperByIndex indexMapper = new DynamicIndexMapperByIndex(designSchema);
int[] actualIndexMap = indexMapper.computeIndexMap(runtimeSchema);
assertArrayEquals(expectedIndexMap, actualIndexMap);
}
/**
* Checks {@link DynamicIndexMapperByIndex#computeIndexMap()} returns int array, which size equals n+1 and
* with values which equal indexes of corresponding fields in runtime schema, where n - number of fields in design schema
* and dynamic field position is in the end
*/
@Test
public void testComputeIndexMapEnd() {
int[] expectedIndexMap = { 0, 1, 2, -1 };
Schema designSchema = SchemaBuilder.builder().record("Record") //
.prop(DiSchemaConstants.TALEND6_DYNAMIC_COLUMN_POSITION, "3").prop(SchemaConstants.INCLUDE_ALL_FIELDS, "true")
.fields() //
.name("col0").type().intType().noDefault() //
.name("col1").type().stringType().noDefault() //
.name("col2").type().intType().noDefault() //
.endRecord(); //
Schema runtimeSchema = SchemaBuilder.builder().record("Record").fields() //
.name("col0").type().intType().noDefault() //
.name("col1").type().intType().noDefault() //
.name("col2").type().intType().noDefault() //
.name("col3_1").type().stringType().noDefault() //
.name("col3_2").type().intType().noDefault() //
.endRecord(); //
DynamicIndexMapperByIndex indexMapper = new DynamicIndexMapperByIndex(designSchema);
int[] actualIndexMap = indexMapper.computeIndexMap(runtimeSchema);
assertArrayEquals(expectedIndexMap, actualIndexMap);
}
/**
* This test-case shows that {@link DynamicIndexMapperByIndex#computeIndexMap()} can't be used, when fields of
* design schema are organized in different order in runtime schema. For such case
* {@link DynamicIndexMapperByName#computeIndexMap()} should be used
*/
@Test
public void testComputeIndexMapDiffOrder() {
int[] expectedIndexMap = { 1, 0, 2, -1 };
Schema designSchema = SchemaBuilder.builder().record("Record") //
.prop(DiSchemaConstants.TALEND6_DYNAMIC_COLUMN_POSITION, "3").prop(SchemaConstants.INCLUDE_ALL_FIELDS, "true")
.fields() //
.name("col1").type().intType().noDefault() //
.name("col0").type().stringType().noDefault() //
.name("col2").type().intType().noDefault() //
.endRecord(); //
Schema runtimeSchema = SchemaBuilder.builder().record("Record").fields() //
.name("col0").type().intType().noDefault() //
.name("col1").type().intType().noDefault() //
.name("col2").type().intType().noDefault() //
.name("col3_1").type().stringType().noDefault() //
.name("col3_2").type().intType().noDefault() //
.endRecord(); //
DynamicIndexMapperByIndex indexMapper = new DynamicIndexMapperByIndex(designSchema);
int[] actualIndexMap = indexMapper.computeIndexMap(runtimeSchema);
assertThat(actualIndexMap, not(equalTo(expectedIndexMap)));
}
/**
* Checks {@link DynamicIndexMapperByIndex#DynamicIndexMapperByIndex(Schema, Schema)} throws {@link IllegalArgumentException}
* if design schema argument doesn't contain dynamic field properties
*/
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("unused")
public void testIndexMapperConstructorThrowsException() {
Schema designSchema = SchemaBuilder.builder().record("Record").fields() //
.name("col0").type().intType().noDefault() //
.name("col1").type().stringType().noDefault() //
.name("col2").type().intType().noDefault() //
.endRecord(); //
DynamicIndexMapperByIndex indexMapper = new DynamicIndexMapperByIndex(designSchema);
}
/**
* Checks {@link DynamicIndexMapperByIndex#computeDynamicFieldsIndexes()} returns list, which contains indexes of runtime
* dynamic fields
* (i.e. fields, which are present in runtime schema, but are not present in design schema)
*/
@Test
public void testComputeDynamicFieldsIndexes() {
List<Integer> expectedIndexes = Arrays.asList(3, 4);
Schema designSchema = SchemaBuilder.builder().record("Record") //
.prop(DiSchemaConstants.TALEND6_DYNAMIC_COLUMN_POSITION, "3") //
.prop(SchemaConstants.INCLUDE_ALL_FIELDS, "true").fields() //
.name("col0").type().intType().noDefault() //
.name("col1").type().stringType().noDefault() //
.name("col2").type().intType().noDefault() //
.endRecord(); //
Schema runtimeSchema = SchemaBuilder.builder().record("Record").fields() //
.name("col0").type().intType().noDefault() //
.name("col1").type().intType().noDefault() //
.name("col2").type().intType().noDefault() //
.name("col3_1").type().stringType().noDefault() //
.name("col3_2").type().intType().noDefault() //
.endRecord(); //
DynamicIndexMapperByIndex indexMapper = new DynamicIndexMapperByIndex(designSchema);
List<Integer> actualIndexes = indexMapper.computeDynamicFieldsIndexes(runtimeSchema);
assertThat(actualIndexes, IsIterableContainingInOrder.contains(expectedIndexes.toArray()));
}
}
| |
/**
* Generated with Acceleo
*/
package org.wso2.developerstudio.eclipse.gmf.esb.parts.impl;
// Start of user code for imports
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.context.impl.EObjectPropertiesEditionContext;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.impl.parts.CompositePropertiesEditionPart;
import org.eclipse.emf.eef.runtime.policies.PropertiesEditingPolicy;
import org.eclipse.emf.eef.runtime.providers.PropertiesEditingProvider;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable;
import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable.ReferencesTableListener;
import org.eclipse.emf.eef.runtime.ui.widgets.TabElementTreeSelectionDialog;
import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableContentProvider;
import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.ClassMediatorInputConnectorPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;
import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;
// End of user code
/**
*
*
*/
public class ClassMediatorInputConnectorPropertiesEditionPartImpl extends CompositePropertiesEditionPart implements ISWTPropertiesEditionPart, ClassMediatorInputConnectorPropertiesEditionPart {
protected ReferencesTable incomingLinks;
protected List<ViewerFilter> incomingLinksBusinessFilters = new ArrayList<ViewerFilter>();
protected List<ViewerFilter> incomingLinksFilters = new ArrayList<ViewerFilter>();
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public ClassMediatorInputConnectorPropertiesEditionPartImpl(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite)
*
*/
public Composite createFigure(final Composite parent) {
view = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(view);
return view;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart#
* createControls(org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(Composite view) {
CompositionSequence classMediatorInputConnectorStep = new BindingCompositionSequence(propertiesEditionComponent);
classMediatorInputConnectorStep
.addStep(EsbViewsRepository.ClassMediatorInputConnector.Properties.class)
.addStep(EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks);
composer = new PartComposer(classMediatorInputConnectorStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == EsbViewsRepository.ClassMediatorInputConnector.Properties.class) {
return createPropertiesGroup(parent);
}
if (key == EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks) {
return createIncomingLinksAdvancedReferencesTable(parent);
}
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(Composite parent) {
Group propertiesGroup = new Group(parent, SWT.NONE);
propertiesGroup.setText(EsbMessages.ClassMediatorInputConnectorPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesGroupData = new GridData(GridData.FILL_HORIZONTAL);
propertiesGroupData.horizontalSpan = 3;
propertiesGroup.setLayoutData(propertiesGroupData);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
return propertiesGroup;
}
/**
*
*/
protected Composite createIncomingLinksAdvancedReferencesTable(Composite parent) {
String label = getDescription(EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks, EsbMessages.ClassMediatorInputConnectorPropertiesEditionPart_IncomingLinksLabel);
this.incomingLinks = new ReferencesTable(label, new ReferencesTableListener() {
public void handleAdd() { addIncomingLinks(); }
public void handleEdit(EObject element) { editIncomingLinks(element); }
public void handleMove(EObject element, int oldIndex, int newIndex) { moveIncomingLinks(element, oldIndex, newIndex); }
public void handleRemove(EObject element) { removeFromIncomingLinks(element); }
public void navigateTo(EObject element) { }
});
this.incomingLinks.setHelpText(propertiesEditionComponent.getHelpContent(EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks, EsbViewsRepository.SWT_KIND));
this.incomingLinks.createControls(parent);
this.incomingLinks.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (e.item != null && e.item.getData() instanceof EObject) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(ClassMediatorInputConnectorPropertiesEditionPartImpl.this, EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.CHANGE, PropertiesEditionEvent.SELECTION_CHANGED, null, e.item.getData()));
}
}
});
GridData incomingLinksData = new GridData(GridData.FILL_HORIZONTAL);
incomingLinksData.horizontalSpan = 3;
this.incomingLinks.setLayoutData(incomingLinksData);
this.incomingLinks.disableMove();
incomingLinks.setID(EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks);
incomingLinks.setEEFType("eef::AdvancedReferencesTable"); //$NON-NLS-1$
return parent;
}
/**
*
*/
protected void addIncomingLinks() {
TabElementTreeSelectionDialog dialog = new TabElementTreeSelectionDialog(incomingLinks.getInput(), incomingLinksFilters, incomingLinksBusinessFilters,
"incomingLinks", propertiesEditionComponent.getEditingContext().getAdapterFactory(), current.eResource()) {
@Override
public void process(IStructuredSelection selection) {
for (Iterator<?> iter = selection.iterator(); iter.hasNext();) {
EObject elem = (EObject) iter.next();
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(ClassMediatorInputConnectorPropertiesEditionPartImpl.this, EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks,
PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.ADD, null, elem));
}
incomingLinks.refresh();
}
};
dialog.open();
}
/**
*
*/
protected void moveIncomingLinks(EObject element, int oldIndex, int newIndex) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(ClassMediatorInputConnectorPropertiesEditionPartImpl.this, EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.MOVE, element, newIndex));
incomingLinks.refresh();
}
/**
*
*/
protected void removeFromIncomingLinks(EObject element) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(ClassMediatorInputConnectorPropertiesEditionPartImpl.this, EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.REMOVE, null, element));
incomingLinks.refresh();
}
/**
*
*/
protected void editIncomingLinks(EObject element) {
EObjectPropertiesEditionContext context = new EObjectPropertiesEditionContext(propertiesEditionComponent.getEditingContext(), propertiesEditionComponent, element, adapterFactory);
PropertiesEditingProvider provider = (PropertiesEditingProvider)adapterFactory.adapt(element, PropertiesEditingProvider.class);
if (provider != null) {
PropertiesEditingPolicy policy = provider.getPolicy(context);
if (policy != null) {
policy.execute();
incomingLinks.refresh();
}
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.ClassMediatorInputConnectorPropertiesEditionPart#initIncomingLinks(org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings)
*/
public void initIncomingLinks(ReferencesTableSettings settings) {
if (current.eResource() != null && current.eResource().getResourceSet() != null)
this.resourceSet = current.eResource().getResourceSet();
ReferencesTableContentProvider contentProvider = new ReferencesTableContentProvider();
incomingLinks.setContentProvider(contentProvider);
incomingLinks.setInput(settings);
incomingLinksBusinessFilters.clear();
incomingLinksFilters.clear();
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.ClassMediatorInputConnector.Properties.incomingLinks);
if (eefElementEditorReadOnlyState && incomingLinks.getTable().isEnabled()) {
incomingLinks.setEnabled(false);
incomingLinks.setToolTipText(EsbMessages.ClassMediatorInputConnector_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !incomingLinks.getTable().isEnabled()) {
incomingLinks.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.ClassMediatorInputConnectorPropertiesEditionPart#updateIncomingLinks()
*
*/
public void updateIncomingLinks() {
incomingLinks.refresh();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.ClassMediatorInputConnectorPropertiesEditionPart#addFilterIncomingLinks(ViewerFilter filter)
*
*/
public void addFilterToIncomingLinks(ViewerFilter filter) {
incomingLinksFilters.add(filter);
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.ClassMediatorInputConnectorPropertiesEditionPart#addBusinessFilterIncomingLinks(ViewerFilter filter)
*
*/
public void addBusinessFilterToIncomingLinks(ViewerFilter filter) {
incomingLinksBusinessFilters.add(filter);
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.ClassMediatorInputConnectorPropertiesEditionPart#isContainedInIncomingLinksTable(EObject element)
*
*/
public boolean isContainedInIncomingLinksTable(EObject element) {
return ((ReferencesTableSettings)incomingLinks.getInput()).contains(element);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return EsbMessages.ClassMediatorInputConnector_Part_Title;
}
// Start of user code additional methods
// End of user code
}
| |
/****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
/*
* ScanManagerConfig.java
*
* Created on July 13, 2006, 3:42 PM
*
* @(#)ScanManagerConfig.java 1.5 10/03/23
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Oracle or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
package com.sun.jmx.examples.scandir.config;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
/**
* The <code>ScanManagerConfig</code> Java Bean is used to model
* the configuration of the {@link
* com.sun.jmx.examples.scandir.ScanManagerMXBean ScanManagerMXBean}.
*
* The {@link
* com.sun.jmx.examples.scandir.ScanManagerMXBean ScanManagerMXBean} will
* use this configuration to initialize the {@link
* com.sun.jmx.examples.scandir.ResultLoggerFactoryMXBean ResultLoggerFactoryMXBean}
* and create the {@link
* com.sun.jmx.examples.scandir.DirectoryScannerMXBean DirectoryScannerMXBeans}
* <p>
* This class is annotated for XML binding.
* </p>
*
* @author Sun Microsystems, 2006 - All rights reserved.
**/
@XmlRootElement(name="ScanManager",
namespace="jmx:com.sun.jmx.examples.scandir.config")
public class ScanManagerConfig {
// A LOGGER for this class
//
// private static final Logger LOGGER=
// LoggerFactory.getLogger(ScanManagerConfig.class.getName());
/**
* A set of DirectoryScannerConfig objects indexed by their names.
**/
private final Map<String, DirectoryScannerConfig> directoryScanners;
/**
* The initial Result Log configuration.
*/
private ResultLogConfig initialResultLogConfig;
/**
* Holds value of property name. The name of the configuration
* usually corresponds to
* the value of the {@code name=} key of the {@code ObjectName}
* of the {@link
* com.sun.jmx.examples.scandir.ScanDirConfigMXBean
* ScanDirConfigMXBean} which owns this configuration.
**/
private String name;
/**
* Creates a new instance of ScanManagerConfig.
* <p>You should not use this constructor directly, but use
* {@link #ScanManagerConfig(String)} instead.
* </p>
* <p>This constructor is tagged deprecated so that the compiler
* will generate a warning if it is used by mistake.
* </p>
* @deprecated Use {@link #ScanManagerConfig(String)} instead. This
* constructor is used through reflection by the XML
* binding framework.
*/
public ScanManagerConfig() {
this(null,true);
}
/**
* Creates a new instance of ScanManagerConfig.
* @param name The name of the configuration which usually corresponds to
* the value of the {@code name=} key of the {@code ObjectName}
* of the {@link
* com.sun.jmx.examples.scandir.ScanDirConfigMXBean
* ScanDirConfigMXBean} which owns this configuration.
**/
public ScanManagerConfig(String name) {
this(name,false);
}
// Our private constructor...
private ScanManagerConfig(String name, boolean allowsNull) {
if (name == null && allowsNull==false)
throw new IllegalArgumentException("name=null");
this.name = name;
directoryScanners = new LinkedHashMap<String,DirectoryScannerConfig>();
this.initialResultLogConfig = new ResultLogConfig();
this.initialResultLogConfig.setMemoryMaxRecords(1024);
}
// Creates an array for deep equality.
private Object[] toArray() {
final Object[] thisconfig = {
name,directoryScanners,initialResultLogConfig
};
return thisconfig;
}
// equals
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof ScanManagerConfig)) return false;
final ScanManagerConfig other = (ScanManagerConfig)o;
if (this.directoryScanners.size() != other.directoryScanners.size())
return false;
return Arrays.deepEquals(toArray(),other.toArray());
}
@Override
public int hashCode() {
final String key = name;
if (key == null) return 0;
else return key.hashCode();
}
/**
* Gets the name of this configuration. The name of the configuration
* usually corresponds to
* the value of the {@code name=} key of the {@code ObjectName}
* of the {@link
* com.sun.jmx.examples.scandir.ScanDirConfigMXBean
* ScanDirConfigMXBean} which owns this configuration.
* @return The name of this configuration.
*/
@XmlAttribute(name="name",required=true)
public String getName() {
return this.name;
}
/**
* Sets the name of this configuration. The name of the configuration
* usually corresponds to
* the value of the {@code name=} key of the {@code ObjectName}
* of the {@link
* com.sun.jmx.examples.scandir.ScanDirConfigMXBean
* ScanDirConfigMXBean} which owns this configuration.
* <p>Once set this value cannot change.</p>
* @param name The name of this configuration.
*/
public void setName(String name) {
if (this.name == null)
this.name = name;
else if (name == null)
throw new IllegalArgumentException("name=null");
else if (!name.equals(this.name))
throw new IllegalArgumentException("name="+name);
}
/**
* Gets the list of Directory Scanner configured by this
* configuration. From each element in this list, the
* {@link com.sun.jmx.examples.scandir.ScanManagerMXBean ScanManagerMXBean}
* will create, initialize, and register a {@link
* com.sun.jmx.examples.scandir.DirectoryScannerMXBean}.
* @return The list of Directory Scanner configured by this configuration.
*/
@XmlElementWrapper(name="DirectoryScannerList",
namespace=XmlConfigUtils.NAMESPACE)
@XmlElementRef
public DirectoryScannerConfig[] getScanList() {
return directoryScanners.values().toArray(new DirectoryScannerConfig[0]);
}
/**
* Sets the list of Directory Scanner configured by this
* configuration. From each element in this list, the
* {@link com.sun.jmx.examples.scandir.ScanManagerMXBean ScanManagerMXBean}
* will create, initialize, and register a {@link
* com.sun.jmx.examples.scandir.DirectoryScannerMXBean}.
* @param scans The list of Directory Scanner configured by this configuration.
*/
public void setScanList(DirectoryScannerConfig[] scans) {
directoryScanners.clear();
for (DirectoryScannerConfig scan : scans)
directoryScanners.put(scan.getName(),scan);
}
/**
* Get a directory scanner by its name.
*
* @param name The name of the directory scanner. This is the
* value returned by {@link
* DirectoryScannerConfig#getName()}.
* @return The named {@code DirectoryScannerConfig}
*/
public DirectoryScannerConfig getScan(String name) {
return directoryScanners.get(name);
}
/**
* Adds a directory scanner to the list.
* <p>If a directory scanner
* configuration by that name already exists in the list, it will
* be replaced by the given <var>scan</var>.
* </p>
* @param scan The {@code DirectoryScannerConfig} to add to the list.
* @return The replaced {@code DirectoryScannerConfig}, or {@code null}
* if there was no {@code DirectoryScannerConfig} by that name
* in the list.
*/
public DirectoryScannerConfig putScan(DirectoryScannerConfig scan) {
return this.directoryScanners.put(scan.getName(),scan);
}
// XML value of this object.
public String toString() {
return XmlConfigUtils.toString(this);
}
/**
* Removes the named directory scanner from the list.
*
* @param name The name of the directory scanner. This is the
* value returned by {@link
* DirectoryScannerConfig#getName()}.
* @return The removed {@code DirectoryScannerConfig}, or {@code null}
* if there was no directory scanner by that name in the list.
*/
public DirectoryScannerConfig removeScan(String name) {
return this.directoryScanners.remove(name);
}
/**
* Gets the initial Result Log Configuration.
* @return The initial Result Log Configuration.
*/
@XmlElement(name="InitialResultLogConfig",namespace=XmlConfigUtils.NAMESPACE)
public ResultLogConfig getInitialResultLogConfig() {
return this.initialResultLogConfig;
}
/**
* Sets the initial Result Log Configuration.
* @param initialLogConfig The initial Result Log Configuration.
*/
public void setInitialResultLogConfig(ResultLogConfig initialLogConfig) {
this.initialResultLogConfig = initialLogConfig;
}
/**
* Creates a copy of this object, with the specified name.
* @param newname the name of the copy.
* @return A copy of this object.
**/
public ScanManagerConfig copy(String newname) {
return copy(newname,this);
}
// Copy by XML cloning, then change the name.
//
private static ScanManagerConfig
copy(String newname, ScanManagerConfig other) {
ScanManagerConfig newbean = XmlConfigUtils.xmlClone(other);
newbean.name = newname;
return newbean;
}
}
| |
/*---------------------------------------------------------------
* Copyright 2005 by the Radiological Society of North America
*
* This source software is released under the terms of the
* RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
*----------------------------------------------------------------*/
package org.rsna.ctp.stdstages.anonymizer.dicom;
import org.apache.log4j.Logger;
import org.rsna.util.FileUtil;
import org.rsna.util.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.StringReader;
import java.util.Hashtable;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A DICOM Anonymizer script.
*/
public class DAScript {
static final Logger logger = Logger.getLogger(DAScript.class);
static Hashtable<String,DAScript> scripts = new Hashtable<String,DAScript>();
public File file;
public String script;
public boolean scriptIsXML = false;
public String xmlScript = null;
public Document xml = null;
public Properties properties = null;
public long lastVersionLoaded = 0;
/**
* Get the singleton instance of a DAScript, loading a new instance
* if the script file has changed.
* @param file the file containing the script.
*/
public static synchronized DAScript getInstance(File file) {
//First see if we already have an instance in the table
String path = file.getAbsolutePath().replaceAll("\\\\","/");
DAScript das = scripts.get(path);
if ( (das != null) && das.isCurrent() ) return das;
//We didn't get a current instance from the table; create one.
das = new DAScript(file);
//Put this instance in the table and then return it.
scripts.put(path, das);
return das;
}
/**
* Protected constructor; create a DAScript from either a properties file or an XML file.
* @param file the file containing the script.
*/
protected DAScript(File file) {
this.file = file;
this.script = FileUtil.getText(file, FileUtil.utf8);
this.lastVersionLoaded = file.lastModified();
//See if this might be an xml document.
Pattern xmlPattern = Pattern.compile("^\\s*<", Pattern.DOTALL | Pattern.MULTILINE);
Matcher xmlMatcher = xmlPattern.matcher(script);
scriptIsXML = xmlMatcher.find();
}
/**
* Determine whether the script file has changed since it was last loaded.
* If the script file has changed in the last 5 seconds, it is ignored
* to ensure that we don't jump on a file that is still being modified.
* @return true if this DAScript instance is up-to-date; false if the file has changed.
*/
public boolean isCurrent() {
long lastModified = file.lastModified();
long age = System.currentTimeMillis() - lastModified;
return ( (lastVersionLoaded >= lastModified) || (age < 5000) );
}
/**
* Get the script as an XML string.
* @return the script as an XML string
*/
public String toXMLString() {
if (scriptIsXML) return script;
if (xmlScript != null) return xmlScript;
if (xml == null) toXML();
if (xml != null) {
xmlScript = XmlUtil.toString(xml);
return xmlScript;
}
xmlScript = "<script/>";
return xmlScript;
}
public Properties toProperties() {
if (properties != null) return properties;
if (!scriptIsXML) {
try {
//This is a kludge to make it compile in Java 1.5 so the folks at NCI can
//build it. The props.load(Reader) method is not supported in 1.5; only 1.6.
/*Java1.5*/ ByteArrayInputStream sr = new ByteArrayInputStream(script.getBytes("ISO-8859-1"));
/*Java1.6*/ /*StringReader sr = new StringReader(script);*/
properties = new Properties();
properties.load(sr);
}
catch (Exception ex) {
logger.warn("Unable to read the properties stream.");
}
return properties;
}
return (properties = makeProperties());
}
//This method must only be called when the script is XML.
//If it is called with an XML script, it returns an empty
//Properties object.
private Properties makeProperties() {
Properties props = new Properties();
if (toXML() == null) return props;
Element root = xml.getDocumentElement();
Node child = root.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element eChild = (Element)child;
String tag = eChild.getTagName();
if (tag.equals("p")) addParam(props, eChild);
else if (tag.equals("e")) addElement(props, eChild);
else if (tag.equals("k")) addKeep(props, eChild);
else if (tag.equals("r")) addRemove(props, eChild);
}
child = child.getNextSibling();
}
properties = props;
return props;
}
private void addParam(Properties props, Element x) {
String key = "param." + x.getAttribute("t");
String value = x.getTextContent();
props.setProperty(key, value);
}
private void addElement(Properties props, Element x) {
String sel = (x.getAttribute("en").equals("T") ? "" : "#");
String t = x.getAttribute("t");
String elem = "[" + t.substring(0,4) + "," + t.substring(4) + "]";
String name = x.getAttribute("n");
String key = sel + "set." + elem + name;
String value = x.getTextContent().trim();
props.setProperty(key, value);
}
private void addKeep(Properties props, Element x) {
String sel = (x.getAttribute("en").equals("T") ? "" : "#");
String t = x.getAttribute("t");
String group = "group" + t.substring(2,4);
String key = sel + "keep." + group;
props.setProperty(key, "");
}
private void addRemove(Properties props, Element x) {
String sel = (x.getAttribute("en").equals("T") ? "" : "#");
String t = x.getAttribute("t");
String key = sel + "remove." + t;
props.setProperty(key, "");
}
public Document toXML() {
if (xml == null) {
if (scriptIsXML) {
//This is an XML file; parse it.
try { xml = XmlUtil.getDocument(script); }
catch (Exception ex) { logger.warn(ex); }
}
else {
//This must be a properties file; convert
//it to XML, save the result, and return it;
try {
Document doc = XmlUtil.getDocument();
Element root = doc.createElement("script");
doc.appendChild(root);
BufferedReader br = new BufferedReader(new StringReader(script));
String line;
while ( (line=br.readLine()) != null ) {
line = line.trim();
int k = line.indexOf("=");
if (k != -1) {
String left = line.substring(0,k);
String right = line.substring(k+1);
if (left.startsWith("param.")) {
root.appendChild(createParam(doc, left, right));
}
else if (left.startsWith("set.") || left.startsWith("#set.")) {
root.appendChild(createElement(doc, left, right));
}
else if (left.startsWith("keep.") || left.startsWith("#keep.")) {
root.appendChild(createKeep(doc, left, right));
}
else if (left.startsWith("remove.") || left.startsWith("#remove.")) {
root.appendChild(createRemove(doc, left, right));
}
}
}
xml = doc;
}
catch (Exception ex) { logger.warn(ex); }
}
}
return xml;
}
private Element createParam(Document doc, String left, String right) {
Element p = doc.createElement("p");
p.setAttribute("t", left.substring(6).trim());
p.appendChild(doc.createTextNode(right));
return p;
}
private Element createElement(Document doc, String left, String right) {
Element e = doc.createElement("e");
String en;
if (left.startsWith("#")) {
en = "F";
left = left.substring(1);
}
else en = "T";
e.setAttribute("en", en);
String t = "00000000";
String n = "";
int q = left.indexOf("[");
if (q != -1) {
int qq = left.indexOf("]", q);
if (qq != -1) {
t = left.substring(q, qq);
t = t.replaceAll("[^0-9a-fA-f]", "");
n = left.substring(qq+1).trim();
}
}
e.setAttribute("t", t);
e.setAttribute("n", n);
e.appendChild(doc.createTextNode(right));
return e;
}
private Element createKeep(Document doc, String left, String right) {
Element k = doc.createElement("k");
String en;
if (left.startsWith("#")) {
en = "F";
left = left.substring(1);
}
else en = "T";
k.setAttribute("en", en);
String t = left.substring(10).trim();
while (t.length() < 4) t = "0" + t;
k.setAttribute("t", t);
k.setAttribute("n", right.trim());
return k;
}
private Element createRemove(Document doc, String left, String right) {
Element r = doc.createElement("r");
String en;
if (left.startsWith("#")) {
en = "F";
left = left.substring(1);
}
else en = "T";
r.setAttribute("en", en);
String t = left.substring(7).trim();
r.setAttribute("t", t);
String n = "";
if (t.equals("privategroups")) n="Remove private groups [recommended]";
else if (t.equals("unspecifiedelements")) n="Remove unchecked elements";
else if (t.equals("curves")) n="Remove curves";
else if (t.equals("overlays")) n="Remove overlays";
r.setAttribute("n", n);
return r;
}
}
| |
/**
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.central.repo;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.exceptions.NoHostAvailableException;
import com.google.common.base.StandardSystemProperty;
import com.google.common.base.Strings;
import com.google.common.io.Files;
import org.rauschig.jarchivelib.ArchiveFormat;
import org.rauschig.jarchivelib.Archiver;
import org.rauschig.jarchivelib.ArchiverFactory;
import org.rauschig.jarchivelib.CompressionType;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.TimeUnit.SECONDS;
// see copies of this class in glowroot-agent-cassandra-plugin and glowroot-webdriver-tests
class CassandraWrapper {
static final String CASSANDRA_VERSION;
private static final String CASSANDRA_JAVA_HOME;
static {
if (System.getProperty("os.name").startsWith("Windows")) {
// Cassandra 2.1 has issues on Windows
// see https://issues.apache.org/jira/browse/CASSANDRA-10673
CASSANDRA_VERSION = "2.2.16";
} else {
CASSANDRA_VERSION = "2.1.21";
}
String javaVersion = StandardSystemProperty.JAVA_VERSION.value();
if (javaVersion.startsWith("1.7") || javaVersion.startsWith("1.8")) {
CASSANDRA_JAVA_HOME = System.getProperty("java.home");
} else {
CASSANDRA_JAVA_HOME = System.getProperty("cassandra.java.home");
if (Strings.isNullOrEmpty(CASSANDRA_JAVA_HOME)) {
throw new IllegalStateException("Cassandra 2.x itself requires Java 7 or Java 8,"
+ " but this test is running under Java " + javaVersion + ", so you must"
+ " provide -Dcassandra.java.home=... (or run this test under Java 7 or"
+ " Java 8)");
}
}
}
private static Process process;
private static ExecutorService consolePipeExecutorService;
static void start() throws Exception {
File baseDir = new File("cassandra");
File cassandraDir = new File(baseDir, "apache-cassandra-" + CASSANDRA_VERSION);
if (!cassandraDir.exists()) {
try {
downloadAndExtract(baseDir);
} catch (EOFException e) {
// partial download, try again
System.out.println("Retrying...");
downloadAndExtract(baseDir);
}
}
List<String> command = buildCommandLine(cassandraDir);
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.directory(new File(cassandraDir, "bin"));
processBuilder.redirectErrorStream(true);
process = processBuilder.start();
ConsoleOutputPipe consoleOutputPipe =
new ConsoleOutputPipe(process.getInputStream(), System.out);
consolePipeExecutorService = Executors.newSingleThreadExecutor();
consolePipeExecutorService.submit(consoleOutputPipe);
waitForCassandra();
}
static void stop() throws Exception {
process.destroy();
process.waitFor();
consolePipeExecutorService.shutdown();
if (!consolePipeExecutorService.awaitTermination(10, SECONDS)) {
throw new IllegalStateException("Could not terminate executor");
}
}
private static void downloadAndExtract(File baseDir) throws IOException {
// using System.out to make sure user sees why there is a big delay here
System.out.print("Downloading Cassandra " + CASSANDRA_VERSION + "...");
URL url = new URL("https://www-us.apache.org/dist/cassandra/" + CASSANDRA_VERSION
+ "/apache-cassandra-" + CASSANDRA_VERSION + "-bin.tar.gz");
InputStream in = url.openStream();
File archiveFile = File.createTempFile("cassandra-" + CASSANDRA_VERSION + "-", ".tar.gz");
Files.asByteSink(archiveFile).writeFrom(in);
in.close();
Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
archiver.extract(archiveFile, baseDir);
archiveFile.delete();
System.out.println(" OK");
File cassandraDir = new File(baseDir, "apache-cassandra-" + CASSANDRA_VERSION);
File confDir = new File(cassandraDir, "conf");
// reduce logging to stdout
File logbackXmlFile = new File(confDir, "logback.xml");
String xml = Files.asCharSource(logbackXmlFile, UTF_8).read();
xml = xml.replace("<root level=\"INFO\">", "<root level=\"ERROR\">");
xml = xml.replace("<logger name=\"org.apache.cassandra\" level=\"DEBUG\"/>", "");
Files.asCharSink(logbackXmlFile, UTF_8).write(xml);
// long timeouts needed on slow travis ci machines
File yamlFile = new File(confDir, "cassandra.yaml");
String yaml = Files.asCharSource(yamlFile, UTF_8).read();
yaml = yaml.replaceAll("(?m)^read_request_timeout_in_ms: .*$",
"read_request_timeout_in_ms: 30000");
yaml = yaml.replaceAll("(?m)^write_request_timeout_in_ms: .*$",
"write_request_timeout_in_ms: 30000");
Files.asCharSink(yamlFile, UTF_8).write(yaml);
}
private static List<String> buildCommandLine(File cassandraDir) {
List<String> command = new ArrayList<>();
String javaExecutable =
CASSANDRA_JAVA_HOME + File.separator + "bin" + File.separator + "java";
command.add(javaExecutable);
command.add("-cp");
command.add(buildClasspath(cassandraDir));
command.add("-javaagent:" + cassandraDir.getAbsolutePath() + "/lib/jamm-0.3.0.jar");
command.add("-Dlogback.configurationFile=logback.xml");
command.add("-Dcassandra.jmx.local.port=7199");
command.add("-Dcassandra");
command.add("-Dcassandra-foreground=yes");
command.add("-Dcassandra.logdir=" + cassandraDir.getAbsolutePath() + "/log");
command.add("-Dcassandra.storagedir=" + cassandraDir.getAbsolutePath() + "/data");
// this is used inside low-entropy docker containers
String sourceOfRandomness = System.getProperty("java.security.egd");
if (sourceOfRandomness != null) {
command.add("-Djava.security.egd=" + sourceOfRandomness);
}
command.add("-Xmx256m");
// leave as much memory as possible to old gen
command.add("-XX:NewRatio=20");
command.add("org.apache.cassandra.service.CassandraDaemon");
return command;
}
private static String buildClasspath(File cassandraDir) {
File libDir = new File(cassandraDir, "lib");
File confDir = new File(cassandraDir, "conf");
String classpath = confDir.getAbsolutePath();
for (File file : libDir.listFiles()) {
if (file.getName().endsWith(".jar")) {
classpath += File.pathSeparator + file.getAbsolutePath();
}
}
return classpath;
}
private static void waitForCassandra() throws InterruptedException {
while (true) {
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
try {
cluster.connect();
cluster.close();
return;
} catch (NoHostAvailableException e) {
cluster.close();
SECONDS.sleep(1);
}
}
}
static class ConsoleOutputPipe implements Runnable {
private final InputStream in;
private final OutputStream out;
ConsoleOutputPipe(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
@Override
public void run() {
byte[] buffer = new byte[100];
try {
while (true) {
int n = in.read(buffer);
if (n == -1) {
break;
}
out.write(buffer, 0, n);
}
} catch (IOException e) {
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.