gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Copyright (C) 2017 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.gapid.views; import static com.google.gapid.util.Colors.BLACK; import static com.google.gapid.util.Colors.DARK_LUMINANCE_THRESHOLD; import static com.google.gapid.util.Colors.WHITE; import static com.google.gapid.util.Colors.getLuminance; import static com.google.gapid.util.Colors.rgb; import static com.google.gapid.util.Loadable.MessageType.Error; import static com.google.gapid.util.Loadable.MessageType.Info; import static com.google.gapid.widgets.Widgets.createComposite; import static com.google.gapid.widgets.Widgets.createDropDownViewer; import static com.google.gapid.widgets.Widgets.createGroup; import static com.google.gapid.widgets.Widgets.createStandardTabFolder; import static com.google.gapid.widgets.Widgets.createStandardTabItem; import static com.google.gapid.widgets.Widgets.createTableViewer; import static com.google.gapid.widgets.Widgets.disposeAllChildren; import static com.google.gapid.widgets.Widgets.packColumns; import static com.google.gapid.widgets.Widgets.scheduleIfNotDisposed; import static java.util.logging.Level.FINE; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gapid.lang.glsl.GlslSourceConfiguration; import com.google.gapid.models.Analytics.View; import com.google.gapid.models.Capture; import com.google.gapid.models.CommandStream; import com.google.gapid.models.CommandStream.CommandIndex; import com.google.gapid.models.Models; import com.google.gapid.models.Resources; import com.google.gapid.proto.core.pod.Pod; import com.google.gapid.proto.service.Service; import com.google.gapid.proto.service.Service.ClientAction; import com.google.gapid.proto.service.api.API; import com.google.gapid.rpc.Rpc; import com.google.gapid.rpc.RpcException; import com.google.gapid.rpc.SingleInFlight; import com.google.gapid.rpc.UiCallback; import com.google.gapid.util.Loadable; import com.google.gapid.util.Messages; import com.google.gapid.util.ProtoDebugTextFormat; import com.google.gapid.widgets.LoadablePanel; import com.google.gapid.widgets.Theme; import com.google.gapid.widgets.Widgets; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ST; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.TabFolder; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.util.logging.Logger; /** * View allowing the inspection and editing of the shader resources. */ public class ShaderView extends Composite implements Tab, Capture.Listener, CommandStream.Listener, Resources.Listener { protected static final Logger LOG = Logger.getLogger(ShaderView.class.getName()); protected final Models models; private final Widgets widgets; private final SingleInFlight shaderRpcController = new SingleInFlight(); private final SingleInFlight programRpcController = new SingleInFlight(); private final LoadablePanel<Composite> loading; private boolean uiBuiltWithPrograms; public ShaderView(Composite parent, Models models, Widgets widgets) { super(parent, SWT.NONE); this.models = models; this.widgets = widgets; setLayout(new FillLayout()); loading = LoadablePanel.create(this, widgets, panel -> createComposite(panel, new FillLayout(SWT.VERTICAL))); updateUi(true); models.capture.addListener(this); models.commands.addListener(this); models.resources.addListener(this); addListener(SWT.Dispose, e -> { models.capture.removeListener(this); models.commands.removeListener(this); models.resources.removeListener(this); }); } private Control createShaderTab(Composite parent) { ShaderPanel panel = new ShaderPanel(parent, models, widgets.theme, Type.shader((data, src) -> { API.Shader shader = (data == null) ? null : (API.Shader)data.resource; if (shader != null) { models.analytics.postInteraction(View.Shaders, ClientAction.Edit); models.resources.updateResource(data.info, API.ResourceData.newBuilder() .setShader(shader.toBuilder() .setSource(src)) .build()); } })); panel.addListener(SWT.Selection, e -> { models.analytics.postInteraction(View.Shaders, ClientAction.SelectShader); getShaderSource((Data)e.data, panel::setSource); }); return panel; } private Control createProgramTab(Composite parent) { SashForm splitter = new SashForm(parent, SWT.VERTICAL); ShaderPanel panel = new ShaderPanel(splitter, models, widgets.theme, Type.program()); Composite uniformsGroup = createGroup(splitter, "Uniforms"); UniformsPanel uniforms = new UniformsPanel(uniformsGroup); splitter.setWeights(models.settings.shaderSplitterWeights); panel.addListener(SWT.Selection, e -> { models.analytics.postInteraction(View.Shaders, ClientAction.SelectProgram); getProgramSource((Data)e.data, program -> scheduleIfNotDisposed(uniforms, () -> uniforms.setUniforms(program)), panel::setSource); }); splitter.addListener( SWT.Dispose, e -> models.settings.shaderSplitterWeights = splitter.getWeights()); return splitter; } private void getShaderSource(Data data, Consumer<ShaderPanel.Source[]> callback) { shaderRpcController.start().listen(models.resources.loadResource(data.info), new UiCallback<API.ResourceData, ShaderPanel.Source>(this, LOG) { @Override protected ShaderPanel.Source onRpcThread(Rpc.Result<API.ResourceData> result) throws RpcException, ExecutionException { API.Shader shader = result.get().getShader(); data.resource = shader; return ShaderPanel.Source.of(shader); } @Override protected void onUiThread(ShaderPanel.Source result) { callback.accept(new ShaderPanel.Source[] { result }); } }); } private void getProgramSource( Data data, Consumer<API.Program> onProgramLoaded, Consumer<ShaderPanel.Source[]> callback) { programRpcController.start().listen(models.resources.loadResource(data.info), new UiCallback<API.ResourceData, ShaderPanel.Source[]>(this, LOG) { @Override protected ShaderPanel.Source[] onRpcThread(Rpc.Result<API.ResourceData> result) throws RpcException, ExecutionException { API.Program program = result.get().getProgram(); data.resource = program; onProgramLoaded.accept(program); return ShaderPanel.Source.of(program); } @Override protected void onUiThread(ShaderPanel.Source[] result) { callback.accept(result); } }); } @Override public Control getControl() { return this; } @Override public void reinitialize() { onCaptureLoadingStart(false); updateUi(false); updateLoading(); } @Override public void onCaptureLoadingStart(boolean maintainState) { loading.showMessage(Info, Messages.LOADING_CAPTURE); } @Override public void onCaptureLoaded(Loadable.Message error) { if (error != null) { loading.showMessage(Error, Messages.CAPTURE_LOAD_FAILURE); } } @Override public void onCommandsLoaded() { if (!models.commands.isLoaded()) { loading.showMessage(Info, Messages.CAPTURE_LOAD_FAILURE); } else { updateLoading(); } } @Override public void onCommandsSelected(CommandIndex path) { updateLoading(); } @Override public void onResourcesLoaded() { if (!models.resources.isLoaded()) { loading.showMessage(Info, Messages.CAPTURE_LOAD_FAILURE); } else { updateUi(false); updateLoading(); } } private void updateLoading() { if (models.commands.isLoaded() && models.resources.isLoaded()) { if (models.commands.getSelectedCommands() == null) { loading.showMessage(Info, Messages.SELECT_COMMAND); } else { loading.stopLoading(); } } } private void updateUi(boolean force) { boolean hasPrograms = true; if (models.resources.isLoaded()) { hasPrograms = models.resources.getResources().stream() .filter(r -> r.getType() == API.ResourceType.ProgramResource) .findAny() .isPresent(); } else if (!force) { return; } if (force || hasPrograms != uiBuiltWithPrograms) { LOG.log(FINE, "(Re-)creating the shader UI, force: {0}, programs: {1}", new Object[] { force, hasPrograms }); uiBuiltWithPrograms = hasPrograms; disposeAllChildren(loading.getContents()); if (hasPrograms) { TabFolder folder = createStandardTabFolder(loading.getContents()); createStandardTabItem(folder, "Shaders", createShaderTab(folder)); createStandardTabItem(folder, "Programs", createProgramTab(folder)); } else { createShaderTab(loading.getContents()); } loading.getContents().requestLayout(); } } /** * Panel displaying the source code of a shader or program. */ private static class ShaderPanel extends Composite implements Resources.Listener, CommandStream.Listener { private final Models models; private final Theme theme; protected final Type type; private final ComboViewer shaderCombo; private final Composite sourceComposite; private final Button pushButton; private SourceViewer shaderSourceViewer; private boolean lastUpdateContainedAllShaders = false; private List<Data> shaders = Collections.emptyList(); public ShaderPanel(Composite parent, Models models, Theme theme, Type type) { super(parent, SWT.NONE); this.models = models; this.theme = theme; this.type = type; setLayout(new GridLayout(1, false)); shaderCombo = createShaderSelector(); sourceComposite = createComposite(this, new FillLayout(SWT.VERTICAL)); shaderCombo.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); sourceComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); if (type.isEditable()) { pushButton = Widgets.createButton(this, "Push Changes", e -> type.updateShader( (Data)shaderCombo.getElementAt(shaderCombo.getCombo().getSelectionIndex()), shaderSourceViewer.getDocument().get())); pushButton.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, false, false)); pushButton.setEnabled(false); } else { pushButton = null; } models.commands.addListener(this); models.resources.addListener(this); addListener(SWT.Dispose, e -> { models.commands.removeListener(this); models.resources.removeListener(this); }); shaderCombo.getCombo().addListener(SWT.Selection, e -> updateSelection()); updateShaders(); } private ComboViewer createShaderSelector() { ComboViewer combo = createDropDownViewer(this); combo.setContentProvider(ArrayContentProvider.getInstance()); combo.setLabelProvider(new LabelProvider()); return combo; } private SourceViewer createSourcePanel(Composite parent, Source source) { Group group = createGroup(parent, source.label); SourceViewer viewer = new SourceViewer(group, null, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); StyledText textWidget = viewer.getTextWidget(); viewer.setEditable(type.isEditable()); textWidget.setFont(theme.monoSpaceFont()); textWidget.setKeyBinding(ST.SELECT_ALL, ST.SELECT_ALL); viewer.configure(new GlslSourceConfiguration(theme)); viewer.setDocument(GlslSourceConfiguration.createDocument(source.source)); textWidget.addListener(SWT.KeyDown, e -> { if (isKey(e, SWT.MOD1, 'z')) { viewer.doOperation(ITextOperationTarget.UNDO); } else if (isKey(e, SWT.MOD1, 'y') || isKey(e, SWT.MOD1 | SWT.SHIFT, 'z')) { viewer.doOperation(ITextOperationTarget.REDO); } }); return viewer; } private static boolean isKey(Event e, int stateMask, int keyCode) { return (e.stateMask & stateMask) == stateMask && e.keyCode == keyCode; } public void clearSource() { shaderSourceViewer = null; disposeAllChildren(sourceComposite); if (pushButton != null) { pushButton.setEnabled(false); } } public void setSource(Source[] sources) { clearSource(); SashForm sourceSash = new SashForm(sourceComposite, SWT.VERTICAL); for (Source source : sources) { shaderSourceViewer = createSourcePanel(sourceSash, source); } sourceSash.requestLayout(); if (sources.length > 0 && pushButton != null) { pushButton.setEnabled(true); } } @Override public void onResourcesLoaded() { lastUpdateContainedAllShaders = false; updateShaders(); } @Override public void onCommandsSelected(CommandIndex path) { updateShaders(); } private void updateShaders() { if (models.resources.isLoaded() && models.commands.getSelectedCommands() != null) { Resources.ResourceList resources = models.resources.getResources(type.type); // If we previously had created the dropdown with all the shaders and didn't skip any // this time, the dropdown does not need to change. if (!lastUpdateContainedAllShaders || !resources.complete) { if (resources.isEmpty()) { shaders = Collections.emptyList(); } else { shaders = Lists.newArrayList(new Data(null) { @Override public String toString() { return type.selectMessage; } }); resources.stream() .map(r -> new Data(r.resource)) .forEach(shaders::add); } lastUpdateContainedAllShaders = resources.complete; int selection = shaderCombo.getCombo().getSelectionIndex(); shaderCombo.setInput(shaders); shaderCombo.refresh(); if (selection >= 0 && selection < shaders.size()) { shaderCombo.getCombo().select(selection); } else if (!shaders.isEmpty()) { shaderCombo.getCombo().select(0); } } else { for (Data data : shaders) { data.resource = null; } } updateSelection(); } } private void updateSelection() { int index = shaderCombo.getCombo().getSelectionIndex(); if (index <= 0) { // Ignore the null item selection. clearSource(); } else { Event event = new Event(); event.data = shaderCombo.getElementAt(index); notifyListeners(SWT.Selection, event); } } public static class Source { private static final Source EMPTY_PROGRAM = new Source("Program", "// No shaders attached to this program at this point in the trace."); private static final String EMPTY_SHADER = "// No source attached to this shader at this point in the trace."; public final String label; public final String source; public Source(String label, String source) { this.label = label; this.source = source; } public static Source of(API.Shader shader) { return new Source(shader.getType() + " Shader", shader.getSource().isEmpty() ? EMPTY_SHADER : shader.getSource()); } public static Source[] of(API.Program program) { if (program.getShadersCount() == 0) { return new Source[] { EMPTY_PROGRAM }; } Source[] source = new Source[program.getShadersCount()]; for (int i = 0; i < source.length; i++) { source[i] = of(program.getShaders(i)); } return source; } } protected static interface UpdateShader { public void updateShader(Data data, String newSource); } } /** * Panel displaying the uniforms of the current shader program. */ private static class UniformsPanel extends Composite { private final TableViewer table; private final Map<API.Uniform, Image> images = Maps.newIdentityHashMap(); public UniformsPanel(Composite parent) { super(parent, SWT.NONE); setLayout(new FillLayout(SWT.VERTICAL)); table = createTableViewer( this, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL); table.setContentProvider(new ArrayContentProvider()); Widgets.<API.Uniform>createTableColumn(table, "Location", uniform -> String.valueOf(uniform.getUniformLocation())); Widgets.<API.Uniform>createTableColumn(table, "Name", API.Uniform::getName); Widgets.<API.Uniform>createTableColumn(table, "Type", uniform -> String.valueOf(uniform.getType())); Widgets.<API.Uniform>createTableColumn(table, "Format", uniform -> String.valueOf(uniform.getFormat())); Widgets.<API.Uniform>createTableColumn(table, "Value", uniform -> { Pod.Value value = uniform.getValue().getPod(); // TODO switch (uniform.getType()) { case Int32: return String.valueOf(value.getSint32Array().getValList()); case Uint32: return String.valueOf(value.getUint32Array().getValList()); case Bool: return String.valueOf(value.getBoolArray().getValList()); case Float: return String.valueOf(value.getFloat32Array().getValList()); case Double: return String.valueOf(value.getFloat64Array().getValList()); default: return ProtoDebugTextFormat.shortDebugString(value); } },this::getImage); packColumns(table.getTable()); addListener(SWT.Dispose, e -> clearImages()); } public void setUniforms(API.Program program) { List<API.Uniform> uniforms = Lists.newArrayList(program.getUniformsList()); Collections.sort(uniforms, (a, b) -> a.getUniformLocation() - b.getUniformLocation()); clearImages(); table.setInput(uniforms); table.refresh(); packColumns(table.getTable()); table.getTable().requestLayout(); } private Image getImage(API.Uniform uniform) { if (!images.containsKey(uniform)) { Image image = null; Pod.Value value = uniform.getValue().getPod(); // TODO switch (uniform.getType()) { case Float: { List<Float> values = value.getFloat32Array().getValList(); if ((values.size() == 3 || values.size() == 4) && isColorRange(values.get(0)) && isColorRange(values.get(1)) && isColorRange(values.get(2))) { image = createImage(values.get(0), values.get(1), values.get(2)); } break; } case Double: { List<Double> values = value.getFloat64Array().getValList(); if ((values.size() == 3 || values.size() == 4) && isColorRange(values.get(0)) && isColorRange(values.get(1)) && isColorRange(values.get(2))) { image = createImage(values.get(0), values.get(1), values.get(2)); } break; } default: // Not a color. } images.put(uniform, image); } return images.get(uniform); } private static boolean isColorRange(double v) { return v >= 0 && v <= 1; } private Image createImage(double r, double g, double b) { ImageData data = new ImageData(12, 12, 1, new PaletteData( (getLuminance(r, g, b) < DARK_LUMINANCE_THRESHOLD) ? WHITE : BLACK, rgb(r, g, b)), 1, new byte[] { 0, 0, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 0, 0 } /* Square of 1s with a border of 0s (and padding to 2 bytes per row) */); return new Image(getDisplay(), data); } private void clearImages() { for (Image image : images.values()) { if (image != null) { image.dispose(); } } images.clear(); } } /** * Distinguishes between shaders and programs. */ private static class Type implements ShaderPanel.UpdateShader { public final API.ResourceType type; public final String selectMessage; public final ShaderPanel.UpdateShader onSourceEdited; public Type( API.ResourceType type, String selectMessage, ShaderPanel.UpdateShader onSourceEdited) { this.type = type; this.selectMessage = selectMessage; this.onSourceEdited = onSourceEdited; } public static Type shader(ShaderPanel.UpdateShader onSourceEdited) { return new Type(API.ResourceType.ShaderResource, Messages.SELECT_SHADER, onSourceEdited); } public static Type program() { return new Type(API.ResourceType.ProgramResource, Messages.SELECT_PROGRAM, null); } @Override public void updateShader(Data data, String newSource) { onSourceEdited.updateShader(data, newSource); } public boolean isEditable() { return onSourceEdited != null; } } /** * Shader or program data. */ private static class Data { public final Service.Resource info; public Object resource; public Data(Service.Resource info) { this.info = info; } @Override public String toString() { String handle = info.getHandle(); String label = info.getLabel(); return (label.isEmpty()) ? handle : handle + " [" + label + "]"; } } }
/* * 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.transport; import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.Version; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.settings.ClusterDynamicSettings; import org.elasticsearch.cluster.settings.DynamicSettings; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.metrics.MeanMetric; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.BoundTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.common.util.concurrent.ConcurrentMapLong; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.elasticsearch.common.util.concurrent.FutureUtils; import org.elasticsearch.node.settings.NodeSettingsService; import org.elasticsearch.threadpool.ThreadPool; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import static org.elasticsearch.common.settings.ImmutableSettings.Builder.EMPTY_SETTINGS; /** * */ public class TransportService extends AbstractLifecycleComponent<TransportService> { private final AtomicBoolean started = new AtomicBoolean(false); protected final Transport transport; protected final ThreadPool threadPool; volatile ImmutableMap<String, TransportRequestHandler> serverHandlers = ImmutableMap.of(); final Object serverHandlersMutex = new Object(); final ConcurrentMapLong<RequestHolder> clientHandlers = ConcurrentCollections.newConcurrentMapLongWithAggressiveConcurrency(); final AtomicLong requestIds = new AtomicLong(); final CopyOnWriteArrayList<TransportConnectionListener> connectionListeners = new CopyOnWriteArrayList<>(); // An LRU (don't really care about concurrency here) that holds the latest timed out requests so if they // do show up, we can print more descriptive information about them final Map<Long, TimeoutInfoHolder> timeoutInfoHandlers = Collections.synchronizedMap(new LinkedHashMap<Long, TimeoutInfoHolder>(100, .75F, true) { protected boolean removeEldestEntry(Map.Entry eldest) { return size() > 100; } }); private final TransportService.Adapter adapter; // tracer log public static final String SETTING_TRACE_LOG_INCLUDE = "transport.tracer.include"; public static final String SETTING_TRACE_LOG_EXCLUDE = "transport.tracer.exclude"; private final ESLogger tracerLog; volatile String[] tracerLogInclude; volatile String[] tracelLogExclude; private final ApplySettings settingsListener = new ApplySettings(); public TransportService(Transport transport, ThreadPool threadPool) { this(EMPTY_SETTINGS, transport, threadPool); } @Inject public TransportService(Settings settings, Transport transport, ThreadPool threadPool) { super(settings); this.transport = transport; this.threadPool = threadPool; this.tracerLogInclude = settings.getAsArray(SETTING_TRACE_LOG_INCLUDE, Strings.EMPTY_ARRAY, true); this.tracelLogExclude = settings.getAsArray(SETTING_TRACE_LOG_EXCLUDE, new String[]{"internal:discovery/zen/fd*"}, true); tracerLog = Loggers.getLogger(logger, ".tracer"); adapter = createAdapter(); } protected Adapter createAdapter() { return new Adapter(); } // These need to be optional as they don't exist in the context of a transport client @Inject(optional = true) public void setDynamicSettings(NodeSettingsService nodeSettingsService, @ClusterDynamicSettings DynamicSettings dynamicSettings) { dynamicSettings.addDynamicSettings(SETTING_TRACE_LOG_INCLUDE, SETTING_TRACE_LOG_INCLUDE + ".*"); dynamicSettings.addDynamicSettings(SETTING_TRACE_LOG_EXCLUDE, SETTING_TRACE_LOG_EXCLUDE + ".*"); nodeSettingsService.addListener(settingsListener); } class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { String[] newTracerLogInclude = settings.getAsArray(SETTING_TRACE_LOG_INCLUDE, TransportService.this.tracerLogInclude, true); String[] newTracerLogExclude = settings.getAsArray(SETTING_TRACE_LOG_EXCLUDE, TransportService.this.tracelLogExclude, true); if (newTracerLogInclude == TransportService.this.tracerLogInclude && newTracerLogExclude == TransportService.this.tracelLogExclude) { return; } if (Arrays.equals(newTracerLogInclude, TransportService.this.tracerLogInclude) && Arrays.equals(newTracerLogExclude, TransportService.this.tracelLogExclude)) { return; } TransportService.this.tracerLogInclude = newTracerLogInclude; TransportService.this.tracelLogExclude = newTracerLogExclude; logger.info("tracer log updated to use include: {}, exclude: {}", newTracerLogInclude, newTracerLogExclude); } } // used for testing public void applySettings(Settings settings) { settingsListener.onRefreshSettings(settings); } @Override protected void doStart() throws ElasticsearchException { adapter.rxMetric.clear(); adapter.txMetric.clear(); transport.transportServiceAdapter(adapter); transport.start(); if (transport.boundAddress() != null && logger.isInfoEnabled()) { logger.info("{}", transport.boundAddress()); } boolean setStarted = started.compareAndSet(false, true); assert setStarted : "service was already started"; } @Override protected void doStop() throws ElasticsearchException { final boolean setStopped = started.compareAndSet(true, false); assert setStopped : "service has already been stopped"; try { transport.stop(); } finally { // in case the transport is not connected to our local node (thus cleaned on node disconnect) // make sure to clean any leftover on going handles for (Map.Entry<Long, RequestHolder> entry : clientHandlers.entrySet()) { final RequestHolder holderToNotify = clientHandlers.remove(entry.getKey()); if (holderToNotify != null) { // callback that an exception happened, but on a different thread since we don't // want handlers to worry about stack overflows threadPool.generic().execute(new Runnable() { @Override public void run() { holderToNotify.handler().handleException(new TransportException("transport stopped, action: " + holderToNotify.action())); } }); } } } } @Override protected void doClose() throws ElasticsearchException { transport.close(); } public boolean addressSupported(Class<? extends TransportAddress> address) { return transport.addressSupported(address); } public TransportInfo info() { BoundTransportAddress boundTransportAddress = boundAddress(); if (boundTransportAddress == null) { return null; } return new TransportInfo(boundTransportAddress, transport.profileBoundAddresses()); } public TransportStats stats() { return new TransportStats(transport.serverOpen(), adapter.rxMetric.count(), adapter.rxMetric.sum(), adapter.txMetric.count(), adapter.txMetric.sum()); } public BoundTransportAddress boundAddress() { return transport.boundAddress(); } public boolean nodeConnected(DiscoveryNode node) { return transport.nodeConnected(node); } public void connectToNode(DiscoveryNode node) throws ConnectTransportException { transport.connectToNode(node); } public void connectToNodeLight(DiscoveryNode node) throws ConnectTransportException { transport.connectToNodeLight(node); } public void disconnectFromNode(DiscoveryNode node) { transport.disconnectFromNode(node); } public void addConnectionListener(TransportConnectionListener listener) { connectionListeners.add(listener); } public void removeConnectionListener(TransportConnectionListener listener) { connectionListeners.remove(listener); } public <T extends TransportResponse> TransportFuture<T> submitRequest(DiscoveryNode node, String action, TransportRequest request, TransportResponseHandler<T> handler) throws TransportException { return submitRequest(node, action, request, TransportRequestOptions.EMPTY, handler); } public <T extends TransportResponse> TransportFuture<T> submitRequest(DiscoveryNode node, String action, TransportRequest request, TransportRequestOptions options, TransportResponseHandler<T> handler) throws TransportException { PlainTransportFuture<T> futureHandler = new PlainTransportFuture<>(handler); sendRequest(node, action, request, options, futureHandler); return futureHandler; } public <T extends TransportResponse> void sendRequest(final DiscoveryNode node, final String action, final TransportRequest request, final TransportResponseHandler<T> handler) { sendRequest(node, action, request, TransportRequestOptions.EMPTY, handler); } public <T extends TransportResponse> void sendRequest(final DiscoveryNode node, final String action, final TransportRequest request, final TransportRequestOptions options, TransportResponseHandler<T> handler) { if (node == null) { throw new ElasticsearchIllegalStateException("can't send request to a null node"); } final long requestId = newRequestId(); TimeoutHandler timeoutHandler = null; try { clientHandlers.put(requestId, new RequestHolder<>(handler, node, action, timeoutHandler)); if (started.get() == false) { // if we are not started the exception handling will remove the RequestHolder again and calls the handler to notify the caller. // it will only notify if the toStop code hasn't done the work yet. throw new TransportException("TransportService is closed stopped can't send request"); } if (options.timeout() != null) { timeoutHandler = new TimeoutHandler(requestId); timeoutHandler.future = threadPool.schedule(options.timeout(), ThreadPool.Names.GENERIC, timeoutHandler); } transport.sendRequest(node, requestId, action, request, options); } catch (final Throwable e) { // usually happen either because we failed to connect to the node // or because we failed serializing the message final RequestHolder holderToNotify = clientHandlers.remove(requestId); // if the scheduler raise a EsRejectedExecutionException (due to shutdown), we may have a timeout handler, but no future if (timeoutHandler != null) { FutureUtils.cancel(timeoutHandler.future); } // If holderToNotify == null then handler has already been taken care of. if (holderToNotify != null) { // callback that an exception happened, but on a different thread since we don't // want handlers to worry about stack overflows final SendRequestTransportException sendRequestException = new SendRequestTransportException(node, action, e); threadPool.executor(ThreadPool.Names.GENERIC).execute(new Runnable() { @Override public void run() { holderToNotify.handler().handleException(sendRequestException); } }); } } } private boolean shouldTraceAction(String action) { if (tracerLogInclude.length > 0) { if (Regex.simpleMatch(tracerLogInclude, action) == false) { return false; } } if (tracelLogExclude.length > 0) { return !Regex.simpleMatch(tracelLogExclude, action); } return true; } private long newRequestId() { return requestIds.getAndIncrement(); } public TransportAddress[] addressesFromString(String address) throws Exception { return transport.addressesFromString(address); } public void registerHandler(String action, TransportRequestHandler handler) { synchronized (serverHandlersMutex) { TransportRequestHandler handlerReplaced = serverHandlers.get(action); serverHandlers = MapBuilder.newMapBuilder(serverHandlers).put(action, handler).immutableMap(); if (handlerReplaced != null) { logger.warn("Registered two transport handlers for action {}, handlers: {}, {}", action, handler, handlerReplaced); } } } public void removeHandler(String action) { synchronized (serverHandlersMutex) { serverHandlers = MapBuilder.newMapBuilder(serverHandlers).remove(action).immutableMap(); } } protected TransportRequestHandler getHandler(String action) { return serverHandlers.get(action); } protected class Adapter implements TransportServiceAdapter { final MeanMetric rxMetric = new MeanMetric(); final MeanMetric txMetric = new MeanMetric(); @Override public void received(long size) { rxMetric.inc(size); } @Override public void sent(long size) { txMetric.inc(size); } @Override public void onRequestSent(DiscoveryNode node, long requestId, String action, TransportRequest request, TransportRequestOptions options) { if (traceEnabled() && shouldTraceAction(action)) { traceRequestSent(node, requestId, action, options); } } protected boolean traceEnabled() { return tracerLog.isTraceEnabled(); } @Override public void onResponseSent(long requestId, String action, TransportResponse response, TransportResponseOptions options) { if (traceEnabled() && shouldTraceAction(action)) { traceResponseSent(requestId, action); } } @Override public void onResponseSent(long requestId, String action, Throwable t) { if (traceEnabled() && shouldTraceAction(action)) { traceResponseSent(requestId, action, t); } } protected void traceResponseSent(long requestId, String action, Throwable t) { tracerLog.trace("[{}][{}] sent error response (error: [{}])", requestId, action, t.getMessage()); } @Override public void onResponseReceived(long requestId) { if (traceEnabled()) { // try to resolve the request DiscoveryNode sourceNode = null; String action = null; RequestHolder holder = clientHandlers.get(requestId); if (holder != null) { action = holder.action(); sourceNode = holder.node(); } else { // lets see if its in the timeout holder TimeoutInfoHolder timeoutInfoHolder = timeoutInfoHandlers.get(requestId); if (timeoutInfoHolder != null) { action = timeoutInfoHolder.action(); sourceNode = timeoutInfoHolder.node(); } } if (action == null) { traceUnresolvedResponse(requestId); } else if (shouldTraceAction(action)) { traceReceivedResponse(requestId, sourceNode, action); } } } @Override public void onRequestReceived(long requestId, String action) { if (traceEnabled() && shouldTraceAction(action)) { traceReceivedRequest(requestId, action); } } @Override public TransportRequestHandler handler(String action, Version version) { return serverHandlers.get(ActionNames.incomingAction(action, version)); } @Override public TransportResponseHandler remove(long requestId) { RequestHolder holder = clientHandlers.remove(requestId); if (holder == null) { // lets see if its in the timeout holder TimeoutInfoHolder timeoutInfoHolder = timeoutInfoHandlers.remove(requestId); if (timeoutInfoHolder != null) { long time = System.currentTimeMillis(); logger.warn("Received response for a request that has timed out, sent [{}ms] ago, timed out [{}ms] ago, action [{}], node [{}], id [{}]", time - timeoutInfoHolder.sentTime(), time - timeoutInfoHolder.timeoutTime(), timeoutInfoHolder.action(), timeoutInfoHolder.node(), requestId); } else { logger.warn("Transport response handler not found of id [{}]", requestId); } return null; } holder.cancel(); return holder.handler(); } @Override public void raiseNodeConnected(final DiscoveryNode node) { threadPool.generic().execute(new Runnable() { @Override public void run() { for (TransportConnectionListener connectionListener : connectionListeners) { connectionListener.onNodeConnected(node); } } }); } @Override public void raiseNodeDisconnected(final DiscoveryNode node) { try { for (final TransportConnectionListener connectionListener : connectionListeners) { threadPool.generic().execute(new Runnable() { @Override public void run() { connectionListener.onNodeDisconnected(node); } }); } for (Map.Entry<Long, RequestHolder> entry : clientHandlers.entrySet()) { RequestHolder holder = entry.getValue(); if (holder.node().equals(node)) { final RequestHolder holderToNotify = clientHandlers.remove(entry.getKey()); if (holderToNotify != null) { // callback that an exception happened, but on a different thread since we don't // want handlers to worry about stack overflows threadPool.generic().execute(new Runnable() { @Override public void run() { holderToNotify.handler().handleException(new NodeDisconnectedException(node, holderToNotify.action())); } }); } } } } catch (EsRejectedExecutionException ex) { logger.debug("Rejected execution on NodeDisconnected", ex); } } @Override public String action(String action, Version version) { return ActionNames.outgoingAction(action, version); } protected void traceReceivedRequest(long requestId, String action) { tracerLog.trace("[{}][{}] received request", requestId, action); } protected void traceResponseSent(long requestId, String action) { tracerLog.trace("[{}][{}] sent response", requestId, action); } protected void traceReceivedResponse(long requestId, DiscoveryNode sourceNode, String action) { tracerLog.trace("[{}][{}] received response from [{}]", requestId, action, sourceNode); } protected void traceUnresolvedResponse(long requestId) { tracerLog.trace("[{}] received response but can't resolve it to a request", requestId); } protected void traceRequestSent(DiscoveryNode node, long requestId, String action, TransportRequestOptions options) { tracerLog.trace("[{}][{}] sent to [{}] (timeout: [{}])", requestId, action, node, options.timeout()); } } class TimeoutHandler implements Runnable { private final long requestId; private final long sentTime = System.currentTimeMillis(); ScheduledFuture future; TimeoutHandler(long requestId) { this.requestId = requestId; } public long sentTime() { return sentTime; } @Override public void run() { if (future.isCancelled()) { return; } final RequestHolder holder = clientHandlers.remove(requestId); if (holder != null) { // add it to the timeout information holder, in case we are going to get a response later long timeoutTime = System.currentTimeMillis(); timeoutInfoHandlers.put(requestId, new TimeoutInfoHolder(holder.node(), holder.action(), sentTime, timeoutTime)); holder.handler().handleException(new ReceiveTimeoutTransportException(holder.node(), holder.action(), "request_id [" + requestId + "] timed out after [" + (timeoutTime - sentTime) + "ms]")); } } } static class TimeoutInfoHolder { private final DiscoveryNode node; private final String action; private final long sentTime; private final long timeoutTime; TimeoutInfoHolder(DiscoveryNode node, String action, long sentTime, long timeoutTime) { this.node = node; this.action = action; this.sentTime = sentTime; this.timeoutTime = timeoutTime; } public DiscoveryNode node() { return node; } public String action() { return action; } public long sentTime() { return sentTime; } public long timeoutTime() { return timeoutTime; } } static class RequestHolder<T extends TransportResponse> { private final TransportResponseHandler<T> handler; private final DiscoveryNode node; private final String action; private final TimeoutHandler timeout; RequestHolder(TransportResponseHandler<T> handler, DiscoveryNode node, String action, TimeoutHandler timeout) { this.handler = handler; this.node = node; this.action = action; this.timeout = timeout; } public TransportResponseHandler<T> handler() { return handler; } public DiscoveryNode node() { return this.node; } public String action() { return this.action; } public void cancel() { if (timeout != null) { FutureUtils.cancel(timeout.future); } } } }
/******************************************************************************* * * Pentaho Big Data * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.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 com.pentaho.big.data.bundles.impl.shim.hbase.table; import com.pentaho.big.data.bundles.impl.shim.hbase.connectionPool.HBaseConnectionHandle; import com.pentaho.big.data.bundles.impl.shim.hbase.connectionPool.HBaseConnectionPool; import com.pentaho.big.data.bundles.impl.shim.hbase.meta.HBaseValueMetaInterfaceFactoryImpl; import org.pentaho.bigdata.api.hbase.mapping.Mapping; import org.pentaho.bigdata.api.hbase.table.HBaseTable; import org.pentaho.bigdata.api.hbase.table.HBaseTableWriteOperationManager; import org.pentaho.bigdata.api.hbase.table.ResultScannerBuilder; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.hbase.shim.api.HBaseValueMeta; import org.pentaho.hbase.shim.spi.HBaseBytesUtilShim; import java.io.IOException; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Properties; /** * Created by bryan on 1/22/16. */ public class HBaseTableImpl implements HBaseTable { private static final Class<?> PKG = HBaseTableImpl.class; private final HBaseConnectionPool hBaseConnectionPool; private final HBaseValueMetaInterfaceFactoryImpl hBaseValueMetaInterfaceFactory; private final HBaseBytesUtilShim hBaseBytesUtilShim; private final String name; public HBaseTableImpl( HBaseConnectionPool hBaseConnectionPool, HBaseValueMetaInterfaceFactoryImpl hBaseValueMetaInterfaceFactory, HBaseBytesUtilShim hBaseBytesUtilShim, String name ) { this.hBaseConnectionPool = hBaseConnectionPool; this.hBaseValueMetaInterfaceFactory = hBaseValueMetaInterfaceFactory; this.hBaseBytesUtilShim = hBaseBytesUtilShim; this.name = name; } @Override public boolean exists() throws IOException { try ( HBaseConnectionHandle hBaseConnectionHandle = hBaseConnectionPool.getConnectionHandle() ) { return hBaseConnectionHandle.getConnection().tableExists( name ); } catch ( Exception e ) { throw new IOException( e ); } } @Override public boolean disabled() throws IOException { try ( HBaseConnectionHandle hBaseConnectionHandle = hBaseConnectionPool.getConnectionHandle() ) { return hBaseConnectionHandle.getConnection().isTableDisabled( name ); } catch ( Exception e ) { throw new IOException( e ); } } @Override public boolean available() throws IOException { try ( HBaseConnectionHandle hBaseConnectionHandle = hBaseConnectionPool.getConnectionHandle() ) { return hBaseConnectionHandle.getConnection().isTableAvailable( name ); } catch ( Exception e ) { throw new IOException( e ); } } @Override public void disable() throws IOException { try ( HBaseConnectionHandle hBaseConnectionHandle = hBaseConnectionPool.getConnectionHandle() ) { hBaseConnectionHandle.getConnection().disableTable( name ); } catch ( Exception e ) { throw new IOException( e ); } } @Override public void enable() throws IOException { try ( HBaseConnectionHandle hBaseConnectionHandle = hBaseConnectionPool.getConnectionHandle() ) { hBaseConnectionHandle.getConnection().enableTable( name ); } catch ( Exception e ) { throw new IOException( e ); } } @Override public void delete() throws IOException { try ( HBaseConnectionHandle hBaseConnectionHandle = hBaseConnectionPool.getConnectionHandle() ) { hBaseConnectionHandle.getConnection().deleteTable( name ); } catch ( Exception e ) { throw new IOException( e ); } } @Override public void create( List<String> colFamilyNames, Properties creationProps ) throws IOException { try ( HBaseConnectionHandle hBaseConnectionHandle = hBaseConnectionPool.getConnectionHandle() ) { hBaseConnectionHandle.getConnection().createTable( name, colFamilyNames, creationProps ); } catch ( Exception e ) { throw new IOException( e ); } } @Override public ResultScannerBuilder createScannerBuilder( byte[] keyLowerBound, byte[] keyUpperBound ) { return new ResultScannerBuilderImpl( hBaseConnectionPool, hBaseValueMetaInterfaceFactory, hBaseBytesUtilShim, name, 0, keyLowerBound, keyUpperBound ); } @Override public ResultScannerBuilder createScannerBuilder( Mapping tableMapping, String dateOrNumberConversionMaskForKey, String keyStartS, String keyStopS, String scannerCacheSize, LogChannelInterface log, VariableSpace vars ) throws KettleException { byte[] keyLowerBound = null; byte[] keyUpperBound = null; org.pentaho.hbase.shim.api.Mapping.KeyType keyType = org.pentaho.hbase.shim.api.Mapping.KeyType.valueOf( tableMapping.getKeyType().name() ); // Set up the scan if ( !Const.isEmpty( keyStartS ) ) { keyStartS = vars.environmentSubstitute( keyStartS ); String convM = dateOrNumberConversionMaskForKey; if ( tableMapping.getKeyType() == Mapping.KeyType.BINARY ) { // assume we have a hex encoded string keyLowerBound = HBaseValueMeta.encodeKeyValue( keyStartS, keyType, hBaseBytesUtilShim ); } else if ( tableMapping.getKeyType() != Mapping.KeyType.STRING ) { // allow a conversion mask in the start key field to override any // specified for // the key in the user specified fields String[] parts = keyStartS.split( "@" ); if ( parts.length == 2 ) { keyStartS = parts[ 0 ]; convM = parts[ 1 ]; } if ( !Const.isEmpty( convM ) && convM.length() > 0 ) { if ( tableMapping.getKeyType() == Mapping.KeyType.DATE || tableMapping.getKeyType() == Mapping.KeyType.UNSIGNED_DATE ) { SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern( convM ); try { Date d = sdf.parse( keyStartS ); keyLowerBound = HBaseValueMeta.encodeKeyValue( d, keyType, hBaseBytesUtilShim ); } catch ( ParseException e ) { throw new KettleException( BaseMessages.getString( PKG, "HBaseInput.Error.UnableToParseLowerBoundKeyValue", keyStartS ), e ); } } else { // Number type // Double/Float or Long/Integer DecimalFormat df = new DecimalFormat(); df.applyPattern( convM ); Number num = null; try { num = df.parse( keyStartS ); keyLowerBound = HBaseValueMeta.encodeKeyValue( num, keyType, hBaseBytesUtilShim ); } catch ( ParseException e ) { throw new KettleException( BaseMessages.getString( PKG, "HBaseInput.Error.UnableToParseLowerBoundKeyValue", keyStartS ), e ); } } } else { // just try it as a string keyLowerBound = HBaseValueMeta.encodeKeyValue( keyStartS, keyType, hBaseBytesUtilShim ); } } else { // it is a string keyLowerBound = HBaseValueMeta.encodeKeyValue( keyStartS, keyType, hBaseBytesUtilShim ); } if ( !Const.isEmpty( keyStopS ) ) { keyStopS = vars.environmentSubstitute( keyStopS ); convM = dateOrNumberConversionMaskForKey; if ( tableMapping.getKeyType() == Mapping.KeyType.BINARY ) { // assume we have a hex encoded string keyUpperBound = HBaseValueMeta.encodeKeyValue( keyStopS, keyType, hBaseBytesUtilShim ); } else if ( tableMapping.getKeyType() != Mapping.KeyType.STRING ) { // allow a conversion mask in the stop key field to override any // specified for // the key in the user specified fields String[] parts = keyStopS.split( "@" ); if ( parts.length == 2 ) { keyStopS = parts[ 0 ]; convM = parts[ 1 ]; } if ( !Const.isEmpty( convM ) && convM.length() > 0 ) { if ( tableMapping.getKeyType() == Mapping.KeyType.DATE || tableMapping.getKeyType() == Mapping.KeyType.UNSIGNED_DATE ) { SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern( convM ); try { Date d = sdf.parse( keyStopS ); keyUpperBound = HBaseValueMeta.encodeKeyValue( d, keyType, hBaseBytesUtilShim ); } catch ( ParseException e ) { throw new KettleException( BaseMessages.getString( PKG, "HBaseInput.Error.UnableToParseUpperBoundKeyValue", keyStopS ), e ); } } else { // Number type // Double/Float or Long/Integer DecimalFormat df = new DecimalFormat(); df.applyPattern( convM ); Number num = null; try { num = df.parse( keyStopS ); keyUpperBound = HBaseValueMeta.encodeKeyValue( num, keyType, hBaseBytesUtilShim ); } catch ( ParseException e ) { throw new KettleException( BaseMessages.getString( PKG, "HBaseInput.Error.UnableToParseUpperBoundKeyValue", keyStopS ), e ); } } } else { // just try it as a string keyUpperBound = HBaseValueMeta.encodeKeyValue( keyStopS, keyType, hBaseBytesUtilShim ); } } else { // it is a string keyUpperBound = HBaseValueMeta.encodeKeyValue( keyStopS, keyType, hBaseBytesUtilShim ); } } } int cacheSize = 0; // set any user-specified scanner caching if ( !Const.isEmpty( scannerCacheSize ) ) { String temp = vars.environmentSubstitute( scannerCacheSize ); cacheSize = Integer.parseInt( temp ); if ( log != null ) { log.logBasic( BaseMessages .getString( PKG, "HBaseInput.Message.SettingScannerCaching", cacheSize ) ); } } return new ResultScannerBuilderImpl( hBaseConnectionPool, hBaseValueMetaInterfaceFactory, hBaseBytesUtilShim, name, cacheSize, keyLowerBound, keyUpperBound ); } @Override public List<String> getColumnFamilies() throws IOException { try ( HBaseConnectionHandle hBaseConnectionHandle = hBaseConnectionPool.getConnectionHandle() ) { return hBaseConnectionHandle.getConnection().getTableFamiles( name ); } catch ( Exception e ) { throw new IOException( e ); } } @Override public boolean keyExists( byte[] key ) throws IOException { try ( HBaseConnectionHandle hBaseConnectionHandle = hBaseConnectionPool.getConnectionHandle( name ) ) { return hBaseConnectionHandle.getConnection().sourceTableRowExists( key ); } catch ( Exception e ) { throw new IOException( e ); } } @Override public HBaseTableWriteOperationManager createWriteOperationManager( Long writeBufferSize ) throws IOException { Properties targetTableProps = new Properties(); if ( writeBufferSize != null ) { targetTableProps.setProperty( org.pentaho.hbase.shim.spi.HBaseConnection.HTABLE_WRITE_BUFFER_SIZE_KEY, writeBufferSize.toString() ); } return new HBaseTableWriteOperationManagerImpl( hBaseConnectionPool.getConnectionHandle( name, targetTableProps ), writeBufferSize != null ); } @Override public void close() throws IOException { } }
/* * Copyright (C) 2017 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 androidx.appcompat.widget; import static android.view.View.SYSTEM_UI_FLAG_LOW_PROFILE; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX; import android.content.Context; import android.text.TextUtils; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.accessibility.AccessibilityManager; import androidx.annotation.RestrictTo; import androidx.core.view.ViewCompat; import androidx.core.view.ViewConfigurationCompat; /** * Event handler used used to emulate the behavior of {@link View#setTooltipText(CharSequence)} * prior to API level 26. * * @hide */ @RestrictTo(LIBRARY_GROUP_PREFIX) class TooltipCompatHandler implements View.OnLongClickListener, View.OnHoverListener, View.OnAttachStateChangeListener { private static final String TAG = "TooltipCompatHandler"; private static final long LONG_CLICK_HIDE_TIMEOUT_MS = 2500; private static final long HOVER_HIDE_TIMEOUT_MS = 15000; private static final long HOVER_HIDE_TIMEOUT_SHORT_MS = 3000; private final View mAnchor; private final CharSequence mTooltipText; private final int mHoverSlop; private final Runnable mShowRunnable = () -> show(false); private final Runnable mHideRunnable = this::hide; private int mAnchorX; private int mAnchorY; private TooltipPopup mPopup; private boolean mFromTouch; private boolean mForceNextChangeSignificant; // The handler currently scheduled to show a tooltip, triggered by a hover // (there can be only one). private static TooltipCompatHandler sPendingHandler; // The handler currently showing a tooltip (there can be only one). private static TooltipCompatHandler sActiveHandler; /** * Set the tooltip text for the view. * * @param view view to set the tooltip on * @param tooltipText the tooltip text */ public static void setTooltipText(View view, CharSequence tooltipText) { // The code below is not attempting to update the tooltip text // for a pending or currently active tooltip, because it may lead // to updating the wrong tooltip in in some rare cases (e.g. when // action menu item views are recycled). Instead, the tooltip is // canceled/hidden. This might still be the wrong tooltip, // but hiding a wrong tooltip is less disruptive UX. if (sPendingHandler != null && sPendingHandler.mAnchor == view) { setPendingHandler(null); } if (TextUtils.isEmpty(tooltipText)) { if (sActiveHandler != null && sActiveHandler.mAnchor == view) { sActiveHandler.hide(); } view.setOnLongClickListener(null); view.setLongClickable(false); view.setOnHoverListener(null); } else { new TooltipCompatHandler(view, tooltipText); } } private TooltipCompatHandler(View anchor, CharSequence tooltipText) { mAnchor = anchor; mTooltipText = tooltipText; mHoverSlop = ViewConfigurationCompat.getScaledHoverSlop( ViewConfiguration.get(mAnchor.getContext())); forceNextChangeSignificant(); mAnchor.setOnLongClickListener(this); mAnchor.setOnHoverListener(this); } @Override public boolean onLongClick(View v) { mAnchorX = v.getWidth() / 2; mAnchorY = v.getHeight() / 2; show(true); return true; } @Override public boolean onHover(View v, MotionEvent event) { if (mPopup != null && mFromTouch) { return false; } AccessibilityManager manager = (AccessibilityManager) mAnchor.getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (manager.isEnabled() && manager.isTouchExplorationEnabled()) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_HOVER_MOVE: if (mAnchor.isEnabled() && mPopup == null && updateAnchorPos(event)) { setPendingHandler(this); } break; case MotionEvent.ACTION_HOVER_EXIT: forceNextChangeSignificant(); hide(); break; } return false; } @Override public void onViewAttachedToWindow(View v) { // no-op. } @Override public void onViewDetachedFromWindow(View v) { hide(); } @SuppressWarnings("deprecation") void show(boolean fromTouch) { if (!ViewCompat.isAttachedToWindow(mAnchor)) { return; } setPendingHandler(null); if (sActiveHandler != null) { sActiveHandler.hide(); } sActiveHandler = this; mFromTouch = fromTouch; mPopup = new TooltipPopup(mAnchor.getContext()); mPopup.show(mAnchor, mAnchorX, mAnchorY, mFromTouch, mTooltipText); // Only listen for attach state change while the popup is being shown. mAnchor.addOnAttachStateChangeListener(this); final long timeout; if (mFromTouch) { timeout = LONG_CLICK_HIDE_TIMEOUT_MS; } else if ((ViewCompat.getWindowSystemUiVisibility(mAnchor) & SYSTEM_UI_FLAG_LOW_PROFILE) == SYSTEM_UI_FLAG_LOW_PROFILE) { timeout = HOVER_HIDE_TIMEOUT_SHORT_MS - ViewConfiguration.getLongPressTimeout(); } else { timeout = HOVER_HIDE_TIMEOUT_MS - ViewConfiguration.getLongPressTimeout(); } mAnchor.removeCallbacks(mHideRunnable); mAnchor.postDelayed(mHideRunnable, timeout); } void hide() { if (sActiveHandler == this) { sActiveHandler = null; if (mPopup != null) { mPopup.hide(); mPopup = null; forceNextChangeSignificant(); mAnchor.removeOnAttachStateChangeListener(this); } else { Log.e(TAG, "sActiveHandler.mPopup == null"); } } if (sPendingHandler == this) { setPendingHandler(null); } mAnchor.removeCallbacks(mHideRunnable); } private static void setPendingHandler(TooltipCompatHandler handler) { if (sPendingHandler != null) { sPendingHandler.cancelPendingShow(); } sPendingHandler = handler; if (sPendingHandler != null) { sPendingHandler.scheduleShow(); } } private void scheduleShow() { mAnchor.postDelayed(mShowRunnable, ViewConfiguration.getLongPressTimeout()); } private void cancelPendingShow() { mAnchor.removeCallbacks(mShowRunnable); } /** * Update the anchor position if it significantly (that is by at least mHoverSlope) * different from the previously stored position. Ignoring insignificant changes * filters out the jitter which is typical for such input sources as stylus. * * @return True if the position has been updated. */ private boolean updateAnchorPos(MotionEvent event) { final int newAnchorX = (int) event.getX(); final int newAnchorY = (int) event.getY(); if (mForceNextChangeSignificant || Math.abs(newAnchorX - mAnchorX) > mHoverSlop || Math.abs(newAnchorY - mAnchorY) > mHoverSlop) { mAnchorX = newAnchorX; mAnchorY = newAnchorY; mForceNextChangeSignificant = false; return true; } return false; } /** * Ensure that the next change is considered significant. */ private void forceNextChangeSignificant() { mForceNextChangeSignificant = true; } }
/* * Copyright 2008 The MITRE Corporation (http://www.mitre.org/). 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 org.mitre.mrald.output; import java.sql.*; import java.io.*; import org.mitre.mrald.control.*; import java.util.HashMap; import org.mitre.mrald.util.*; /** * This Output class is the HTML output returned when a User clicks on the * Retrieve Data button on the original Update form. * *@author Gail Hamilton *@created January 8, 2004 *@version 1.0 */ public class UpdateListOutput extends HTMLOutput { private String keyTable = null; private String[] primaryKeyCols = null; private String datasource = null; private DBMetaData md = null; private HashMap fkInfo; private String successRedir; /** * Constructor for the HTMLOutput object * *@since */ public UpdateListOutput() { super(); } /** * This is method that is called from the Workflow. For this step, the * limits are set and the database connection is established. The passed * MsgObject is searched for special DB connection information (looking for * a Datasource name with the value representing the name of the properties * file that houses the connection information). If none is found, the * default is used. * *@param msg Description of * Parameter *@exception org.mitre.mrald.control.WorkflowStepException Description of * Exception *@since 1.2 */ public @Override void execute( MsgObject msg ) throws org.mitre.mrald.control.WorkflowStepException { successRedir = msg.getValue("SuccessUrl")[0]; //Get the value that contains the column Name, and table Name of the label column. keyTable = msg.getValue( "table" )[0]; datasource = msg.getValue( "Datasource" )[0]; keyTable = MiscUtils.replace( keyTable, "\"", "" ); primaryKeyCols = msg.getValue( "PrimaryKey" ); String datasource = msg.getValue( FormTags.DATASOURCE_TAG )[0]; md = MetaData.getDbMetaData( datasource ); TableMetaData tableInfo = null; //If the primary key is not specified then look up in the database if ( primaryKeyCols.length == 0 ) { if ( keyTable != null ) { tableInfo = md.getTableMetaData( keyTable ); primaryKeyCols = ( String[] ) tableInfo.getPrimaryKeys().toArray(); } else { throw new org.mitre.mrald.control.WorkflowStepException( "You must have a table specified to Update." ); } } fkInfo = getFKInfo( msg ); User user = ( User ) msg.getReq().getSession().getAttribute( Config.getProperty( "cookietag" ) ); if ( user == null ) { throw new org.mitre.mrald.control.WorkflowStepException( "You must login to perform this operation" ); } super.execute( msg ); } /** * Retrieve the contents of the result set and send them to out as the guts * of an HTML table. This includes only the header row with the field names * as column titles and the each query result as table rows. The * <table> * , <HTML>, <body>, <title>and <style>tags are not included. * *@param out the output stream *@exception ServletException Description of the Exception *@exception IOException Description of the Exception *@exception SQLException Description of the Exception *@since 1.2 */ public @Override void printBody( ) throws IOException, SQLException { out.println( "<table><tr>" ); out.println( "<form enctype='x-www-form-urlencoded' action='FormSubmit' method='POST' name=\"o\">" ); if( datasource != null && !datasource.equals(Config.EMPTY_STR) ) { out.println( "<input type=\"hidden\" name=\"Datasource\" value=\"" + datasource + "\" />"); } out.println( "<input name=\"Schema\" type=\"hidden\" value=\"public\"><input name=\"form\" type=\"hidden\" value=\"Update Table " + keyTable + "\"><input value='UpdateRow' name='workflow' type='hidden'>" ); /* * niceNames[] contains the column names, either from the db field name or specified in the HTML form */ StringBuffer headerRow = new StringBuffer( "<tr>" ); for ( int p = 0; p < niceNames.length; p++ ) { headerRow.append( "<th>" + niceNames[p] + "</th>" ); } headerRow.append( "<th>Update</th></tr>" ); out.println( headerRow.toString() ); /* * Iterate through the ResultSet and extract the rows * if a custom format exists, use it, otherwise print the column name */ int row_count = 0; float fileSize = 0; String formattedString; ResultSetMetaData rsmd = rs.getMetaData(); String fkValues = ""; while ( ( rs.next() ) && ( ( lineLimitSize == -1 ) || ( row_count < lineLimitSize ) ) && ( ( mbLimitSize == -1 ) || ( fileSize < mbLimitSize ) ) ) { out.print( "<tr>" ); boolean isPk = false; // boolean isFk = false; String pkValues = ""; for ( int i = 0; i < niceNames.length; i++ ) { String colName = rsmd.getColumnName( i + 1 ); for ( int j = 0; j < primaryKeyCols.length; j++ ) { if ( primaryKeyCols[j].equals( colName ) ) { isPk = true; pkValues = pkValues + "&" + colName + "="; } } if ( fkInfo.containsKey( colName ) ) { fkValues = fkValues + ( String ) fkInfo.get( colName ); } /* * Custom formatting here */ if ( classNames[i].equals( "Timestamp" ) ) { formattedString = getAndFormat( rs.getTimestamp( i + 1 ), formats[i] ); if ( isPk ) { pkValues = pkValues + rs.getTimestamp( i + 1 ); } } else if ( classNames[i].equals( "BigDecimal" ) ) { formattedString = getAndFormat( rs.getBigDecimal( i + 1 ), formats[i] ); if ( isPk ) { pkValues = pkValues + rs.getBigDecimal( i + 1 ); } } else { if ( isPk ) { pkValues = pkValues + rs.getString( i + 1 ); } formattedString = rs.getString( i + 1 ); } out.print( "<td>" + formattedString + "</td>" ); try { fileSize += formattedString.length() + 9; //9 for tags } catch ( NullPointerException npe ) { fileSize += 13; //13 for tags and "null" } isPk = false; } // ENDFOR //Add the checkbox with the associated information String updateInfo = "<td><input type='hidden' name='updateRow" + row_count + "' value=\"Table" + FormTags.NAMEVALUE_TOKEN_STR + keyTable + "~Column" + FormTags.NAMEVALUE_TOKEN_STR + primaryKeyCols[0] + "~Value" + FormTags.NAMEVALUE_TOKEN_STR + rs.getString( 1 ) + "\">"; out.println( updateInfo ); updateInfo = "<input type='button' name='updateRow" + row_count + "' value='Update' onclick=\"dest='Update.jsp?datasource=" + datasource + "&tableName=" + keyTable + MiscUtils.checkApostrophe( pkValues ) + fkValues + "&SuccessUrl=" + successRedir + "'; location=dest\">"; out.println( updateInfo ); String deleteInfo = "<input type='button' name='deleteRow" + row_count + "' value='Delete' onclick=\"location='Delete.jsp?datasource=" + datasource + "&tableName=" + keyTable + MiscUtils.checkApostrophe( pkValues ) + "';\"></td>"; out.println( deleteInfo ); out.println( "</tr>" ); row_count++; fileSize += 10; //for row tags // for very large result sets, break it up in several tables if ( row_count / 1000.0 == ( int ) ( row_count / 1000.0 ) ) { out.println( "</table><table border='1' cellpadding='3'>" + headerRow.toString() ); } } recordsReturned = row_count; bytesReturned = fileSize; } /** * Need to get the values for the Table Name of the label , and the column * name e.g. In format "Table:VolumeLabel~Column:VolumeId" * *@param msg Description of the Parameter *@return The javaScript value *@since 1.2 */ private HashMap<String,String> getFKInfo( MsgObject msg ) { int i = 1; String[] fks = msg.getValue( "fKey" + i ); HashMap<String,String> linkInfo = new HashMap<String,String>(); String fKeyInfo; while ( i < 100 ) { if ( ( fks == null ) || ( fks.length == 0 ) || ( fks[0].equals( "" ) ) ) { i++; fks = msg.getValue( "fKey" + i ); continue; } fKeyInfo = "&" + "fKey" + i + "=" + fks[0]; fKeyInfo = fKeyInfo + "&" + "fKeyTable" + i + "=" + msg.getValue( "fKeyTable" + i )[0]; fKeyInfo = fKeyInfo + "&" + "fKeyId" + i + "=" + msg.getValue( "fKeyId" + i )[0]; fKeyInfo = fKeyInfo + "&" + "fKeyList" + i + "=" + msg.getValue( "fKeyList" + i )[0]; linkInfo.put( fks[0], fKeyInfo ); i++; fks = msg.getValue( "fKey" + i ); } return linkInfo; } /** * Need to get the values for the Table Name of the label , and the column * name e.g. In format "Table:VolumeLabel~Column:VolumeId" * *@param md Description of the Parameter *@param tableInfo Description of the Parameter *@return The javaScript value *@since 1.2 */ /* PM: Never used! private HashMap getFKInfo( DBMetaData md, TableMetaData tableInfo ) { StringBuffer fKeyInfo = new StringBuffer(); HashMap linkInfo = new HashMap(); String[] columns = ( String[] ) tableInfo.getColumnNames().toArray(); String tableName = tableInfo.getName(); for ( int i = 0; i < columns.length; i++ ) { fKeyInfo = new StringBuffer(); Link link = md.getFKLinkData( tableName, columns[i] ); fKeyInfo.append( "&" + "fKey" + i + "=" + columns[i] ); fKeyInfo.append( "&" + "fKeyTable" + i + "=" + link.getFtable() ); fKeyInfo.append( "&" + "fKeyId" + i + "=" + link.getPcolumn() ); fKeyInfo.append( "&" + "fKeyList" + i + "=" + link.getFcolumn() ); linkInfo.put( columns[i], fKeyInfo.toString() ); } return linkInfo; }*/ /** * Need to get the values for the Table Name of the label , and the column * name e.g. In format "Table:VolumeLabel~Column:VolumeId" * *@return The javaScript value *@since 1.2 */ /* PM: Never used! private String getJavaScript() { //String js = "<script type=\"text/javascript\"> String js = "\n function CheckAll() { \n alert('In CheckAll'); \n var len = form.elements.length;\n" + " for (var i = 0; i < len; i++){ \n var e = form.elements[i]; \n if (e.type==\"checkbox\") { e.checked = true;} \n } \n } \n" + " function ClearAll() { \n var ml = document.o; \n var len = ml.elements.length;\n" + " for (var i = 0; i < len; i++){ \n var e = form.elements[i];\n if (e.type==\"checkbox\") { e.checked = false;} \n } \n } \n "; //</script>\n return js; }*/ }
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.idea.maven; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.StdModuleTypes; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.rt.execution.junit.FileComparisonFailure; import com.intellij.testFramework.EdtTestUtil; import com.intellij.testFramework.PsiTestUtil; import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import com.intellij.util.ExceptionUtil; import gnu.trove.THashSet; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.maven.indices.MavenIndicesManager; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.server.MavenServerManager; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; import java.awt.*; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; import java.util.List; import java.util.concurrent.TimeUnit; public abstract class MavenTestCase extends UsefulTestCase { protected static final MavenConsole NULL_MAVEN_CONSOLE = new NullMavenConsole(); // should not be static protected static MavenProgressIndicator EMPTY_MAVEN_PROCESS = new MavenProgressIndicator(new EmptyProgressIndicator(ModalityState.NON_MODAL)); private File ourTempDir; protected IdeaProjectTestFixture myTestFixture; protected Project myProject; protected File myDir; protected VirtualFile myProjectRoot; protected VirtualFile myProjectPom; protected List<VirtualFile> myAllPoms = new ArrayList<>(); @Override protected void setUp() throws Exception { super.setUp(); ensureTempDirCreated(); myDir = new File(ourTempDir, getTestName(false)); FileUtil.ensureExists(myDir); setUpFixtures(); myProject = myTestFixture.getProject(); MavenWorkspaceSettingsComponent.getInstance(myProject).loadState(new MavenWorkspaceSettings()); String home = getTestMavenHome(); if (home != null) { getMavenGeneralSettings().setMavenHome(home); } EdtTestUtil.runInEdtAndWait(() -> { restoreSettingsFile(); ApplicationManager.getApplication().runWriteAction(() -> { try { setUpInWriteAction(); } catch (Throwable e) { try { tearDown(); } catch (Exception e1) { e1.printStackTrace(); } throw new RuntimeException(e); } }); }); } @Override protected void tearDown() throws Exception { try { MavenServerManager.getInstance().shutdown(true); MavenArtifactDownloader.awaitQuiescence(100, TimeUnit.SECONDS); myProject = null; EdtTestUtil.runInEdtAndWait(() -> tearDownFixtures()); MavenIndicesManager.getInstance().clear(); } finally { super.tearDown(); FileUtil.delete(myDir); // cannot use reliably the result of the com.intellij.openapi.util.io.FileUtil.delete() method // because com.intellij.openapi.util.io.FileUtilRt.deleteRecursivelyNIO() does not honor this contract if (myDir.exists()) { System.err.println("Cannot delete " + myDir); //printDirectoryContent(myDir); myDir.deleteOnExit(); } resetClassFields(getClass()); } } private void ensureTempDirCreated() throws IOException { if (ourTempDir != null) return; ourTempDir = new File(FileUtil.getTempDirectory(), "mavenTests"); FileUtil.delete(ourTempDir); FileUtil.ensureExists(ourTempDir); } protected void setUpFixtures() throws Exception { myTestFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getName()).getFixture(); myTestFixture.setUp(); } protected void setUpInWriteAction() throws Exception { File projectDir = new File(myDir, "project"); projectDir.mkdirs(); myProjectRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectDir); } private static void printDirectoryContent(File dir) { File[] files = dir.listFiles(); if (files == null) return; for (File file: files) { System.out.println(file.getAbsolutePath()); if (file.isDirectory()) { printDirectoryContent(file); } } } protected void tearDownFixtures() throws Exception { try { myTestFixture.tearDown(); } finally { myTestFixture = null; } } private void resetClassFields(final Class<?> aClass) { if (aClass == null) return; final Field[] fields = aClass.getDeclaredFields(); for (Field field: fields) { final int modifiers = field.getModifiers(); if ((modifiers & Modifier.FINAL) == 0 && (modifiers & Modifier.STATIC) == 0 && !field.getType().isPrimitive()) { field.setAccessible(true); try { field.set(this, null); } catch (IllegalAccessException e) { e.printStackTrace(); } } } if (aClass == MavenTestCase.class) return; resetClassFields(aClass.getSuperclass()); } @Override protected void runTest() throws Throwable { try { if (runInWriteAction()) { try { WriteAction.runAndWait(() -> super.runTest()); } catch (Throwable throwable) { ExceptionUtil.rethrowAllAsUnchecked(throwable); } } else { super.runTest(); } } catch (Exception throwable) { Throwable each = throwable; do { if (each instanceof HeadlessException) { printIgnoredMessage("Doesn't work in Headless environment"); return; } } while ((each = each.getCause()) != null); throw throwable; } } @Override protected void invokeTestRunnable(@NotNull Runnable runnable) { runnable.run(); } protected boolean runInWriteAction() { return false; } protected static String getRoot() { if (SystemInfo.isWindows) return "c:"; return ""; } protected static String getEnvVar() { if (SystemInfo.isWindows) { return "TEMP"; } else if (SystemInfo.isLinux) return "HOME"; return "TMPDIR"; } protected MavenGeneralSettings getMavenGeneralSettings() { return MavenProjectsManager.getInstance(myProject).getGeneralSettings(); } protected MavenImportingSettings getMavenImporterSettings() { return MavenProjectsManager.getInstance(myProject).getImportingSettings(); } protected String getRepositoryPath() { String path = getRepositoryFile().getPath(); return FileUtil.toSystemIndependentName(path); } protected File getRepositoryFile() { return getMavenGeneralSettings().getEffectiveLocalRepository(); } protected void setRepositoryPath(String path) { getMavenGeneralSettings().setLocalRepository(path); } protected String getProjectPath() { return myProjectRoot.getPath(); } protected String getParentPath() { return myProjectRoot.getParent().getPath(); } protected String pathFromBasedir(String relPath) { return pathFromBasedir(myProjectRoot, relPath); } protected static String pathFromBasedir(VirtualFile root, String relPath) { return FileUtil.toSystemIndependentName(root.getPath() + "/" + relPath); } protected VirtualFile updateSettingsXml(String content) throws IOException { return updateSettingsXmlFully(createSettingsXmlContent(content)); } protected VirtualFile updateSettingsXmlFully(@NonNls @Language("XML") String content) throws IOException { File ioFile = new File(myDir, "settings.xml"); ioFile.createNewFile(); VirtualFile f = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile); setFileContent(f, content, true); getMavenGeneralSettings().setUserSettingsFile(f.getPath()); return f; } protected void deleteSettingsXml() throws IOException { WriteCommandAction.writeCommandAction(myProject).run(() -> { VirtualFile f = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(myDir, "settings.xml")); if (f != null) f.delete(this); }); } private static String createSettingsXmlContent(String content) { String mirror = System.getProperty("idea.maven.test.mirror", // use JB maven proxy server for internal use by default, see details at // https://confluence.jetbrains.com/display/JBINT/Maven+proxy+server "http://maven.labs.intellij.net/repo1"); return "<settings>" + content + "<mirrors>" + " <mirror>" + " <id>jb-central-proxy</id>" + " <url>" + mirror + "</url>" + " <mirrorOf>external:*,!flex-repository</mirrorOf>" + " </mirror>" + "</mirrors>" + "</settings>"; } protected void restoreSettingsFile() throws IOException { updateSettingsXml(""); } protected Module createModule(String name) { return createModule(name, StdModuleTypes.JAVA); } protected Module createModule(final String name, final ModuleType type) { try { return WriteCommandAction.writeCommandAction(myProject).compute(() -> { VirtualFile f = createProjectSubFile(name + "/" + name + ".iml"); Module module = ModuleManager.getInstance(myProject).newModule(f.getPath(), type.getId()); PsiTestUtil.addContentRoot(module, f.getParent()); return module; }); } catch (IOException e) { throw new RuntimeException(e); } } protected VirtualFile createProjectPom(@NotNull @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) { return myProjectPom = createPomFile(myProjectRoot, xml); } protected VirtualFile createModulePom(String relativePath, @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) { return createPomFile(createProjectSubDir(relativePath), xml); } protected VirtualFile createPomFile(final VirtualFile dir, @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) { VirtualFile f = dir.findChild("pom.xml"); if (f == null) { try { f = WriteAction.computeAndWait(() -> { VirtualFile res = dir.createChildData(null, "pom.xml"); return res; }); } catch (IOException e) { throw new RuntimeException(e); } myAllPoms.add(f); } setFileContent(f, createPomXml(xml), true); return f; } @NonNls @Language(value = "XML") public static String createPomXml(@NonNls @Language(value = "XML", prefix = "<project>", suffix = "</project>") String xml) { return "<?xml version=\"1.0\"?>" + "<project xmlns=\"http://maven.apache.org/POM/4.0.0\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">" + " <modelVersion>4.0.0</modelVersion>" + xml + "</project>"; } protected VirtualFile createProfilesXmlOldStyle(String xml) { return createProfilesFile(myProjectRoot, xml, true); } protected VirtualFile createProfilesXmlOldStyle(String relativePath, String xml) { return createProfilesFile(createProjectSubDir(relativePath), xml, true); } protected VirtualFile createProfilesXml(String xml) { return createProfilesFile(myProjectRoot, xml, false); } protected VirtualFile createProfilesXml(String relativePath, String xml) { return createProfilesFile(createProjectSubDir(relativePath), xml, false); } private static VirtualFile createProfilesFile(VirtualFile dir, String xml, boolean oldStyle) { return createProfilesFile(dir, createValidProfiles(xml, oldStyle)); } protected VirtualFile createFullProfilesXml(String content) { return createProfilesFile(myProjectRoot, content); } protected VirtualFile createFullProfilesXml(String relativePath, String content) { return createProfilesFile(createProjectSubDir(relativePath), content); } private static VirtualFile createProfilesFile(final VirtualFile dir, String content) { VirtualFile f = dir.findChild("profiles.xml"); if (f == null) { try { f = WriteAction.computeAndWait(() -> { VirtualFile res = dir.createChildData(null, "profiles.xml"); return res; }); } catch (IOException e) { throw new RuntimeException(e); } } setFileContent(f, content, true); return f; } @Language("XML") private static String createValidProfiles(String xml, boolean oldStyle) { if (oldStyle) { return "<?xml version=\"1.0\"?>" + "<profiles>" + xml + "</profiles>"; } return "<?xml version=\"1.0\"?>" + "<profilesXml>" + "<profiles>" + xml + "</profiles>" + "</profilesXml>"; } protected void deleteProfilesXml() throws IOException { WriteCommandAction.writeCommandAction(myProject).run(() -> { VirtualFile f = myProjectRoot.findChild("profiles.xml"); if (f != null) f.delete(this); }); } protected void createStdProjectFolders() { createProjectSubDirs("src/main/java", "src/main/resources", "src/test/java", "src/test/resources"); } protected void createProjectSubDirs(String... relativePaths) { for (String path: relativePaths) { createProjectSubDir(path); } } protected VirtualFile createProjectSubDir(String relativePath) { File f = new File(getProjectPath(), relativePath); f.mkdirs(); return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f); } protected VirtualFile createProjectSubFile(String relativePath) throws IOException { File f = new File(getProjectPath(), relativePath); f.getParentFile().mkdirs(); f.createNewFile(); return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f); } protected VirtualFile createProjectSubFile(String relativePath, String content) throws IOException { VirtualFile file = createProjectSubFile(relativePath); setFileContent(file, content, false); return file; } private static void setFileContent(final VirtualFile file, final String content, final boolean advanceStamps) { try { WriteAction.runAndWait(() -> { if (advanceStamps) { file.setBinaryContent(content.getBytes(), -1, file.getTimeStamp() + 4000); } else { file.setBinaryContent(content.getBytes(), file.getModificationStamp(), file.getTimeStamp()); } }); } catch (IOException e) { throw new RuntimeException(e); } } protected static <T, U> void assertOrderedElementsAreEqual(Collection<U> actual, Collection<T> expected) { assertOrderedElementsAreEqual(actual, expected.toArray()); } protected static <T> void assertUnorderedElementsAreEqual(Collection<T> actual, Collection<T> expected) { assertEquals(new HashSet<>(expected), new HashSet<>(actual)); } protected static void assertUnorderedPathsAreEqual(Collection<String> actual, Collection<String> expected) { assertEquals(new SetWithToString<>(new THashSet<>(expected, FileUtil.PATH_HASHING_STRATEGY)), new SetWithToString<>(new THashSet<>(actual, FileUtil.PATH_HASHING_STRATEGY))); } protected static <T> void assertUnorderedElementsAreEqual(T[] actual, T... expected) { assertUnorderedElementsAreEqual(Arrays.asList(actual), expected); } protected static <T> void assertUnorderedElementsAreEqual(Collection<T> actual, T... expected) { assertUnorderedElementsAreEqual(actual, Arrays.asList(expected)); } protected static <T, U> void assertOrderedElementsAreEqual(Collection<U> actual, T... expected) { String s = "\nexpected: " + Arrays.asList(expected) + "\nactual: " + new ArrayList<>(actual); assertEquals(s, expected.length, actual.size()); List<U> actualList = new ArrayList<>(actual); for (int i = 0; i < expected.length; i++) { T expectedElement = expected[i]; U actualElement = actualList.get(i); assertEquals(s, expectedElement, actualElement); } } protected static <T> void assertContain(List<? extends T> actual, T... expected) { List<T> expectedList = Arrays.asList(expected); assertTrue("expected: " + expectedList + "\n" + "actual: " + actual.toString(), actual.containsAll(expectedList)); } protected static <T> void assertDoNotContain(List<T> actual, T... expected) { List<T> actualCopy = new ArrayList<>(actual); actualCopy.removeAll(Arrays.asList(expected)); assertEquals(actual.toString(), actualCopy.size(), actual.size()); } protected static void assertUnorderedLinesWithFile(String filePath, String expectedText) { try { assertSameLinesWithFile(filePath, expectedText); } catch (FileComparisonFailure e) { String expected = e.getExpected(); String actual = e.getActual(); assertUnorderedElementsAreEqual(expected.split("\n"), actual.split("\n")); } } protected boolean ignore() { printIgnoredMessage(null); return true; } protected boolean hasMavenInstallation() { boolean result = getTestMavenHome() != null; if (!result) printIgnoredMessage("Maven installation not found"); return result; } private void printIgnoredMessage(String message) { String toPrint = "Ignored"; if (message != null) { toPrint += ", because " + message; } toPrint += ": " + getClass().getSimpleName() + "." + getName(); System.out.println(toPrint); } private static String getTestMavenHome() { return System.getProperty("idea.maven.test.home"); } private static class SetWithToString<T> extends AbstractSet<T> { private final Set<T> myDelegate; SetWithToString(@NotNull Set<T> delegate) { myDelegate = delegate; } @Override public int size() { return myDelegate.size(); } @Override public boolean contains(Object o) { return myDelegate.contains(o); } @NotNull @Override public Iterator<T> iterator() { return myDelegate.iterator(); } @Override public boolean containsAll(Collection<?> c) { return myDelegate.containsAll(c); } @Override public boolean equals(Object o) { return myDelegate.equals(o); } @Override public int hashCode() { return myDelegate.hashCode(); } } }
package org.html5index.generator; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import org.html5index.docscan.DefaultModelReader; import org.html5index.model.Artifact; import org.html5index.model.Library; import org.html5index.model.Model; import org.html5index.model.Operation; import org.html5index.model.Parameter; import org.html5index.model.Property; import org.html5index.model.Type; public class JsdocGenerator implements Runnable { File root = new File("gen/jsdoc"); Model model; // MUST BE SORTED for binary search static final String[] NUMBER_TYPES = { "int", "long", "long long", "short", "unsigned int", "unsigned long", "unsigned long long", "unsigned short", }; public JsdocGenerator(Model model) { this.model = model; } public void run() { try { root.mkdirs(); File file = new File(root, "index.html"); PrintWriter indexWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); indexWriter.println("<html>"); indexWriter.println("<head><title>JsDoc Export</title></head>"); indexWriter.println("<p><em>Experimental</em> HTML5 API JsDoc export</p>"); indexWriter.println("<body>"); indexWriter.println("<ul>"); for (Library l: model.getLibraries()) { generateLibrary(l, indexWriter); } indexWriter.println("</ul>"); indexWriter.println("</body>"); indexWriter.println("</html>"); indexWriter.close(); } catch(Exception e) { throw new RuntimeException(e); } } public void generateExport(PrintWriter writer, Type type) throws IOException { if (type.getKind() == Type.Kind.INTERFACE) { writer.println("goog.provides('" + type.getName() + "')"); } } public String jsdocType(Type type) { String name = type.getName(); // This should really be a type flag. boolean optional = name.endsWith("?"); if (optional) { name = name.substring(0, name.length() - 1); } if (name.equals("any")) { name = "*"; } else if (name.equals("object")) { name = "Object"; } else if (name.equals("DOMString")) { name = "string"; } switch(type.getKind()) { case PRIMITIVE: return (Arrays.binarySearch(NUMBER_TYPES, name) < 0) ? name : "number"; case UNION: StringBuilder sb = new StringBuilder("("); for (Type t: type.getTypes()) { if (sb.length() > 1) { sb.append('|'); } sb.append(jsdocType(t)); } sb.append(')'); return sb.toString(); default: // TODO: Package name! return name; } } public String documentation(Artifact a) { String result = a.getDocumentationSummary(); return result == null ? "" : result; } public void generateOperation(PrintWriter out, Operation op) { out.println(); out.println("/**"); if (op.getDocumentationSummary() != null) { out.println(" * " + documentation(op).replace("\n", "\n * ")); out.println(" *"); } for (Parameter p: op.getParameters()) { out.println(" * @param {" + jsdocType(p.getType()) + "} " + p.getName() + " " + documentation(p)); } if (op.hasModifier(Operation.CONSTRUCTOR)) { out.println(" * @constructor"); } else if (op.getType() != null) { out.println(" * @return {" + jsdocType(op.getType()) + "}"); } out.println(" */"); out.print(op.getOwner().getName()); if (!op.hasModifier(Operation.CONSTRUCTOR)) { if (!op.hasModifier(Operation.STATIC)) { out.print(".prototype"); } out.print("."); out.print(op.getName()); } out.print (" = function("); boolean first = true; for (Parameter p: op.getParameters()) { if (first) { first = false; } else { out.print(", "); } out.print(p.getName()); } out.print(") {"); if (op.hasModifier(Operation.CONSTRUCTOR)) { out.println(); generateProperties(out, op.getOwner(), false); } out.println("};"); } public void generateProperties(PrintWriter out, Type type, boolean statics) { String indent = statics ? "" : " "; for (Property p: type.getOwnProperties()) { if (p.hasModifier(Property.STATIC) != statics) { continue; } out.println(); out.println(indent + "/**"); if (p.getDocumentation() != null) { out.println(indent + " * " + documentation(p).replace("\n", "\n" + indent + " * ")); } out.println(indent + " * @type {" + jsdocType(p.getType()) + "}"); out.println(indent + " */"); out.println(indent + (statics ? jsdocType(type) : "this") + "." + p.getName() + " = null;"); } } public void generateInterface(PrintWriter out, Type type) { Collection<Operation> constructors = type.getConstructors(); if (constructors.size() == 0) { out.println(); out.println("/**"); out.println(" * @interface"); out.println(" */"); out.println(type.getName() + " = function() {"); generateProperties(out, type, false); out.println("};"); } else { generateOperation(out, constructors.iterator().next()); } generateProperties(out, type, true); for (Operation op: type.getOwnOperations()) { generateOperation(out, op); } out.println(); } public void generateType(PrintWriter out, Type type) throws IOException { switch (type.getKind()) { case INTERFACE: generateInterface(out, type); break; default: out.println("// Skipped: " + type); } } public void generateLibrary(Library library, PrintWriter indexWriter) throws IOException { String name = library.getName() + ".js"; indexWriter.println("<li><a href='" + name + "'>" + name + "</a></li>"); File file = new File(root, name); PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); for (Type type: library.getTypes()) { generateExport(out, type); } out.println(""); out.println(""); for (Type type: library.getTypes()) { generateType(out, type); } out.close(); } public static void main(String[] args) { JsdocGenerator gen = new JsdocGenerator(DefaultModelReader.readModel()); gen.run(); } }
/* * Copyright 2015-present Facebook, 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.facebook.buck.util.cache; import com.facebook.buck.io.ArchiveMemberPath; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.model.Pair; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.hash.HashCode; import java.io.IOException; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.Optional; import java.util.function.Function; /** * Wraps a collection of {@link ProjectFilesystem}-specific {@link ProjectFileHashCache}s as a * single cache, implementing a Chain of Responsibility to find and forward operations to the * correct inner cache. As this "multi"-cache is meant to handle paths across different * {@link ProjectFilesystem}s, as opposed to paths within the same {@link ProjectFilesystem}, it is * a distinct type from {@link ProjectFileHashCache}. * <p> * This "stacking" approach provides a few appealing properties: * 1) It makes it easier to module path roots with differing hash cached lifetime requirements. * Hashes of paths from roots watched by watchman can be cached indefinitely, until a watchman * event triggers invalidation. Hashes of paths under roots not watched by watchman, however, * can only be cached for the duration of a single build (as we have no way to know when these * paths are modified). By using separate {@link ProjectFileHashCache}s per path root, we can * construct a new {@link StackedFileHashCache} on each build composed of either persistent or * ephemeral per-root inner caches that properly manager the lifetime of cached hashes from their * root. * 2) Modeling the hash cache around path root and sub-paths also works well with a current * limitation with our watchman events in which they only store relative paths, with no reference * to the path root they originated from. If we stored hashes internally indexed by absolute * path, then we wouldn't know where to anchor the search to resolve the path that a watchman * event refers to (e.g. a watch event for `foo.h` could refer to `/a/b/foo.h` or `/a/b/c/foo.h`, * depending on where the project root is). By indexing hashes by pairs of project root and * sub-path, it's easier to identity paths to invalidate (e.g. `foo.h` would invalidate * (`/a/b/`,`foo.h`) and not (`/a/b/`,`c/foo.h`)). * 3) Since the current implementation of inner caches and callers generally use path root and * sub-path pairs, it allows avoiding any overhead converting to/from absolute paths. */ public class StackedFileHashCache implements FileHashCache { private final ImmutableList<? extends ProjectFileHashCache> caches; public StackedFileHashCache(ImmutableList<? extends ProjectFileHashCache> caches) { this.caches = caches; } /** * @return the {@link ProjectFileHashCache} which handles the given relative {@link Path} under * the given {@link ProjectFilesystem}. */ private Optional<? extends ProjectFileHashCache> lookup( ProjectFilesystem filesystem, Path path) { for (ProjectFileHashCache cache : caches) { // TODO(andrewjcg): This should check for equal filesystems probably shouldn't be using the // root path, but we currently rely on this behavior. if (cache.getFilesystem().getRootPath().equals(filesystem.getRootPath()) && cache.willGet(path)) { return Optional.of(cache); } } return Optional.empty(); } private Optional<Pair<ProjectFileHashCache, Path>> lookup(Path path) { Preconditions.checkArgument(path.isAbsolute()); for (ProjectFileHashCache cache : caches) { Optional<Path> relativePath = cache.getFilesystem().getPathRelativeToProjectRoot(path); if (relativePath.isPresent() && cache.willGet(relativePath.get())) { return Optional.of(new Pair<>(cache, relativePath.get())); } } return Optional.empty(); } private Optional<Pair<ProjectFileHashCache, ArchiveMemberPath>> lookup(ArchiveMemberPath path) { Preconditions.checkArgument(path.isAbsolute()); for (ProjectFileHashCache cache : caches) { Optional<ArchiveMemberPath> relativePath = cache.getFilesystem().getPathRelativeToProjectRoot(path.getArchivePath()) .map(path::withArchivePath); if (relativePath.isPresent() && cache.willGet(relativePath.get())) { return Optional.of(new Pair<>(cache, relativePath.get())); } } return Optional.empty(); } @Override public void invalidate(Path path) { Optional<Pair<ProjectFileHashCache, Path>> found = lookup(path); if (found.isPresent()) { found.get().getFirst().invalidate(found.get().getSecond()); } } @Override public void invalidateAll() { for (ProjectFileHashCache cache : caches) { cache.invalidateAll(); } } @Override public HashCode get(Path path) throws IOException { Optional<Pair<ProjectFileHashCache, Path>> found = lookup(path); if (!found.isPresent()) { throw new NoSuchFileException(path.toString()); } return found.get().getFirst().get(found.get().getSecond()); } @Override public long getSize(Path path) throws IOException { Optional<Pair<ProjectFileHashCache, Path>> found = lookup(path); if (!found.isPresent()) { throw new NoSuchFileException(path.toString()); } return found.get().getFirst().getSize(found.get().getSecond()); } @Override public HashCode get(ArchiveMemberPath archiveMemberPath) throws IOException { Optional<Pair<ProjectFileHashCache, ArchiveMemberPath>> found = lookup(archiveMemberPath); if (!found.isPresent()) { throw new NoSuchFileException(archiveMemberPath.toString()); } return found.get().getFirst().get(found.get().getSecond()); } @Override public void set(Path path, HashCode hashCode) throws IOException { Optional<Pair<ProjectFileHashCache, Path>> found = lookup(path); if (found.isPresent()) { found.get().getFirst().set(found.get().getSecond(), hashCode); } } @Override public FileHashCacheVerificationResult verify() throws IOException { FileHashCacheVerificationResult.Builder builder = FileHashCacheVerificationResult.builder(); int cachesExamined = 1; int filesExamined = 0; for (ProjectFileHashCache cache : caches) { FileHashCacheVerificationResult result = cache.verify(); cachesExamined += result.getCachesExamined(); filesExamined += result.getFilesExamined(); builder.addAllVerificationErrors(result.getVerificationErrors()); } return builder .setCachesExamined(cachesExamined) .setFilesExamined(filesExamined) .build(); } @Override public HashCode get(ProjectFilesystem filesystem, Path path) throws IOException { return lookup(filesystem, path) .orElseThrow(() -> new NoSuchFileException(filesystem.resolve(path).toString())) .get(path); } @Override public HashCode get(ProjectFilesystem filesystem, ArchiveMemberPath path) throws IOException { return lookup(filesystem, path.getArchivePath()) .orElseThrow( () -> new NoSuchFileException(filesystem.resolve(path.getArchivePath()).toString())) .get(path); } @Override public long getSize(ProjectFilesystem filesystem, Path path) throws IOException { return lookup(filesystem, path) .orElseThrow(() -> new NoSuchFileException(filesystem.resolve(path).toString())) .getSize(path); } @Override public void invalidate(ProjectFilesystem filesystem, Path path) { lookup(filesystem, path).ifPresent(cache -> cache.invalidate(path)); } @Override public void set(ProjectFilesystem filesystem, Path path, HashCode hashCode) throws IOException { Optional<? extends ProjectFileHashCache> cache = lookup(filesystem, path); if (cache.isPresent()) { cache.get().set(path, hashCode); } } public StackedFileHashCache newDecoratedFileHashCache( Function<ProjectFileHashCache, ProjectFileHashCache> decorateDelegate) { ImmutableList.Builder<ProjectFileHashCache> decoratedCaches = ImmutableList.builder(); for (ProjectFileHashCache cache : caches) { decoratedCaches.add(decorateDelegate.apply(cache)); } return new StackedFileHashCache(decoratedCaches.build()); } }
/* * Copyright 2019 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 com.ait.lienzo.client.core.shape.toolbox.items.impl; import com.ait.lienzo.client.core.event.NodeMouseEnterHandler; import com.ait.lienzo.client.core.event.NodeMouseExitHandler; import com.ait.lienzo.client.core.shape.Group; import com.ait.lienzo.client.core.shape.IPrimitive; import com.ait.lienzo.client.core.shape.toolbox.GroupItem; import com.ait.lienzo.client.core.shape.toolbox.items.AbstractDecoratedItem; import com.ait.lienzo.client.core.shape.toolbox.items.AbstractPrimitiveItem; import com.ait.lienzo.client.core.shape.toolbox.items.DecoratorItem; import com.ait.lienzo.client.core.shape.toolbox.items.TooltipItem; import com.ait.lienzo.client.core.types.BoundingBox; import com.ait.lienzo.client.core.types.Point2D; import com.ait.tooling.common.api.java.util.function.BiConsumer; import com.ait.tooling.common.api.java.util.function.Supplier; import com.ait.tooling.nativetools.client.event.HandlerRegistrationManager; import com.google.gwt.event.shared.HandlerRegistration; public abstract class AbstractGroupItem<T extends AbstractGroupItem> extends AbstractDecoratedItem<T> { private final GroupItem groupItem; private final HandlerRegistrationManager registrations = new HandlerRegistrationManager(); private DecoratorItem<?> decorator; private TooltipItem<?> tooltip; private HandlerRegistration mouseEnterHandlerRegistration; private HandlerRegistration mouseExitHandlerRegistration; private Supplier<BoundingBox> boundingBoxSupplier = new Supplier<BoundingBox>() { @Override public BoundingBox get() { return AbstractGroupItem.this.getPrimitive().getComputedBoundingPoints().getBoundingBox(); } }; protected AbstractGroupItem(final GroupItem groupItem) { this.groupItem = groupItem; } @Override public T decorate(final DecoratorItem<?> decorator) { if (isDecorated()) { this.decorator.destroy(); } this.decorator = decorator; attachDecorator(); return cast(); } @Override @SuppressWarnings("unchecked") public T tooltip(final TooltipItem tooltip) { initTooltip(tooltip); return cast(); } @Override public boolean isVisible() { return groupItem.isVisible(); } public void showDecorator() { if (isDecorated()) { this.decorator.show(); final IPrimitive<?> primitive = getDecoratorPrimitive(); if (null != primitive) { primitive.moveToBottom(); } } } public void showTooltip() { if (hasTooltip()) { this.tooltip.show(); } } public void hideDecorator() { if (isDecorated()) { this.decorator.hide(); } } public void hideTooltip() { if (hasTooltip()) { this.tooltip.hide(); } } public T useShowExecutor(final BiConsumer<Group, Runnable> executor) { this.groupItem.useShowExecutor(executor); return cast(); } public T useHideExecutor(final BiConsumer<Group, Runnable> executor) { this.groupItem.useHideExecutor(executor); return cast(); } public boolean isDecorated() { return null != this.decorator; } public boolean hasTooltip() { return null != this.tooltip; } public HandlerRegistrationManager registrations() { return registrations; } protected T register(final HandlerRegistration registration) { registrations.register(registration); return cast(); } @Override public void destroy() { groupItem.destroy(); decorate(null); tooltip(null); destroyHandlers(); getPrimitive().removeFromParent(); } @Override public Group asPrimitive() { return groupItem.asPrimitive(); } @Override public Supplier<BoundingBox> getBoundingBox() { return boundingBoxSupplier; } @Override public T onMouseEnter(final NodeMouseEnterHandler handler) { if (null != mouseEnterHandlerRegistration) { mouseEnterHandlerRegistration.removeHandler(); } mouseEnterHandlerRegistration = registerMouseEnterHandler(handler); return cast(); } @Override public T onMouseExit(final NodeMouseExitHandler handler) { assert null != handler; if (null != mouseExitHandlerRegistration) { mouseExitHandlerRegistration.removeHandler(); } mouseExitHandlerRegistration = registerMouseExitHandler(handler); return cast(); } protected T setBoundingBox(final Supplier<BoundingBox> supplier) { this.boundingBoxSupplier = supplier; return cast(); } protected HandlerRegistration registerMouseEnterHandler(final NodeMouseEnterHandler handler) { assert null != handler; HandlerRegistration reg = getPrimitive() .setListening(true) .addNodeMouseEnterHandler(handler); register(reg); return reg; } protected HandlerRegistration registerMouseExitHandler(final NodeMouseExitHandler handler) { assert null != handler; HandlerRegistration reg = getPrimitive() .setListening(true) .addNodeMouseExitHandler(handler); register(reg); return reg; } protected GroupItem getGroupItem() { return groupItem; } public DecoratorItem<?> getDecorator() { return decorator; } protected TooltipItem<?> getTooltip() { return tooltip; } @SuppressWarnings("unchecked") private void initTooltip(final TooltipItem<?> tooltipItem) { if (hasTooltip()) { this.tooltip.destroy(); } this.tooltip = tooltipItem; if (hasTooltip()) { attachTooltip(); updateAddOnsVisibility(); } } private void attachDecorator() { if (isDecorated()) { decorator.setBoundingBox(getBoundingBox().get()); final IPrimitive<?> primitive = getDecoratorPrimitive(); if (null != primitive) { add(primitive); } updateAddOnsVisibility(); } } void add(IPrimitive<?> primitive) { groupItem.add(primitive); } private IPrimitive<?> getDecoratorPrimitive() { if (null != decorator && decorator instanceof AbstractPrimitiveItem) { return ((AbstractPrimitiveItem) decorator).asPrimitive(); } return null; } private void attachTooltip() { tooltip.forComputedBoundingBox(new Supplier<BoundingBox>() { @Override public BoundingBox get() { return AbstractGroupItem.this.computeAbsoluteBoundingBox(5); } }); if (tooltip instanceof AbstractPrimitiveItem) { add(((AbstractPrimitiveItem) tooltip).asPrimitive()); } } private BoundingBox computeAbsoluteBoundingBox(final double pad) { final BoundingBox bb = getBoundingBox().get(); final Point2D computedLocation = asPrimitive().getComputedLocation(); return new BoundingBox(computedLocation.getX() - pad, computedLocation.getY() - pad, computedLocation.getX() + bb.getWidth() + pad, computedLocation.getY() + bb.getHeight() + pad); } protected void updateAddOnsVisibility() { if (isVisible()) { showAddOns(); } else { hideAddOns(); } } protected void showAddOns() { showDecorator(); showTooltip(); } protected void hideAddOns() { hideDecorator(); hideTooltip(); } private void destroyHandlers() { registrations.removeHandler(); } @SuppressWarnings("unchecked") private T cast() { return (T) this; } }
/* * 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.druid.indexing.firehose; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair; import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.inject.Binder; import com.google.inject.Module; import org.apache.druid.client.coordinator.CoordinatorClient; import org.apache.druid.data.input.Firehose; import org.apache.druid.data.input.FirehoseFactory; import org.apache.druid.data.input.InputRow; import org.apache.druid.data.input.impl.DimensionsSpec; import org.apache.druid.data.input.impl.InputRowParser; import org.apache.druid.data.input.impl.JSONParseSpec; import org.apache.druid.data.input.impl.MapInputRowParser; import org.apache.druid.data.input.impl.TimeAndDimsParseSpec; import org.apache.druid.data.input.impl.TimestampSpec; import org.apache.druid.guice.GuiceAnnotationIntrospector; import org.apache.druid.guice.GuiceInjectableValues; import org.apache.druid.guice.GuiceInjectors; import org.apache.druid.indexing.common.ReingestionTimelineUtils; import org.apache.druid.indexing.common.RetryPolicyConfig; import org.apache.druid.indexing.common.RetryPolicyFactory; import org.apache.druid.indexing.common.SegmentLoaderFactory; import org.apache.druid.indexing.common.TestUtils; import org.apache.druid.indexing.common.config.TaskStorageConfig; import org.apache.druid.indexing.common.task.NoopTask; import org.apache.druid.indexing.common.task.Task; import org.apache.druid.indexing.overlord.HeapMemoryTaskStorage; import org.apache.druid.indexing.overlord.Segments; import org.apache.druid.indexing.overlord.TaskLockbox; import org.apache.druid.indexing.overlord.TaskStorage; import org.apache.druid.java.util.common.FileUtils; import org.apache.druid.java.util.common.IOE; import org.apache.druid.java.util.common.Intervals; import org.apache.druid.java.util.common.JodaUtils; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.java.util.emitter.service.ServiceEmitter; import org.apache.druid.math.expr.ExprMacroTable; import org.apache.druid.metadata.IndexerSQLMetadataStorageCoordinator; import org.apache.druid.query.aggregation.DoubleSumAggregatorFactory; import org.apache.druid.query.aggregation.LongSumAggregatorFactory; import org.apache.druid.query.expression.TestExprMacroTable; import org.apache.druid.query.filter.SelectorDimFilter; import org.apache.druid.segment.IndexIO; import org.apache.druid.segment.IndexMergerV9; import org.apache.druid.segment.IndexSpec; import org.apache.druid.segment.TestHelper; import org.apache.druid.segment.column.ColumnHolder; import org.apache.druid.segment.incremental.IncrementalIndex; import org.apache.druid.segment.incremental.IncrementalIndexSchema; import org.apache.druid.segment.incremental.OnheapIncrementalIndex; import org.apache.druid.segment.loading.LocalDataSegmentPuller; import org.apache.druid.segment.loading.LocalLoadSpec; import org.apache.druid.segment.realtime.firehose.CombiningFirehoseFactory; import org.apache.druid.segment.realtime.plumber.SegmentHandoffNotifierFactory; import org.apache.druid.segment.transform.ExpressionTransform; import org.apache.druid.segment.transform.TransformSpec; import org.apache.druid.server.metrics.NoopServiceEmitter; import org.apache.druid.timeline.DataSegment; import org.apache.druid.timeline.TimelineObjectHolder; import org.apache.druid.timeline.partition.NumberedPartitionChunk; import org.apache.druid.timeline.partition.NumberedShardSpec; import org.apache.druid.timeline.partition.PartitionChunk; import org.apache.druid.timeline.partition.PartitionHolder; import org.easymock.EasyMock; import org.joda.time.Interval; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * */ @RunWith(Parameterized.class) public class IngestSegmentFirehoseFactoryTest { private static final ObjectMapper MAPPER; private static final IndexMergerV9 INDEX_MERGER_V9; private static final IndexIO INDEX_IO; private static final TaskStorage TASK_STORAGE; private static final IndexerSQLMetadataStorageCoordinator MDC; private static final TaskLockbox TASK_LOCKBOX; private static final Task TASK; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); static { TestUtils testUtils = new TestUtils(); MAPPER = setupInjectablesInObjectMapper(TestHelper.makeJsonMapper()); INDEX_MERGER_V9 = testUtils.getTestIndexMergerV9(); INDEX_IO = testUtils.getTestIndexIO(); TASK_STORAGE = new HeapMemoryTaskStorage( new TaskStorageConfig(null) { } ); MDC = new IndexerSQLMetadataStorageCoordinator(null, null, null) { private final Set<DataSegment> published = new HashSet<>(); @Override public List<DataSegment> retrieveUsedSegmentsForIntervals( String dataSource, List<Interval> interval, Segments visibility ) { return ImmutableList.copyOf(SEGMENT_SET); } @Override public List<DataSegment> retrieveUnusedSegmentsForInterval(String dataSource, Interval interval) { return ImmutableList.of(); } @Override public Set<DataSegment> announceHistoricalSegments(Set<DataSegment> segments) { Set<DataSegment> added = new HashSet<>(); for (final DataSegment segment : segments) { if (published.add(segment)) { added.add(segment); } } return ImmutableSet.copyOf(added); } @Override public void deleteSegments(Set<DataSegment> segments) { // do nothing } }; TASK_LOCKBOX = new TaskLockbox(TASK_STORAGE, MDC); TASK = NoopTask.create(); TASK_LOCKBOX.add(TASK); } @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> constructorFeeder() throws IOException { final IndexSpec indexSpec = new IndexSpec(); final IncrementalIndexSchema schema = new IncrementalIndexSchema.Builder() .withMinTimestamp(JodaUtils.MIN_INSTANT) .withDimensionsSpec(ROW_PARSER) .withMetrics( new LongSumAggregatorFactory(METRIC_LONG_NAME, DIM_LONG_NAME), new DoubleSumAggregatorFactory(METRIC_FLOAT_NAME, DIM_FLOAT_NAME) ) .build(); final IncrementalIndex index = new OnheapIncrementalIndex.Builder() .setIndexSchema(schema) .setMaxRowCount(MAX_ROWS * MAX_SHARD_NUMBER) .build(); for (Integer i = 0; i < MAX_ROWS; ++i) { index.add(ROW_PARSER.parseBatch(buildRow(i.longValue())).get(0)); } if (!PERSIST_DIR.mkdirs() && !PERSIST_DIR.exists()) { throw new IOE("Could not create directory at [%s]", PERSIST_DIR.getAbsolutePath()); } INDEX_MERGER_V9.persist(index, PERSIST_DIR, indexSpec, null); final CoordinatorClient cc = new CoordinatorClient(null, null) { @Override public Collection<DataSegment> fetchUsedSegmentsInDataSourceForIntervals( String dataSource, List<Interval> intervals ) { return ImmutableSet.copyOf(SEGMENT_SET); } }; SegmentHandoffNotifierFactory notifierFactory = EasyMock.createNiceMock(SegmentHandoffNotifierFactory.class); EasyMock.replay(notifierFactory); final SegmentLoaderFactory slf = new SegmentLoaderFactory(null, MAPPER); final RetryPolicyFactory retryPolicyFactory = new RetryPolicyFactory(new RetryPolicyConfig()); Collection<Object[]> values = new ArrayList<>(); for (InputRowParser parser : Arrays.<InputRowParser>asList( ROW_PARSER, new MapInputRowParser( new JSONParseSpec( new TimestampSpec(TIME_COLUMN, "auto", null), new DimensionsSpec( DimensionsSpec.getDefaultSchemas(ImmutableList.of()), ImmutableList.of(DIM_FLOAT_NAME, DIM_LONG_NAME), ImmutableList.of() ), null, null, null ) ) )) { for (List<String> dim_names : Arrays.<List<String>>asList(null, ImmutableList.of(DIM_NAME))) { for (List<String> metric_names : Arrays.<List<String>>asList( null, ImmutableList.of(METRIC_LONG_NAME, METRIC_FLOAT_NAME) )) { for (Boolean wrapInCombining : Arrays.asList(false, true)) { final IngestSegmentFirehoseFactory isfFactory = new IngestSegmentFirehoseFactory( TASK.getDataSource(), Intervals.ETERNITY, null, new SelectorDimFilter(DIM_NAME, DIM_VALUE, null), dim_names, metric_names, null, INDEX_IO, cc, slf, retryPolicyFactory ); final FirehoseFactory factory = wrapInCombining ? new CombiningFirehoseFactory(ImmutableList.of(isfFactory)) : isfFactory; values.add( new Object[]{ StringUtils.format( "DimNames[%s]MetricNames[%s]ParserDimNames[%s]WrapInCombining[%s]", dim_names == null ? "null" : "dims", metric_names == null ? "null" : "metrics", parser == ROW_PARSER ? "dims" : "null", wrapInCombining ), factory, parser } ); } } } } return values; } public static ObjectMapper setupInjectablesInObjectMapper(ObjectMapper objectMapper) { objectMapper.registerModule( new SimpleModule("testModule").registerSubtypes(LocalLoadSpec.class) ); final GuiceAnnotationIntrospector guiceIntrospector = new GuiceAnnotationIntrospector(); objectMapper.setAnnotationIntrospectors( new AnnotationIntrospectorPair( guiceIntrospector, objectMapper.getSerializationConfig().getAnnotationIntrospector() ), new AnnotationIntrospectorPair( guiceIntrospector, objectMapper.getDeserializationConfig().getAnnotationIntrospector() ) ); objectMapper.setInjectableValues( new GuiceInjectableValues( GuiceInjectors.makeStartupInjectorWithModules( ImmutableList.of( new Module() { @Override public void configure(Binder binder) { binder.bind(LocalDataSegmentPuller.class); binder.bind(ExprMacroTable.class).toInstance(TestExprMacroTable.INSTANCE); } } ) ) ) ); return objectMapper; } public IngestSegmentFirehoseFactoryTest( String testName, FirehoseFactory factory, InputRowParser rowParser ) { this.factory = factory; // Must decorate the parser, since IngestSegmentFirehoseFactory will undecorate it. this.rowParser = TransformSpec.NONE.decorate(rowParser); } private static final Logger log = new Logger(IngestSegmentFirehoseFactoryTest.class); private static final String DATA_SOURCE_NAME = "testDataSource"; private static final String DATA_SOURCE_VERSION = "version"; private static final Integer BINARY_VERSION = -1; private static final String DIM_NAME = "testDimName"; private static final String DIM_VALUE = "testDimValue"; private static final String DIM_LONG_NAME = "testDimLongName"; private static final String DIM_FLOAT_NAME = "testDimFloatName"; private static final String METRIC_LONG_NAME = "testLongMetric"; private static final String METRIC_FLOAT_NAME = "testFloatMetric"; private static final Long METRIC_LONG_VALUE = 1L; private static final Float METRIC_FLOAT_VALUE = 1.0f; private static final String TIME_COLUMN = "ts"; private static final Integer MAX_SHARD_NUMBER = 10; private static final Integer MAX_ROWS = 10; private static final File TMP_DIR = FileUtils.createTempDir(); private static final File PERSIST_DIR = Paths.get(TMP_DIR.getAbsolutePath(), "indexTestMerger").toFile(); private static final List<DataSegment> SEGMENT_SET = new ArrayList<>(MAX_SHARD_NUMBER); private final FirehoseFactory<InputRowParser> factory; private final InputRowParser rowParser; private File tempDir; private static final InputRowParser<Map<String, Object>> ROW_PARSER = new MapInputRowParser( new TimeAndDimsParseSpec( new TimestampSpec(TIME_COLUMN, "auto", null), new DimensionsSpec( DimensionsSpec.getDefaultSchemas(ImmutableList.of(DIM_NAME)), ImmutableList.of(DIM_FLOAT_NAME, DIM_LONG_NAME), ImmutableList.of() ) ) ); private static Map<String, Object> buildRow(Long ts) { return ImmutableMap.of( TIME_COLUMN, ts, DIM_NAME, DIM_VALUE, DIM_FLOAT_NAME, METRIC_FLOAT_VALUE, DIM_LONG_NAME, METRIC_LONG_VALUE ); } private static DataSegment buildSegment(Integer shardNumber) { Preconditions.checkArgument(shardNumber < MAX_SHARD_NUMBER); Preconditions.checkArgument(shardNumber >= 0); return new DataSegment( DATA_SOURCE_NAME, Intervals.ETERNITY, DATA_SOURCE_VERSION, ImmutableMap.of( "type", "local", "path", PERSIST_DIR.getAbsolutePath() ), ImmutableList.of(DIM_NAME), ImmutableList.of(METRIC_LONG_NAME, METRIC_FLOAT_NAME), new NumberedShardSpec( shardNumber, MAX_SHARD_NUMBER ), BINARY_VERSION, 0L ); } @BeforeClass public static void setUpStatic() { for (int i = 0; i < MAX_SHARD_NUMBER; ++i) { SEGMENT_SET.add(buildSegment(i)); } } @AfterClass public static void tearDownStatic() { recursivelyDelete(TMP_DIR); } private static void recursivelyDelete(final File dir) { if (dir != null) { if (dir.isDirectory()) { final File[] files = dir.listFiles(); if (files != null) { for (File file : files) { recursivelyDelete(file); } } } else { if (!dir.delete()) { log.warn("Could not delete file at [%s]", dir.getAbsolutePath()); } } } } @Before public void setup() throws IOException { tempDir = temporaryFolder.newFolder(); } @After public void teardown() { tempDir.delete(); } @Test public void sanityTest() { if (factory instanceof CombiningFirehoseFactory) { // This method tests IngestSegmentFirehoseFactory-specific methods. return; } final IngestSegmentFirehoseFactory isfFactory = (IngestSegmentFirehoseFactory) factory; Assert.assertEquals(TASK.getDataSource(), isfFactory.getDataSource()); if (isfFactory.getDimensions() != null) { Assert.assertArrayEquals(new String[]{DIM_NAME}, isfFactory.getDimensions().toArray()); } Assert.assertEquals(Intervals.ETERNITY, isfFactory.getInterval()); if (isfFactory.getMetrics() != null) { Assert.assertEquals( ImmutableSet.of(METRIC_LONG_NAME, METRIC_FLOAT_NAME), ImmutableSet.copyOf(isfFactory.getMetrics()) ); } } @Test public void simpleFirehoseReadingTest() throws IOException { Assert.assertEquals(MAX_SHARD_NUMBER.longValue(), SEGMENT_SET.size()); Integer rowcount = 0; try (final Firehose firehose = factory.connect(rowParser, TMP_DIR)) { while (firehose.hasMore()) { InputRow row = firehose.nextRow(); Assert.assertArrayEquals(new String[]{DIM_NAME}, row.getDimensions().toArray()); Assert.assertArrayEquals(new String[]{DIM_VALUE}, row.getDimension(DIM_NAME).toArray()); Assert.assertEquals(METRIC_LONG_VALUE.longValue(), row.getMetric(METRIC_LONG_NAME)); Assert.assertEquals( METRIC_FLOAT_VALUE, row.getMetric(METRIC_FLOAT_NAME).floatValue(), METRIC_FLOAT_VALUE * 0.0001 ); ++rowcount; } } Assert.assertEquals((int) MAX_SHARD_NUMBER * MAX_ROWS, (int) rowcount); } @Test public void testTransformSpec() throws IOException { Assert.assertEquals(MAX_SHARD_NUMBER.longValue(), SEGMENT_SET.size()); Integer rowcount = 0; final TransformSpec transformSpec = new TransformSpec( new SelectorDimFilter(ColumnHolder.TIME_COLUMN_NAME, "1", null), ImmutableList.of( new ExpressionTransform(METRIC_FLOAT_NAME, METRIC_FLOAT_NAME + " * 10", ExprMacroTable.nil()) ) ); int skipped = 0; try (final Firehose firehose = factory.connect(transformSpec.decorate(rowParser), TMP_DIR)) { while (firehose.hasMore()) { InputRow row = firehose.nextRow(); if (row == null) { skipped++; continue; } Assert.assertArrayEquals(new String[]{DIM_NAME}, row.getDimensions().toArray()); Assert.assertArrayEquals(new String[]{DIM_VALUE}, row.getDimension(DIM_NAME).toArray()); Assert.assertEquals(METRIC_LONG_VALUE.longValue(), row.getMetric(METRIC_LONG_NAME).longValue()); Assert.assertEquals( METRIC_FLOAT_VALUE * 10, row.getMetric(METRIC_FLOAT_NAME).floatValue(), METRIC_FLOAT_VALUE * 0.0001 ); ++rowcount; } } Assert.assertEquals(90, skipped); Assert.assertEquals((int) MAX_ROWS, (int) rowcount); } @Test public void testGetUniqueDimensionsAndMetrics() { final int numSegmentsPerPartitionChunk = 5; final int numPartitionChunksPerTimelineObject = 10; final int numSegments = numSegmentsPerPartitionChunk * numPartitionChunksPerTimelineObject; final Interval interval = Intervals.of("2017-01-01/2017-01-02"); final String version = "1"; final List<TimelineObjectHolder<String, DataSegment>> timelineSegments = new ArrayList<>(); for (int i = 0; i < numPartitionChunksPerTimelineObject; i++) { final List<PartitionChunk<DataSegment>> chunks = new ArrayList<>(); for (int j = 0; j < numSegmentsPerPartitionChunk; j++) { final List<String> dims = IntStream.range(i, i + numSegmentsPerPartitionChunk) .mapToObj(suffix -> "dim" + suffix) .collect(Collectors.toList()); final List<String> metrics = IntStream.range(i, i + numSegmentsPerPartitionChunk) .mapToObj(suffix -> "met" + suffix) .collect(Collectors.toList()); final DataSegment segment = new DataSegment( "ds", interval, version, ImmutableMap.of(), dims, metrics, new NumberedShardSpec(numPartitionChunksPerTimelineObject, i), 1, 1 ); final PartitionChunk<DataSegment> partitionChunk = new NumberedPartitionChunk<>( i, numPartitionChunksPerTimelineObject, segment ); chunks.add(partitionChunk); } final TimelineObjectHolder<String, DataSegment> timelineHolder = new TimelineObjectHolder<>( interval, version, new PartitionHolder<>(chunks) ); timelineSegments.add(timelineHolder); } final String[] expectedDims = new String[]{ "dim9", "dim10", "dim11", "dim12", "dim13", "dim8", "dim7", "dim6", "dim5", "dim4", "dim3", "dim2", "dim1", "dim0" }; final String[] expectedMetrics = new String[]{ "met9", "met10", "met11", "met12", "met13", "met8", "met7", "met6", "met5", "met4", "met3", "met2", "met1", "met0" }; Assert.assertEquals( Arrays.asList(expectedDims), ReingestionTimelineUtils.getUniqueDimensions(timelineSegments, null) ); Assert.assertEquals( Arrays.asList(expectedMetrics), ReingestionTimelineUtils.getUniqueMetrics(timelineSegments) ); } private static ServiceEmitter newMockEmitter() { return new NoopServiceEmitter(); } }
/* * Copyright 2014-2019 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.servicecatalog.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Summary information about a product view. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ProductViewSummary" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ProductViewSummary implements Serializable, Cloneable, StructuredPojo { /** * <p> * The product view identifier. * </p> */ private String id; /** * <p> * The product identifier. * </p> */ private String productId; /** * <p> * The name of the product. * </p> */ private String name; /** * <p> * The owner of the product. Contact the product administrator for the significance of this value. * </p> */ private String owner; /** * <p> * Short description of the product. * </p> */ private String shortDescription; /** * <p> * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * </p> */ private String type; /** * <p> * The distributor of the product. Contact the product administrator for the significance of this value. * </p> */ private String distributor; /** * <p> * Indicates whether the product has a default path. If the product does not have a default path, call * <a>ListLaunchPaths</a> to disambiguate between paths. Otherwise, <a>ListLaunchPaths</a> is not required, and the * output of <a>ProductViewSummary</a> can be used directly with <a>DescribeProvisioningParameters</a>. * </p> */ private Boolean hasDefaultPath; /** * <p> * The email contact information to obtain support for this Product. * </p> */ private String supportEmail; /** * <p> * The description of the support for this Product. * </p> */ private String supportDescription; /** * <p> * The URL information to obtain support for this Product. * </p> */ private String supportUrl; /** * <p> * The product view identifier. * </p> * * @param id * The product view identifier. */ public void setId(String id) { this.id = id; } /** * <p> * The product view identifier. * </p> * * @return The product view identifier. */ public String getId() { return this.id; } /** * <p> * The product view identifier. * </p> * * @param id * The product view identifier. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withId(String id) { setId(id); return this; } /** * <p> * The product identifier. * </p> * * @param productId * The product identifier. */ public void setProductId(String productId) { this.productId = productId; } /** * <p> * The product identifier. * </p> * * @return The product identifier. */ public String getProductId() { return this.productId; } /** * <p> * The product identifier. * </p> * * @param productId * The product identifier. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withProductId(String productId) { setProductId(productId); return this; } /** * <p> * The name of the product. * </p> * * @param name * The name of the product. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the product. * </p> * * @return The name of the product. */ public String getName() { return this.name; } /** * <p> * The name of the product. * </p> * * @param name * The name of the product. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withName(String name) { setName(name); return this; } /** * <p> * The owner of the product. Contact the product administrator for the significance of this value. * </p> * * @param owner * The owner of the product. Contact the product administrator for the significance of this value. */ public void setOwner(String owner) { this.owner = owner; } /** * <p> * The owner of the product. Contact the product administrator for the significance of this value. * </p> * * @return The owner of the product. Contact the product administrator for the significance of this value. */ public String getOwner() { return this.owner; } /** * <p> * The owner of the product. Contact the product administrator for the significance of this value. * </p> * * @param owner * The owner of the product. Contact the product administrator for the significance of this value. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withOwner(String owner) { setOwner(owner); return this; } /** * <p> * Short description of the product. * </p> * * @param shortDescription * Short description of the product. */ public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } /** * <p> * Short description of the product. * </p> * * @return Short description of the product. */ public String getShortDescription() { return this.shortDescription; } /** * <p> * Short description of the product. * </p> * * @param shortDescription * Short description of the product. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withShortDescription(String shortDescription) { setShortDescription(shortDescription); return this; } /** * <p> * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * </p> * * @param type * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * @see ProductType */ public void setType(String type) { this.type = type; } /** * <p> * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * </p> * * @return The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * @see ProductType */ public String getType() { return this.type; } /** * <p> * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * </p> * * @param type * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * @return Returns a reference to this object so that method calls can be chained together. * @see ProductType */ public ProductViewSummary withType(String type) { setType(type); return this; } /** * <p> * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * </p> * * @param type * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * @see ProductType */ public void setType(ProductType type) { withType(type); } /** * <p> * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * </p> * * @param type * The product type. Contact the product administrator for the significance of this value. If this value is * <code>MARKETPLACE</code>, the product was created by AWS Marketplace. * @return Returns a reference to this object so that method calls can be chained together. * @see ProductType */ public ProductViewSummary withType(ProductType type) { this.type = type.toString(); return this; } /** * <p> * The distributor of the product. Contact the product administrator for the significance of this value. * </p> * * @param distributor * The distributor of the product. Contact the product administrator for the significance of this value. */ public void setDistributor(String distributor) { this.distributor = distributor; } /** * <p> * The distributor of the product. Contact the product administrator for the significance of this value. * </p> * * @return The distributor of the product. Contact the product administrator for the significance of this value. */ public String getDistributor() { return this.distributor; } /** * <p> * The distributor of the product. Contact the product administrator for the significance of this value. * </p> * * @param distributor * The distributor of the product. Contact the product administrator for the significance of this value. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withDistributor(String distributor) { setDistributor(distributor); return this; } /** * <p> * Indicates whether the product has a default path. If the product does not have a default path, call * <a>ListLaunchPaths</a> to disambiguate between paths. Otherwise, <a>ListLaunchPaths</a> is not required, and the * output of <a>ProductViewSummary</a> can be used directly with <a>DescribeProvisioningParameters</a>. * </p> * * @param hasDefaultPath * Indicates whether the product has a default path. If the product does not have a default path, call * <a>ListLaunchPaths</a> to disambiguate between paths. Otherwise, <a>ListLaunchPaths</a> is not required, * and the output of <a>ProductViewSummary</a> can be used directly with * <a>DescribeProvisioningParameters</a>. */ public void setHasDefaultPath(Boolean hasDefaultPath) { this.hasDefaultPath = hasDefaultPath; } /** * <p> * Indicates whether the product has a default path. If the product does not have a default path, call * <a>ListLaunchPaths</a> to disambiguate between paths. Otherwise, <a>ListLaunchPaths</a> is not required, and the * output of <a>ProductViewSummary</a> can be used directly with <a>DescribeProvisioningParameters</a>. * </p> * * @return Indicates whether the product has a default path. If the product does not have a default path, call * <a>ListLaunchPaths</a> to disambiguate between paths. Otherwise, <a>ListLaunchPaths</a> is not required, * and the output of <a>ProductViewSummary</a> can be used directly with * <a>DescribeProvisioningParameters</a>. */ public Boolean getHasDefaultPath() { return this.hasDefaultPath; } /** * <p> * Indicates whether the product has a default path. If the product does not have a default path, call * <a>ListLaunchPaths</a> to disambiguate between paths. Otherwise, <a>ListLaunchPaths</a> is not required, and the * output of <a>ProductViewSummary</a> can be used directly with <a>DescribeProvisioningParameters</a>. * </p> * * @param hasDefaultPath * Indicates whether the product has a default path. If the product does not have a default path, call * <a>ListLaunchPaths</a> to disambiguate between paths. Otherwise, <a>ListLaunchPaths</a> is not required, * and the output of <a>ProductViewSummary</a> can be used directly with * <a>DescribeProvisioningParameters</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withHasDefaultPath(Boolean hasDefaultPath) { setHasDefaultPath(hasDefaultPath); return this; } /** * <p> * Indicates whether the product has a default path. If the product does not have a default path, call * <a>ListLaunchPaths</a> to disambiguate between paths. Otherwise, <a>ListLaunchPaths</a> is not required, and the * output of <a>ProductViewSummary</a> can be used directly with <a>DescribeProvisioningParameters</a>. * </p> * * @return Indicates whether the product has a default path. If the product does not have a default path, call * <a>ListLaunchPaths</a> to disambiguate between paths. Otherwise, <a>ListLaunchPaths</a> is not required, * and the output of <a>ProductViewSummary</a> can be used directly with * <a>DescribeProvisioningParameters</a>. */ public Boolean isHasDefaultPath() { return this.hasDefaultPath; } /** * <p> * The email contact information to obtain support for this Product. * </p> * * @param supportEmail * The email contact information to obtain support for this Product. */ public void setSupportEmail(String supportEmail) { this.supportEmail = supportEmail; } /** * <p> * The email contact information to obtain support for this Product. * </p> * * @return The email contact information to obtain support for this Product. */ public String getSupportEmail() { return this.supportEmail; } /** * <p> * The email contact information to obtain support for this Product. * </p> * * @param supportEmail * The email contact information to obtain support for this Product. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withSupportEmail(String supportEmail) { setSupportEmail(supportEmail); return this; } /** * <p> * The description of the support for this Product. * </p> * * @param supportDescription * The description of the support for this Product. */ public void setSupportDescription(String supportDescription) { this.supportDescription = supportDescription; } /** * <p> * The description of the support for this Product. * </p> * * @return The description of the support for this Product. */ public String getSupportDescription() { return this.supportDescription; } /** * <p> * The description of the support for this Product. * </p> * * @param supportDescription * The description of the support for this Product. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withSupportDescription(String supportDescription) { setSupportDescription(supportDescription); return this; } /** * <p> * The URL information to obtain support for this Product. * </p> * * @param supportUrl * The URL information to obtain support for this Product. */ public void setSupportUrl(String supportUrl) { this.supportUrl = supportUrl; } /** * <p> * The URL information to obtain support for this Product. * </p> * * @return The URL information to obtain support for this Product. */ public String getSupportUrl() { return this.supportUrl; } /** * <p> * The URL information to obtain support for this Product. * </p> * * @param supportUrl * The URL information to obtain support for this Product. * @return Returns a reference to this object so that method calls can be chained together. */ public ProductViewSummary withSupportUrl(String supportUrl) { setSupportUrl(supportUrl); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getId() != null) sb.append("Id: ").append(getId()).append(","); if (getProductId() != null) sb.append("ProductId: ").append(getProductId()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getOwner() != null) sb.append("Owner: ").append(getOwner()).append(","); if (getShortDescription() != null) sb.append("ShortDescription: ").append(getShortDescription()).append(","); if (getType() != null) sb.append("Type: ").append(getType()).append(","); if (getDistributor() != null) sb.append("Distributor: ").append(getDistributor()).append(","); if (getHasDefaultPath() != null) sb.append("HasDefaultPath: ").append(getHasDefaultPath()).append(","); if (getSupportEmail() != null) sb.append("SupportEmail: ").append(getSupportEmail()).append(","); if (getSupportDescription() != null) sb.append("SupportDescription: ").append(getSupportDescription()).append(","); if (getSupportUrl() != null) sb.append("SupportUrl: ").append(getSupportUrl()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ProductViewSummary == false) return false; ProductViewSummary other = (ProductViewSummary) obj; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; if (other.getProductId() == null ^ this.getProductId() == null) return false; if (other.getProductId() != null && other.getProductId().equals(this.getProductId()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getOwner() == null ^ this.getOwner() == null) return false; if (other.getOwner() != null && other.getOwner().equals(this.getOwner()) == false) return false; if (other.getShortDescription() == null ^ this.getShortDescription() == null) return false; if (other.getShortDescription() != null && other.getShortDescription().equals(this.getShortDescription()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getDistributor() == null ^ this.getDistributor() == null) return false; if (other.getDistributor() != null && other.getDistributor().equals(this.getDistributor()) == false) return false; if (other.getHasDefaultPath() == null ^ this.getHasDefaultPath() == null) return false; if (other.getHasDefaultPath() != null && other.getHasDefaultPath().equals(this.getHasDefaultPath()) == false) return false; if (other.getSupportEmail() == null ^ this.getSupportEmail() == null) return false; if (other.getSupportEmail() != null && other.getSupportEmail().equals(this.getSupportEmail()) == false) return false; if (other.getSupportDescription() == null ^ this.getSupportDescription() == null) return false; if (other.getSupportDescription() != null && other.getSupportDescription().equals(this.getSupportDescription()) == false) return false; if (other.getSupportUrl() == null ^ this.getSupportUrl() == null) return false; if (other.getSupportUrl() != null && other.getSupportUrl().equals(this.getSupportUrl()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); hashCode = prime * hashCode + ((getProductId() == null) ? 0 : getProductId().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getOwner() == null) ? 0 : getOwner().hashCode()); hashCode = prime * hashCode + ((getShortDescription() == null) ? 0 : getShortDescription().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getDistributor() == null) ? 0 : getDistributor().hashCode()); hashCode = prime * hashCode + ((getHasDefaultPath() == null) ? 0 : getHasDefaultPath().hashCode()); hashCode = prime * hashCode + ((getSupportEmail() == null) ? 0 : getSupportEmail().hashCode()); hashCode = prime * hashCode + ((getSupportDescription() == null) ? 0 : getSupportDescription().hashCode()); hashCode = prime * hashCode + ((getSupportUrl() == null) ? 0 : getSupportUrl().hashCode()); return hashCode; } @Override public ProductViewSummary clone() { try { return (ProductViewSummary) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.servicecatalog.model.transform.ProductViewSummaryMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package org.apache.gora.oracle; import oracle.kv.*; import org.apache.gora.GoraTestDriver; import org.apache.gora.oracle.store.OracleStore; import org.apache.commons.io.FileUtils; import java.io.*; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Driver to set up an embedded Oracle database instance for use in our * unit tests. * @author Apostolos Giannakidis */ public class GoraOracleTestDriver extends GoraTestDriver { private static Logger log = LoggerFactory.getLogger(GoraOracleTestDriver.class); private static String storeName = "kvstore"; //the default kvstore name private static String serverHostName = "localhost"; //the default hostname to connect to private static String serverHostPort = "5000"; //the default port to connect to //milliseconds to sleep after the server process executes private final long MILLISTOSLEEP = 11000; //number of times to retry to start the service, in case it fails to start private final int TIMESTORETRY = 4; private static KVStore kvstore; // reference to the kvstore Process proc; // reference to the kvstore process /** * Constructor */ public GoraOracleTestDriver() { super(OracleStore.class); } @Override public void setUpClass() throws Exception { super.setUpClass(); log.info("Initializing Oracle NoSQL driver."); initOracleNoSQLSever(); // start the Oracle NoSQL server createKVStore(); //connect to the Oracle NoSQL server } @Override public void tearDownClass() throws Exception { super.tearDownClass(); if (proc != null) { proc.destroy(); proc = null; log.info("Process killed"); } cleanupDirectoriesFailover(); log.info("Finished Oracle NoSQL driver."); } /** * Initiate the Oracle NoSQL server on the default port. * Waits MILLISTOSLEEP seconds in order for the service to start. * @return * @throws IOException */ private void initOracleNoSQLSever() throws IOException { log.info("initOracleNoSQLSever started"); if (proc != null) proc.destroy(); proc = null; /* Spawn a new process in order to start the Oracle NoSQL service. */ proc = Runtime.getRuntime().exec(new String[]{"java","-jar","lib-ext/kv-2.0.39/kvstore.jar", "kvlite"}); InputStream stdin = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); try { Thread.sleep(MILLISTOSLEEP); } catch (InterruptedException e) { e.printStackTrace(); } if ( (proc == null) ) log.info("Server not started"); else log.info("Server started"); log.info("initOracleNoSQLSever finished"); } /** * Creates the Oracle NoSQL store and returns a specific object * @return the kvstore handle * @throws IOException */ private KVStore createKVStore() throws IOException { log.info("createKVStore started"); if (kvstore!=null){ log.info("kvstore was not null. Closing the kvstore..."); kvstore.close(); kvstore=null; } log.info("storeName:"+storeName+", host:"+ serverHostName +":"+ serverHostPort); boolean started = false; for(int i=1;i<=TIMESTORETRY;i++){ try { kvstore = KVStoreFactory.getStore // create the kv store (new KVStoreConfig(storeName, serverHostName + ":" + serverHostPort)); started = true; }catch (FaultException fe){ log.info("Service seems to be down: "+fe.getMessage()); log.info("Trying to restart the service. Retry:"+i); initOracleNoSQLSever(); // start the service continue; // and loop again to try to connect } if (started) break; } if (kvstore == null){ log.error("KVStore was not opened."); log.error("Terminated because Oracle NoSQL service cannot be started."); try { tearDownClass(); } catch (Exception e) { e.printStackTrace(); } System.exit(-1); } else log.info("KVStore opened: "+kvstore.toString()); log.info("kvstore returned"); return kvstore; } /** * Setter for Properties. Required by the Gora API. * @param properties the properties object to be set */ @Override protected void setProperties(Properties properties) { super.setProperties(properties); } /** * Helper method to get the serialised value directly from the database * @param myKey the key of the key/value pair * @return the fetched, serialised value */ public byte[] get(Key myKey){ ValueVersion vv = null; vv = kvstore.get(myKey); if (vv != null) { Value value = vv.getValue(); return value.getValue(); } else return null; } /** * Helper method to get the kvstore handle * @return the kvstore handle */ public KVStore getKvstore(){ return kvstore; } /** * Simply cleans up Oracle NoSQL's output from the Unit tests. * In the case of a failure, it waits 250 msecs and tries again, 3 times in total. */ public void cleanupDirectoriesFailover() { int tries = 3; while (tries-- > 0) { try { cleanupDirectories(); break; } catch (Exception e) { //ignore exception try { Thread.sleep(250); } catch (InterruptedException e1) { //ignore exception } } } } /** * Cleans up Oracle NoSQL's temp base directory. * @throws Exception * if an error occurs */ public void cleanupDirectories() throws Exception { File dirFile = new File("kvroot"); if (dirFile.exists()) { FileUtils.deleteDirectory(dirFile); } } }
/* * Copyright 2006-2006 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.openspaces.core; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openspaces.core.exception.DefaultExceptionTranslator; import org.openspaces.core.exception.ExceptionTranslator; import org.openspaces.core.transaction.DefaultTransactionProvider; import org.openspaces.core.transaction.TransactionProvider; import org.openspaces.core.transaction.manager.JiniPlatformTransactionManager; import org.openspaces.core.util.SpaceUtils; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.Constants; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.util.Assert; import com.gigaspaces.client.ChangeModifiers; import com.gigaspaces.client.ClearModifiers; import com.gigaspaces.client.CountModifiers; import com.gigaspaces.client.ReadModifiers; import com.gigaspaces.client.TakeModifiers; import com.gigaspaces.client.WriteModifiers; import com.gigaspaces.internal.client.cache.ISpaceCache; import com.gigaspaces.internal.client.spaceproxy.ISpaceProxy; import com.j_spaces.core.IJSpace; /** * <p>A factory bean creating {@link org.openspaces.core.GigaSpace GigaSpace} implementation. * The implementation created is {@link org.openspaces.core.DefaultGigaSpace DefaultGigaSpace} which * allows for pluggable {@link com.j_spaces.core.IJSpace IJSpace}, * {@link org.openspaces.core.transaction.TransactionProvider TransactionProvider}, and * {@link org.openspaces.core.exception.ExceptionTranslator ExceptionTranslator}. * * <p>The factory requires an {@link com.j_spaces.core.IJSpace IJSpace} which can be either * directly acquired or build using one of the several space factory beans provided in * <code>org.openspaces.core.space</code>. * * <p>The factory accepts an optional {@link org.openspaces.core.transaction.TransactionProvider TransactionProvider} * which defaults to {@link org.openspaces.core.transaction.DefaultTransactionProvider DefaultTransactionProvider}. * The transactional context used is based on * {@link #setTransactionManager(org.springframework.transaction.PlatformTransactionManager)} * and if no transaction manager is provided, will use the space as the context. * * <p>When using {@link org.openspaces.core.transaction.manager.LocalJiniTransactionManager} there is no need * to pass the transaction manager to this factory, since both by default will use the space as the * transactional context. When working with {@link org.openspaces.core.transaction.manager.LookupJiniTransactionManager} * (which probably means Mahalo and support for more than one space as transaction resources) the transaction * manager should be provided to this class. * * <p>The factory accepts an optional {@link org.openspaces.core.exception.ExceptionTranslator ExceptionTranslator} * which defaults to {@link org.openspaces.core.exception.DefaultExceptionTranslator DefaultExceptionTranslator}. * * <p>A clustered flag allows to control if this GigaSpace instance will work against a clustered view of * the space or directly against a clustered member. This flag has no affect when not working in a * clustered mode (partitioned or primary/backup). By default if this flag is not set it will be set * automatically by this factory. It will be set to <code>true</code> if the space is an embedded one AND * the space is not a local cache proxy. It will be set to <code>false</code> otherwise (i.e. the space * is not an embedded space OR the space is a local cache proxy). A local cache proxy is an <code>IJSpace</code> * that is injected using {@link #setSpace(com.j_spaces.core.IJSpace)} and was created using either * {@link org.openspaces.core.space.cache.LocalViewSpaceFactoryBean} or * {@link org.openspaces.core.space.cache.LocalCacheSpaceFactoryBean}. * * <p>The factory allows to set the default read/take timeout and write lease when using * the same operations without the relevant parameters. * * <p>The factory also allows to set the default isolation level for read operations that will * be performed by {@link org.openspaces.core.GigaSpace} API. The isolation level can be set * either using {@link #setDefaultIsolationLevel(int)} or {@link #setDefaultIsolationLevelName(String)}. * Note, this setting will apply when not working under Spring declarative transactions or when using * Spring declarative transaction with the default isolation level * ({@link org.springframework.transaction.TransactionDefinition#ISOLATION_DEFAULT}). * * @author kimchy * @see org.openspaces.core.GigaSpace * @see org.openspaces.core.DefaultGigaSpace * @see org.openspaces.core.transaction.TransactionProvider * @see org.openspaces.core.exception.ExceptionTranslator * @see org.openspaces.core.transaction.manager.AbstractJiniTransactionManager */ public class GigaSpaceFactoryBean implements InitializingBean, DisposableBean, FactoryBean, BeanNameAware { private static final Log logger = LogFactory.getLog(GigaSpaceFactoryBean.class); /** * Prefix for the isolation constants defined in TransactionDefinition */ public static final String PREFIX_ISOLATION = "ISOLATION_"; /** * Constants instance for TransactionDefinition */ private static final Constants constants = new Constants(TransactionDefinition.class); private ISpaceProxy space; private TransactionProvider txProvider; private DefaultTransactionProvider defaultTxProvider; private ExceptionTranslator exTranslator; private PlatformTransactionManager transactionManager; private Boolean clustered; private long defaultReadTimeout = 0; private long defaultTakeTimeout = 0; private long defaultWriteLease = Long.MAX_VALUE; private int defaultIsolationLevel = TransactionDefinition.ISOLATION_DEFAULT; private WriteModifiers[] defaultWriteModifiers; private ReadModifiers[] defaultReadModifiers; private TakeModifiers[] defaultTakeModifiers; private ClearModifiers[] defaultClearModifiers; private CountModifiers[] defaultCountModifiers; private ChangeModifiers[] defaultChangeModifiers; private String beanName; private DefaultGigaSpace gigaSpace; /** * <p>Sets the space that will be used by the created {@link org.openspaces.core.GigaSpace}. * This is a required parameter to the factory. * * @param space The space used */ public void setSpace(IJSpace space) { this.space = (ISpaceProxy) space; } /** * <p>Sets the transaction provider that will be used by the created {@link org.openspaces.core.GigaSpace}. * This is an optional parameter and defaults to {@link org.openspaces.core.transaction.DefaultTransactionProvider}. * * @param txProvider The transaction provider to use */ public void setTxProvider(TransactionProvider txProvider) { this.txProvider = txProvider; } /** * <p>Sets the exception translator that will be used by the created {@link org.openspaces.core.GigaSpace}. * This is an optional parameter and defaults to {@link org.openspaces.core.exception.DefaultExceptionTranslator}. * * @param exTranslator The exception translator to use */ public void setExTranslator(ExceptionTranslator exTranslator) { this.exTranslator = exTranslator; } /** * <p>Sets the cluster flag controlling if this {@link org.openspaces.core.GigaSpace} will work with a clustered * view of the space or directly with a cluster member. By default if this flag is not set it will be set * automatically by this factory. It will be set to <code>false</code> if the space is an embedded one AND * the space is not a local cache proxy. It will be set to <code>true</code> otherwise (i.e. the space * is not an embedded space OR the space is a local cache proxy). * * @param clustered If the {@link org.openspaces.core.GigaSpace} is going to work with a clustered view of the * space or directly with a cluster member */ public void setClustered(boolean clustered) { this.clustered = clustered; } /** * <p>Sets the default read timeout for {@link org.openspaces.core.GigaSpace#read(Object)} and * {@link org.openspaces.core.GigaSpace#readIfExists(Object)} operations. Default to 0. */ public void setDefaultReadTimeout(long defaultReadTimeout) { this.defaultReadTimeout = defaultReadTimeout; } /** * <p>Sets the default take timeout for {@link org.openspaces.core.GigaSpace#take(Object)} and * {@link org.openspaces.core.GigaSpace#takeIfExists(Object)} operations. Default to 0. */ public void setDefaultTakeTimeout(long defaultTakeTimeout) { this.defaultTakeTimeout = defaultTakeTimeout; } /** * <p>Sets the default write lease for {@link org.openspaces.core.GigaSpace#write(Object)} operation. * Default to {@link net.jini.core.lease.Lease#FOREVER}. */ public void setDefaultWriteLease(long defaultWriteLease) { this.defaultWriteLease = defaultWriteLease; } /** * Set the default isolation level by the name of the corresponding constant in * TransactionDefinition, e.g. "ISOLATION_DEFAULT". * * @param constantName name of the constant * @throws IllegalArgumentException if the supplied value is not resolvable * to one of the <code>ISOLATION_</code> constants or is <code>null</code> * @see #setDefaultIsolationLevel(int) * @see org.springframework.transaction.TransactionDefinition#ISOLATION_DEFAULT */ public final void setDefaultIsolationLevelName(String constantName) throws IllegalArgumentException { if (constantName == null || !constantName.startsWith(PREFIX_ISOLATION)) { throw new IllegalArgumentException("Only isolation constants allowed"); } setDefaultIsolationLevel(constants.asNumber(constantName).intValue()); } /** * Set the default isolation level. Must be one of the isolation constants * in the TransactionDefinition interface. Default is ISOLATION_DEFAULT. * * @throws IllegalArgumentException if the supplied value is not * one of the <code>ISOLATION_</code> constants * @see org.springframework.transaction.TransactionDefinition#ISOLATION_DEFAULT */ public void setDefaultIsolationLevel(int defaultIsolationLevel) { if (!constants.getValues(PREFIX_ISOLATION).contains( Integer.valueOf(defaultIsolationLevel))) { throw new IllegalArgumentException("Only values of isolation constants allowed"); } this.defaultIsolationLevel = defaultIsolationLevel; } /** * Set the default {@link WriteModifiers} to be used for write operations * on the {@link GigaSpace} instance. * Defaults to {@link WriteModifiers#UPDATE_OR_WRITE} * @param defaultWriteModifiers The default write modifiers. * @see {@link WriteModifiers} */ public void setDefaultWriteModifiers(WriteModifiers[] defaultWriteModifiers) { this.defaultWriteModifiers = defaultWriteModifiers; } /** * Set the default {@link ReadModifiers} to be used for read operations * on the {@link GigaSpace} instance. * Defaults to {@link ReadModifiers#READ_COMMITTED} * @param defaultReadModifiers The default read modifiers. * @see {@link ReadModifiers} */ public void setDefaultReadModifiers(ReadModifiers[] defaultReadModifiers) { this.defaultReadModifiers = defaultReadModifiers; } /** * Set the default {@link TakeModifiers} to be used for take operations * on the {@link GigaSpace} instance. * Defaults to {@link TakeModifiers#NONE} * @param defaultTakeModifiers The default take modifiers. * @see {@link TakeModifiers} */ public void setDefaultTakeModifiers(TakeModifiers[] defaultTakeModifiers) { this.defaultTakeModifiers = defaultTakeModifiers; } /** * Set the default {@link CountModifiers} to be used for count operations * on the {@link GigaSpace} instance. * Defaults to {@link CountModifiers#NONE} * @param defaultCountModifiers The default count modifiers. * @see {@link CountModifiers} */ public void setDefaultCountModifiers(CountModifiers[] defaultCountModifiers) { this.defaultCountModifiers = defaultCountModifiers; } /** * Set the default {@link ClearModifiers} to be used for clear operations * on the {@link GigaSpace} instance. * Defaults to {@link ClearModifiers#NONE} * @param defaultClearModifiers The default clear modifiers. * @see {@link ClearModifiers} */ public void setDefaultClearModifiers(ClearModifiers[] defaultClearModifiers) { this.defaultClearModifiers = defaultClearModifiers; } /** * Set the default {@link ChangeModifiers} to be used for change operations * on the {@link GigaSpace} instance. * Defaults to {@link ChangeModifiers#NONE} * @param defaultChangeModifiers The default change modifiers. * @see {@link ChangeModifiers} */ public void setDefaultChangeModifiers(ChangeModifiers[] defaultChangeModifiers) { this.defaultChangeModifiers = defaultChangeModifiers; } /** * <p>Set the transaction manager to enable transactional operations. Can be <code>null</code> * if transactional support is not required or the default space is used as a transactional context. */ public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } public void setBeanName(String beanName) { this.beanName = beanName; } /** * Constructs the {@link org.openspaces.core.GigaSpace} instance using the * {@link org.openspaces.core.DefaultGigaSpace} implementation. Uses the clustered flag to * get a cluster member directly (if set to <code>false</code>) and applies the different * defaults). */ public void afterPropertiesSet() { Assert.notNull(this.space, "space property is required"); ISpaceProxy space = this.space; if (clustered == null) { // in case the space is a local cache space, set the clustered flag to true since we do // not want to get the actual member (the cluster flag was set on the local cache already) if (space instanceof ISpaceCache) { clustered = true; if (logger.isDebugEnabled()) { logger.debug("Clustered flag automatically set to [" + clustered + "] since the space is a local cache space for bean [" + beanName + "]"); } } else { clustered = SpaceUtils.isRemoteProtocol(space); if (logger.isDebugEnabled()) { logger.debug("Clustered flag automatically set to [" + clustered + "] for bean [" + beanName + "]"); } } } if (!clustered && space.isClustered()) { space = (ISpaceProxy) SpaceUtils.getClusterMemberSpace(space); } if (exTranslator == null) { exTranslator = new DefaultExceptionTranslator(); } if (txProvider == null) { Object transactionalContext = null; if (transactionManager != null && transactionManager instanceof JiniPlatformTransactionManager) { transactionalContext = ((JiniPlatformTransactionManager) transactionManager).getTransactionalContext(); } defaultTxProvider = new DefaultTransactionProvider(transactionalContext, transactionManager); txProvider = defaultTxProvider; } gigaSpace = new DefaultGigaSpace(space, txProvider, exTranslator, defaultIsolationLevel); gigaSpace.setDefaultReadTimeout(defaultReadTimeout); gigaSpace.setDefaultTakeTimeout(defaultTakeTimeout); gigaSpace.setDefaultWriteLease(defaultWriteLease); setDefaultModifiers(); gigaSpace.setName(beanName == null ? space.getName() : beanName); } private void setDefaultModifiers() { if (defaultWriteModifiers != null) { gigaSpace.setDefaultWriteModifiers(new WriteModifiers(defaultWriteModifiers)); } if (defaultReadModifiers != null) { gigaSpace.setDefaultReadModifiers(new ReadModifiers(defaultReadModifiers)); } if (defaultTakeModifiers != null) { gigaSpace.setDefaultTakeModifiers(new TakeModifiers(defaultTakeModifiers)); } if (defaultCountModifiers != null) { gigaSpace.setDefaultCountModifiers(new CountModifiers(defaultCountModifiers)); } if (defaultClearModifiers != null) { gigaSpace.setDefaultClearModifiers(new ClearModifiers(defaultClearModifiers)); } if (defaultChangeModifiers != null) { gigaSpace.setDefaultChangeModifiers(new ChangeModifiers(defaultChangeModifiers)); } } /** * Return {@link org.openspaces.core.GigaSpace} implementation constructed in * the {@link #afterPropertiesSet()} phase. */ public Object getObject() { return this.gigaSpace; } public Class<? extends GigaSpace> getObjectType() { return (gigaSpace == null ? GigaSpace.class : gigaSpace.getClass()); } /** * Returns <code>true</code> as this is a singleton. */ public boolean isSingleton() { return true; } /* (non-Javadoc) * @see org.springframework.beans.factory.DisposableBean#destroy() */ @Override public void destroy() throws Exception { if (defaultTxProvider != null) defaultTxProvider.destroy(); } }
/* * 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 com.intellij.codeInsight.completion; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementPresentation; import com.intellij.navigation.ChooseByNameContributor; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileNameMatcher; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.PsiReference; import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference; import com.intellij.psi.impl.source.resolve.reference.impl.providers.*; import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.ProjectScope; import com.intellij.util.ArrayUtil; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; import static com.intellij.patterns.PlatformPatterns.psiElement; /** * @author spleaner */ public class FilePathCompletionContributor extends CompletionContributor { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.FilePathCompletionContributor"); public FilePathCompletionContributor() { extend(CompletionType.BASIC, psiElement(), new CompletionProvider<CompletionParameters>() { @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { final PsiReference psiReference = parameters.getPosition().getContainingFile().findReferenceAt(parameters.getOffset()); if (getReference(psiReference) != null) { final String shortcut = getActionShortcut(IdeActions.ACTION_CLASS_NAME_COMPLETION); final CompletionService service = CompletionService.getCompletionService(); if (/*StringUtil.isEmpty(service.getAdvertisementText()) &&*/ shortcut != null) { service.setAdvertisementText(CodeInsightBundle.message("class.completion.file.path", shortcut)); } } } }); extend(CompletionType.CLASS_NAME, psiElement(), new CompletionProvider<CompletionParameters>() { @Override protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull final CompletionResultSet _result) { @NotNull final CompletionResultSet result = _result.caseInsensitive(); final PsiElement e = parameters.getPosition(); final Project project = e.getProject(); final PsiReference psiReference = parameters.getPosition().getContainingFile().findReferenceAt(parameters.getOffset()); final Pair<FileReference, Boolean> fileReferencePair = getReference(psiReference); if (fileReferencePair != null) { final FileReference first = fileReferencePair.getFirst(); if (first == null) return; final FileReferenceSet set = first.getFileReferenceSet(); String prefix = set.getPathString().substring(0, parameters.getOffset() - set.getElement().getTextRange().getStartOffset() - set.getStartInElement()); final String textBeforePosition = e.getContainingFile().getText().substring(0, parameters.getOffset()); if (!textBeforePosition.endsWith(prefix)) { final int len = textBeforePosition.length(); final String fragment = len > 100 ? textBeforePosition.substring(len - 100) : textBeforePosition; throw new AssertionError("prefix should be some actual file string just before caret: " + prefix + "\n text=" + fragment + ";\npathString=" + set.getPathString() + ";\nelementText=" + e.getParent().getText()); } List<String> pathPrefixParts = null; int lastSlashIndex; if ((lastSlashIndex = prefix.lastIndexOf('/')) != -1) { pathPrefixParts = StringUtil.split(prefix.substring(0, lastSlashIndex), "/"); prefix = prefix.substring(lastSlashIndex + 1); } final CompletionResultSet __result = result.withPrefixMatcher(prefix).caseInsensitive(); final PsiFile originalFile = parameters.getOriginalFile(); final VirtualFile contextFile = originalFile.getVirtualFile(); if (contextFile != null) { final String[] fileNames = getAllNames(project); final Set<String> resultNames = new TreeSet<String>(); for (String fileName : fileNames) { if (filenameMatchesPrefixOrType(fileName, prefix, set.getSuitableFileTypes(), parameters.getInvocationCount())) { resultNames.add(fileName); } } final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); final Module contextModule = index.getModuleForFile(contextFile); if (contextModule != null) { final FileReferenceHelper contextHelper = FileReferenceHelperRegistrar.getNotNullHelper(originalFile); final GlobalSearchScope scope = ProjectScope.getProjectScope(project); for (final String name : resultNames) { ProgressManager.checkCanceled(); final PsiFile[] files = FilenameIndex.getFilesByName(project, name, scope); if (files.length > 0) { for (final PsiFile file : files) { ProgressManager.checkCanceled(); final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null && virtualFile.isValid() && virtualFile != contextFile) { if (contextHelper.isMine(project, virtualFile)) { if (pathPrefixParts == null || fileMatchesPathPrefix(contextHelper.getPsiFileSystemItem(project, virtualFile), pathPrefixParts)) { __result.addElement(new FilePathLookupItem(file, contextHelper)); } } } } } } } } if (set.getSuitableFileTypes().length > 0 && parameters.getInvocationCount() == 1) { final String shortcut = getActionShortcut(IdeActions.ACTION_CLASS_NAME_COMPLETION); final CompletionService service = CompletionService.getCompletionService(); if (shortcut != null) { service.setAdvertisementText(CodeInsightBundle.message("class.completion.file.path.all.variants", shortcut)); } } if (fileReferencePair.getSecond()) result.stopHere(); } } }); } private static boolean filenameMatchesPrefixOrType(final String fileName, final String prefix, final FileType[] suitableFileTypes, final int invocationCount) { final boolean prefixMatched = prefix.length() == 0 || StringUtil.startsWithIgnoreCase(fileName, prefix); if (prefixMatched && (suitableFileTypes.length == 0 || invocationCount > 1)) return true; if (prefixMatched) { final String extension = FileUtil.getExtension(fileName); if (extension.length() == 0) return false; for (final FileType fileType : suitableFileTypes) { final List<FileNameMatcher> matchers = FileTypeManager.getInstance().getAssociations(fileType); for (final FileNameMatcher matcher : matchers) { if (matcher.accept(fileName)) return true; } } } return false; } private static boolean fileMatchesPathPrefix(@Nullable final PsiFileSystemItem file, @NotNull final List<String> pathPrefix) { if (file == null) return false; final List<String> contextParts = new ArrayList<String>(); PsiFileSystemItem parentFile = file; PsiFileSystemItem parent; while ((parent = parentFile.getParent()) != null) { if (parent.getName().length() > 0) contextParts.add(0, parent.getName().toLowerCase()); parentFile = parent; } final String path = StringUtil.join(contextParts, "/"); int nextIndex = 0; for (final String s : pathPrefix) { if ((nextIndex = path.indexOf(s.toLowerCase(), nextIndex)) == -1) return false; } return true; } private static String[] getAllNames(@NotNull final Project project) { Set<String> names = new HashSet<String>(); final ChooseByNameContributor[] nameContributors = ChooseByNameContributor.FILE_EP_NAME.getExtensions(); for (final ChooseByNameContributor contributor : nameContributors) { try { names.addAll(Arrays.asList(contributor.getNames(project, false))); } catch (ProcessCanceledException ex) { // index corruption detected, ignore } catch (Exception ex) { LOG.error(ex); } } return ArrayUtil.toStringArray(names); } @Nullable private static Pair<FileReference, Boolean> getReference(final PsiReference original) { if (original == null) { return null; } if (original instanceof PsiMultiReference) { final PsiMultiReference multiReference = (PsiMultiReference)original; for (PsiReference reference : multiReference.getReferences()) { if (reference instanceof FileReference) { return Pair.create((FileReference) reference, false); } } } else if (original instanceof FileReferenceOwner) { final FileReference fileReference = ((FileReferenceOwner)original).getLastFileReference(); if (fileReference != null) { return Pair.create(fileReference, true); } } return null; } public class FilePathLookupItem extends LookupElement { private final String myName; private final String myPath; private final String myInfo; private final Icon myIcon; private final PsiFile myFile; private final FileReferenceHelper myReferenceHelper; public FilePathLookupItem(@NotNull final PsiFile file, @NotNull final FileReferenceHelper referenceHelper) { myName = file.getName(); myPath = file.getVirtualFile().getPath(); myReferenceHelper = referenceHelper; myInfo = FileInfoManager.getFileAdditionalInfo(file); myIcon = file.getFileType().getIcon(); myFile = file; } @SuppressWarnings({"HardCodedStringLiteral"}) @Override public String toString() { return String.format("%s%s", myName, myInfo == null ? "" : " (" + myInfo + ")"); } @NotNull @Override public Object getObject() { return myFile; } @NotNull public String getLookupString() { return myName; } @Override public void handleInsert(InsertionContext context) { if (myFile.isValid()) { final PsiReference psiReference = context.getFile().findReferenceAt(context.getStartOffset()); final Pair<FileReference, Boolean> fileReferencePair = getReference(psiReference); LOG.assertTrue(fileReferencePair != null); fileReferencePair.getFirst().bindToElement(myFile, true); } } @Override public void renderElement(LookupElementPresentation presentation) { final VirtualFile virtualFile = myFile.getVirtualFile(); LOG.assertTrue(virtualFile != null); final PsiFileSystemItem root = myReferenceHelper.findRoot(myFile.getProject(), virtualFile); final String relativePath = PsiFileSystemItemUtil.getRelativePath(root, myReferenceHelper.getPsiFileSystemItem(myFile.getProject(), virtualFile)); final StringBuilder sb = new StringBuilder(); if (myInfo != null) { sb.append(" (").append(myInfo); } if (relativePath != null && !relativePath.equals(myName)) { if (myInfo != null) { sb.append(", "); } else { sb.append(" ("); } sb.append(relativePath); } if (sb.length() > 0) { sb.append(')'); } presentation.setItemText(myName); if (sb.length() > 0) { presentation.setTailText(sb.toString(), true); } presentation.setIcon(myIcon); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FilePathLookupItem that = (FilePathLookupItem)o; if (!myName.equals(that.myName)) return false; if (!myPath.equals(that.myPath)) return false; return true; } @Override public int hashCode() { int result = myName.hashCode(); result = 31 * result + myPath.hashCode(); return result; } } }
/* * 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.sysml.runtime.util; import java.util.Arrays; import java.util.Random; import org.apache.sysml.runtime.controlprogram.parfor.stat.Timing; /** * Utilities for sorting, primarily used for SparseRows. * */ public class SortUtils { /** * * @param start * @param end * @param indexes * @return */ public static boolean isSorted(int start, int end, int[] indexes) { boolean ret = true; for( int i=start+1; i<end; i++ ) if( indexes[i]<indexes[i-1] ){ ret = false; break; } return ret; } /** * * @param iStart * @param iEnd * @param dVals * * @return true/false, if its sorted or not. */ public static boolean isSorted(int iStart, int iEnd, double[] dVals) { boolean ret = true; for( int i=iStart+1; i<iEnd; i++ ) if( dVals[i]<dVals[i-1] ){ ret = false; break; } return ret; } /** * In-place sort of two arrays, only indexes is used for comparison and values * of same position are sorted accordingly. * * @param start * @param end * @param indexes * @param values */ public static void sortByIndex(int start, int end, int[] indexes, double[] values) { int tempIx; double tempVal; int length = end - start; if (length < 7) { for (int i = start + 1; i < end; i++) { for (int j = i; j > start && indexes[j - 1] > indexes[j]; j--) { tempIx = indexes[j]; indexes[j] = indexes[j - 1]; indexes[j - 1] = tempIx; tempVal = values[j]; values[j] = values[j - 1]; values[j - 1] = tempVal; } } return; } int middle = (start + end) / 2; if (length > 7) { int bottom = start; int top = end - 1; if (length > 40) { length /= 8; bottom = med3(indexes, bottom, bottom + length, bottom + (2 * length)); middle = med3(indexes, middle - length, middle, middle + length); top = med3(indexes, top - (2 * length), top - length, top); } middle = med3(indexes, bottom, middle, top); } int partionValue = indexes[middle]; int a, b, c, d; a = b = start; c = d = end - 1; while (true) { while (b <= c && indexes[b] <= partionValue) { if (indexes[b] == partionValue) { tempIx = indexes[a]; indexes[a] = indexes[b]; indexes[b] = tempIx; tempVal = values[a]; values[a++] = values[b]; values[b] = tempVal; } b++; } while (c >= b && indexes[c] >= partionValue) { if (indexes[c] == partionValue) { tempIx = indexes[c]; indexes[c] = indexes[d]; indexes[d] = tempIx; tempVal = values[c]; values[c] = values[d]; values[d--] = tempVal; } c--; } if (b > c) { break; } tempIx = indexes[b]; indexes[b] = indexes[c]; indexes[c] = tempIx; tempVal = values[b]; values[b++] = values[c]; values[c--] = tempVal; } length = a - start < b - a ? a - start : b - a; int l = start; int h = b - length; while (length-- > 0) { tempIx = indexes[l]; indexes[l] = indexes[h]; indexes[h] = tempIx; tempVal = values[l]; values[l++] = values[h]; values[h++] = tempVal; } length = d - c < end - 1 - d ? d - c : end - 1 - d; l = b; h = end - length; while (length-- > 0) { tempIx = indexes[l]; indexes[l] = indexes[h]; indexes[h] = tempIx; tempVal = values[l]; values[l++] = values[h]; values[h++] = tempVal; } if ((length = b - a) > 0) { sortByIndex(start, start + length, indexes, values); } if ((length = d - c) > 0) { sortByIndex(end - length, end, indexes, values); } } /** * * @param start * @param end * @param values * @param valuesXXX */ public static void sortByValue(int start, int end, double[] values, int[] indexes) { double tempVal; int tempIx; int length = end - start; if (length < 7) { for (int i = start + 1; i < end; i++) { for (int j = i; j > start && values[j - 1] > values[j]; j--) { tempVal = values[j]; values[j] = values[j - 1]; values[j - 1] = tempVal; tempIx = indexes[j]; indexes[j] = indexes[j - 1]; indexes[j - 1] = tempIx; } } return; } int middle = (start + end) / 2; if (length > 7) { int bottom = start; int top = end - 1; if (length > 40) { length /= 8; bottom = med3(values, bottom, bottom + length, bottom + (2 * length)); middle = med3(values, middle - length, middle, middle + length); top = med3(values, top - (2 * length), top - length, top); } middle = med3(values, bottom, middle, top); } double partionValue = values[middle]; int a, b, c, d; a = b = start; c = d = end - 1; while (true) { while (b <= c && values[b] <= partionValue) { if (values[b] == partionValue) { tempVal = values[a]; values[a] = values[b]; values[b] = tempVal; tempIx = indexes[a]; indexes[a++] = indexes[b]; indexes[b] = tempIx; } b++; } while (c >= b && values[c] >= partionValue) { if (values[c] == partionValue) { tempVal = values[c]; values[c] = values[d]; values[d] = tempVal; tempIx = indexes[c]; indexes[c] = indexes[d]; indexes[d--] = tempIx; } c--; } if (b > c) { break; } tempVal = values[b]; values[b] = values[c]; values[c] = tempVal; tempIx = indexes[b]; indexes[b++] = indexes[c]; indexes[c--] = tempIx; } length = a - start < b - a ? a - start : b - a; int l = start; int h = b - length; while (length-- > 0) { tempVal = values[l]; values[l] = values[h]; values[h] = tempVal; tempIx = indexes[l]; indexes[l++] = indexes[h]; indexes[h++] = tempIx; } length = d - c < end - 1 - d ? d - c : end - 1 - d; l = b; h = end - length; while (length-- > 0) { tempVal = values[l]; values[l] = values[h]; values[h] = tempVal; tempIx = indexes[l]; indexes[l++] = indexes[h]; indexes[h++] = tempIx; } if ((length = b - a) > 0) { sortByValue(start, start + length, values, indexes); } if ((length = d - c) > 0) { sortByValue(end - length, end, values, indexes); } } /** * In-place sort of two arrays, only indexes is used for comparison and values * of same position are sorted accordingly. * * @param start * @param end * @param indexes * @param values */ public static void sortByValueStable(int start, int end, double[] values, int[] indexes) { sortByValue(start, end, values, indexes); // Maintain the stability of the index order. for( int i=0; i<values.length-1; i++ ) { double tmp = values[i]; //determine run of equal values int len = 0; while( i+len+1<values.length && tmp==values[i+len+1] ) len++; //unstable sort of run indexes (equal value guaranteed) if( len>0 ) { Arrays.sort(indexes, i, i+len+1); i += len; //skip processed run } } } /** * * @param array * @param a * @param b * @param c * @return */ private static int med3(int[] array, int a, int b, int c) { int x = array[a], y = array[b], z = array[c]; return x < y ? (y < z ? b : (x < z ? c : a)) : (y > z ? b : (x > z ? c : a)); } /** * * @param array * @param a * @param b * @param c * @return */ private static int med3(double[] array, int a, int b, int c) { double x = array[a], y = array[b], z = array[c]; return x < y ? (y < z ? b : (x < z ? c : a)) : (y > z ? b : (x > z ? c : a)); } public static void main(String[] args) { int n = 10000000; int[] indexes = new int[n]; double[] values = new double[n]; Random rand = new Random(); for( int i=0; i<n; i++ ) { indexes[i] = rand.nextInt(); values[i] = rand.nextDouble(); } System.out.println("Running quicksort test ..."); Timing time = new Timing(); time.start(); SortUtils.sortByIndex(0, indexes.length, indexes, values); System.out.println("quicksort n="+n+" in "+time.stop()+"ms."); time.start(); boolean flag = SortUtils.isSorted(0, indexes.length, indexes); System.out.println("check sorted n="+n+" in "+time.stop()+"ms, "+flag+"."); } }
package com.eaw1805.data.dto.common; import com.eaw1805.data.constants.ProductionSiteConstants; import com.eaw1805.data.constants.TerrainConstants; import java.io.Serializable; /** * Data-transfer object for the information for the Sector types. */ public class SectorDTO extends PositionDTO implements com.google.gwt.user.client.rpc.IsSerializable, Serializable { /** * Required by Serializable interface. */ static final long serialVersionUID = 31L; //NOPMD /** * Population size for each level. */ private static final int[] POP_LEVELS = {1000, 4000, 10000, 20000, 40000, 60000, 90000, 120000, 160000, 200000}; private static final int NORTH = 0; private static final int EAST = 1; private static final int SOUTH = 2; private static final int WEST = 3; /** * Sector's identification number. */ private int id; // NOPMD /** * Sector's population. */ private int population; /** * Sector's terrain. */ private TerrainDTO terrain; /** * Sector's terrain id. */ private int terrainId; /** * Sector's natural resource. */ private NaturalResourceDTO natResDTO; /** * Sector's natural resource id. */ private int natResId; /** * The Sector's production site. */ private ProductionSiteDTO productionSiteDTO; /** * The Sector's production site. */ private int productionSiteId; /** * The nation that this sector belongs to. */ private NationDTO nationDTO; /** * The nation that this sector belongs to. */ private int nationId; /** * The Sector's political sphere. */ private String politicalSphere; /** * Indicates if this is a economy city. */ private boolean tradeCity; /** * Indicates if this sector was struck by an epidemic during the previous turn. */ private boolean epidemic; /** * Indicates if this sector has rebelled during the previous turn. */ private boolean rebelled; /** * If the sector is a sea-shore. */ private boolean isByTheSea; /** * If the sector was properly maintained during last turn. */ private boolean payed; /** * The name of the sector. */ private String name; /** * The image that represents the state of the sector. */ private String image; /** * The image that represents the geographic info of the sector (no winter). */ private String imageGeo; /** * Indication for storm affecting the sector or is centered on this sector. */ private int storm; /** * Indication if the sector needs to be conquered. */ private boolean needsConquer; /** * Indication if the sector is visible under fog-of-war rules. */ private boolean visible; /** * If the sector is affected by winter. */ private boolean winter; /** * Counter for turns until fully assimilated after a conquer. */ private int conqueredCounter; /** * Indication the progress of building a complex production site. */ private int buildProgress; /** * Signals if the sector was conquered this turn. */ private boolean conquered; /** * Indicator if there is river in the north side of the sector. */ private boolean riverNorth; /** * Indicator if there is river in the east side of the sector. */ private boolean riverEast; /** * Indicator if there is river in the south side of the sector. */ private boolean riverSouth; /** * Indicator if there is river in the west side of the sector. */ private boolean riverWest; /** * The type of the climatic zone. */ private char climaticZone; /** * Default SectorDTO's constructor. */ public SectorDTO() { // Empty constructor isByTheSea = false; } /** * Get the Identification number of the sector. * * @return the identification number of the sector. */ public int getId() { return id; } /** * Set the Identification number of the sector. * * @param identity the identification number of the sector. */ public void setId(final int identity) { this.id = identity; } /** * Get the population of the sector. * * @return the population of the sector. */ public Integer getPopulation() { return population; } /** * Set the population of the sector. * * @param pop the population of the sector. */ public void setPopulation(final int pop) { this.population = pop; } /** * Get the terrain of the sector. * * @return the terrain of the sector. */ public TerrainDTO getTerrain() { return terrain; } /** * Set the terrain of the sector. * * @param value the terrain of the sector. */ public void setTerrain(final TerrainDTO value) { this.terrain = value; } /** * Get the terrain of the sector. * * @return the terrain of the sector. */ public int getTerrainId() { return terrainId; } /** * Set the terrain of the sector. * * @param value the terrain of the sector. */ public void setTerrainId(final int value) { this.terrainId = value; } /** * Get the natural resource number of the sector. * * @return the natural resource number of the sector. */ public NaturalResourceDTO getNatResDTO() { return natResDTO; } /** * Set the natural resource of the sector. * * @param value the natural resource of the sector. */ public void setNatResDTO(final NaturalResourceDTO value) { this.natResDTO = value; } /** * Get the natural resource number of the sector. * * @return the natural resource number of the sector. */ public int getNatResId() { return natResId; } /** * Set the natural resource of the sector. * * @param value the natural resource of the sector. */ public void setNatResId(final int value) { this.natResId = value; } /** * Get the production site of the sector. * * @return the production site of the sector. */ public ProductionSiteDTO getProductionSiteDTO() { return productionSiteDTO; } /** * Set the natural resource of the sector. * * @param value the production site of the sector. */ public void setProductionSiteDTO(final ProductionSiteDTO value) { this.productionSiteDTO = value; } /** * Get the production site of the sector. * * @return the production site of the sector. */ public int getProductionSiteId() { return productionSiteId; } /** * Set the natural resource of the sector. * * @param value the production site of the sector. */ public void setProductionSiteId(final int value) { this.productionSiteId = value; } /** * Get the nation this sector belongs to. * * @return the nation this sector belongs to. */ public NationDTO getNationDTO() { return nationDTO; } /** * Set the nation this sector belongs to. * * @param value The nation this sector belongs to. */ public void setNationDTO(final NationDTO value) { this.nationDTO = value; } /** * Get the nation this sector belongs to. * * @return the nation this sector belongs to. */ public int getNationId() { return nationId; } /** * Set the nation this sector belongs to. * * @param value The nation this sector belongs to. */ public void setNationId(final int value) { this.nationId = value; } /** * Get the political sphere of influence. * * @return the political sphere of influence. */ public char getPoliticalSphere() { return politicalSphere.charAt(0); } /** * Set the political sphere of influence. * * @param thisPSphere the political sphere of influence. */ public void setPoliticalSphere(final char thisPSphere) { this.politicalSphere = String.valueOf(thisPSphere); } /** * Get the indicator if this sector is a the economy city. * * @return true if this sector is a the economy city. */ public boolean getTradeCity() { return tradeCity; } /** * Set the indicator if this sector is a the economy city. * * @param value true if this sector is a the economy city. */ public void setTradeCity(final boolean value) { this.tradeCity = value; } /** * Get the indicator if this sector was struck by an epidemic. * * @return the indicator if this sector was struck by an epidemic. */ public boolean getEpidemic() { return epidemic; } /** * Set the indicator if this sector was struck by an epidemic. * * @param value the indicator if this sector was struck by an epidemic. */ public void setEpidemic(final boolean value) { this.epidemic = value; } /** * Get the indicator if this sector has rebelled. * * @return the indicator if this sector has rebelled. */ public boolean getRebelled() { return rebelled; } /** * Set the indicator if this sector has rebelled. * * @param value the indicator if this sector has rebelled. */ public void setRebelled(final boolean value) { this.rebelled = value; } /** * Set if the sector is a sea-shore sector. * * @param value true if it is a sea-shore sector. */ public void setByTheSea(final boolean value) { this.isByTheSea = value; } /** * Check if the sector is a sea-shore sector. * * @return true if the sector isd a sea-shore sector. */ public boolean isByTheSea() { return isByTheSea; } /** * Get the indicator if this sector was properly maintained or not. * * @return true if this sector was properly maintained. */ public boolean getPayed() { return payed; } /** * Set the indicator if this sector was properly maintained or not. * * @param value true if this sector was properly maintained or not. */ public void setPayed(final boolean value) { this.payed = value; } /** * Check if the sector has a shipyard or a barrack. * * @return true if the sector has a shipyard or a barrack. */ public boolean hasShipyardOrBarracks() { return (getProductionSiteId() == ProductionSiteConstants.PS_BARRACKS) || (getProductionSiteId() == ProductionSiteConstants.PS_BARRACKS_FS) || (getProductionSiteId() == ProductionSiteConstants.PS_BARRACKS_FM) || (getProductionSiteId() == ProductionSiteConstants.PS_BARRACKS_FL) || (getProductionSiteId() == ProductionSiteConstants.PS_BARRACKS_FH); } /** * Determine the level of the sector based on the population size. * * @return the corresponding level. */ public final int populationCount() { int popCount = POP_LEVELS[getPopulation()]; // Deserts have max 500 for level 0 if (getTerrain().getId() == TerrainConstants.TERRAIN_D) { popCount = 500; } return popCount; } /** * Get the name of the sector. * * @return the name of the sector. */ public String getName() { return name; } /** * Set the name of the sector. * * @param value the name of the sector. */ public void setName(final String value) { this.name = value; } /** * Get the image that represents the state of the sector. * * @return the image that represents the state of the sector. */ public String getImage() { return image; } /** * Set the image that represents the state of the sector. * * @param value the image that represents the state of the sector. */ public void setImage(final String value) { this.image = value; } /** * Get the image that represents the geographic state of the sector. * * @return the image that represents the state of the sector. */ public String getImageGeo() { return imageGeo; } /** * Set the image that represents the geographic state of the sector. * * @param value the image that represents the state of the sector. */ public void setImageGeo(final String value) { imageGeo = value; } /** * Get the indication for storm affecting the sector or is centered on this sector. * * @return the indication for storm affecting the sector or is centered on this sector. */ public int getStorm() { return storm; } /** * Set the indication for storm affecting the sector or is centered on this sector. * * @param value the indication for storm affecting the sector or is centered on this sector. */ public void setStorm(final int value) { this.storm = value; } /** * Get the Indication if the sector needs to be conquered. * * @return the Indication if the sector needs to be conquered. */ public boolean getNeedsConquer() { return needsConquer; } /** * Set the Indication if the sector needs to be conquered. * * @param value the Indication if the sector needs to be conquered. */ public void setNeedsConquer(final boolean value) { this.needsConquer = value; } /** * Get the Indication if the sector is visible under fog-of-war rules. * * @return the Indication if the sector is visible under fog-of-war rules. */ public boolean getVisible() { return visible; } /** * Set the Indication if the sector is visible under fog-of-war rules. * * @param value the Indication if the sector is visible under fog-of-war rules. */ public void setVisible(final boolean value) { this.visible = value; } /** * Get if the sector is affected by winter. * * @return if the sector is affected by winter. */ public boolean getWinter() { return winter; } /** * Set if the sector is affected by winter. * * @param value if the sector is affected by winter. */ public void setWinter(final boolean value) { this.winter = value; } /** * Get the counter for turns until fully assimilated after a conquer. * * @return the counter for turns until fully assimilated after a conquer. */ public int getConqueredCounter() { return conqueredCounter; } /** * Set the counter for turns until fully assimilated after a conquer. * * @param counter the counter for turns until fully assimilated after a conquer. */ public void setConqueredCounter(final int counter) { conqueredCounter = counter; } /** * Get indicator on the progress of building a complex production site. * * @return indicator on the progress of building a complex production site. */ public int getBuildProgress() { return buildProgress; } /** * Set the indicator on the progress of building a complex production site. * * @param value indicator on the progress of building a complex production site. */ public void setBuildProgress(final int value) { this.buildProgress = value; } /** * Get if the sector was conquered this turn. * @return if the sector was conquered this turn. */ public boolean getConquered() { return conquered; } /** * Set if the sector was conquered this turn. * @param value if the sector was conquered this turn. */ public void setConquered(final boolean value) { this.conquered = value; } /** * Get if there is river in the north side of the sector. * * @return True if sector has river in the north side. */ public boolean isRiverNorth() { return riverNorth; } /** * Set if there is river in the north side of this sector. * * @param value The value to set. */ public void setRiverNorth(boolean value) { this.riverNorth = value; } /** * Get if there is river in the east side of the sector. * * @return True if sector has river in the east side. */ public boolean isRiverEast() { return riverEast; } /** * Set if there is river in the east side of this sector. * * @param value The value to set. */ public void setRiverEast(boolean value) { this.riverEast = value; } /** * Get if there is river in the south side of the sector. * * @return True if sector has river in the south side. */ public boolean isRiverSouth() { return riverSouth; } /** * Set if there is river in the south side of this sector. * * @param value The value to set. */ public void setRiverSouth(boolean value) { this.riverSouth = value; } /** * Get if there is river in the west side of the sector. * * @return True if sector has river in the west side. */ public boolean isRiverWest() { return riverWest; } /** * Set if there is river in the west side of this sector. * * @param value The value to set. */ public void setRiverWest(boolean value) { this.riverWest = value; } /** * Get the climatic zone for this sector. * * @return The climatic zone indicator. */ public char getClimaticZone() { return climaticZone; } /** * Set the climatic zone. * * @param climaticZone The value to set. */ public void setClimaticZone(char climaticZone) { this.climaticZone = climaticZone; } }
/* * 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.testsuites; import junit.framework.TestSuite; import org.apache.ignite.internal.processors.cache.CacheLocalQueryDetailMetricsSelfTest; import org.apache.ignite.internal.processors.cache.CacheLocalQueryMetricsSelfTest; import org.apache.ignite.internal.processors.cache.CacheOffheapBatchIndexingSingleTypeTest; import org.apache.ignite.internal.processors.cache.CachePartitionedQueryDetailMetricsDistributedSelfTest; import org.apache.ignite.internal.processors.cache.CachePartitionedQueryDetailMetricsLocalSelfTest; import org.apache.ignite.internal.processors.cache.CachePartitionedQueryMetricsDistributedSelfTest; import org.apache.ignite.internal.processors.cache.CachePartitionedQueryMetricsLocalSelfTest; import org.apache.ignite.internal.processors.cache.CacheQueryNewClientSelfTest; import org.apache.ignite.internal.processors.cache.CacheQueryOffheapEvictDataLostTest; import org.apache.ignite.internal.processors.cache.CacheReplicatedQueryDetailMetricsDistributedSelfTest; import org.apache.ignite.internal.processors.cache.CacheReplicatedQueryDetailMetricsLocalSelfTest; import org.apache.ignite.internal.processors.cache.CacheReplicatedQueryMetricsDistributedSelfTest; import org.apache.ignite.internal.processors.cache.CacheReplicatedQueryMetricsLocalSelfTest; import org.apache.ignite.internal.processors.cache.CacheSqlQueryValueCopySelfTest; import org.apache.ignite.internal.processors.cache.GridCacheCrossCacheQuerySelfTest; import org.apache.ignite.internal.processors.cache.GridCacheQueryIndexDisabledSelfTest; import org.apache.ignite.internal.processors.cache.GridCacheQueryIndexingDisabledSelfTest; import org.apache.ignite.internal.processors.cache.GridCacheQueryInternalKeysSelfTest; import org.apache.ignite.internal.processors.cache.GridCacheQuerySerializationSelfTest; import org.apache.ignite.internal.processors.cache.IgniteBinaryObjectFieldsQuerySelfTest; import org.apache.ignite.internal.processors.cache.IgniteBinaryObjectLocalQueryArgumentsTest; import org.apache.ignite.internal.processors.cache.IgniteBinaryObjectQueryArgumentsOffheapLocalTest; import org.apache.ignite.internal.processors.cache.IgniteBinaryObjectQueryArgumentsOffheapTest; import org.apache.ignite.internal.processors.cache.IgniteBinaryObjectQueryArgumentsTest; import org.apache.ignite.internal.processors.cache.IgniteBinaryWrappedObjectFieldsQuerySelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheCollocatedQuerySelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheDeleteSqlQuerySelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheDistributedJoinCollocatedAndNotTest; import org.apache.ignite.internal.processors.cache.IgniteCacheDistributedJoinCustomAffinityMapper; import org.apache.ignite.internal.processors.cache.IgniteCacheDistributedJoinNoIndexTest; import org.apache.ignite.internal.processors.cache.IgniteCacheDistributedJoinPartitionedAndReplicatedTest; import org.apache.ignite.internal.processors.cache.IgniteCacheDistributedJoinQueryConditionsTest; import org.apache.ignite.internal.processors.cache.IgniteCacheDistributedJoinTest; import org.apache.ignite.internal.processors.cache.IgniteCacheDuplicateEntityConfigurationSelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheFieldsQueryNoDataSelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheInsertSqlQuerySelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheJoinPartitionedAndReplicatedTest; import org.apache.ignite.internal.processors.cache.IgniteCacheJoinQueryWithAffinityKeyTest; import org.apache.ignite.internal.processors.cache.IgniteCacheLargeResultSelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheMergeSqlQuerySelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheNoClassQuerySelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheOffheapEvictQueryTest; import org.apache.ignite.internal.processors.cache.IgniteCacheOffheapIndexScanTest; import org.apache.ignite.internal.processors.cache.IgniteCacheP2pUnmarshallingQueryErrorTest; import org.apache.ignite.internal.processors.cache.IgniteCachePrimitiveFieldsQuerySelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheQueryH2IndexingLeakTest; import org.apache.ignite.internal.processors.cache.IgniteCacheQueryIndexSelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheQueryLoadSelfTest; import org.apache.ignite.internal.processors.cache.IgniteCacheUpdateSqlQuerySelfTest; import org.apache.ignite.internal.processors.cache.IgniteCrossCachesJoinsQueryTest; import org.apache.ignite.internal.processors.cache.IncorrectQueryEntityTest; import org.apache.ignite.internal.processors.cache.QueryEntityCaseMismatchTest; import org.apache.ignite.internal.processors.cache.SqlFieldsQuerySelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCacheAtomicFieldsQuerySelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCacheAtomicNearEnabledFieldsQuerySelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCacheAtomicNearEnabledQuerySelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCacheAtomicQuerySelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCacheDistributedQueryCancelSelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCachePartitionedFieldsQueryP2PEnabledSelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCachePartitionedFieldsQuerySelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCachePartitionedQueryP2PDisabledSelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCachePartitionedQuerySelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCachePartitionedSnapshotEnabledQuerySelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCacheQueryAbstractDistributedJoinSelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCacheQueryNoRebalanceSelfTest; import org.apache.ignite.internal.processors.cache.distributed.near.IgniteCacheQueryStopOnCancelOrTimeoutDistributedJoinSelfTest; import org.apache.ignite.internal.processors.cache.distributed.replicated.IgniteCacheReplicatedFieldsQueryP2PEnabledSelfTest; import org.apache.ignite.internal.processors.cache.distributed.replicated.IgniteCacheReplicatedFieldsQuerySelfTest; import org.apache.ignite.internal.processors.cache.distributed.replicated.IgniteCacheReplicatedQueryP2PDisabledSelfTest; import org.apache.ignite.internal.processors.cache.distributed.replicated.IgniteCacheReplicatedQuerySelfTest; import org.apache.ignite.internal.processors.cache.local.IgniteCacheLocalAtomicQuerySelfTest; import org.apache.ignite.internal.processors.cache.local.IgniteCacheLocalFieldsQuerySelfTest; import org.apache.ignite.internal.processors.cache.local.IgniteCacheLocalQueryCancelOrTimeoutSelfTest; import org.apache.ignite.internal.processors.cache.local.IgniteCacheLocalQuerySelfTest; import org.apache.ignite.internal.processors.cache.query.GridCacheQueryTransformerSelfTest; import org.apache.ignite.internal.processors.cache.query.GridCacheSwapScanQuerySelfTest; import org.apache.ignite.internal.processors.cache.query.IgniteCacheQueryCacheDestroySelfTest; import org.apache.ignite.internal.processors.cache.query.IndexingSpiQuerySelfTest; import org.apache.ignite.internal.processors.cache.query.IndexingSpiQueryTxSelfTest; import org.apache.ignite.internal.processors.query.IgniteQueryDedicatedPoolTest; import org.apache.ignite.internal.processors.query.IgniteSqlEntryCacheModeAgnosticTest; import org.apache.ignite.internal.processors.query.IgniteSqlSchemaIndexingTest; import org.apache.ignite.internal.processors.query.IgniteSqlSegmentedIndexSelfTest; import org.apache.ignite.internal.processors.query.IgniteSqlSplitterSelfTest; import org.apache.ignite.internal.processors.query.h2.GridH2IndexingInMemSelfTest; import org.apache.ignite.internal.processors.query.h2.GridH2IndexingOffheapSelfTest; import org.apache.ignite.internal.processors.query.h2.opt.GridH2TableSelfTest; import org.apache.ignite.internal.processors.query.h2.sql.BaseH2CompareQueryTest; import org.apache.ignite.internal.processors.query.h2.sql.GridQueryParsingTest; import org.apache.ignite.internal.processors.query.h2.sql.H2CompareBigQueryDistributedJoinsTest; import org.apache.ignite.internal.processors.query.h2.sql.H2CompareBigQueryTest; import org.apache.ignite.spi.communication.tcp.GridOrderedMessageCancelSelfTest; import org.apache.ignite.testframework.IgniteTestSuite; /** * Test suite for cache queries. */ public class IgniteCacheQuerySelfTestSuite extends TestSuite { /** * @return Test suite. * @throws Exception If failed. */ public static TestSuite suite() throws Exception { IgniteTestSuite suite = new IgniteTestSuite("Ignite Cache Queries Test Suite"); // H2 tests. suite.addTest(new TestSuite(GridH2TableSelfTest.class)); suite.addTest(new TestSuite(GridH2IndexingInMemSelfTest.class)); suite.addTest(new TestSuite(GridH2IndexingOffheapSelfTest.class)); // Parsing suite.addTestSuite(GridQueryParsingTest.class); // Config. suite.addTestSuite(IgniteCacheDuplicateEntityConfigurationSelfTest.class); suite.addTestSuite(IncorrectQueryEntityTest.class); // Queries tests. suite.addTestSuite(IgniteSqlSplitterSelfTest.class); suite.addTestSuite(IgniteSqlSegmentedIndexSelfTest.class); suite.addTestSuite(IgniteSqlSchemaIndexingTest.class); suite.addTestSuite(GridCacheQueryIndexDisabledSelfTest.class); suite.addTestSuite(IgniteCacheQueryLoadSelfTest.class); suite.addTestSuite(IgniteCacheLocalQuerySelfTest.class); suite.addTestSuite(IgniteCacheLocalAtomicQuerySelfTest.class); suite.addTestSuite(IgniteCacheReplicatedQuerySelfTest.class); suite.addTestSuite(IgniteCacheReplicatedQueryP2PDisabledSelfTest.class); suite.addTestSuite(IgniteCachePartitionedQuerySelfTest.class); suite.addTestSuite(IgniteCachePartitionedSnapshotEnabledQuerySelfTest.class); suite.addTestSuite(IgniteCacheAtomicQuerySelfTest.class); suite.addTestSuite(IgniteCacheAtomicNearEnabledQuerySelfTest.class); suite.addTestSuite(IgniteCachePartitionedQueryP2PDisabledSelfTest.class); suite.addTestSuite(IgniteCacheQueryIndexSelfTest.class); suite.addTestSuite(IgniteCacheCollocatedQuerySelfTest.class); suite.addTestSuite(IgniteCacheLargeResultSelfTest.class); suite.addTestSuite(GridCacheQueryInternalKeysSelfTest.class); suite.addTestSuite(IgniteCacheOffheapEvictQueryTest.class); suite.addTestSuite(IgniteCacheOffheapIndexScanTest.class); suite.addTestSuite(IgniteCacheQueryAbstractDistributedJoinSelfTest.class); suite.addTestSuite(GridCacheCrossCacheQuerySelfTest.class); suite.addTestSuite(GridCacheQuerySerializationSelfTest.class); suite.addTestSuite(IgniteBinaryObjectFieldsQuerySelfTest.class); suite.addTestSuite(IgniteBinaryWrappedObjectFieldsQuerySelfTest.class); suite.addTestSuite(IgniteCacheQueryH2IndexingLeakTest.class); suite.addTestSuite(IgniteCacheQueryNoRebalanceSelfTest.class); suite.addTestSuite(GridCacheQueryTransformerSelfTest.class); suite.addTestSuite(IgniteCachePrimitiveFieldsQuerySelfTest.class); suite.addTestSuite(IgniteCacheJoinQueryWithAffinityKeyTest.class); suite.addTestSuite(IgniteCacheDistributedJoinCollocatedAndNotTest.class); suite.addTestSuite(IgniteCacheDistributedJoinPartitionedAndReplicatedTest.class); suite.addTestSuite(IgniteCacheDistributedJoinQueryConditionsTest.class); suite.addTestSuite(IgniteCacheDistributedJoinTest.class); suite.addTestSuite(IgniteCacheJoinPartitionedAndReplicatedTest.class); suite.addTestSuite(IgniteCacheDistributedJoinNoIndexTest.class); suite.addTestSuite(IgniteCrossCachesJoinsQueryTest.class); suite.addTestSuite(IgniteCacheDistributedJoinCustomAffinityMapper.class); suite.addTestSuite(IgniteCacheMergeSqlQuerySelfTest.class); suite.addTestSuite(IgniteCacheInsertSqlQuerySelfTest.class); suite.addTestSuite(IgniteCacheUpdateSqlQuerySelfTest.class); suite.addTestSuite(IgniteCacheDeleteSqlQuerySelfTest.class); suite.addTestSuite(IgniteBinaryObjectQueryArgumentsTest.class); suite.addTestSuite(IgniteBinaryObjectQueryArgumentsOffheapTest.class); suite.addTestSuite(IgniteBinaryObjectQueryArgumentsOffheapLocalTest.class); suite.addTestSuite(IgniteBinaryObjectLocalQueryArgumentsTest.class); suite.addTestSuite(IndexingSpiQuerySelfTest.class); suite.addTestSuite(IndexingSpiQueryTxSelfTest.class); // Fields queries. suite.addTestSuite(SqlFieldsQuerySelfTest.class); suite.addTestSuite(IgniteCacheLocalFieldsQuerySelfTest.class); suite.addTestSuite(IgniteCacheReplicatedFieldsQuerySelfTest.class); suite.addTestSuite(IgniteCacheReplicatedFieldsQueryP2PEnabledSelfTest.class); suite.addTestSuite(IgniteCachePartitionedFieldsQuerySelfTest.class); suite.addTestSuite(IgniteCacheAtomicFieldsQuerySelfTest.class); suite.addTestSuite(IgniteCacheAtomicNearEnabledFieldsQuerySelfTest.class); suite.addTestSuite(IgniteCachePartitionedFieldsQueryP2PEnabledSelfTest.class); suite.addTestSuite(IgniteCacheFieldsQueryNoDataSelfTest.class); suite.addTestSuite(GridCacheQueryIndexingDisabledSelfTest.class); suite.addTestSuite(GridCacheSwapScanQuerySelfTest.class); suite.addTestSuite(GridOrderedMessageCancelSelfTest.class); suite.addTestSuite(CacheQueryOffheapEvictDataLostTest.class); // Ignite cache and H2 comparison. suite.addTestSuite(BaseH2CompareQueryTest.class); suite.addTestSuite(H2CompareBigQueryTest.class); suite.addTestSuite(H2CompareBigQueryDistributedJoinsTest.class); // Cache query metrics. suite.addTestSuite(CacheLocalQueryMetricsSelfTest.class); suite.addTestSuite(CachePartitionedQueryMetricsDistributedSelfTest.class); suite.addTestSuite(CachePartitionedQueryMetricsLocalSelfTest.class); suite.addTestSuite(CacheReplicatedQueryMetricsDistributedSelfTest.class); suite.addTestSuite(CacheReplicatedQueryMetricsLocalSelfTest.class); // Cache query metrics. suite.addTestSuite(CacheLocalQueryDetailMetricsSelfTest.class); suite.addTestSuite(CachePartitionedQueryDetailMetricsDistributedSelfTest.class); suite.addTestSuite(CachePartitionedQueryDetailMetricsLocalSelfTest.class); suite.addTestSuite(CacheReplicatedQueryDetailMetricsDistributedSelfTest.class); suite.addTestSuite(CacheReplicatedQueryDetailMetricsLocalSelfTest.class); // Unmarshalling query test. suite.addTestSuite(IgniteCacheP2pUnmarshallingQueryErrorTest.class); suite.addTestSuite(IgniteCacheNoClassQuerySelfTest.class); // Cancellation. suite.addTestSuite(IgniteCacheDistributedQueryCancelSelfTest.class); suite.addTestSuite(IgniteCacheLocalQueryCancelOrTimeoutSelfTest.class); suite.addTestSuite(IgniteCacheQueryStopOnCancelOrTimeoutDistributedJoinSelfTest.class); // Other. suite.addTestSuite(CacheQueryNewClientSelfTest.class); suite.addTestSuite(CacheOffheapBatchIndexingSingleTypeTest.class); suite.addTestSuite(CacheSqlQueryValueCopySelfTest.class); suite.addTestSuite(IgniteCacheQueryCacheDestroySelfTest.class); suite.addTestSuite(IgniteQueryDedicatedPoolTest.class); suite.addTestSuite(IgniteSqlEntryCacheModeAgnosticTest.class); suite.addTestSuite(QueryEntityCaseMismatchTest.class); return suite; } }
package com.rs.game.player.content; import java.util.HashMap; import java.util.Map; import com.rs.game.Animation; import com.rs.game.ForceTalk; import com.rs.game.Graphics; import com.rs.game.World; import com.rs.game.WorldObject; import com.rs.game.WorldTile; import com.rs.game.item.Item; import com.rs.game.minigames.PuroPuro; import com.rs.game.npc.NPC; import com.rs.game.player.Player; import com.rs.game.player.Skills; import com.rs.game.tasks.WorldTask; import com.rs.game.tasks.WorldTasksManager; import com.rs.utils.Utils; public class Hunter { public static final Animation CAPTURE_ANIMATION = new Animation(6606); public enum FlyingEntities { BABY_IMPLING(1, 1, 20, 25, 17, new Item[] { new Item(946, 1), new Item(1755, 1), new Item(1734, 1), new Item(1733, 1), new Item(2347, 1), new Item(1985, 1) }, null, null, null), YOUNG_IMPLING(1, 1, 48, 65, 22, new Item[] { new Item(361, 1), new Item(1901, 1), new Item(1539, 5), new Item(1784, 4), new Item(1523, 1), new Item(7936, 1), new Item(5970, 1) }, new Item[] { new Item(855, 1), new Item(1353, 1), new Item(2293, 1), new Item(7178, 1), new Item(247, 1), new Item(453, 1), new Item(1777, 1), new Item(231, 1), new Item(2347, 1) }, new Item[] { new Item(1097, 1), new Item(1157, 1), new Item(8778, 1), new Item(133, 1), new Item(2359, 1), }, null), GOURMET_IMPLING(1, 1, 82, 113, 28, null, null, null, null), EARTH_IMPLING(1, 1, 126, 177, 36, null, null, null, null), ESSENCE_IMPLING(1, 1, 160, 225, 42, null, null, null, null), ELECTIC_IMPLING(1, 1, 205, 289, 50, null, null, null, null), SPIRIT_IMPLING(1, 1, 227, 321, 54, null, null, null, null), NATURE_IMPLING(1, 1, 250, 353, 58, null, null, null, null), MAGPIE_IMPLING(1, 1, 289, 409, 65, null, null, null, null), NINJA_IMPLING(1, 1, 339, 481, 74, null, null, null, null), PIRATE_IMPLING(1, 1, 350, 497, 76, null, null, null, null), DRAGON_IMPLING(1, 1, 390, 553, 83, null, null, null, null), ZOMBIE_IMPLING(1, 1, 412, 585, 87, null, null, null, null), KINGLY_IMPLING(1, 1, 434, 617, 91, new Item[] { new Item(1705, Utils.random(3, 11)), new Item(1684, 3), new Item(1618, Utils.random(17, 34)), new Item(990, 2) }, new Item[] { new Item(1631, 1), new Item(1615, 1), new Item(9341, 40 + Utils.getRandom(30)), new Item(9342, 57), new Item(15511, 1), new Item(15509, 1), new Item(15505, 1), new Item(15507, 1), new Item(15503, 1), new Item(11212, 40 + Utils.random(104)), new Item(9193, 62 + Utils.random(8)), new Item(11230, Utils.random(182, 319)), new Item(11232, 70), new Item(1306, Utils.random(1, 2)), new Item(1249, 1) }, null, new Item[] { new Item(7158, 1), new Item(2366, 1), new Item(6571, 1) }), BUTTERFLYTEST(1, 1, 434, 617, 91, null, null, null, null) { @Override public void effect(Player player) { //stat boost } }; static final Map<Short, FlyingEntities> flyingEntities = new HashMap<Short, FlyingEntities>(); static { for (FlyingEntities impling : FlyingEntities.values()) flyingEntities.put((short) impling.reward, impling); } public static FlyingEntities forItem(short reward) { return flyingEntities.get(reward); } private int npcId, level, reward; private double puroExperience, rsExperience; private Item[] rarleyCommon, common, rare, extremelyRare; private Graphics graphics; private FlyingEntities(int npcId, int reward, double puroExperience, double rsExperience, int level, Graphics graphics, Item[] rarleyCommon, Item[] common, Item[] rare, Item[] extremelyRare) { this.npcId = npcId; this.reward = reward; this.puroExperience = puroExperience; this.rsExperience = rsExperience; this.level = level; this.rarleyCommon = rarleyCommon; this.common = common; this.rare = rare; this.extremelyRare = extremelyRare; this.graphics = graphics; } private FlyingEntities(int npcId, int reward, double puroExperience, double rsExperience, int level, Item[] rarleyCommon, Item[] common, Item[] rare, Item[] extremelyRare) { this.npcId = npcId; this.reward = reward; this.puroExperience = puroExperience; this.rsExperience = rsExperience; this.level = level; this.rarleyCommon = rarleyCommon; this.common = common; this.rare = rare; this.extremelyRare = extremelyRare; } public int getNpcId() { return npcId; } public int getLevel() { return level; } public int getReward() { return reward; } public double getPuroExperience() { return puroExperience; } public double getRsExperience() { return rsExperience; } public Item[] getRarleyCommon() { return rarleyCommon; } public Item[] getCommon() { return common; } public Item[] getRare() { return rare; } public Item[] getExtremelyRare() { return extremelyRare; } public Graphics getGraphics() { return graphics; } public void effect(Player player) { } } public interface DynamicFormula { public int getExtraProbablity(Player player); } public static void captureFlyingEntity(final Player player, final NPC npc) {//LOL @ name and each hunter skill should have different formulas I beleive final String name = npc.getDefinitions().name.toUpperCase(); final FlyingEntities instance = FlyingEntities.valueOf(name); final boolean isImpling = name.toLowerCase().contains("impling"); if (!player.getInventory().containsItem(isImpling ? 1 : 11, 1)) return; player.lock(1); player.getPackets().sendGameMessage("You swing your net..."); player.setNextAnimation(CAPTURE_ANIMATION); WorldTasksManager.schedule(new WorldTask() { @Override public void run() { if (isSuccessful(player, instance.getLevel(), new DynamicFormula() { @Override public int getExtraProbablity(Player player) { if (player.getInventory().containsItem(3000, 1) || player.getEquipment().getItem(3).getId() == 3000) return 3;//magic net else if (player.getInventory().containsItem(3001, 1) || player.getEquipment().getItem(3).getId() == 3000) return 2;//regular net return 1;//hands } })) { player.getSkills().addXp(Skills.HUNTER, player.getControlerManager().getControler() instanceof PuroPuro ? instance.getPuroExperience() : instance.getRsExperience()); npc.finish(); player.getInventory().addItem(new Item(instance.getReward(), 1)); player.getPackets().sendGameMessage("...and you successfully caputure the "+ name.toLowerCase()); } else { if (isImpling) { npc.setNextForceTalk(new ForceTalk("Tehee, you missed me!")); WorldTasksManager.schedule(new WorldTask() { @Override public void run() { WorldTile teleTile = npc; for (int trycount = 0; trycount < 10; trycount++) { teleTile = new WorldTile(npc, 10); if (World.canMoveNPC(npc.getPlane(), teleTile.getX(), teleTile.getY(), player.getSize())) break; teleTile = npc; } npc.setNextWorldTile(teleTile); } }); } player.getPackets().sendGameMessage("...you stumble and miss the "+ name.toLowerCase()); } } }); } public static void openJar(Player player, FlyingEntities instance) { boolean isImpling = instance.toString().toLowerCase().contains("impling"); if (isImpling) { int chance = Utils.getRandom(100); Item item = null; if (chance <= 30) { item = instance.getRarleyCommon()[Utils.random(instance.getRarleyCommon().length)]; } else if (chance <= 60) { item = instance.getCommon()[Utils.random(instance.getCommon().length)]; } else if (chance <= 80) { item = instance.getRare()[Utils.random(instance.getRare().length)]; } else if (chance == 100) { item = instance.getExtremelyRare()[Utils.random(instance.getExtremelyRare().length)]; } player.getInventory().addItem(item); } else instance.effect(player); if (Utils.random(100) > 93) { player.getInventory().deleteItem(new Item(isImpling ? 50 : 51, 1)); player.getPackets().sendGameMessage("You press too hard on the jar and the glass shatters in your hands."); } } static int[] requiredLogs = new int[] {1151, 1153, 1155, 1157, 1519, 1521, 13567, 1521, 2862, 10810, 6332, 12581}; public static void createLoggedObject(Player player, WorldObject object, boolean kebbits) { if (!player.getInventory().containsOneItem(requiredLogs)) { player.getPackets().sendGameMessage("You need to have logs to create this trap."); return; } player.lock(3); player.getActionManager().setActionDelay(3); player.setNextAnimation(new Animation(5208));//all animation for everything :L if (World.removeTemporaryObject(object, 300000, false)) {//five minute delay World.spawnTemporaryObject(new WorldObject(kebbits ? 19206 : -1, object.getType(), object.getRotation(), object), 300000, false);//TODO Item item = null; for (int requiredLog : requiredLogs) { if ((item = player.getInventory().getItems().lookup(requiredLog)) != null) { player.getInventory().deleteItem(item); } } } } public static boolean isSuccessful(Player player, int dataLevel, DynamicFormula formula) { int hunterlevel = player.getSkills().getLevel(Skills.HUNTER); int increasedProbability = formula == null ? 1 : formula.getExtraProbablity(player); int level = Utils.random(hunterlevel + increasedProbability) + 1; double ratio = level / (Utils.random(dataLevel + 4) + 1); if (Math.round(ratio * dataLevel) < dataLevel) { return false; } return true; } }
/* * 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 my.home.lehome.fragment; import android.content.Context; import android.graphics.Point; import android.graphics.Rect; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import my.home.lehome.R; import my.home.lehome.mvp.presenters.MessageViewPresenter; import my.home.lehome.mvp.views.SendMessageView; public class MessageFragment extends Fragment implements SendMessageView { public static final String TAG = "MessageFragment"; enum STATE { IDLE, RECORDING, SENDING } MessageViewPresenter mMessageViewPresenter; private int mScreenWidth; private int mScreenHeight; private ProgressBar mStateProgressBar; // private WaveformView mWaveformView; private Button mSendButton; private MessageViewHandler mHandler; private STATE mState = STATE.IDLE; private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() { private Rect rect; @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); mMessageViewPresenter.startRecording(); mSendButton.setPressed(true); return true; } else if (event.getAction() == MotionEvent.ACTION_UP) { if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) { mMessageViewPresenter.cancelRecording(); } else { mMessageViewPresenter.finishRecording(); } mSendButton.setPressed(false); return true; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { if (mState == STATE.RECORDING) { if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) { mSendButton.setText(getString(R.string.message_release_to_cancel)); } else { mSendButton.setText(getString(R.string.message_release_to_send)); } } return true; } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { mSendButton.setPressed(false); } return false; } }; private View.OnClickListener mOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { mMessageViewPresenter.cancelSending(); } }; public MessageFragment() { } public static MessageFragment newInstance() { MessageFragment fragment = new MessageFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupData(); } @Override public void onStart() { super.onStart(); mMessageViewPresenter.start(); } @Override public void onStop() { mMessageViewPresenter.stop(); super.onStop(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Display display = getActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); mScreenWidth = size.x; mScreenHeight = size.y; View contentView = inflater.inflate(R.layout.fragment_send_message, container, false); setupViews(contentView); return contentView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } private void setupData() { mMessageViewPresenter = new MessageViewPresenter(this); mHandler = new MessageViewHandler(); } @Override public void setupViews(View rootView) { mSendButton = (Button) rootView.findViewById(R.id.send_message_btn); mSendButton.setOnTouchListener(mOnTouchListener); mStateProgressBar = (ProgressBar) rootView.findViewById(R.id.message_state_progressBar); mStateProgressBar.setVisibility(View.INVISIBLE); // mWaveformView = (WaveformView) rootView.findViewById(R.id.message_voice_vitrualizer); setRetainInstance(true); } @Override public Context getContext() { return getActivity(); } @Override public void onRecordingBegin() { mSendButton.setText(getString(R.string.message_release_to_send)); mStateProgressBar.setProgress(0); mStateProgressBar.setVisibility(View.VISIBLE); mState = STATE.RECORDING; } @Override public void onRecordingEnd() { mSendButton.setText(getString(R.string.message_press_to_speak)); mStateProgressBar.setProgress(0); mStateProgressBar.setVisibility(View.INVISIBLE); mState = STATE.IDLE; } @Override public void putDataForWaveform(short[] notProcessData, int len) { // mWaveformView.updateAudioData(notProcessData, len); } @Override public void onRecordingAmplitude(double amplitude) { Log.d(TAG, amplitude + " | " + (int) amplitude); mStateProgressBar.setProgress((int) amplitude); } @Override public void onSendingMsgBegin(String tag) { mSendButton.setText(getString(R.string.message_sending)); mSendButton.setOnTouchListener(null); mSendButton.setOnClickListener(mOnClickListener); mState = STATE.SENDING; } @Override public void onSendingMsgSuccess(String tag) { mSendButton.setText(getString(R.string.message_press_to_speak)); mSendButton.setOnTouchListener(mOnTouchListener); mSendButton.setOnClickListener(null); mState = STATE.IDLE; Toast.makeText(getActivity(), getString(R.string.message_sending_success), Toast.LENGTH_SHORT).show(); } @Override public void onSendingMsgFail(String tag) { mSendButton.setText(getString(R.string.message_press_to_speak)); mSendButton.setOnTouchListener(mOnTouchListener); mSendButton.setOnClickListener(null); mState = STATE.IDLE; Toast.makeText(getActivity(), getString(R.string.message_sending_fail), Toast.LENGTH_SHORT).show(); } private class MessageViewHandler extends Handler { @Override public void handleMessage(Message msg) { super.handleMessage(msg); } } }
package com.cs1635.classme; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.support.v7.app.ActionBarActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.animation.AlphaAnimation; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.shared.Post; import org.apmem.tools.layouts.FlowLayout; import java.io.File; import java.util.ArrayList; /** * Created by Robert McDermot on 4/4/14. */ public class CreateNoteActivity extends ActionBarActivity { Activity activity = this; EditText postText, postTitle; Uri captureUri; ArrayList<String> attachmentNames = new ArrayList<String>(), attachmentKeys = new ArrayList<String>(), deleteKeys = new ArrayList<String>(); FlowLayout attachmentsPanel; Post editPost; AlertDialog d; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.create_note); BuckCourse.rememberPosition(BuckCourse.Position.NOTES); postTitle = (EditText) findViewById(R.id.post_title); postText = (EditText) findViewById(R.id.post_text); Bundle bundle = getIntent().getBundleExtra("bundle"); if(bundle != null) editPost = (Post) bundle.getSerializable("post"); ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "temp.jpg"); captureUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); final AlphaAnimation alphaUp = new AlphaAnimation(.2f, 1f); //hack for view.setAlpha in api < 11 alphaUp.setDuration(0); alphaUp.setFillAfter(true); final AlphaAnimation alphaDown = new AlphaAnimation(1f, .2f); alphaDown.setDuration(0); alphaDown.setFillAfter(true); final LinearLayout shareLayout = (LinearLayout) findViewById(R.id.shareLayout); shareLayout.startAnimation(alphaDown); TextWatcher textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if(postText.getText().length() > 0 && postTitle.getText().length() > 0) shareLayout.startAnimation(alphaUp); else shareLayout.startAnimation(alphaDown); } @Override public void onTextChanged(CharSequence s, int start, int before, int count){} @Override public void afterTextChanged(Editable s){} }; postText.addTextChangedListener(textWatcher); postTitle.addTextChangedListener(textWatcher); if(editPost != null) { postText.setText(editPost.getPostContent()); postTitle.setText(editPost.getPostTitle()); if(postText.getText().length() > 0 && postTitle.getText().length() > 0) shareLayout.startAnimation(alphaUp); else shareLayout.startAnimation(alphaDown); } LinearLayout photoLayout = (LinearLayout) findViewById(R.id.photoLayout); photoLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new PhotoDialog(activity); } }); LinearLayout fileLayout = (LinearLayout) findViewById(R.id.fileLayout); fileLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent chooseFile; Intent intent; chooseFile = new Intent(Intent.ACTION_GET_CONTENT); chooseFile.setType("*/*"); intent = Intent.createChooser(chooseFile, "Choose a file"); startActivityForResult(intent, 3); } }); LinearLayout cancelLayout = (LinearLayout) findViewById(R.id.cancelLayout); cancelLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(editPost != null && editPost.getPostContent().equals(postText.getText().toString())) finish(); else if(postText.getText().toString().length() != 0) { AlertDialog.Builder builder = new AlertDialog.Builder(activity) .setTitle("Addendum Mobile") .setMessage("Do you want to discard this post?") .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { activity.finish(); } }); builder.create().show(); } else finish(); } }); shareLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(editPost != null) { postText.setText(postText.getText().toString().replaceAll("\n", "<br>")); editPost.setPostContent(postText.getText().toString()); editPost.setPostTitle(postTitle.getText().toString()); editPost.setAttachmentKeys(attachmentKeys); editPost.setAttachmentNames(attachmentNames); new EditPostTask(activity, attachmentKeys, attachmentNames, deleteKeys, editPost).execute(); } else { if(postText.getText().length() > 0 && postTitle.getText().length() > 0) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); new PostUploadTask(activity, attachmentKeys, attachmentNames, deleteKeys).execute(postTitle.getText().toString(), postText.getText().toString().replaceAll("\n", "<br>"), prefs.getString("loggedIn", ""), BuckCourse.classId, "Note"); } } } }); attachmentsPanel = (FlowLayout) findViewById(R.id.attachmentsPanel); if(editPost != null) { attachmentNames = editPost.getAttachmentNames(); attachmentKeys = editPost.getAttachmentKeys(); for(int i = 0; i < attachmentKeys.size(); i++) { LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View layout = inflater.inflate(R.layout.attachment, null); final TextView name = (TextView) layout.findViewById(R.id.fileName); name.setText(attachmentNames.get(i)); ImageView delete = (ImageView) layout.findViewById(R.id.delete); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for(int i = 0; i < attachmentNames.size(); i++) { if(attachmentNames.get(i).equals(name.getText())) { attachmentNames.remove(i); String key = attachmentKeys.remove(i); attachmentsPanel.removeView(layout); new DeleteAttachmentsTask().execute(key); } } } }); attachmentsPanel.addView(layout); } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { String filePath; if(resultCode != Activity.RESULT_OK) { Toast.makeText(this, "Unable to get file", Toast.LENGTH_SHORT).show(); return; } if(requestCode == 0) filePath = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "temp.png").getPath(); else { filePath = getFilePathFromContentUri(data.getData()); } new FileUploadTask(requestCode == 3, activity, attachmentKeys, attachmentNames, deleteKeys, attachmentsPanel, postText).execute(filePath); } private String getFilePathFromContentUri(Uri uri) { String filePath; try { String[] filePathColumn = {MediaStore.Files.FileColumns.DATA}; Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndexOrThrow(filePathColumn[0]); filePath = cursor.getString(columnIndex); cursor.close(); } catch(Exception e) { filePath = uri.getPath(); } return filePath; } }
/** * 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.commons.cli; import java.util.*; /** * <p><code>Parser</code> creates {@link CommandLine}s.</p> * * @author John Keyes (john at integralsource.com) * @see Parser * @version $Revision: 551815 $ */ public abstract class Parser implements CommandLineParser { /** commandline instance */ private CommandLine cmd; private boolean eatTheRest, processArg, processPropertiesBreakLoop; private Option opt; private ParseException exceptionToThrow; /** * <p>Subclasses must implement this method to reduce * the <code>arguments</code> that have been passed to the parse * method.</p> * * @param opts The Options to parse the arguments by. * @param arguments The arguments that have to be flattened. * @param stopAtNonOption specifies whether to stop * flattening when a non option has been encountered * @return a String array of the flattened arguments */ protected abstract String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption); /** * <p>Parses the specified <code>arguments</code> * based on the specifed {@link Options}.</p> * * @param options the <code>Options</code> * @param arguments the <code>arguments</code> * @return the <code>CommandLine</code> * @throws ParseException if an error occurs when parsing the * arguments. */ public CommandLine parse(Options options, String[] arguments) throws ParseException { return parse(options, arguments, null, false); } /** * Parse the arguments according to the specified options and * properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @return the list of atomic option and value tokens * * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ public CommandLine parse(Options options, String[] arguments, Properties properties) throws ParseException { return parse(options, arguments, properties, false); } /** * <p>Parses the specified <code>arguments</code> * based on the specifed {@link Options}.</p> * * @param options the <code>Options</code> * @param arguments the <code>arguments</code> * @param stopAtNonOption specifies whether to stop * interpreting the arguments when a non option has * been encountered and to add them to the CommandLines * args list. * * @return the <code>CommandLine</code> * @throws ParseException if an error occurs when parsing the * arguments. */ public CommandLine parse(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException { return parse(options, arguments, null, stopAtNonOption); } private boolean processArgCheckException() { boolean res = opt.getValues() == null && !opt.hasOptionalArg(); if (res) exceptionToThrow = new MissingArgumentException( "Missing argument for option:" + opt.getKey()); return res; } /** * Parse the arguments according to the specified options and * properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @param stopAtNonOption stop parsing the arguments when the first * non option is encountered. * * @return the list of atomic option and value tokens * * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ public CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption) throws ParseException { // clear out the data in options in case it's been used before (CLI-71) options.helpOptions().forEach(o -> ((Option)o).clearValues()); List requiredOptions = options.getRequiredOptions(); cmd = new CommandLine(); eatTheRest = processArg = false; exceptionToThrow = null; List<String> tokenList = Arrays .asList(flatten(options, arguments == null ? new String[0] : arguments, stopAtNonOption)); // process each flattened token tokenList.stream().forEachOrdered(t -> { // Abort in case of exception. if (exceptionToThrow != null) return; if (processArg) // found an Option, not an argument if (options.hasOption(t) && t.startsWith("-")) { processArg = false; if (processArgCheckException()) return; } else // found a value try { opt.addValueForProcessing(Util .stripLeadingAndTrailingQuotes(t)); } catch (RuntimeException exp) { processArg = false; if (processArgCheckException()) return; } if (processArg) return; // eat the remaining tokens if (eatTheRest) { // ensure only one double-dash is added if (!"--".equals(t)) cmd.addArg(t); return; } // the value is the double-dash OR single dash and stopAtNonOption=true. if ((t+stopAtNonOption).matches("-true|--(true|false)")) { eatTheRest = true; return; } // the value is a single dash if ("-".equals(t)) { cmd.addArg(t); return; } // the value is an option if (t.startsWith("-")) { if (!options.hasOption(t)) { if (eatTheRest = stopAtNonOption) cmd.addArg(t); else // <processOptions> // if there is no option throw an exceptionToThrow = new UnrecognizedOptionException( "Unrecognized option: " + t); return; } // get the option represented by arg opt = options.getOption(t); // if the option is a required option remove the option from // the requiredOptions list if (opt.isRequired()) requiredOptions.remove(opt.getKey()); // if the option is in an OptionGroup make that option the // selected // option of the group OptionGroup group = options.getOptionGroup(opt); if (group != null) { if (group.isRequired()) requiredOptions.remove(group); try { group.setSelected(opt); } catch (AlreadySelectedException e) { exceptionToThrow = e; return; } } // set the option on the command line cmd.addOption(opt); // if the option takes an argument value processArg = opt.hasArg(); // </processOptions> return; } // the value is an argument cmd.addArg(t); eatTheRest = stopAtNonOption; }); // In case the loop ends while still in "processArg" mode. if (processArg) processArgCheckException(); // Throw any exception that should have been thrown from the forEach. if (exceptionToThrow != null) throw exceptionToThrow; // <processProperties> if (properties != null) { processPropertiesBreakLoop = false; properties.stringPropertyNames().stream().forEachOrdered(optionName -> { if (processPropertiesBreakLoop) return; if (!cmd.hasOption(optionName)) { Option opt = options.getOption(optionName); // get the value from the properties instance String value = properties.getProperty(optionName); if (opt.hasArg()) { if (opt.getValues() == null || opt.getValues().length == 0) try { opt.addValueForProcessing(value); } catch (RuntimeException exp) { // if we cannot add the value don't worry about it } } else if (processPropertiesBreakLoop = !value.toLowerCase().matches("yes|true|1")) // if the value is not yes, true or 1 then don't add the // option to the CommandLine return; cmd.addOption(opt); } }); } // </processProperties> if (requiredOptions.isEmpty()) return cmd; String buff = requiredOptions.size() == 1 ? "Missing required option: " : "Missing required options: "; // loop through the required options throw new MissingOptionException((String)requiredOptions.stream().reduce(buff, (a,b) -> "" + a + b)); } }
// 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. package org.chromium.mojo.bindings; import android.test.suitebuilder.annotation.SmallTest; import org.chromium.base.test.util.UrlUtils; import org.chromium.mojo.HandleMock; import org.chromium.mojo.MojoTestCase; import org.chromium.mojo.bindings.test.mojom.mojo.ConformanceTestInterface; import org.chromium.mojo.bindings.test.mojom.mojo.IntegrationTestInterface; import org.chromium.mojo.bindings.test.mojom.mojo.IntegrationTestInterfaceTestHelper; import org.chromium.mojo.system.Handle; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Testing validation upon deserialization using the interfaces defined in the * mojo/public/interfaces/bindings/tests/validation_test_interfaces.mojom file. * <p> * One needs to pass '--test_data=bindings:{path to mojo/public/interfaces/bindings/tests/data}' to * the test_runner script for this test to find the validation data it needs. */ public class ValidationTest extends MojoTestCase { /** * The path where validation test data is. */ private static final File VALIDATION_TEST_DATA_PATH = new File(UrlUtils.getIsolatedTestFilePath( "mojo/public/interfaces/bindings/tests/data/validation")); /** * The data needed for a validation test. */ private static class TestData { public File dataFile; public ValidationTestUtil.Data inputData; public String expectedResult; } private static class DataFileFilter implements FileFilter { private final String mPrefix; public DataFileFilter(String prefix) { this.mPrefix = prefix; } @Override public boolean accept(File pathname) { // TODO(yzshen, qsr): skip some interface versioning tests. if (pathname.getName().startsWith("conformance_mthd13_good_2")) { return false; } return pathname.isFile() && pathname.getName().startsWith(mPrefix) && pathname.getName().endsWith(".data"); } } private static String getStringContent(File f) throws FileNotFoundException { try (Scanner scanner = new Scanner(f)) { scanner.useDelimiter("\\Z"); StringBuilder result = new StringBuilder(); while (scanner.hasNext()) { result.append(scanner.next()); } return result.toString().trim(); } } private static List<TestData> getTestData(String prefix) throws FileNotFoundException { List<TestData> results = new ArrayList<TestData>(); // Fail if the test data is not present. if (!VALIDATION_TEST_DATA_PATH.isDirectory()) { fail("No test data directory found. " + "Expected directory at: " + VALIDATION_TEST_DATA_PATH); } File[] files = VALIDATION_TEST_DATA_PATH.listFiles(new DataFileFilter(prefix)); if (files != null) { for (File dataFile : files) { File resultFile = new File(dataFile.getParent(), dataFile.getName().replaceFirst("\\.data$", ".expected")); TestData testData = new TestData(); testData.dataFile = dataFile; testData.inputData = ValidationTestUtil.parseData(getStringContent(dataFile)); testData.expectedResult = getStringContent(resultFile); results.add(testData); } } return results; } /** * Runs all the test with the given prefix on the given {@link MessageReceiver}. */ private static void runTest(String prefix, MessageReceiver messageReceiver) throws FileNotFoundException { List<TestData> testData = getTestData(prefix); for (TestData test : testData) { assertNull("Unable to read: " + test.dataFile.getName() + ": " + test.inputData.getErrorMessage(), test.inputData.getErrorMessage()); List<Handle> handles = new ArrayList<Handle>(); for (int i = 0; i < test.inputData.getHandlesCount(); ++i) { handles.add(new HandleMock()); } Message message = new Message(test.inputData.getData(), handles); boolean passed = messageReceiver.accept(message); if (passed && !test.expectedResult.equals("PASS")) { fail("Input: " + test.dataFile.getName() + ": The message should have been refused. Expected error: " + test.expectedResult); } if (!passed && test.expectedResult.equals("PASS")) { fail("Input: " + test.dataFile.getName() + ": The message should have been accepted."); } } } private static class RoutingMessageReceiver implements MessageReceiver { private final MessageReceiverWithResponder mRequest; private final MessageReceiver mResponse; private RoutingMessageReceiver(MessageReceiverWithResponder request, MessageReceiver response) { this.mRequest = request; this.mResponse = response; } /** * @see MessageReceiver#accept(Message) */ @Override public boolean accept(Message message) { try { MessageHeader header = message.asServiceMessage().getHeader(); if (header.hasFlag(MessageHeader.MESSAGE_IS_RESPONSE_FLAG)) { return mResponse.accept(message); } else { return mRequest.acceptWithResponder(message, new SinkMessageReceiver()); } } catch (DeserializationException e) { return false; } } /** * @see MessageReceiver#close() */ @Override public void close() { } } /** * A trivial message receiver that refuses all messages it receives. */ private static class SinkMessageReceiver implements MessageReceiverWithResponder { @Override public boolean accept(Message message) { return true; } @Override public void close() { } @Override public boolean acceptWithResponder(Message message, MessageReceiver responder) { return true; } } /** * Testing the conformance suite. */ @SmallTest public void testConformance() throws FileNotFoundException { runTest("conformance_", ConformanceTestInterface.MANAGER.buildStub(null, ConformanceTestInterface.MANAGER.buildProxy(null, new SinkMessageReceiver()))); } /** * Testing the integration suite for message headers. */ @SmallTest public void testIntegrationMessageHeader() throws FileNotFoundException { runTest("integration_msghdr_", new RoutingMessageReceiver(IntegrationTestInterface.MANAGER.buildStub(null, IntegrationTestInterface.MANAGER.buildProxy(null, new SinkMessageReceiver())), IntegrationTestInterfaceTestHelper .newIntegrationTestInterfaceMethodCallback())); } /** * Testing the integration suite for request messages. */ @SmallTest public void testIntegrationRequestMessage() throws FileNotFoundException { runTest("integration_intf_rqst_", new RoutingMessageReceiver(IntegrationTestInterface.MANAGER.buildStub(null, IntegrationTestInterface.MANAGER.buildProxy(null, new SinkMessageReceiver())), IntegrationTestInterfaceTestHelper .newIntegrationTestInterfaceMethodCallback())); } /** * Testing the integration suite for response messages. */ @SmallTest public void testIntegrationResponseMessage() throws FileNotFoundException { runTest("integration_intf_resp_", new RoutingMessageReceiver(IntegrationTestInterface.MANAGER.buildStub(null, IntegrationTestInterface.MANAGER.buildProxy(null, new SinkMessageReceiver())), IntegrationTestInterfaceTestHelper .newIntegrationTestInterfaceMethodCallback())); } }
/** * File: AnnotationSetNode.java Copyright (c) 2010 phyo 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 synergyviewcore.annotations.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.TypedQuery; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import synergyviewcommons.collections.CollectionChangeListener; import synergyviewcommons.collections.IObservableList; import synergyviewcommons.collections.ObservableList; import synergyviewcore.Activator; import synergyviewcore.annotations.ui.editors.CollectionMediaClipAnnotationEditor; import synergyviewcore.model.ModelPersistenceException; import synergyviewcore.navigation.model.AbstractParent; import synergyviewcore.navigation.model.DisposeException; import synergyviewcore.navigation.model.IParentNode; import synergyviewcore.projects.ui.NodeEditorInput; import synergyviewcore.resource.ResourceLoader; import synergyviewcore.subjects.model.Subject; /** * The Class AnnotationSetNode. * * @author phyo */ public class AnnotationSetNode extends AbstractParent<AnnotationSet> { /** The Constant ANNOTATION_ICON. */ public static final String ANNOTATION_ICON = "note.png"; /** The annotation attribute map. */ private Map<Annotation, AnnotationAttributeController> annotationAttributeMap = new HashMap<Annotation, AnnotationAttributeController>(); /** The annotation list. */ private IObservableList<List<Annotation>, Annotation> annotationList; /** The e manager factory. */ private EntityManagerFactory eManagerFactory; /** The subject annotation map. */ private Map<Subject, IObservableList<List<Annotation>, Annotation>> subjectAnnotationMap = new HashMap<Subject, IObservableList<List<Annotation>, Annotation>>(); /** The subject list. */ private IObservableList<List<Subject>, Subject> subjectList; /** * Instantiates a new annotation set node. * * @param annotationSet * the annotation set * @param parentValue * the parent value */ public AnnotationSetNode(AnnotationSet annotationSet, IParentNode parentValue) { super(annotationSet, parentValue); this.setLabel(annotationSet.getName()); eManagerFactory = this.getEMFactoryProvider().getEntityManagerFactory(); initialise(); } /** * Adds the annotation list change listener. * * @param listener * the listener */ public void addAnnotationListChangeListener(CollectionChangeListener listener) { annotationList.addChangeListener(listener); } /** * Adds the annotation list change listener. * * @param listener * the listener * @param subject * the subject * @throws Exception * the exception */ public void addAnnotationListChangeListener(CollectionChangeListener listener, Subject subject) throws Exception { // Check the parameter if (subject == null) { throw new IllegalArgumentException("Subject parameter is null"); } IObservableList<List<Annotation>, Annotation> tempList = subjectAnnotationMap.get(subject); if (tempList == null) { throw new IllegalArgumentException("Subject not found"); } tempList.addChangeListener(listener); } /** * Adds the annotations. * * @param annotations * the annotations * @param subject * the subject * @throws ModelPersistenceException * the model persistence exception */ public void addAnnotations(List<Annotation> annotations, Subject subject) throws ModelPersistenceException { EntityManager entityManager = null; IObservableList<List<Annotation>, Annotation> tempList = subjectAnnotationMap.get(subject); if (tempList != null) { try { for (Annotation annotation : annotations) { if (!isAnntationWithinClip(annotation)) { throw new Exception("Unable to add annotation with the following text as it is out of media clip area: " + annotation.getText()); } } entityManager = eManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); for (Annotation annotation : annotations) { annotation.setAnnotationSet(this.getResource()); annotation.setSubject(subject); entityManager.persist(annotation); annotationAttributeMap.put(annotation, new AnnotationAttributeController(annotation, eManagerFactory)); } entityManager.getTransaction().commit(); tempList.addAll(annotations); annotationList.addAll(annotations); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); throw new ModelPersistenceException("Unable to add annotation", ex); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } } /** * Adds the subject list change listener. * * @param listener * the listener */ public void addSubjectListChangeListener(CollectionChangeListener listener) { subjectList.addChangeListener(listener); } /** * Adds the subjects. * * @param subjects * the subjects * @throws ModelPersistenceException * the model persistence exception */ public void addSubjects(List<Subject> subjects) throws ModelPersistenceException { EntityManager entityManager = null; if (!subjectList.containsAll(subjects)) { try { entityManager = eManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); for (Subject subject : subjects) { List<Annotation> annotationList = new ArrayList<Annotation>(); subjectAnnotationMap.put(subject, new ObservableList<List<Annotation>, Annotation>(annotationList)); } subjectList.addAll(subjects); entityManager.merge(resource); entityManager.getTransaction().commit(); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); throw new ModelPersistenceException("Unable to add subjects.", ex); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } } /* * (non-Javadoc) * * @see synergyviewcommons.jface.node.INode#dispose() */ public void dispose() throws DisposeException { // Find the close the editor related to this annotation set Display.getDefault().asyncExec(new Runnable() { public void run() { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { for (IWorkbenchPage pageRef : window.getPages()) { for (IEditorReference editorRef : pageRef.getEditorReferences()) { try { if (editorRef.getId().compareTo(CollectionMediaClipAnnotationEditor.ID) == 0) { NodeEditorInput cNodeEditorInput = (NodeEditorInput) editorRef.getEditorInput(); if (AnnotationSetNode.this == cNodeEditorInput.getNode()) { pageRef.closeEditor(editorRef.getEditor(false), false); } } } catch (PartInitException ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); } } } } } }); } /** * Gets the annotation attribute controller. * * @param annotation * the annotation * @return the annotation attribute controller */ public AnnotationAttributeController getAnnotationAttributeController(Annotation annotation) { return annotationAttributeMap.get(annotation); } /** * Gets the annotation list. * * @return the annotation list */ public List<Annotation> getAnnotationList() { return annotationList.getReadOnlyList(); } /** * Gets the annotation list. * * @param subject * the subject * @return the annotation list */ public List<Annotation> getAnnotationList(Subject subject) { // TODO throws exception if (subjectList.contains(subject) && subjectAnnotationMap.containsKey(subject)) { return subjectAnnotationMap.get(subject).getReadOnlyList(); } else { return null; } } /* * (non-Javadoc) * * @see synergyviewcommons.jface.node.IParentNode#getChildrenNames() */ public List<String> getChildrenNames() { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see synergyviewcore.navigation.model.AbstractNode#getIcon() */ public ImageDescriptor getIcon() { return ResourceLoader.getIconDescriptor(ANNOTATION_ICON); } /** * Gets the subject list. * * @return the subject list */ public List<Subject> getSubjectList() { return subjectList.getReadOnlyList(); } /** * Hide caption. * * @param value * the value */ public void hideCaption(boolean value) { EntityManager entityManager = null; this.resource.setHideCaption(value); try { entityManager = eManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.merge(this.resource); entityManager.getTransaction().commit(); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } /** * Initialise. */ private void initialise() { EntityManager entityManager = null; try { entityManager = eManagerFactory.createEntityManager(); entityManager.merge(resource); subjectList = new ObservableList<List<Subject>, Subject>(resource.getSubjectList()); List<Annotation> tempAnnotationList = new ArrayList<Annotation>(); for (Subject subject : subjectList.getReadOnlyList()) { TypedQuery<Annotation> annotationQuery = entityManager.createQuery("SELECT A from Annotation A WHERE A.subject = :subject AND A.annotationSet = :set", Annotation.class); annotationQuery.setParameter("subject", subject); annotationQuery.setParameter("set", resource); IObservableList<List<Annotation>, Annotation> tempList = new ObservableList<List<Annotation>, Annotation>(annotationQuery.getResultList()); for (Annotation annotation : tempList.getReadOnlyList()) { tempAnnotationList.add(annotation); annotation.setAnnotationSet(resource); annotationAttributeMap.put(annotation, new AnnotationAttributeController(annotation, eManagerFactory)); } subjectAnnotationMap.put(subject, tempList); } resource.setAnnotationList(tempAnnotationList); resource.sortAnnoatationList(); annotationList = new ObservableList<List<Annotation>, Annotation>(resource.getAnnotationList()); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } /** * Checks if is anntation within clip. * * @param annotation * the annotation * @return true, if is anntation within clip */ private boolean isAnntationWithinClip(Annotation annotation) { long clipStartMilli = this.getResource().getCollectionMediaClip().getStartOffset(); long clipEndMilli = clipStartMilli + this.getResource().getCollectionMediaClip().getDuration(); if (annotation instanceof IntervalAnnotation) { IntervalAnnotation iAnnotation = (IntervalAnnotation) annotation; if ((iAnnotation.getStartTime() >= clipStartMilli) && ((iAnnotation.getDuration() + iAnnotation.getStartTime()) <= clipEndMilli)) { return true; } else { return false; } } else { if ((annotation.getStartTime() >= clipStartMilli) && (annotation.getStartTime() <= clipEndMilli)) { return true; } else { return false; } } } /** * Move annotation. * * @param annotation * the annotation * @param fromSubject * the from subject * @param toSubject * the to subject * @throws ModelPersistenceException * the model persistence exception */ public void moveAnnotation(Annotation annotation, Subject fromSubject, Subject toSubject) throws ModelPersistenceException { EntityManager entityManager = null; try { entityManager = eManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); annotation.setSubject(toSubject); entityManager.merge(annotation); entityManager.getTransaction().commit(); subjectAnnotationMap.get(fromSubject).remove(annotation); subjectAnnotationMap.get(toSubject).add(annotation); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); throw new ModelPersistenceException("Unable to update annotation", ex); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } /** * Removes the annotation list change listener. * * @param listener * the listener */ public void removeAnnotationListChangeListener(CollectionChangeListener listener) { annotationList.removeChangeListener(listener); } /** * Removes the annotation list change listener. * * @param listener * the listener * @param subject * the subject * @throws Exception * the exception */ public void removeAnnotationListChangeListener(CollectionChangeListener listener, Subject subject) throws Exception { // Check the parameter if (subject == null) { throw new IllegalArgumentException("Subject parameter is null"); } IObservableList<List<Annotation>, Annotation> tempList = subjectAnnotationMap.get(subject); if (tempList != null) { tempList.removeChangeListener(listener); } } /** * Removes the annotations. * * @param annotations * the annotations * @param subject * the subject * @throws ModelPersistenceException * the model persistence exception */ public void removeAnnotations(List<Annotation> annotations, Subject subject) throws ModelPersistenceException { EntityManager entityManager = null; IObservableList<List<Annotation>, Annotation> tempList = subjectAnnotationMap.get(subject); if (tempList != null) { try { entityManager = eManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); for (Annotation annotation : annotations) { Annotation annoToRemove = entityManager.merge(annotation); entityManager.remove(annoToRemove); } entityManager.getTransaction().commit(); for (Annotation annotation : annotations) { annotationAttributeMap.remove(annotation); } tempList.removeAll(annotations); annotationList.removeAll(annotations); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); throw new ModelPersistenceException("Unable to remove annotation.", ex); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } } /** * Removes the subject list change listener. * * @param listener * the listener */ public void removeSubjectListChangeListener(CollectionChangeListener listener) { subjectList.removeChangeListener(listener); } /** * Removes the subjects. * * @param subjects * the subjects * @throws ModelPersistenceException * the model persistence exception */ public void removeSubjects(List<Subject> subjects) throws ModelPersistenceException { // TODO this needs to be in one transaction EntityManager entityManager = null; if (subjectList.containsAll(subjects)) { for (Subject subject : subjects) { if (!subjectAnnotationMap.containsKey(subject)) { return; } } try { for (Subject subject : subjects) { this.removeAnnotations(subjectAnnotationMap.get(subject), subject); subjectAnnotationMap.remove(subject); } entityManager = eManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); subjectList.removeAll(subjects); entityManager.merge(resource); entityManager.getTransaction().commit(); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); throw new ModelPersistenceException("Unable to remove subjects.", ex); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } } /** * Rename annotation set. * * @param newName * the new name * @throws ModelPersistenceException * the model persistence exception */ public void renameAnnotationSet(String newName) throws ModelPersistenceException { EntityManager entityManager = null; try { entityManager = eManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); this.resource.setName(newName); entityManager.merge(this.resource); entityManager.getTransaction().commit(); this.setLabel(resource.getName()); this.getViewerProvider().getTreeViewer().refresh(this); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); throw new ModelPersistenceException("Unable to update annotation set", ex); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } /** * Sets the lock. * * @param isLock * the new lock */ public void setLock(boolean isLock) { this.resource.setLock(isLock); EntityManager entityManager = null; try { entityManager = eManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.merge(this.resource); entityManager.getTransaction().commit(); this.getViewerProvider().getTreeViewer().refresh(this); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } /** * Update annotation. * * @param annotation * the annotation * @throws ModelPersistenceException * the model persistence exception */ // public void addAttributeToAnnotation(Annotation annotation, // List<Attribute> attributesToAdd) { // EntityManager entityManager = null; // try { // for (Attribute a : attributesToAdd) { // if (!annotation.getAttributes().contains(a)) // annotation.getAttributes().add(a); // } // entityManager = eManagerFactory.createEntityManager(); // entityManager.getTransaction().begin(); // entityManager.merge(annotation); // entityManager.getTransaction().commit(); // } catch (Exception ex) { // IStatus status = new // Status(IStatus.ERROR,Activator.PLUGIN_ID,ex.getMessage(), ex); // logger.log(status); // } finally { // if (entityManager.isOpen()) // entityManager.close(); // } // } public void updateAnnotation(Annotation annotation) throws ModelPersistenceException { EntityManager entityManager = null; try { entityManager = eManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.merge(annotation); entityManager.getTransaction().commit(); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex); logger.log(status); throw new ModelPersistenceException("Unable to update annotation", ex); } finally { if (entityManager.isOpen()) { entityManager.close(); } } } }
/** * * 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.master; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.ClusterStatus; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MetaTableAccessor; import org.apache.hadoop.hbase.MiniHBaseCluster; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.RegionLocator; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.master.RegionState.State; import org.apache.hadoop.hbase.protobuf.RequestConverter; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.regionserver.Region; import org.apache.hadoop.hbase.testclassification.FlakeyTests; import org.apache.hadoop.hbase.testclassification.LargeTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSTableDescriptors; import org.apache.hadoop.hbase.util.FSUtils; import org.apache.hadoop.hbase.util.JVMClusterUtil.MasterThread; import org.apache.hadoop.hbase.zookeeper.MetaTableLocator; import org.junit.Test; import org.junit.experimental.categories.Category; @Category({FlakeyTests.class, LargeTests.class}) public class TestMasterFailover { private static final Log LOG = LogFactory.getLog(TestMasterFailover.class); HRegion createRegion(final HRegionInfo hri, final Path rootdir, final Configuration c, final HTableDescriptor htd) throws IOException { HRegion r = HBaseTestingUtility.createRegionAndWAL(hri, rootdir, c, htd); // The above call to create a region will create an wal file. Each // log file create will also create a running thread to do syncing. We need // to close out this log else we will have a running thread trying to sync // the file system continuously which is ugly when dfs is taken away at the // end of the test. HBaseTestingUtility.closeRegionAndWAL(r); return r; } // TODO: Next test to add is with testing permutations of the RIT or the RS // killed are hosting ROOT and hbase:meta regions. private void log(String string) { LOG.info("\n\n" + string + " \n\n"); } /** * Simple test of master failover. * <p> * Starts with three masters. Kills a backup master. Then kills the active * master. Ensures the final master becomes active and we can still contact * the cluster. * @throws Exception */ @Test (timeout=240000) public void testSimpleMasterFailover() throws Exception { final int NUM_MASTERS = 3; final int NUM_RS = 3; // Start the cluster HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); TEST_UTIL.startMiniCluster(NUM_MASTERS, NUM_RS); MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); // get all the master threads List<MasterThread> masterThreads = cluster.getMasterThreads(); // wait for each to come online for (MasterThread mt : masterThreads) { assertTrue(mt.isAlive()); } // verify only one is the active master and we have right number int numActive = 0; int activeIndex = -1; ServerName activeName = null; HMaster active = null; for (int i = 0; i < masterThreads.size(); i++) { if (masterThreads.get(i).getMaster().isActiveMaster()) { numActive++; activeIndex = i; active = masterThreads.get(activeIndex).getMaster(); activeName = active.getServerName(); } } assertEquals(1, numActive); assertEquals(NUM_MASTERS, masterThreads.size()); LOG.info("Active master " + activeName); // Check that ClusterStatus reports the correct active and backup masters assertNotNull(active); ClusterStatus status = active.getClusterStatus(); assertTrue(status.getMaster().equals(activeName)); assertEquals(2, status.getBackupMastersSize()); assertEquals(2, status.getBackupMasters().size()); // attempt to stop one of the inactive masters int backupIndex = (activeIndex == 0 ? 1 : activeIndex - 1); HMaster master = cluster.getMaster(backupIndex); LOG.debug("\n\nStopping a backup master: " + master.getServerName() + "\n"); cluster.stopMaster(backupIndex, false); cluster.waitOnMaster(backupIndex); // Verify still one active master and it's the same for (int i = 0; i < masterThreads.size(); i++) { if (masterThreads.get(i).getMaster().isActiveMaster()) { assertTrue(activeName.equals(masterThreads.get(i).getMaster().getServerName())); activeIndex = i; active = masterThreads.get(activeIndex).getMaster(); } } assertEquals(1, numActive); assertEquals(2, masterThreads.size()); int rsCount = masterThreads.get(activeIndex).getMaster().getClusterStatus().getServersSize(); LOG.info("Active master " + active.getServerName() + " managing " + rsCount + " regions servers"); assertEquals(4, rsCount); // Check that ClusterStatus reports the correct active and backup masters assertNotNull(active); status = active.getClusterStatus(); assertTrue(status.getMaster().equals(activeName)); assertEquals(1, status.getBackupMastersSize()); assertEquals(1, status.getBackupMasters().size()); // kill the active master LOG.debug("\n\nStopping the active master " + active.getServerName() + "\n"); cluster.stopMaster(activeIndex, false); cluster.waitOnMaster(activeIndex); // wait for an active master to show up and be ready assertTrue(cluster.waitForActiveAndReadyMaster()); LOG.debug("\n\nVerifying backup master is now active\n"); // should only have one master now assertEquals(1, masterThreads.size()); // and he should be active active = masterThreads.get(0).getMaster(); assertNotNull(active); status = active.getClusterStatus(); ServerName mastername = status.getMaster(); assertTrue(mastername.equals(active.getServerName())); assertTrue(active.isActiveMaster()); assertEquals(0, status.getBackupMastersSize()); assertEquals(0, status.getBackupMasters().size()); int rss = status.getServersSize(); LOG.info("Active master " + mastername.getServerName() + " managing " + rss + " region servers"); assertEquals(4, rss); // Stop the cluster TEST_UTIL.shutdownMiniCluster(); } /** * Test region in pending_open/close when master failover */ @Test (timeout=180000) public void testPendingOpenOrCloseWhenMasterFailover() throws Exception { final int NUM_MASTERS = 1; final int NUM_RS = 1; // Create config to use for this cluster Configuration conf = HBaseConfiguration.create(); // Start the cluster HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(conf); TEST_UTIL.startMiniCluster(NUM_MASTERS, NUM_RS); MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); log("Cluster started"); // get all the master threads List<MasterThread> masterThreads = cluster.getMasterThreads(); assertEquals(1, masterThreads.size()); // only one master thread, let's wait for it to be initialized assertTrue(cluster.waitForActiveAndReadyMaster()); HMaster master = masterThreads.get(0).getMaster(); assertTrue(master.isActiveMaster()); assertTrue(master.isInitialized()); // Create a table with a region online Table onlineTable = TEST_UTIL.createTable(TableName.valueOf("onlineTable"), "family"); onlineTable.close(); // Create a table in META, so it has a region offline HTableDescriptor offlineTable = new HTableDescriptor( TableName.valueOf(Bytes.toBytes("offlineTable"))); offlineTable.addFamily(new HColumnDescriptor(Bytes.toBytes("family"))); FileSystem filesystem = FileSystem.get(conf); Path rootdir = FSUtils.getRootDir(conf); FSTableDescriptors fstd = new FSTableDescriptors(conf, filesystem, rootdir); fstd.createTableDescriptor(offlineTable); HRegionInfo hriOffline = new HRegionInfo(offlineTable.getTableName(), null, null); createRegion(hriOffline, rootdir, conf, offlineTable); MetaTableAccessor.addRegionToMeta(master.getConnection(), hriOffline); log("Regions in hbase:meta and namespace have been created"); // at this point we only expect 3 regions to be assigned out // (catalogs and namespace, + 1 online region) assertEquals(3, cluster.countServedRegions()); HRegionInfo hriOnline = null; try (RegionLocator locator = TEST_UTIL.getConnection().getRegionLocator(TableName.valueOf("onlineTable"))) { hriOnline = locator.getRegionLocation(HConstants.EMPTY_START_ROW).getRegionInfo(); } RegionStates regionStates = master.getAssignmentManager().getRegionStates(); RegionStateStore stateStore = master.getAssignmentManager().getRegionStateStore(); // Put the online region in pending_close. It is actually already opened. // This is to simulate that the region close RPC is not sent out before failover RegionState oldState = regionStates.getRegionState(hriOnline); RegionState newState = new RegionState( hriOnline, State.PENDING_CLOSE, oldState.getServerName()); stateStore.updateRegionState(HConstants.NO_SEQNUM, newState, oldState); // Put the offline region in pending_open. It is actually not opened yet. // This is to simulate that the region open RPC is not sent out before failover oldState = new RegionState(hriOffline, State.OFFLINE); newState = new RegionState(hriOffline, State.PENDING_OPEN, newState.getServerName()); stateStore.updateRegionState(HConstants.NO_SEQNUM, newState, oldState); HRegionInfo failedClose = new HRegionInfo(offlineTable.getTableName(), null, null); createRegion(failedClose, rootdir, conf, offlineTable); MetaTableAccessor.addRegionToMeta(master.getConnection(), failedClose); oldState = new RegionState(failedClose, State.PENDING_CLOSE); newState = new RegionState(failedClose, State.FAILED_CLOSE, newState.getServerName()); stateStore.updateRegionState(HConstants.NO_SEQNUM, newState, oldState); HRegionInfo failedOpen = new HRegionInfo(offlineTable.getTableName(), null, null); createRegion(failedOpen, rootdir, conf, offlineTable); MetaTableAccessor.addRegionToMeta(master.getConnection(), failedOpen); // Simulate a region transitioning to failed open when the region server reports the // transition as FAILED_OPEN oldState = new RegionState(failedOpen, State.PENDING_OPEN); newState = new RegionState(failedOpen, State.FAILED_OPEN, newState.getServerName()); stateStore.updateRegionState(HConstants.NO_SEQNUM, newState, oldState); HRegionInfo failedOpenNullServer = new HRegionInfo(offlineTable.getTableName(), null, null); LOG.info("Failed open NUll server " + failedOpenNullServer.getEncodedName()); createRegion(failedOpenNullServer, rootdir, conf, offlineTable); MetaTableAccessor.addRegionToMeta(master.getConnection(), failedOpenNullServer); // Simulate a region transitioning to failed open when the master couldn't find a plan for // the region oldState = new RegionState(failedOpenNullServer, State.OFFLINE); newState = new RegionState(failedOpenNullServer, State.FAILED_OPEN, null); stateStore.updateRegionState(HConstants.NO_SEQNUM, newState, oldState); // Stop the master log("Aborting master"); cluster.abortMaster(0); cluster.waitOnMaster(0); log("Master has aborted"); // Start up a new master log("Starting up a new master"); master = cluster.startMaster().getMaster(); log("Waiting for master to be ready"); cluster.waitForActiveAndReadyMaster(); log("Master is ready"); // Wait till no region in transition any more TEST_UTIL.waitUntilNoRegionsInTransition(60000); // Get new region states since master restarted regionStates = master.getAssignmentManager().getRegionStates(); // Both pending_open (RPC sent/not yet) regions should be online assertTrue(regionStates.isRegionOnline(hriOffline)); assertTrue(regionStates.isRegionOnline(hriOnline)); assertTrue(regionStates.isRegionOnline(failedClose)); assertTrue(regionStates.isRegionOnline(failedOpenNullServer)); assertTrue(regionStates.isRegionOnline(failedOpen)); log("Done with verification, shutting down cluster"); // Done, shutdown the cluster TEST_UTIL.shutdownMiniCluster(); } /** * Test meta in transition when master failover */ @Test(timeout = 180000) public void testMetaInTransitionWhenMasterFailover() throws Exception { final int NUM_MASTERS = 1; final int NUM_RS = 1; // Start the cluster HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); TEST_UTIL.startMiniCluster(NUM_MASTERS, NUM_RS); MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); log("Cluster started"); log("Moving meta off the master"); HMaster activeMaster = cluster.getMaster(); HRegionServer rs = cluster.getRegionServer(0); ServerName metaServerName = cluster.getLiveRegionServerThreads() .get(0).getRegionServer().getServerName(); activeMaster.move(HRegionInfo.FIRST_META_REGIONINFO.getEncodedNameAsBytes(), Bytes.toBytes(metaServerName.getServerName())); TEST_UTIL.waitUntilNoRegionsInTransition(60000); assertEquals("Meta should be assigned on expected regionserver", metaServerName, activeMaster.getMetaTableLocator() .getMetaRegionLocation(activeMaster.getZooKeeper())); // Now kill master, meta should remain on rs, where we placed it before. log("Aborting master"); activeMaster.abort("test-kill"); cluster.waitForMasterToStop(activeMaster.getServerName(), 30000); log("Master has aborted"); // meta should remain where it was RegionState metaState = MetaTableLocator.getMetaRegionState(rs.getZooKeeper()); assertEquals("hbase:meta should be onlined on RS", metaState.getServerName(), rs.getServerName()); assertEquals("hbase:meta should be onlined on RS", metaState.getState(), State.OPEN); // Start up a new master log("Starting up a new master"); activeMaster = cluster.startMaster().getMaster(); log("Waiting for master to be ready"); cluster.waitForActiveAndReadyMaster(); log("Master is ready"); // ensure meta is still deployed on RS metaState = MetaTableLocator.getMetaRegionState(activeMaster.getZooKeeper()); assertEquals("hbase:meta should be onlined on RS", metaState.getServerName(), rs.getServerName()); assertEquals("hbase:meta should be onlined on RS", metaState.getState(), State.OPEN); // Update meta state as PENDING_OPEN, then kill master // that simulates, that RS successfully deployed, but // RPC was lost right before failure. // region server should expire (how it can be verified?) MetaTableLocator.setMetaLocation(activeMaster.getZooKeeper(), rs.getServerName(), State.PENDING_OPEN); Region meta = rs.getFromOnlineRegions(HRegionInfo.FIRST_META_REGIONINFO.getEncodedName()); rs.removeFromOnlineRegions(meta, null); ((HRegion)meta).close(); log("Aborting master"); activeMaster.abort("test-kill"); cluster.waitForMasterToStop(activeMaster.getServerName(), 30000); log("Master has aborted"); // Start up a new master log("Starting up a new master"); activeMaster = cluster.startMaster().getMaster(); log("Waiting for master to be ready"); cluster.waitForActiveAndReadyMaster(); log("Master is ready"); TEST_UTIL.waitUntilNoRegionsInTransition(60000); log("Meta was assigned"); metaState = MetaTableLocator.getMetaRegionState(activeMaster.getZooKeeper()); assertEquals("hbase:meta should be onlined on RS", metaState.getServerName(), rs.getServerName()); assertEquals("hbase:meta should be onlined on RS", metaState.getState(), State.OPEN); // Update meta state as PENDING_CLOSE, then kill master // that simulates, that RS successfully deployed, but // RPC was lost right before failure. // region server should expire (how it can be verified?) MetaTableLocator.setMetaLocation(activeMaster.getZooKeeper(), rs.getServerName(), State.PENDING_CLOSE); log("Aborting master"); activeMaster.abort("test-kill"); cluster.waitForMasterToStop(activeMaster.getServerName(), 30000); log("Master has aborted"); rs.getRSRpcServices().closeRegion(null, RequestConverter.buildCloseRegionRequest( rs.getServerName(), HRegionInfo.FIRST_META_REGIONINFO.getEncodedName())); // Start up a new master log("Starting up a new master"); activeMaster = cluster.startMaster().getMaster(); log("Waiting for master to be ready"); cluster.waitForActiveAndReadyMaster(); log("Master is ready"); TEST_UTIL.waitUntilNoRegionsInTransition(60000); log("Meta was assigned"); // Done, shutdown the cluster TEST_UTIL.shutdownMiniCluster(); } }
/** * 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.orc.impl; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; class Fpc { /** * A modified version of FPC. * * The original FPC is described in "High Throughput Compression of * Double-Precision Floating-Point Data" by Martin Burtscher and Paruj * Ratanaworabhan. Visit http://cs.txstate.edu/~burtscher/research/FPC/ * for more information. * * This modified FPC has two main differences. The first difference is that it * tries to multiply values by one thousand when it doesn't loss any precision. * The second difference is that it truncates trailing zeros, while the * original FPC truncates leading zeros. They are mainly reasonable for real * world data sets and standard benchmark data sets, such as TPC-DS. * * A data set usually has a limited number of digits in its fractional part. * For example, world's most traded ten currencies(USD, EUR, JPY, GBP, AUD, * CAD, CHF, CNY, SEK, NZD) have fractional units, which are cents of basic * units. * * A small integer value has many trailing zeros in the IEEE 754 * double-precision binary floating-point format. The original FPC truncates * leading zeros of XOR bits. Truncating trailing zeros makes compression ratio * higher. * @see FpcExtractor */ static class FpcCompressor { private static int PREDICTOR_N = 1 << 7; private static int EXPONENT = 3; private static double POWER_OF_TEN = Math.pow(10, EXPONENT); private static double MAX = Math.pow(10, 13 - EXPONENT); private static double MIN = -MAX; private final int tableSize; private final Predictor dfcmPredictor; private final Predictor fcmPredictor; private final OutputStream output; private byte[] bytes; private int position; FpcCompressor(OutputStream output) throws IOException { this(PREDICTOR_N, output); } private FpcCompressor(int tableSize, OutputStream output) throws IOException { this.tableSize = tableSize; this.output = output; this.dfcmPredictor = new DfcmPredictor(tableSize); this.fcmPredictor = new FcmPredictor(tableSize); } private void encodeValue(long diff, byte flag) throws IOException { final int nbytes = (flag & 7); final int nshift = (64 - (nbytes >= 3 ? nbytes + 1 : nbytes) * 8); diff >>>= nshift; switch(nbytes) { case 7: // 8 bytes bytes[position++] = (byte) (diff & 0xFF); diff >>>= 8; case 6: // 7 bytes bytes[position++] = (byte) (diff & 0xFF); diff >>>= 8; case 5: // 6 bytes bytes[position++] = (byte) (diff & 0xFF); diff >>>= 8; case 4: // 5 bytes bytes[position++] = (byte) (diff & 0xFF); diff >>>= 8; case 3: // 4, 3 bytes bytes[position++] = (byte) (diff & 0xFF); diff >>>= 8; bytes[position++] = (byte) (diff & 0xFF); diff >>>= 8; case 2: // 2 bytes bytes[position++] = (byte) (diff & 0xFF); diff >>>= 8; case 1: // 1 byte bytes[position++] = (byte) (diff & 0xFF); case 0: // 0 byte break; default: throw new IllegalArgumentException(); } } private boolean isValidAfterMulDiv(double[] literals, int numLiterals) { for (int i = 0; i < numLiterals; i++) { final double d = literals[i]; if (d < MIN || d > MAX) { return false; } } for (int i = 0; i < numLiterals; i++) { final double d = literals[i]; if (Double.doubleToLongBits((d * POWER_OF_TEN) / POWER_OF_TEN) != Double.doubleToLongBits(d)) { return false; } } return true; } void compress(double[] literals, int numLiterals) throws IOException { // clear long prevDiff = 0; byte prevFlag = 0; dfcmPredictor.clear(); fcmPredictor.clear(); // write table size final int tableSizeTrailingZeros = Long.numberOfTrailingZeros(tableSize); output.write(tableSizeTrailingZeros); // expect the number of required bytes final int expectedBytes = (numLiterals / 2) + (numLiterals * 8); if (bytes == null || expectedBytes > bytes.length) { bytes = new byte[expectedBytes * 2]; } else { Arrays.fill(bytes, (byte) 0); } // write an exponent final boolean isValidAfterMulDiv = isValidAfterMulDiv(literals, numLiterals); if (isValidAfterMulDiv) { output.write(EXPONENT); } else { output.write(0); } position = numLiterals / 2; for (int ix = 0; ix != numLiterals; ix++) { // convert double to long bits long bits; if (isValidAfterMulDiv) { bits = Double.doubleToLongBits(literals[ix] * POWER_OF_TEN); } else { bits = Double.doubleToLongBits(literals[ix]); } // DFCM prediction final long dfcmPredicted = dfcmPredictor.predictNext(); dfcmPredictor.update(bits); final long dfcmDiff = bits ^ dfcmPredicted; final int dfcmTrailingZeros; if (dfcmDiff == 0) { dfcmTrailingZeros = 64; } else { dfcmTrailingZeros = Long.numberOfTrailingZeros(dfcmDiff); } // FCM prediction final long fcmPredicted = fcmPredictor.predictNext(); fcmPredictor.update(bits); final long fcmDiff = bits ^ fcmPredicted; final int fcmTrailingZeros; if (fcmDiff == 0) { fcmTrailingZeros = 64; } else { fcmTrailingZeros = Long.numberOfTrailingZeros(fcmDiff); } // decide a prediction between FCM and DFCM then encode its XOR // difference with the original bits int nbytes; final byte flag; final long diff; if (fcmTrailingZeros >= dfcmTrailingZeros) { diff = fcmDiff; nbytes = 8 - (fcmTrailingZeros / 8); if (nbytes > 3) { nbytes--; } // zeroed 4th bit indicates FCM flag = (byte) (nbytes & 7); } else { diff = dfcmDiff; nbytes = 8 - (dfcmTrailingZeros / 8); if (nbytes > 3) { nbytes--; } // 4th bit indicates DFCM flag = (byte) (8 | (nbytes & 7)); } if (ix % 2 == 0) { prevDiff = diff; prevFlag = flag; } else { // we're storing values by pairs to save space byte flags = (byte) ((prevFlag << 4) | flag); bytes[ix >>> 1] = flags; encodeValue(prevDiff, prevFlag); encodeValue(diff, flag); } } if (numLiterals % 2 != 0) { // `input` contains odd number of values so we should use // empty second value that will take one byte in output byte flags = (byte) (prevFlag << 4); bytes[numLiterals >>> 1] = flags; encodeValue(prevDiff, prevFlag); encodeValue(0L, (byte) 0); } // write the number of doubles writeThreeBytes(numLiterals); // write the number of bytes final int numberOfBytes = position; writeThreeBytes(numberOfBytes); // write the byte buffer output.write(bytes, 0, numberOfBytes); } private void writeThreeBytes(int value) throws IOException { output.write((byte) (value & 0xFF)); value >>>= 8; output.write((byte) (value & 0xFF)); value >>>= 8; output.write((byte) (value & 0xFF)); } interface Predictor { void update(long bits); long predictNext(); void clear(); } /** * Ported from Akumuli FcmPredictor. * Visit http://akumuli.org for more information. */ static class FcmPredictor implements Predictor { private final long[] table; private final int mask; private int lastHash; FcmPredictor(int tableSize) { lastHash = 0; mask = tableSize - 1; assert((tableSize & mask) == 0); table = new long[tableSize]; } @Override public long predictNext() { return table[lastHash]; } @Override public void update(long value) { table[lastHash] = value; lastHash = (int) (((lastHash << 6) ^ (value >>> 48)) & mask); } @Override public void clear() { Arrays.fill(table, 0); lastHash = 0; } } /** * Ported from Akumuli DfcmPredictor. * Visit http://akumuli.org for more information. */ static class DfcmPredictor implements Predictor { private final long[] table; private final int mask; private int lastHash; private long lastValue; DfcmPredictor(int tableSize) { lastHash = 0; lastValue = 0; mask = tableSize - 1; assert((tableSize & mask) == 0); table = new long[tableSize]; } @Override public long predictNext() { return table[lastHash] + lastValue; } @Override public void update(long value) { table[lastHash] = value - lastValue; lastHash = (int) (((lastHash << 2) ^ ((value - lastValue) >>> 40)) & mask); lastValue = value; } @Override public void clear() { Arrays.fill(table, 0); lastHash = 0; lastValue = 0; } } } static class FpcExtractor { private final InputStream input; private FpcCompressor.FcmPredictor fcmPredictor; private FpcCompressor.DfcmPredictor dfcmPredictor; private double[] literals; private byte[] bytes; private int tableSize; private int position; int numLiterals; FpcExtractor(InputStream input) throws IOException { this.input = input; } double[] extract() throws IOException { // ensure table size final int newTableSize = (1 << input.read()); if (tableSize != newTableSize) { tableSize = newTableSize; fcmPredictor = new FpcCompressor.FcmPredictor(tableSize); dfcmPredictor = new FpcCompressor.DfcmPredictor(tableSize); } else { fcmPredictor.clear(); dfcmPredictor.clear(); } // read an exponent final int exponent = input.read(); final double powerOfTen = Math.pow(10, exponent); // read the number of doubles and the number of bytes numLiterals = readThreeBytes(); final int numberOfBytes = readThreeBytes(); // ensure buffer sizes if (literals == null) { literals = new double[numLiterals]; } else if (literals.length < numLiterals) { literals = new double[numLiterals * 2]; } if (bytes == null) { bytes = new byte[numberOfBytes]; } else if (bytes.length < numberOfBytes) { bytes = new byte[numberOfBytes * 2]; } int remainingBytes = numberOfBytes; while (remainingBytes > 0) { final int readBytes = input.read(bytes, numberOfBytes - remainingBytes, remainingBytes); if (readBytes == -1) { throw new IOException("Cannot read"); } remainingBytes -= readBytes; } // read double values final int numLiterals_2 = numLiterals / 2; position = numLiterals_2; for (int i = 0; i < numLiterals_2; i++) { final byte flagPair = bytes[i]; final byte firstFlags = (byte) (flagPair >> 4); final byte secondFlags = (byte) (flagPair & 0xF); final double firstValue = decodeValue(firstFlags) / powerOfTen; literals[i * 2] = firstValue; final double secondValue = decodeValue(secondFlags) / powerOfTen; literals[i * 2 + 1] = secondValue; } return literals; } private double decodeValue(byte flags) throws IOException { final long bits; final long fcmPredicted = fcmPredictor.predictNext(); final long dfcmPredicted = dfcmPredictor.predictNext(); int nbytes = flags & 7; long xorDiff = readBytes(nbytes); if ((flags >>> 3) == 0) { // FCM bits = xorDiff ^ fcmPredicted; } else { // DFCM bits = xorDiff ^ dfcmPredicted; } fcmPredictor.update(bits); dfcmPredictor.update(bits); return Double.longBitsToDouble(bits); } private long readBytes(int nbytes) throws IOException { long value = 0; switch (nbytes) { case 7: // 8 bytes value |= (bytes[position++] & 0xFFL); case 6: // 7 bytes value |= (bytes[position++] & 0xFFL) << 8; case 5: // 6 bytes value |= (bytes[position++] & 0xFFL) << 16; case 4: // 5 bytes value |= (bytes[position++] & 0xFFL) << 24; case 3: // 4, 3 bytes value |= (bytes[position++] & 0xFFL) << 32; value |= (bytes[position++] & 0xFFL) << 40; case 2: // 2 bytes value |= (bytes[position++] & 0xFFL) << 48; case 1: // 1 bytes value |= (bytes[position++] & 0xFFL) << 56; case 0: // 0 bytes break; default: throw new IllegalArgumentException(); } return value; } private int readThreeBytes() throws IOException { int value = input.read() & 0xFF; value |= (input.read() & 0xFF) << 8; value |= (input.read() & 0xFF) << 16; return value; } } }
/* * 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.commons.math3.geometry.euclidean.twod; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Locale; import org.apache.commons.math3.exception.MathParseException; import org.junit.Assert; import org.junit.Test; public abstract class Vector2DFormatAbstractTest { Vector2DFormat vector2DFormat = null; Vector2DFormat vector2DFormatSquare = null; protected abstract Locale getLocale(); protected abstract char getDecimalCharacter(); protected Vector2DFormatAbstractTest() { vector2DFormat = Vector2DFormat.getInstance(getLocale()); final NumberFormat nf = NumberFormat.getInstance(getLocale()); nf.setMaximumFractionDigits(2); vector2DFormatSquare = new Vector2DFormat("[", "]", " : ", nf); } @Test public void testSimpleNoDecimals() { Vector2D c = new Vector2D(1, 1); String expected = "{1; 1}"; String actual = vector2DFormat.format(c); Assert.assertEquals(expected, actual); } @Test public void testSimpleWithDecimals() { Vector2D c = new Vector2D(1.23, 1.43); String expected = "{1" + getDecimalCharacter() + "23; 1" + getDecimalCharacter() + "43}"; String actual = vector2DFormat.format(c); Assert.assertEquals(expected, actual); } @Test public void testSimpleWithDecimalsTrunc() { Vector2D c = new Vector2D(1.232323232323, 1.434343434343); String expected = "{1" + getDecimalCharacter() + "2323232323; 1" + getDecimalCharacter() + "4343434343}"; String actual = vector2DFormat.format(c); Assert.assertEquals(expected, actual); } @Test public void testNegativeX() { Vector2D c = new Vector2D(-1.232323232323, 1.43); String expected = "{-1" + getDecimalCharacter() + "2323232323; 1" + getDecimalCharacter() + "43}"; String actual = vector2DFormat.format(c); Assert.assertEquals(expected, actual); } @Test public void testNegativeY() { Vector2D c = new Vector2D(1.23, -1.434343434343); String expected = "{1" + getDecimalCharacter() + "23; -1" + getDecimalCharacter() + "4343434343}"; String actual = vector2DFormat.format(c); Assert.assertEquals(expected, actual); } @Test public void testNegativeZ() { Vector2D c = new Vector2D(1.23, 1.43); String expected = "{1" + getDecimalCharacter() + "23; 1" + getDecimalCharacter() + "43}"; String actual = vector2DFormat.format(c); Assert.assertEquals(expected, actual); } @Test public void testNonDefaultSetting() { Vector2D c = new Vector2D(1, 1); String expected = "[1 : 1]"; String actual = vector2DFormatSquare.format(c); Assert.assertEquals(expected, actual); } @Test public void testDefaultFormatVector2D() { Locale defaultLocal = Locale.getDefault(); Locale.setDefault(getLocale()); Vector2D c = new Vector2D(232.22222222222, -342.3333333333); String expected = "{232" + getDecimalCharacter() + "2222222222; -342" + getDecimalCharacter() + "3333333333}"; String actual = (new Vector2DFormat()).format(c); Assert.assertEquals(expected, actual); Locale.setDefault(defaultLocal); } @Test public void testNan() { Vector2D c = Vector2D.NaN; String expected = "{(NaN); (NaN)}"; String actual = vector2DFormat.format(c); Assert.assertEquals(expected, actual); } @Test public void testPositiveInfinity() { Vector2D c = Vector2D.POSITIVE_INFINITY; String expected = "{(Infinity); (Infinity)}"; String actual = vector2DFormat.format(c); Assert.assertEquals(expected, actual); } @Test public void tesNegativeInfinity() { Vector2D c = Vector2D.NEGATIVE_INFINITY; String expected = "{(-Infinity); (-Infinity)}"; String actual = vector2DFormat.format(c); Assert.assertEquals(expected, actual); } @Test public void testParseSimpleNoDecimals() throws MathParseException { String source = "{1; 1}"; Vector2D expected = new Vector2D(1, 1); Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(expected, actual); } @Test public void testParseIgnoredWhitespace() { Vector2D expected = new Vector2D(1, 1); ParsePosition pos1 = new ParsePosition(0); String source1 = "{1;1}"; Assert.assertEquals(expected, vector2DFormat.parse(source1, pos1)); Assert.assertEquals(source1.length(), pos1.getIndex()); ParsePosition pos2 = new ParsePosition(0); String source2 = " { 1 ; 1 } "; Assert.assertEquals(expected, vector2DFormat.parse(source2, pos2)); Assert.assertEquals(source2.length() - 1, pos2.getIndex()); } @Test public void testParseSimpleWithDecimals() throws MathParseException { String source = "{1" + getDecimalCharacter() + "23; 1" + getDecimalCharacter() + "43}"; Vector2D expected = new Vector2D(1.23, 1.43); Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(expected, actual); } @Test public void testParseSimpleWithDecimalsTrunc() throws MathParseException { String source = "{1" + getDecimalCharacter() + "2323; 1" + getDecimalCharacter() + "4343}"; Vector2D expected = new Vector2D(1.2323, 1.4343); Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(expected, actual); } @Test public void testParseNegativeX() throws MathParseException { String source = "{-1" + getDecimalCharacter() + "2323; 1" + getDecimalCharacter() + "4343}"; Vector2D expected = new Vector2D(-1.2323, 1.4343); Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(expected, actual); } @Test public void testParseNegativeY() throws MathParseException { String source = "{1" + getDecimalCharacter() + "2323; -1" + getDecimalCharacter() + "4343}"; Vector2D expected = new Vector2D(1.2323, -1.4343); Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(expected, actual); } @Test public void testParseNegativeZ() throws MathParseException { String source = "{1" + getDecimalCharacter() + "2323; 1" + getDecimalCharacter() + "4343}"; Vector2D expected = new Vector2D(1.2323, 1.4343); Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(expected, actual); } @Test public void testParseNegativeAll() throws MathParseException { String source = "{-1" + getDecimalCharacter() + "2323; -1" + getDecimalCharacter() + "4343}"; Vector2D expected = new Vector2D(-1.2323, -1.4343); Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(expected, actual); } @Test public void testParseZeroX() throws MathParseException { String source = "{0" + getDecimalCharacter() + "0; -1" + getDecimalCharacter() + "4343}"; Vector2D expected = new Vector2D(0.0, -1.4343); Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(expected, actual); } @Test public void testParseNonDefaultSetting() throws MathParseException { String source = "[1" + getDecimalCharacter() + "2323 : 1" + getDecimalCharacter() + "4343]"; Vector2D expected = new Vector2D(1.2323, 1.4343); Vector2D actual = vector2DFormatSquare.parse(source); Assert.assertEquals(expected, actual); } @Test public void testParseNan() throws MathParseException { String source = "{(NaN); (NaN)}"; Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(Vector2D.NaN, actual); } @Test public void testParsePositiveInfinity() throws MathParseException { String source = "{(Infinity); (Infinity)}"; Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(Vector2D.POSITIVE_INFINITY, actual); } @Test public void testParseNegativeInfinity() throws MathParseException { String source = "{(-Infinity); (-Infinity)}"; Vector2D actual = vector2DFormat.parse(source); Assert.assertEquals(Vector2D.NEGATIVE_INFINITY, actual); } @Test public void testConstructorSingleFormat() { NumberFormat nf = NumberFormat.getInstance(); Vector2DFormat cf = new Vector2DFormat(nf); Assert.assertNotNull(cf); Assert.assertEquals(nf, cf.getFormat()); } @Test public void testForgottenPrefix() { ParsePosition pos = new ParsePosition(0); Assert.assertNull(new Vector2DFormat().parse("1; 1}", pos)); Assert.assertEquals(0, pos.getErrorIndex()); } @Test public void testForgottenSeparator() { ParsePosition pos = new ParsePosition(0); Assert.assertNull(new Vector2DFormat().parse("{1 1}", pos)); Assert.assertEquals(3, pos.getErrorIndex()); } @Test public void testForgottenSuffix() { ParsePosition pos = new ParsePosition(0); Assert.assertNull(new Vector2DFormat().parse("{1; 1 ", pos)); Assert.assertEquals(5, pos.getErrorIndex()); } }
/* * * 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 com.adobe.internal.fxg.dom.strokes; import java.util.ArrayList; import java.util.List; import static com.adobe.fxg.FXGConstants.*; import com.adobe.fxg.FXGException; import com.adobe.fxg.dom.FXGNode; import com.adobe.fxg.util.FXGLog; import com.adobe.fxg.util.FXGLogger; import com.adobe.internal.fxg.dom.DOMParserHelper; import com.adobe.internal.fxg.dom.GradientEntryNode; import com.adobe.internal.fxg.dom.ScalableGradientNode; import com.adobe.internal.fxg.dom.transforms.MatrixNode; import com.adobe.internal.fxg.dom.types.InterpolationMethod; import com.adobe.internal.fxg.dom.types.SpreadMethod; /** * The Class RadialGradientStrokeNode. */ public class RadialGradientStrokeNode extends AbstractStrokeNode implements ScalableGradientNode { private static final double FOCAL_MIN_INCLUSIVE = -1.0; private static final double FOCAL_MAX_INCLUSIVE = 1.0; //-------------------------------------------------------------------------- // // Attributes // //-------------------------------------------------------------------------- /** The horizontal distance to translate the gradient. Default to NaN. */ public double x = Double.NaN; /** The vertical distance to translate the gradient. Default to NaN. */ public double y = Double.NaN; /** The horizontal distance of the unrotated gradient (that will be * compared to the target's width to calculate a scale ratio). */ public double scaleX = Double.NaN; /** The vertical distance of the unrotated gradient (that will be * compared to the target's width to calculate a scale ratio). */ public double scaleY = Double.NaN; /** The clockwise rotation angle in degrees. */ public double rotation = 0.0; /** Indicate how to fill pixels outside the gradient vector. * Defaults to pad. */ public SpreadMethod spreadMethod = SpreadMethod.PAD; /** Indicate how to interpolate between entries of the gradient. * Defaults to rgb. */ public InterpolationMethod interpolationMethod = InterpolationMethod.RGB; /** The placement of the focal point of the radial gradient along the * horizontal center axis of the gradient bounding box. * A value of 1 lies against the right edge of the box; a value of -1 * lies against the left edge. The default value of 0 places it in the * middle of the box.*/ public double focalPointRatio = 0.0; private boolean translateSet; private boolean scaleSet; private boolean rotationSet; //-------------------------------------------------------------------------- // // Children // //-------------------------------------------------------------------------- /** The matrix. */ public MatrixNode matrix; /** The entries. */ public List<GradientEntryNode> entries; //-------------------------------------------------------------------------- // // ScalableGradientNode Implementation // //-------------------------------------------------------------------------- /** * {@inheritDoc} */ public double getX() { return x; } /** * {@inheritDoc} */ public double getY() { return y; } /** * {@inheritDoc} */ public double getScaleX() { return scaleX; } /** * {@inheritDoc} */ public double getScaleY() { return scaleY; } /** * {@inheritDoc} */ public double getRotation() { return rotation; } /** * {@inheritDoc} */ public MatrixNode getMatrixNode() { return matrix; } /** * {@inheritDoc} */ public boolean isLinear() { return false; } //-------------------------------------------------------------------------- // // FXGNode Implementation // //-------------------------------------------------------------------------- /** * Adds an FXG child node to this node. Supported child nodes: * &lt;matrix&gt;, &lt;GradientEntry&gt;. Cannot add a child matrix node if * the discreet transform properties have been set. If there have been * 15 child GradientEntryNode node added, this child node will be * ignored and a message is logged. * * @param child a FXG node * * @throws FXGException if the child is not supported by this node. * @see com.adobe.internal.fxg.dom.AbstractFXGNode#addChild(com.adobe.fxg.dom.FXGNode) */ @Override public void addChild(FXGNode child) { if (child instanceof MatrixNode) { if (translateSet || scaleSet || rotationSet) //Exception:Cannot supply a matrix child if transformation attributes were provided. throw new FXGException(child.getStartLine(), child.getStartColumn(), "InvalidChildMatrixNode"); matrix = (MatrixNode)child; } else if (child instanceof GradientEntryNode) { if (entries == null) { entries = new ArrayList<GradientEntryNode>(4); } else if (entries.size() >= GRADIENT_ENTRIES_MAX_INCLUSIVE) { //Log warning:A RadialGradientStroke cannot define more than 15 GradientEntry elements - extra elements ignored FXGLog.getLogger().log(FXGLogger.WARN, "InvalidRadialGradientStrokeNumElements", null, getDocumentName(), startLine, startColumn); return; } entries.add((GradientEntryNode)child); } else { super.addChild(child); } } /** * Gets the node name. * * @return The unqualified name of a RadialGradientStroke node, without tag * markup. */ public String getNodeName() { return FXG_RADIALGRADIENTSTROKE_ELEMENT; } /** * Set a attribute to this linear gradient stroke node. Delegates to the * parent class to process attributes that are not in the list below. * <p>Stroke attributes include: * <ul> * <li><b>x</b> (Number): The horizontal translation of the gradient transform * that defines the horizontal center of the gradient.</li> * <li><b>y</b> (Number): The horizontal translation of the gradient transform * that defines the horizontal center of the gradient.</li> * <li><b>rotation</b> (Number): The rotation of the gradient transform.</li> * <li><b>scaleX</b> (Number): The horizontal scale of the gradient transform * that defines the width of the (unrotated) gradient.</li> * <li><b>scaleY</b> (Number): The vertical scale of the gradient transform * that defines the width of the (unrotated) gradient.</li> * <li><b>spreadMethod</b> (String): [pad, reflect, repeat]. How to choose * the fill of pixels outside the gradient vector. Defaults to pad.</li> * <li><b>interpolationMethod</b> (String): [rgb, linearRGB): How to * interpolate between entries of the gradient. Defaults to rgb. </li> * <li><b>focalPointRatio</b> (Number): The placement of the focal point * of the radial gradient along the horizontal center axis of the gradient * bounding box. Valid range from -1 to 1. A value of 1 lies against the * right edge of the box; a value of -1 lies against the left edge. The * default value of 0 places it in the middle of the box.</li> * </ul> * </p> * * @param name the name * @param value the value * * @throws FXGException if a value is out of the valid range. * @see com.adobe.internal.fxg.dom.strokes.AbstractStrokeNode#setAttribute(java.lang.String, java.lang.String) */ @Override public void setAttribute(String name, String value) { if (FXG_X_ATTRIBUTE.equals(name)) { x = DOMParserHelper.parseDouble(this, value, name); translateSet = true; } else if (FXG_Y_ATTRIBUTE.equals(name)) { y = DOMParserHelper.parseDouble(this, value, name); translateSet = true; } else if (FXG_ROTATION_ATTRIBUTE.equals(name)) { rotation = DOMParserHelper.parseDouble(this, value, name); rotationSet = true; } else if (FXG_SCALEX_ATTRIBUTE.equals(name)) { scaleX = DOMParserHelper.parseDouble(this, value, name); scaleSet = true; } else if (FXG_SCALEY_ATTRIBUTE.equals(name)) { scaleY = DOMParserHelper.parseDouble(this, value, name); scaleSet = true; } else if (FXG_SPREADMETHOD_ATTRIBUTE.equals(name)) { spreadMethod = DOMParserHelper.parseSpreadMethod(this, value, name, spreadMethod); } else if (FXG_INTERPOLATIONMETHOD_ATTRIBUTE.equals(name)) { interpolationMethod = DOMParserHelper.parseInterpolationMethod(this, value, name, interpolationMethod); } else if (FXG_FOCALPOINTRATIO_ATTRIBUTE.equals(name)) { focalPointRatio = DOMParserHelper.parseDouble(this, value, name, FOCAL_MIN_INCLUSIVE, FOCAL_MAX_INCLUSIVE, focalPointRatio); } else { super.setAttribute(name, value); } } }
/** * 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.processor.loadbalancer; import java.util.List; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicInteger; import org.apache.camel.AsyncCallback; import org.apache.camel.AsyncProcessor; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Traceable; import org.apache.camel.util.AsyncProcessorConverterHelper; import org.apache.camel.util.ExchangeHelper; import org.apache.camel.util.ObjectHelper; /** * This FailOverLoadBalancer will failover to use next processor when an exception occurred * <p/> * This implementation mirrors the logic from the {@link org.apache.camel.processor.Pipeline} in the async variation * as the failover load balancer is a specialized pipeline. So the trick is to keep doing the same as the * pipeline to ensure it works the same and the async routing engine is flawless. */ public class FailOverLoadBalancer extends LoadBalancerSupport implements Traceable, CamelContextAware { private final List<Class<?>> exceptions; private CamelContext camelContext; private boolean roundRobin; private int maximumFailoverAttempts = -1; // stateful counter private final AtomicInteger counter = new AtomicInteger(-1); public FailOverLoadBalancer() { this.exceptions = null; } public FailOverLoadBalancer(List<Class<?>> exceptions) { this.exceptions = exceptions; // validate its all exception types for (Class<?> type : exceptions) { if (!ObjectHelper.isAssignableFrom(Throwable.class, type)) { throw new IllegalArgumentException("Class is not an instance of Throwable: " + type); } } } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } public List<Class<?>> getExceptions() { return exceptions; } public boolean isRoundRobin() { return roundRobin; } public void setRoundRobin(boolean roundRobin) { this.roundRobin = roundRobin; } public int getMaximumFailoverAttempts() { return maximumFailoverAttempts; } public void setMaximumFailoverAttempts(int maximumFailoverAttempts) { this.maximumFailoverAttempts = maximumFailoverAttempts; } /** * Should the given failed Exchange failover? * * @param exchange the exchange that failed * @return <tt>true</tt> to failover */ protected boolean shouldFailOver(Exchange exchange) { if (exchange == null) { return false; } boolean answer = false; if (exchange.getException() != null) { if (exceptions == null || exceptions.isEmpty()) { // always failover if no exceptions defined answer = true; } else { for (Class<?> exception : exceptions) { // will look in exception hierarchy if (exchange.getException(exception) != null) { answer = true; break; } } } } log.trace("Should failover: {} for exchangeId: {}", answer, exchange.getExchangeId()); return answer; } @Override public boolean isRunAllowed() { // determine if we can still run, or the camel context is forcing a shutdown boolean forceShutdown = camelContext.getShutdownStrategy().forceShutdown(this); if (forceShutdown) { log.trace("Run not allowed as ShutdownStrategy is forcing shutting down"); } return !forceShutdown && super.isRunAllowed(); } public boolean process(final Exchange exchange, final AsyncCallback callback) { final List<Processor> processors = getProcessors(); final AtomicInteger index = new AtomicInteger(); final AtomicInteger attempts = new AtomicInteger(); boolean first = true; // use a copy of the original exchange before failover to avoid populating side effects // directly into the original exchange Exchange copy = null; // get the next processor if (isRoundRobin()) { if (counter.incrementAndGet() >= processors.size()) { counter.set(0); } index.set(counter.get()); } log.trace("Failover starting with endpoint index {}", index); while (first || shouldFailOver(copy)) { // can we still run if (!isRunAllowed()) { log.trace("Run not allowed, will reject executing exchange: {}", exchange); if (exchange.getException() == null) { exchange.setException(new RejectedExecutionException()); } // we cannot process so invoke callback callback.done(true); return true; } if (!first) { attempts.incrementAndGet(); // are we exhausted by attempts? if (maximumFailoverAttempts > -1 && attempts.get() > maximumFailoverAttempts) { log.debug("Breaking out of failover after {} failover attempts", attempts); break; } index.incrementAndGet(); counter.incrementAndGet(); } else { // flip first switch first = false; } if (index.get() >= processors.size()) { // out of bounds if (isRoundRobin()) { log.trace("Failover is round robin enabled and therefore starting from the first endpoint"); index.set(0); counter.set(0); } else { // no more processors to try log.trace("Breaking out of failover as we reached the end of endpoints to use for failover"); break; } } // try again but copy original exchange before we failover copy = prepareExchangeForFailover(exchange); Processor processor = processors.get(index.get()); // process the exchange boolean sync = processExchange(processor, exchange, copy, attempts, index, callback, processors); // continue as long its being processed synchronously if (!sync) { log.trace("Processing exchangeId: {} is continued being processed asynchronously", exchange.getExchangeId()); // the remainder of the failover will be completed async // so we break out now, then the callback will be invoked which then continue routing from where we left here return false; } log.trace("Processing exchangeId: {} is continued being processed synchronously", exchange.getExchangeId()); } // and copy the current result to original so it will contain this result of this eip if (copy != null) { ExchangeHelper.copyResults(exchange, copy); } log.debug("Failover complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange); callback.done(true); return true; } /** * Prepares the exchange for failover * * @param exchange the exchange * @return a copy of the exchange to use for failover */ protected Exchange prepareExchangeForFailover(Exchange exchange) { // use a copy of the exchange to avoid side effects on the original exchange return ExchangeHelper.createCopy(exchange, true); } private boolean processExchange(Processor processor, Exchange exchange, Exchange copy, AtomicInteger attempts, AtomicInteger index, AsyncCallback callback, List<Processor> processors) { if (processor == null) { throw new IllegalStateException("No processors could be chosen to process " + copy); } log.debug("Processing failover at attempt {} for {}", attempts, copy); AsyncProcessor albp = AsyncProcessorConverterHelper.convert(processor); return albp.process(copy, new FailOverAsyncCallback(exchange, copy, attempts, index, callback, processors)); } /** * Failover logic to be executed asynchronously if one of the failover endpoints * is a real {@link AsyncProcessor}. */ private final class FailOverAsyncCallback implements AsyncCallback { private final Exchange exchange; private Exchange copy; private final AtomicInteger attempts; private final AtomicInteger index; private final AsyncCallback callback; private final List<Processor> processors; private FailOverAsyncCallback(Exchange exchange, Exchange copy, AtomicInteger attempts, AtomicInteger index, AsyncCallback callback, List<Processor> processors) { this.exchange = exchange; this.copy = copy; this.attempts = attempts; this.index = index; this.callback = callback; this.processors = processors; } public void done(boolean doneSync) { // we only have to handle async completion of the pipeline if (doneSync) { return; } while (shouldFailOver(copy)) { // can we still run if (!isRunAllowed()) { log.trace("Run not allowed, will reject executing exchange: {}", exchange); if (exchange.getException() == null) { exchange.setException(new RejectedExecutionException()); } // we cannot process so invoke callback callback.done(false); } attempts.incrementAndGet(); // are we exhausted by attempts? if (maximumFailoverAttempts > -1 && attempts.get() > maximumFailoverAttempts) { log.trace("Breaking out of failover after {} failover attempts", attempts); break; } index.incrementAndGet(); counter.incrementAndGet(); if (index.get() >= processors.size()) { // out of bounds if (isRoundRobin()) { log.trace("Failover is round robin enabled and therefore starting from the first endpoint"); index.set(0); counter.set(0); } else { // no more processors to try log.trace("Breaking out of failover as we reached the end of endpoints to use for failover"); break; } } // try again but prepare exchange before we failover copy = prepareExchangeForFailover(exchange); Processor processor = processors.get(index.get()); // try to failover using the next processor doneSync = processExchange(processor, exchange, copy, attempts, index, callback, processors); if (!doneSync) { log.trace("Processing exchangeId: {} is continued being processed asynchronously", exchange.getExchangeId()); // the remainder of the failover will be completed async // so we break out now, then the callback will be invoked which then continue routing from where we left here return; } } // and copy the current result to original so it will contain this result of this eip if (copy != null) { ExchangeHelper.copyResults(exchange, copy); } log.debug("Failover complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange); // signal callback we are done callback.done(false); }; } public String toString() { return "FailoverLoadBalancer[" + getProcessors() + "]"; } public String getTraceLabel() { return "failover"; } }
/* * 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 riotcmd; import java.io.InputStream ; import java.io.OutputStream ; import jena.cmd.ArgDecl ; import jena.cmd.CmdException; import jena.cmd.CmdGeneral ; import org.apache.jena.Jena ; import org.apache.jena.atlas.io.IO ; import org.apache.jena.atlas.lib.InternalErrorException ; import org.apache.jena.atlas.lib.Pair ; import org.apache.jena.atlas.web.ContentType ; import org.apache.jena.atlas.web.TypedInputStream ; import org.apache.jena.query.ARQ ; import org.apache.jena.riot.* ; import org.apache.jena.riot.lang.LabelToNode ; import org.apache.jena.riot.lang.StreamRDFCounting ; import org.apache.jena.riot.out.NodeToLabel ; import org.apache.jena.riot.process.inf.InfFactory ; import org.apache.jena.riot.process.inf.InferenceSetupRDFS ; import org.apache.jena.riot.system.* ; import org.apache.jena.riot.tokens.Tokenizer ; import org.apache.jena.riot.tokens.TokenizerFactory ; import org.apache.jena.sparql.core.DatasetGraph ; import org.apache.jena.sparql.core.DatasetGraphFactory ; import arq.cmdline.* ; /** Common framework for running RIOT parsers */ public abstract class CmdLangParse extends CmdGeneral { static { RIOT.init(); } protected ModTime modTime = new ModTime() ; protected ModLangParse modLangParse = new ModLangParse() ; protected ModLangOutput modLangOutput = new ModLangOutput() ; protected InferenceSetupRDFS setup = null ; protected ModSymbol modSymbol = new ModSymbol() ; protected ArgDecl strictDecl = new ArgDecl(ArgDecl.NoValue, "strict") ; protected boolean cmdStrictMode = false ; interface LangHandler { String getItemsName() ; String getRateName() ; } static LangHandler langHandlerQuads = new LangHandler() { @Override public String getItemsName() { return "quads" ; } @Override public String getRateName() { return "QPS" ; } } ; static LangHandler langHandlerTriples = new LangHandler() { @Override public String getItemsName() { return "triples" ; } @Override public String getRateName() { return "TPS" ; } } ; static LangHandler langHandlerAny = new LangHandler() { @Override public String getItemsName() { return "tuples" ; } @Override public String getRateName() { return "TPS" ; } } ; protected LangHandler langHandlerOverall = null ; protected CmdLangParse(String[] argv) { super(argv) ; addModule(modSymbol) ; addModule(modTime) ; addModule(modLangOutput) ; addModule(modLangParse) ; super.modVersion.addClass(Jena.class) ; // Force - sometimes initialization does not cause these // to initialized early enough for reflection. String x1 = ARQ.VERSION ; String x2 = ARQ.BUILD_DATE ; super.modVersion.addClass(RIOT.class) ; } @Override protected String getSummary() { //return getCommandName()+" [--time] [--check|--noCheck] [--sink] [--base=IRI] [--skip | --stopOnError] file ..." ; return getCommandName()+" [--time] [--check|--noCheck] [--sink] [--base=IRI] [--out=FORMAT] file ..." ; } protected long totalMillis = 0 ; protected long totalTuples = 0 ; OutputStream output = System.out ; StreamRDF outputStream = null ; @Override protected void processModulesAndArgs() { cmdStrictMode = super.contains(strictDecl) ; } protected interface PostParseHandler { void postParse(); } @Override protected void exec() { if ( modLangParse.strictMode() ) RIOT.setStrictMode(true) ; if ( modLangParse.getRDFSVocab() != null ) setup = new InferenceSetupRDFS(modLangParse.getRDFSVocab()) ; outputStream = null ; PostParseHandler postParse = null ; outputStream = createStreamSink() ; if ( outputStream == null ) { Pair<StreamRDF, PostParseHandler> p = createAccumulateSink() ; outputStream = p.getLeft() ; postParse = p.getRight(); } try { if ( super.getPositional().isEmpty() ) parseFile("-") ; else { boolean b = super.getPositional().size() > 1 ; for ( String fn : super.getPositional() ) { if ( b && ! super.isQuiet() ) SysRIOT.getLogger().info("File: "+fn) ; parseFile(fn) ; } } } finally { System.err.flush() ; System.out.flush() ; if ( super.getPositional().size() > 1 && modTime.timingEnabled() ) output("Total", totalTuples, totalMillis, langHandlerOverall) ; } if ( postParse != null ) postParse.postParse() ; } public void parseFile(String filename) { TypedInputStream in = null ; if ( filename.equals("-") ) { in = new TypedInputStream(System.in) ; parseFile("http://base/", "stdin", in) ; } else { try { in = RDFDataMgr.open(filename) ; } catch (Exception ex) { System.err.println("Can't open '"+filename+"' "+ex.getMessage()) ; return ; } parseFile(null, filename, in) ; IO.close(in) ; } } public void parseFile(String defaultBaseURI, String filename, TypedInputStream in) { String baseURI = modLangParse.getBaseIRI() ; if ( baseURI == null ) baseURI = defaultBaseURI ; parseRIOT(baseURI, filename, in) ; } protected abstract Lang selectLang(String filename, ContentType contentType, Lang dftLang ) ; protected void parseRIOT(String baseURI, String filename, TypedInputStream in) { ContentType ct = in.getMediaType() ; baseURI = SysRIOT.chooseBaseIRI(baseURI, filename) ; boolean checking = true ; if ( modLangParse.explicitChecking() ) checking = true ; if ( modLangParse.explicitNoChecking() ) checking = false ; ErrorHandler errHandler = null ; if ( checking ) { if ( modLangParse.stopOnBadTerm() ) errHandler = ErrorHandlerFactory.errorHandlerStd ; else // Try to go on if possible. This is the default behaviour. errHandler = ErrorHandlerFactory.errorHandlerWarn ; } if ( modLangParse.skipOnBadTerm() ) { // TODO skipOnBadterm } Lang lang = selectLang(filename, ct, RDFLanguages.NQUADS) ; LangHandler handler = null ; if ( RDFLanguages.isQuads(lang) ) handler = langHandlerQuads ; else if ( RDFLanguages.isTriples(lang) ) handler = langHandlerTriples ; else throw new CmdException("Undefined language: "+lang) ; // If multiple files, choose the overall labels. if ( langHandlerOverall == null ) langHandlerOverall = handler ; else { if ( langHandlerOverall != langHandlerAny ) { if ( langHandlerOverall != handler ) langHandlerOverall = langHandlerAny ; } } // Make a flag. // Input and output subflags. // If input is "label, then output using NodeToLabel.createBNodeByLabelRaw() ; // else use NodeToLabel.createBNodeByLabel() ; // Also, as URI. final boolean labelsAsGiven = false ; NodeToLabel labels = SyntaxLabels.createNodeToLabel() ; if ( labelsAsGiven ) labels = NodeToLabel.createBNodeByLabelEncoded() ; StreamRDF s = outputStream ; if ( setup != null ) s = InfFactory.inf(s, setup) ; StreamRDFCounting sink = StreamRDFLib.count(s) ; s = null ; ReaderRIOT reader = RDFDataMgr.createReader(lang) ; try { if ( checking ) { if ( lang == RDFLanguages.NTRIPLES || lang == RDFLanguages.NQUADS ) reader.setParserProfile(RiotLib.profile(baseURI, false, true, errHandler)) ; else reader.setParserProfile(RiotLib.profile(baseURI, true, true, errHandler)) ; } else reader.setParserProfile(RiotLib.profile(baseURI, false, false, errHandler)) ; if ( labelsAsGiven ) reader.getParserProfile().setLabelToNode(LabelToNode.createUseLabelAsGiven()) ; modTime.startTimer() ; sink.start() ; reader.read(in, baseURI, ct, sink, null) ; sink.finish() ; } catch (RiotException ex) { // Should have handled the exception and logged a message by now. // System.err.println("++++"+ex.getMessage()); if ( modLangParse.stopOnBadTerm() ) return ; } finally { // Not close the output - we may write again to the underlying output stream in another call to parse a file. IO.close(in) ; } long x = modTime.endTimer() ; long n = sink.countTriples()+sink.countQuads() ; if ( modTime.timingEnabled() ) output(filename, n, x, handler) ; totalMillis += x ; totalTuples += n ; } /** Create a streaming output sink if possible */ protected StreamRDF createStreamSink() { if ( modLangParse.toBitBucket() ) return StreamRDFLib.sinkNull() ; RDFFormat fmt = modLangOutput.getOutputStreamFormat() ; if ( fmt == null ) return null ; return StreamRDFWriter.getWriterStream(System.out, fmt) ; } /** Create an accumulating output stream for later pretty printing */ protected Pair<StreamRDF, PostParseHandler> createAccumulateSink() { final DatasetGraph dsg = DatasetGraphFactory.createMem() ; StreamRDF sink = StreamRDFLib.dataset(dsg) ; final RDFFormat fmt = modLangOutput.getOutputFormatted() ; PostParseHandler handler = new PostParseHandler() { @Override public void postParse() { // Try as dataset, then as graph. WriterDatasetRIOTFactory w = RDFWriterRegistry.getWriterDatasetFactory(fmt) ; if ( w != null ) { RDFDataMgr.write(System.out, dsg, fmt) ; return ; } WriterGraphRIOTFactory wg = RDFWriterRegistry.getWriterGraphFactory(fmt) ; if ( wg != null ) { RDFDataMgr.write(System.out, dsg.getDefaultGraph(), fmt) ; return ; } throw new InternalErrorException("failed to find the writer: "+fmt) ; } } ; return Pair.create(sink, handler) ; } protected Tokenizer makeTokenizer(InputStream in) { Tokenizer tokenizer = TokenizerFactory.makeTokenizerUTF8(in) ; return tokenizer ; } protected void output(String label, long numberTriples, long timeMillis, LangHandler handler) { double timeSec = timeMillis/1000.0 ; System.out.flush() ; System.err.printf("%s : %,5.2f sec %,d %s %,.2f %s\n", label, timeMillis/1000.0, numberTriples, handler.getItemsName(), timeSec == 0 ? 0.0 : numberTriples/timeSec, handler.getRateName()) ; } protected void output(String label) { System.err.printf("%s : \n", label) ; } }
/* * 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.tests; import com.facebook.presto.Session; import com.facebook.presto.testing.MaterializedResult; import com.facebook.presto.testing.MaterializedRow; import com.facebook.presto.testing.QueryRunner; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.intellij.lang.annotations.Language; import org.testng.annotations.Test; import static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.INFORMATION_SCHEMA; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.testing.MaterializedResult.resultBuilder; import static com.facebook.presto.tests.QueryAssertions.assertContains; import static com.google.common.collect.Iterables.getOnlyElement; import static java.lang.String.format; import static java.util.Collections.nCopies; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public abstract class AbstractTestDistributedQueries extends AbstractTestApproximateQueries { protected AbstractTestDistributedQueries(QueryRunner queryRunner) { super(queryRunner); } protected AbstractTestDistributedQueries(QueryRunner queryRunner, Session sampledSession) { super(queryRunner, sampledSession); } @Test public void testSetSession() throws Exception { MaterializedResult result = computeActual("SET SESSION test_string = 'bar'"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getSetSessionProperties(), ImmutableMap.of("test_string", "bar")); result = computeActual("SET SESSION connector.connector_long = 999"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getSetSessionProperties(), ImmutableMap.of("connector.connector_long", "999")); result = computeActual("SET SESSION connector.connector_string = 'baz'"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getSetSessionProperties(), ImmutableMap.of("connector.connector_string", "baz")); result = computeActual("SET SESSION connector.connector_string = 'ban' || 'ana'"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getSetSessionProperties(), ImmutableMap.of("connector.connector_string", "banana")); result = computeActual("SET SESSION connector.connector_long = 444"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getSetSessionProperties(), ImmutableMap.of("connector.connector_long", "444")); result = computeActual("SET SESSION connector.connector_long = 111 + 111"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getSetSessionProperties(), ImmutableMap.of("connector.connector_long", "222")); result = computeActual("SET SESSION connector.connector_boolean = 111 < 3"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getSetSessionProperties(), ImmutableMap.of("connector.connector_boolean", "false")); result = computeActual("SET SESSION connector.connector_double = 11.1"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getSetSessionProperties(), ImmutableMap.of("connector.connector_double", "11.1")); } @Test public void testResetSession() throws Exception { MaterializedResult result = computeActual(getSession(), "RESET SESSION test_string"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getResetSessionProperties(), ImmutableSet.of("test_string")); result = computeActual(getSession(), "RESET SESSION connector.connector_string"); assertTrue((Boolean) getOnlyElement(result).getField(0)); assertEquals(result.getResetSessionProperties(), ImmutableSet.of("connector.connector_string")); } @Test public void testCreateTable() throws Exception { assertUpdate("CREATE TABLE test_create (a bigint, b double, c varchar)"); assertTrue(queryRunner.tableExists(getSession(), "test_create")); assertTableColumnNames("test_create", "a", "b", "c"); assertUpdate("DROP TABLE test_create"); assertFalse(queryRunner.tableExists(getSession(), "test_create")); assertUpdate("CREATE TABLE test_create_table_if_not_exists (a bigint, b varchar, c double)"); assertTrue(queryRunner.tableExists(getSession(), "test_create_table_if_not_exists")); assertTableColumnNames("test_create_table_if_not_exists", "a", "b", "c"); assertUpdate("CREATE TABLE IF NOT EXISTS test_create_table_if_not_exists (d bigint, e varchar)"); assertTrue(queryRunner.tableExists(getSession(), "test_create_table_if_not_exists")); assertTableColumnNames("test_create_table_if_not_exists", "a", "b", "c"); assertUpdate("DROP TABLE test_create_table_if_not_exists"); assertFalse(queryRunner.tableExists(getSession(), "test_create_table_if_not_exists")); } @Test public void testCreateTableAsSelect() throws Exception { assertUpdate("CREATE TABLE test_create_table_as_if_not_exists (a bigint, b double)"); assertTrue(queryRunner.tableExists(getSession(), "test_create_table_as_if_not_exists")); assertTableColumnNames("test_create_table_as_if_not_exists", "a", "b"); MaterializedResult materializedRows = computeActual("CREATE TABLE IF NOT EXISTS test_create_table_as_if_not_exists AS SELECT orderkey, discount FROM lineitem"); assertEquals(materializedRows.getRowCount(), 0); assertTrue(queryRunner.tableExists(getSession(), "test_create_table_as_if_not_exists")); assertTableColumnNames("test_create_table_as_if_not_exists", "a", "b"); assertUpdate("DROP TABLE test_create_table_as_if_not_exists"); assertFalse(queryRunner.tableExists(getSession(), "test_create_table_as_if_not_exists")); assertCreateTableAsSelect( "test_select", "SELECT orderdate, orderkey, totalprice FROM orders", "SELECT count(*) FROM orders"); assertCreateTableAsSelect( "test_group", "SELECT orderstatus, sum(totalprice) x FROM orders GROUP BY orderstatus", "SELECT count(DISTINCT orderstatus) FROM orders"); assertCreateTableAsSelect( "test_join", "SELECT count(*) x FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey", "SELECT 1"); assertCreateTableAsSelect( "test_limit", "SELECT orderkey FROM orders ORDER BY orderkey LIMIT 10", "SELECT 10"); assertCreateTableAsSelect( "test_unicode", "SELECT '\u2603' unicode", "SELECT 1"); assertCreateTableAsSelect( "test_with_data", "SELECT * FROM orders WITH DATA", "SELECT * FROM orders", "SELECT count(*) FROM orders"); assertCreateTableAsSelect( "test_with_no_data", "SELECT * FROM orders WITH NO DATA", "SELECT * FROM orders LIMIT 0", "SELECT 0"); assertCreateTableAsSelect( "test_sampled", "SELECT orderkey FROM tpch_sampled.tiny.orders ORDER BY orderkey LIMIT 10", "SELECT orderkey FROM orders ORDER BY orderkey LIMIT 10", "SELECT 10"); // Tests for CREATE TABLE with UNION ALL: exercises PushTableWriteThroughUnion optimizer assertCreateTableAsSelect( "test_union_all", "SELECT orderdate, orderkey, totalprice FROM orders WHERE orderkey % 2 = 0 UNION ALL " + "SELECT orderdate, orderkey, totalprice FROM orders WHERE orderkey % 2 = 1", "SELECT orderdate, orderkey, totalprice FROM orders", "SELECT count(*) FROM orders"); assertCreateTableAsSelect( getSession().withSystemProperty("redistribute_writes", "true"), "test_union_all", "SELECT orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT count(*) + 1 FROM orders"); assertCreateTableAsSelect( getSession().withSystemProperty("redistribute_writes", "false"), "test_union_all", "SELECT orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT count(*) + 1 FROM orders"); assertExplainAnalyze("EXPLAIN ANALYZE CREATE TABLE analyze_test AS SELECT orderstatus FROM orders"); assertQuery("SELECT * from analyze_test", "SELECT orderstatus FROM orders"); assertUpdate("DROP TABLE analyze_test"); } @Test public void testExplainAnalyze() { assertExplainAnalyze("EXPLAIN ANALYZE SELECT * FROM orders"); assertExplainAnalyze("EXPLAIN ANALYZE SELECT count(*), clerk FROM orders GROUP BY clerk"); assertExplainAnalyze( "EXPLAIN ANALYZE SELECT x + y FROM (" + " SELECT orderdate, COUNT(*) x FROM orders GROUP BY orderdate) a JOIN (" + " SELECT orderdate, COUNT(*) y FROM orders GROUP BY orderdate) b ON a.orderdate = b.orderdate"); assertExplainAnalyze("" + "EXPLAIN ANALYZE SELECT *, o2.custkey\n" + " IN (\n" + " SELECT orderkey\n" + " FROM lineitem\n" + " WHERE orderkey % 5 = 0)\n" + "FROM (SELECT * FROM orders WHERE custkey % 256 = 0) o1\n" + "JOIN (SELECT * FROM orders WHERE custkey % 256 = 0) o2\n" + " ON (o1.orderkey IN (SELECT orderkey FROM lineitem WHERE orderkey % 4 = 0)) = (o2.orderkey IN (SELECT orderkey FROM lineitem WHERE orderkey % 4 = 0))\n" + "WHERE o1.orderkey\n" + " IN (\n" + " SELECT orderkey\n" + " FROM lineitem\n" + " WHERE orderkey % 4 = 0)\n" + "ORDER BY o1.orderkey\n" + " IN (\n" + " SELECT orderkey\n" + " FROM lineitem\n" + " WHERE orderkey % 7 = 0)"); assertExplainAnalyze("EXPLAIN ANALYZE SELECT count(*), clerk FROM orders GROUP BY clerk UNION ALL SELECT sum(orderkey), clerk FROM orders GROUP BY clerk"); assertExplainAnalyze("EXPLAIN ANALYZE SHOW COLUMNS FROM orders"); assertExplainAnalyze("EXPLAIN ANALYZE EXPLAIN SELECT count(*) FROM orders"); assertExplainAnalyze("EXPLAIN ANALYZE EXPLAIN ANALYZE SELECT count(*) FROM orders"); assertExplainAnalyze("EXPLAIN ANALYZE SHOW FUNCTIONS"); assertExplainAnalyze("EXPLAIN ANALYZE SHOW TABLES"); assertExplainAnalyze("EXPLAIN ANALYZE SHOW SCHEMAS"); assertExplainAnalyze("EXPLAIN ANALYZE SHOW CATALOGS"); assertExplainAnalyze("EXPLAIN ANALYZE SHOW SESSION"); } @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "EXPLAIN ANALYZE only supported for statements that are queries") public void testExplainAnalyzeDDL() { computeActual("EXPLAIN ANALYZE DROP TABLE orders"); } private void assertExplainAnalyze(@Language("SQL") String query) { String value = getOnlyElement(computeActual(query).getOnlyColumnAsSet()); // TODO: check that rendered plan is as expected, once stats are collected in a consistent way assertTrue(value.contains("Cost: "), format("Expected output to contain \"Cost: \", but it is %s", value)); } private void assertCreateTableAsSelect(String table, @Language("SQL") String query, @Language("SQL") String rowCountQuery) throws Exception { assertCreateTableAsSelect(getSession(), table, query, query, rowCountQuery); } private void assertCreateTableAsSelect(String table, @Language("SQL") String query, @Language("SQL") String expectedQuery, @Language("SQL") String rowCountQuery) throws Exception { assertCreateTableAsSelect(getSession(), table, query, expectedQuery, rowCountQuery); } private void assertCreateTableAsSelect(Session session, String table, @Language("SQL") String query, @Language("SQL") String expectedQuery, @Language("SQL") String rowCountQuery) throws Exception { assertUpdate(session, "CREATE TABLE " + table + " AS " + query, rowCountQuery); assertQuery(session, "SELECT * FROM " + table, expectedQuery); assertUpdate(session, "DROP TABLE " + table); assertFalse(queryRunner.tableExists(session, table)); } @Test public void testRenameTable() throws Exception { assertUpdate("CREATE TABLE test_rename AS SELECT 123 x", 1); assertUpdate("ALTER TABLE test_rename RENAME TO test_rename_new"); MaterializedResult materializedRows = computeActual("SELECT x FROM test_rename_new"); assertEquals(getOnlyElement(materializedRows.getMaterializedRows()).getField(0), 123); // provide new table name in uppercase assertUpdate("ALTER TABLE test_rename_new RENAME TO TEST_RENAME"); materializedRows = computeActual("SELECT x FROM test_rename"); assertEquals(getOnlyElement(materializedRows.getMaterializedRows()).getField(0), 123); assertUpdate("DROP TABLE test_rename"); assertFalse(queryRunner.tableExists(getSession(), "test_rename")); assertFalse(queryRunner.tableExists(getSession(), "test_rename_new")); } @Test public void testRenameColumn() throws Exception { assertUpdate("CREATE TABLE test_rename_column AS SELECT 123 x", 1); assertUpdate("ALTER TABLE test_rename_column RENAME COLUMN x TO y"); MaterializedResult materializedRows = computeActual("SELECT y FROM test_rename_column"); assertEquals(getOnlyElement(materializedRows.getMaterializedRows()).getField(0), 123); assertUpdate("ALTER TABLE test_rename_column RENAME COLUMN y TO Z"); materializedRows = computeActual("SELECT z FROM test_rename_column"); assertEquals(getOnlyElement(materializedRows.getMaterializedRows()).getField(0), 123); assertUpdate("DROP TABLE test_rename_column"); assertFalse(queryRunner.tableExists(getSession(), "test_rename_column")); } @Test public void testAddColumn() throws Exception { assertUpdate("CREATE TABLE test_add_column AS SELECT 123 x", 1); assertUpdate("CREATE TABLE test_add_column_a AS SELECT 234 x, 111 a", 1); assertUpdate("CREATE TABLE test_add_column_ab AS SELECT 345 x, 222 a, 33.3 b", 1); assertQueryFails("ALTER TABLE test_add_column ADD COLUMN x bigint", ".* Column 'x' already exists"); assertQueryFails("ALTER TABLE test_add_column ADD COLUMN X bigint", ".* Column 'X' already exists"); assertUpdate("ALTER TABLE test_add_column ADD COLUMN a bigint"); assertUpdate("INSERT INTO test_add_column SELECT * FROM test_add_column_a", 1); MaterializedResult materializedRows = computeActual("SELECT x, a FROM test_add_column ORDER BY x"); assertEquals(materializedRows.getMaterializedRows().get(0).getField(0), 123); assertEquals(materializedRows.getMaterializedRows().get(0).getField(1), null); assertEquals(materializedRows.getMaterializedRows().get(1).getField(0), 234); assertEquals(materializedRows.getMaterializedRows().get(1).getField(1), 111L); assertUpdate("ALTER TABLE test_add_column ADD COLUMN b double"); assertUpdate("INSERT INTO test_add_column SELECT * FROM test_add_column_ab", 1); materializedRows = computeActual("SELECT x, a, b FROM test_add_column ORDER BY x"); assertEquals(materializedRows.getMaterializedRows().get(0).getField(0), 123); assertEquals(materializedRows.getMaterializedRows().get(0).getField(1), null); assertEquals(materializedRows.getMaterializedRows().get(0).getField(2), null); assertEquals(materializedRows.getMaterializedRows().get(1).getField(0), 234); assertEquals(materializedRows.getMaterializedRows().get(1).getField(1), 111L); assertEquals(materializedRows.getMaterializedRows().get(1).getField(2), null); assertEquals(materializedRows.getMaterializedRows().get(2).getField(0), 345); assertEquals(materializedRows.getMaterializedRows().get(2).getField(1), 222L); assertEquals(materializedRows.getMaterializedRows().get(2).getField(2), 33.3); assertUpdate("DROP TABLE test_add_column"); assertUpdate("DROP TABLE test_add_column_a"); assertUpdate("DROP TABLE test_add_column_ab"); assertFalse(queryRunner.tableExists(getSession(), "test_add_column")); assertFalse(queryRunner.tableExists(getSession(), "test_add_column_a")); assertFalse(queryRunner.tableExists(getSession(), "test_add_column_ab")); } @Test public void testInsert() throws Exception { @Language("SQL") String query = "SELECT orderdate, orderkey, totalprice FROM orders"; assertUpdate("CREATE TABLE test_insert AS " + query + " WITH NO DATA", 0); assertQuery("SELECT count(*) FROM test_insert", "SELECT 0"); assertUpdate("INSERT INTO test_insert " + query, "SELECT count(*) FROM orders"); assertQuery("SELECT * FROM test_insert", query); assertUpdate("INSERT INTO test_insert (orderkey) VALUES (-1)", 1); assertUpdate("INSERT INTO test_insert (orderkey) VALUES (null)", 1); assertUpdate("INSERT INTO test_insert (orderdate) VALUES (DATE '2001-01-01')", 1); assertUpdate("INSERT INTO test_insert (orderkey, orderdate) VALUES (-2, DATE '2001-01-02')", 1); assertUpdate("INSERT INTO test_insert (orderdate, orderkey) VALUES (DATE '2001-01-03', -3)", 1); assertUpdate("INSERT INTO test_insert (totalprice) VALUES (1234)", 1); assertQuery("SELECT * FROM test_insert", query + " UNION ALL SELECT null, -1, null" + " UNION ALL SELECT null, null, null" + " UNION ALL SELECT DATE '2001-01-01', null, null" + " UNION ALL SELECT DATE '2001-01-02', -2, null" + " UNION ALL SELECT DATE '2001-01-03', -3, null" + " UNION ALL SELECT null, null, 1234"); // UNION query produces columns in the opposite order // of how they are declared in the table schema assertUpdate( "INSERT INTO test_insert (orderkey, orderdate, totalprice) " + "SELECT orderkey, orderdate, totalprice FROM orders " + "UNION ALL " + "SELECT orderkey, orderdate, totalprice FROM orders", "SELECT 2 * count(*) FROM orders"); assertUpdate("DROP TABLE test_insert"); assertUpdate("CREATE TABLE test_insert (a ARRAY<DOUBLE>, b ARRAY<BIGINT>)"); assertUpdate("INSERT INTO test_insert (a) VALUES (ARRAY[null])", 1); assertUpdate("INSERT INTO test_insert (a) VALUES (ARRAY[1234])", 1); assertQuery("SELECT a[1] FROM test_insert", "VALUES (null), (1234)"); assertQueryFails("INSERT INTO test_insert (b) VALUES (ARRAY[1.23E1])", "Insert query has mismatched column types: .*"); assertUpdate("DROP TABLE test_insert"); } @Test public void testDelete() throws Exception { // delete half the table, then delete the rest assertUpdate("CREATE TABLE test_delete AS SELECT * FROM orders", "SELECT count(*) FROM orders"); assertUpdate("DELETE FROM test_delete WHERE orderkey % 2 = 0", "SELECT count(*) FROM orders WHERE orderkey % 2 = 0"); assertQuery("SELECT * FROM test_delete", "SELECT * FROM orders WHERE orderkey % 2 <> 0"); assertUpdate("DELETE FROM test_delete", "SELECT count(*) FROM orders WHERE orderkey % 2 <> 0"); assertQuery("SELECT * FROM test_delete", "SELECT * FROM orders LIMIT 0"); assertUpdate("DROP TABLE test_delete"); // delete successive parts of the table assertUpdate("CREATE TABLE test_delete AS SELECT * FROM orders", "SELECT count(*) FROM orders"); assertUpdate("DELETE FROM test_delete WHERE custkey <= 100", "SELECT count(*) FROM orders WHERE custkey <= 100"); assertQuery("SELECT * FROM test_delete", "SELECT * FROM orders WHERE custkey > 100"); assertUpdate("DELETE FROM test_delete WHERE custkey <= 300", "SELECT count(*) FROM orders WHERE custkey > 100 AND custkey <= 300"); assertQuery("SELECT * FROM test_delete", "SELECT * FROM orders WHERE custkey > 300"); assertUpdate("DELETE FROM test_delete WHERE custkey <= 500", "SELECT count(*) FROM orders WHERE custkey > 300 AND custkey <= 500"); assertQuery("SELECT * FROM test_delete", "SELECT * FROM orders WHERE custkey > 500"); assertUpdate("DROP TABLE test_delete"); // delete using a constant property assertUpdate("CREATE TABLE test_delete AS SELECT * FROM orders", "SELECT count(*) FROM orders"); assertUpdate("DELETE FROM test_delete WHERE orderstatus = 'O'", "SELECT count(*) FROM orders WHERE orderstatus = 'O'"); assertQuery("SELECT * FROM test_delete", "SELECT * FROM orders WHERE orderstatus <> 'O'"); assertUpdate("DROP TABLE test_delete"); // delete without matching any rows assertUpdate("CREATE TABLE test_delete AS SELECT * FROM orders", "SELECT count(*) FROM orders"); assertUpdate("DELETE FROM test_delete WHERE rand() < 0", 0); assertUpdate("DROP TABLE test_delete"); // delete with a predicate that optimizes to false assertUpdate("CREATE TABLE test_delete AS SELECT * FROM orders", "SELECT count(*) FROM orders"); assertUpdate("DELETE FROM test_delete WHERE orderkey > 5 AND orderkey < 4", 0); assertUpdate("DROP TABLE test_delete"); // delete using a subquery assertUpdate("CREATE TABLE test_delete AS SELECT * FROM lineitem", "SELECT count(*) FROM lineitem"); assertUpdate( "DELETE FROM test_delete WHERE orderkey IN (SELECT orderkey FROM orders WHERE orderstatus = 'F')", "SELECT count(*) FROM lineitem WHERE orderkey IN (SELECT orderkey FROM orders WHERE orderstatus = 'F')"); assertQuery( "SELECT * FROM test_delete", "SELECT * FROM lineitem WHERE orderkey IN (SELECT orderkey FROM orders WHERE orderstatus <> 'F')"); assertUpdate("DROP TABLE test_delete"); // delete with multiple SemiJoin assertUpdate("CREATE TABLE test_delete AS SELECT * FROM lineitem", "SELECT count(*) FROM lineitem"); assertUpdate( "DELETE FROM test_delete\n" + "WHERE orderkey IN (SELECT orderkey FROM orders WHERE orderstatus = 'F')\n" + " AND orderkey IN (SELECT orderkey FROM orders WHERE custkey % 5 = 0)\n", "SELECT count(*) FROM lineitem\n" + "WHERE orderkey IN (SELECT orderkey FROM orders WHERE orderstatus = 'F')\n" + " AND orderkey IN (SELECT orderkey FROM orders WHERE custkey % 5 = 0)"); assertQuery( "SELECT * FROM test_delete", "SELECT * FROM lineitem\n" + "WHERE orderkey IN (SELECT orderkey FROM orders WHERE orderstatus <> 'F')\n" + " OR orderkey IN (SELECT orderkey FROM orders WHERE custkey % 5 <> 0)"); assertUpdate("DROP TABLE test_delete"); // delete with SemiJoin null handling assertUpdate("CREATE TABLE test_delete AS SELECT * FROM orders", "SELECT count(*) FROM orders"); assertUpdate( "DELETE FROM test_delete\n" + "WHERE (orderkey IN (SELECT CASE WHEN orderkey % 3 = 0 THEN NULL ELSE orderkey END FROM lineitem)) IS NULL\n", "SELECT count(*) FROM orders\n" + "WHERE (orderkey IN (SELECT CASE WHEN orderkey % 3 = 0 THEN NULL ELSE orderkey END FROM lineitem)) IS NULL\n"); assertQuery( "SELECT * FROM test_delete", "SELECT * FROM orders\n" + "WHERE (orderkey IN (SELECT CASE WHEN orderkey % 3 = 0 THEN NULL ELSE orderkey END FROM lineitem)) IS NOT NULL\n"); assertUpdate("DROP TABLE test_delete"); // delete using a scalar subquery assertUpdate("CREATE TABLE test_delete AS SELECT * FROM orders", "SELECT count(*) FROM orders"); assertUpdate("DELETE FROM test_delete WHERE orderkey = (SELECT orderkey FROM orders ORDER BY orderkey LIMIT 1)", 1); assertUpdate("DELETE FROM test_delete WHERE orderkey = (SELECT orderkey FROM orders WHERE false)", 0); assertUpdate("DELETE FROM test_delete WHERE (SELECT true)", "SELECT count(*) - 1 FROM orders"); assertUpdate("DROP TABLE test_delete"); // test EXPLAIN ANALYZE with CTAS assertExplainAnalyze("EXPLAIN ANALYZE CREATE TABLE analyze_test AS SELECT orderstatus FROM orders"); assertQuery("SELECT * from analyze_test", "SELECT orderstatus FROM orders"); // check that INSERT works also assertExplainAnalyze("EXPLAIN ANALYZE INSERT INTO analyze_test SELECT clerk FROM orders"); assertQuery("SELECT * from analyze_test", "SELECT orderstatus FROM orders UNION ALL SELECT clerk FROM orders"); // check DELETE works with EXPLAIN ANALYZE assertExplainAnalyze("EXPLAIN ANALYZE DELETE FROM analyze_test WHERE TRUE"); assertQuery("SELECT COUNT(*) from analyze_test", "SELECT 0"); assertUpdate("DROP TABLE analyze_test"); } @Test public void testDropTableIfExists() throws Exception { assertFalse(queryRunner.tableExists(getSession(), "test_drop_if_exists")); assertUpdate("DROP TABLE IF EXISTS test_drop_if_exists"); assertFalse(queryRunner.tableExists(getSession(), "test_drop_if_exists")); } @Test public void testView() throws Exception { @Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders"; assertUpdate("CREATE VIEW test_view AS SELECT 123 x"); assertUpdate("CREATE OR REPLACE VIEW test_view AS " + query); assertQuery("SELECT * FROM test_view", query); assertQuery( "SELECT * FROM test_view a JOIN test_view b on a.orderkey = b.orderkey", format("SELECT * FROM (%s) a JOIN (%s) b ON a.orderkey = b.orderkey", query, query)); assertQuery("WITH orders AS (SELECT * FROM orders LIMIT 0) SELECT * FROM test_view", query); String name = format("%s.%s.test_view", getSession().getCatalog().get(), getSession().getSchema().get()); assertQuery("SELECT * FROM " + name, query); assertUpdate("DROP VIEW test_view"); } @Test public void testCompatibleTypeChangeForView() throws Exception { assertUpdate("CREATE TABLE test_table_1 AS SELECT 'abcdefg' a", 1); assertUpdate("CREATE VIEW test_view_1 AS SELECT a FROM test_table_1"); assertQuery("SELECT * FROM test_view_1", "VALUES 'abcdefg'"); // replace table with a version that's implicitly coercible to the previous one assertUpdate("DROP TABLE test_table_1"); assertUpdate("CREATE TABLE test_table_1 AS SELECT 'abc' a", 1); assertQuery("SELECT * FROM test_view_1", "VALUES 'abc'"); assertUpdate("DROP VIEW test_view_1"); assertUpdate("DROP TABLE test_table_1"); } @Test public void testCompatibleTypeChangeForView2() throws Exception { assertUpdate("CREATE TABLE test_table_2 AS SELECT BIGINT '1' v", 1); assertUpdate("CREATE VIEW test_view_2 AS SELECT * FROM test_table_2"); assertQuery("SELECT * FROM test_view_2", "VALUES 1"); // replace table with a version that's implicitly coercible to the previous one assertUpdate("DROP TABLE test_table_2"); assertUpdate("CREATE TABLE test_table_2 AS SELECT INTEGER '1' v", 1); assertQuery("SELECT * FROM test_view_2 WHERE v = 1", "VALUES 1"); assertUpdate("DROP VIEW test_view_2"); assertUpdate("DROP TABLE test_table_2"); } @Test public void testViewMetadata() throws Exception { @Language("SQL") String query = "SELECT BIGINT '123' x, 'foo' y"; assertUpdate("CREATE VIEW meta_test_view AS " + query); // test INFORMATION_SCHEMA.TABLES MaterializedResult actual = computeActual(format( "SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = '%s'", getSession().getSchema().get())); MaterializedResult expected = resultBuilder(getSession(), actual.getTypes()) .row("customer", "BASE TABLE") .row("lineitem", "BASE TABLE") .row("meta_test_view", "VIEW") .row("nation", "BASE TABLE") .row("orders", "BASE TABLE") .row("part", "BASE TABLE") .row("partsupp", "BASE TABLE") .row("region", "BASE TABLE") .row("supplier", "BASE TABLE") .build(); assertContains(actual, expected); // test SHOW TABLES actual = computeActual("SHOW TABLES"); MaterializedResult.Builder builder = resultBuilder(getSession(), actual.getTypes()); for (MaterializedRow row : expected.getMaterializedRows()) { builder.row(row.getField(0)); } expected = builder.build(); assertContains(actual, expected); // test INFORMATION_SCHEMA.VIEWS actual = computeActual(format( "SELECT table_name, view_definition FROM information_schema.views WHERE table_schema = '%s'", getSession().getSchema().get())); expected = resultBuilder(getSession(), actual.getTypes()) .row("meta_test_view", formatSqlText(query)) .build(); assertContains(actual, expected); // test SHOW COLUMNS actual = computeActual("SHOW COLUMNS FROM meta_test_view"); expected = resultBuilder(getSession(), VARCHAR, VARCHAR, VARCHAR) .row("x", "bigint", "") .row("y", "varchar(3)", "") .build(); assertEquals(actual, expected); // test SHOW CREATE VIEW String expectedSql = formatSqlText(format( "CREATE VIEW %s.%s.%s AS %s", getSession().getCatalog().get(), getSession().getSchema().get(), "meta_test_view", query)).trim(); actual = computeActual("SHOW CREATE VIEW meta_test_view"); assertEquals(getOnlyElement(actual.getOnlyColumnAsSet()), expectedSql); assertUpdate("DROP VIEW meta_test_view"); } @Test public void testLargeQuerySuccess() throws Exception { assertQuery("SELECT " + Joiner.on(" AND ").join(nCopies(500, "1 = 1")), "SELECT true"); } @Test public void testShowSchemasFromOther() throws Exception { MaterializedResult result = computeActual("SHOW SCHEMAS FROM tpch"); assertTrue(result.getOnlyColumnAsSet().containsAll(ImmutableSet.of(INFORMATION_SCHEMA, "tiny", "sf1"))); } @Test public void testTableSampleSystem() throws Exception { int total = computeActual("SELECT orderkey FROM orders").getMaterializedRows().size(); boolean sampleSizeFound = false; for (int i = 0; i < 100; i++) { int sampleSize = computeActual("SELECT orderkey FROM ORDERS TABLESAMPLE SYSTEM (50)").getMaterializedRows().size(); if (sampleSize > 0 && sampleSize < total) { sampleSizeFound = true; break; } } assertTrue(sampleSizeFound, "Table sample returned unexpected number of rows"); } @Test public void testTableSampleSystemBoundaryValues() throws Exception { MaterializedResult fullSample = computeActual("SELECT orderkey FROM orders TABLESAMPLE SYSTEM (100)"); MaterializedResult emptySample = computeActual("SELECT orderkey FROM orders TABLESAMPLE SYSTEM (0)"); MaterializedResult all = computeActual("SELECT orderkey FROM orders"); assertContains(all, fullSample); assertEquals(emptySample.getMaterializedRows().size(), 0); } @Override @Test public void testTableSamplePoissonizedRescaled() throws Exception { MaterializedResult sample = computeActual("SELECT * FROM orders TABLESAMPLE POISSONIZED (10) RESCALED"); MaterializedResult all = computeExpected("SELECT * FROM orders", sample.getTypes()); assertTrue(!sample.getMaterializedRows().isEmpty()); assertContains(all, sample); } @Test public void testSymbolAliasing() throws Exception { assertUpdate("CREATE TABLE test_symbol_aliasing AS SELECT 1 foo_1, 2 foo_2_4", 1); assertQuery("SELECT foo_1, foo_2_4 FROM test_symbol_aliasing", "SELECT 1, 2"); assertUpdate("DROP TABLE test_symbol_aliasing"); } }
/* * Copyright 2014-2019 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.apigatewayv2.model; import java.io.Serializable; import javax.annotation.Generated; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetApiResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The stage name is typically appended * to this URI to form a complete path to a deployed API stage. * </p> */ private String apiEndpoint; /** * <p> * The API ID. * </p> */ private String apiId; /** * <p> * An API key selection expression. See <a href= * "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions" * >API Key Selection Expressions</a>. * </p> */ private String apiKeySelectionExpression; /** * <p> * The timestamp when the API was created. * </p> */ private java.util.Date createdDate; /** * <p> * The description of the API. * </p> */ private String description; /** * <p> * Avoid validating models when creating a deployment. * </p> */ private Boolean disableSchemaValidation; /** * <p> * The name of the API. * </p> */ private String name; /** * <p> * The API protocol: Currently only WEBSOCKET is supported. * </p> */ private String protocolType; /** * <p> * The route selection expression for the API. * </p> */ private String routeSelectionExpression; /** * <p> * A version identifier for the API. * </p> */ private String version; /** * <p> * The warning messages reported when failonwarnings is turned on during API import. * </p> */ private java.util.List<String> warnings; /** * <p> * The key-value map of strings. The valid character set is [a-zA-Z+-=._:/]. The tag key can be up to 128 characters * and must not start with aws:. The tag value can be up to 256 characters.. * </p> */ private java.util.Map<String, String> tags; /** * <p> * The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The stage name is typically appended * to this URI to form a complete path to a deployed API stage. * </p> * * @param apiEndpoint * The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The stage name is typically * appended to this URI to form a complete path to a deployed API stage. */ public void setApiEndpoint(String apiEndpoint) { this.apiEndpoint = apiEndpoint; } /** * <p> * The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The stage name is typically appended * to this URI to form a complete path to a deployed API stage. * </p> * * @return The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The stage name is typically * appended to this URI to form a complete path to a deployed API stage. */ public String getApiEndpoint() { return this.apiEndpoint; } /** * <p> * The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The stage name is typically appended * to this URI to form a complete path to a deployed API stage. * </p> * * @param apiEndpoint * The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The stage name is typically * appended to this URI to form a complete path to a deployed API stage. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withApiEndpoint(String apiEndpoint) { setApiEndpoint(apiEndpoint); return this; } /** * <p> * The API ID. * </p> * * @param apiId * The API ID. */ public void setApiId(String apiId) { this.apiId = apiId; } /** * <p> * The API ID. * </p> * * @return The API ID. */ public String getApiId() { return this.apiId; } /** * <p> * The API ID. * </p> * * @param apiId * The API ID. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withApiId(String apiId) { setApiId(apiId); return this; } /** * <p> * An API key selection expression. See <a href= * "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions" * >API Key Selection Expressions</a>. * </p> * * @param apiKeySelectionExpression * An API key selection expression. See <a href= * "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions" * >API Key Selection Expressions</a>. */ public void setApiKeySelectionExpression(String apiKeySelectionExpression) { this.apiKeySelectionExpression = apiKeySelectionExpression; } /** * <p> * An API key selection expression. See <a href= * "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions" * >API Key Selection Expressions</a>. * </p> * * @return An API key selection expression. See <a href= * "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions" * >API Key Selection Expressions</a>. */ public String getApiKeySelectionExpression() { return this.apiKeySelectionExpression; } /** * <p> * An API key selection expression. See <a href= * "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions" * >API Key Selection Expressions</a>. * </p> * * @param apiKeySelectionExpression * An API key selection expression. See <a href= * "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions" * >API Key Selection Expressions</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withApiKeySelectionExpression(String apiKeySelectionExpression) { setApiKeySelectionExpression(apiKeySelectionExpression); return this; } /** * <p> * The timestamp when the API was created. * </p> * * @param createdDate * The timestamp when the API was created. */ public void setCreatedDate(java.util.Date createdDate) { this.createdDate = createdDate; } /** * <p> * The timestamp when the API was created. * </p> * * @return The timestamp when the API was created. */ public java.util.Date getCreatedDate() { return this.createdDate; } /** * <p> * The timestamp when the API was created. * </p> * * @param createdDate * The timestamp when the API was created. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withCreatedDate(java.util.Date createdDate) { setCreatedDate(createdDate); return this; } /** * <p> * The description of the API. * </p> * * @param description * The description of the API. */ public void setDescription(String description) { this.description = description; } /** * <p> * The description of the API. * </p> * * @return The description of the API. */ public String getDescription() { return this.description; } /** * <p> * The description of the API. * </p> * * @param description * The description of the API. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withDescription(String description) { setDescription(description); return this; } /** * <p> * Avoid validating models when creating a deployment. * </p> * * @param disableSchemaValidation * Avoid validating models when creating a deployment. */ public void setDisableSchemaValidation(Boolean disableSchemaValidation) { this.disableSchemaValidation = disableSchemaValidation; } /** * <p> * Avoid validating models when creating a deployment. * </p> * * @return Avoid validating models when creating a deployment. */ public Boolean getDisableSchemaValidation() { return this.disableSchemaValidation; } /** * <p> * Avoid validating models when creating a deployment. * </p> * * @param disableSchemaValidation * Avoid validating models when creating a deployment. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withDisableSchemaValidation(Boolean disableSchemaValidation) { setDisableSchemaValidation(disableSchemaValidation); return this; } /** * <p> * Avoid validating models when creating a deployment. * </p> * * @return Avoid validating models when creating a deployment. */ public Boolean isDisableSchemaValidation() { return this.disableSchemaValidation; } /** * <p> * The name of the API. * </p> * * @param name * The name of the API. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the API. * </p> * * @return The name of the API. */ public String getName() { return this.name; } /** * <p> * The name of the API. * </p> * * @param name * The name of the API. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withName(String name) { setName(name); return this; } /** * <p> * The API protocol: Currently only WEBSOCKET is supported. * </p> * * @param protocolType * The API protocol: Currently only WEBSOCKET is supported. * @see ProtocolType */ public void setProtocolType(String protocolType) { this.protocolType = protocolType; } /** * <p> * The API protocol: Currently only WEBSOCKET is supported. * </p> * * @return The API protocol: Currently only WEBSOCKET is supported. * @see ProtocolType */ public String getProtocolType() { return this.protocolType; } /** * <p> * The API protocol: Currently only WEBSOCKET is supported. * </p> * * @param protocolType * The API protocol: Currently only WEBSOCKET is supported. * @return Returns a reference to this object so that method calls can be chained together. * @see ProtocolType */ public GetApiResult withProtocolType(String protocolType) { setProtocolType(protocolType); return this; } /** * <p> * The API protocol: Currently only WEBSOCKET is supported. * </p> * * @param protocolType * The API protocol: Currently only WEBSOCKET is supported. * @return Returns a reference to this object so that method calls can be chained together. * @see ProtocolType */ public GetApiResult withProtocolType(ProtocolType protocolType) { this.protocolType = protocolType.toString(); return this; } /** * <p> * The route selection expression for the API. * </p> * * @param routeSelectionExpression * The route selection expression for the API. */ public void setRouteSelectionExpression(String routeSelectionExpression) { this.routeSelectionExpression = routeSelectionExpression; } /** * <p> * The route selection expression for the API. * </p> * * @return The route selection expression for the API. */ public String getRouteSelectionExpression() { return this.routeSelectionExpression; } /** * <p> * The route selection expression for the API. * </p> * * @param routeSelectionExpression * The route selection expression for the API. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withRouteSelectionExpression(String routeSelectionExpression) { setRouteSelectionExpression(routeSelectionExpression); return this; } /** * <p> * A version identifier for the API. * </p> * * @param version * A version identifier for the API. */ public void setVersion(String version) { this.version = version; } /** * <p> * A version identifier for the API. * </p> * * @return A version identifier for the API. */ public String getVersion() { return this.version; } /** * <p> * A version identifier for the API. * </p> * * @param version * A version identifier for the API. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withVersion(String version) { setVersion(version); return this; } /** * <p> * The warning messages reported when failonwarnings is turned on during API import. * </p> * * @return The warning messages reported when failonwarnings is turned on during API import. */ public java.util.List<String> getWarnings() { return warnings; } /** * <p> * The warning messages reported when failonwarnings is turned on during API import. * </p> * * @param warnings * The warning messages reported when failonwarnings is turned on during API import. */ public void setWarnings(java.util.Collection<String> warnings) { if (warnings == null) { this.warnings = null; return; } this.warnings = new java.util.ArrayList<String>(warnings); } /** * <p> * The warning messages reported when failonwarnings is turned on during API import. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setWarnings(java.util.Collection)} or {@link #withWarnings(java.util.Collection)} if you want to override * the existing values. * </p> * * @param warnings * The warning messages reported when failonwarnings is turned on during API import. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withWarnings(String... warnings) { if (this.warnings == null) { setWarnings(new java.util.ArrayList<String>(warnings.length)); } for (String ele : warnings) { this.warnings.add(ele); } return this; } /** * <p> * The warning messages reported when failonwarnings is turned on during API import. * </p> * * @param warnings * The warning messages reported when failonwarnings is turned on during API import. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withWarnings(java.util.Collection<String> warnings) { setWarnings(warnings); return this; } /** * <p> * The key-value map of strings. The valid character set is [a-zA-Z+-=._:/]. The tag key can be up to 128 characters * and must not start with aws:. The tag value can be up to 256 characters.. * </p> * * @return The key-value map of strings. The valid character set is [a-zA-Z+-=._:/]. The tag key can be up to 128 * characters and must not start with aws:. The tag value can be up to 256 characters.. */ public java.util.Map<String, String> getTags() { return tags; } /** * <p> * The key-value map of strings. The valid character set is [a-zA-Z+-=._:/]. The tag key can be up to 128 characters * and must not start with aws:. The tag value can be up to 256 characters.. * </p> * * @param tags * The key-value map of strings. The valid character set is [a-zA-Z+-=._:/]. The tag key can be up to 128 * characters and must not start with aws:. The tag value can be up to 256 characters.. */ public void setTags(java.util.Map<String, String> tags) { this.tags = tags; } /** * <p> * The key-value map of strings. The valid character set is [a-zA-Z+-=._:/]. The tag key can be up to 128 characters * and must not start with aws:. The tag value can be up to 256 characters.. * </p> * * @param tags * The key-value map of strings. The valid character set is [a-zA-Z+-=._:/]. The tag key can be up to 128 * characters and must not start with aws:. The tag value can be up to 256 characters.. * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; } public GetApiResult addTagsEntry(String key, String value) { if (null == this.tags) { this.tags = new java.util.HashMap<String, String>(); } if (this.tags.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.tags.put(key, value); return this; } /** * Removes all the entries added into Tags. * * @return Returns a reference to this object so that method calls can be chained together. */ public GetApiResult clearTagsEntries() { this.tags = null; return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getApiEndpoint() != null) sb.append("ApiEndpoint: ").append(getApiEndpoint()).append(","); if (getApiId() != null) sb.append("ApiId: ").append(getApiId()).append(","); if (getApiKeySelectionExpression() != null) sb.append("ApiKeySelectionExpression: ").append(getApiKeySelectionExpression()).append(","); if (getCreatedDate() != null) sb.append("CreatedDate: ").append(getCreatedDate()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getDisableSchemaValidation() != null) sb.append("DisableSchemaValidation: ").append(getDisableSchemaValidation()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getProtocolType() != null) sb.append("ProtocolType: ").append(getProtocolType()).append(","); if (getRouteSelectionExpression() != null) sb.append("RouteSelectionExpression: ").append(getRouteSelectionExpression()).append(","); if (getVersion() != null) sb.append("Version: ").append(getVersion()).append(","); if (getWarnings() != null) sb.append("Warnings: ").append(getWarnings()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetApiResult == false) return false; GetApiResult other = (GetApiResult) obj; if (other.getApiEndpoint() == null ^ this.getApiEndpoint() == null) return false; if (other.getApiEndpoint() != null && other.getApiEndpoint().equals(this.getApiEndpoint()) == false) return false; if (other.getApiId() == null ^ this.getApiId() == null) return false; if (other.getApiId() != null && other.getApiId().equals(this.getApiId()) == false) return false; if (other.getApiKeySelectionExpression() == null ^ this.getApiKeySelectionExpression() == null) return false; if (other.getApiKeySelectionExpression() != null && other.getApiKeySelectionExpression().equals(this.getApiKeySelectionExpression()) == false) return false; if (other.getCreatedDate() == null ^ this.getCreatedDate() == null) return false; if (other.getCreatedDate() != null && other.getCreatedDate().equals(this.getCreatedDate()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getDisableSchemaValidation() == null ^ this.getDisableSchemaValidation() == null) return false; if (other.getDisableSchemaValidation() != null && other.getDisableSchemaValidation().equals(this.getDisableSchemaValidation()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getProtocolType() == null ^ this.getProtocolType() == null) return false; if (other.getProtocolType() != null && other.getProtocolType().equals(this.getProtocolType()) == false) return false; if (other.getRouteSelectionExpression() == null ^ this.getRouteSelectionExpression() == null) return false; if (other.getRouteSelectionExpression() != null && other.getRouteSelectionExpression().equals(this.getRouteSelectionExpression()) == false) return false; if (other.getVersion() == null ^ this.getVersion() == null) return false; if (other.getVersion() != null && other.getVersion().equals(this.getVersion()) == false) return false; if (other.getWarnings() == null ^ this.getWarnings() == null) return false; if (other.getWarnings() != null && other.getWarnings().equals(this.getWarnings()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getApiEndpoint() == null) ? 0 : getApiEndpoint().hashCode()); hashCode = prime * hashCode + ((getApiId() == null) ? 0 : getApiId().hashCode()); hashCode = prime * hashCode + ((getApiKeySelectionExpression() == null) ? 0 : getApiKeySelectionExpression().hashCode()); hashCode = prime * hashCode + ((getCreatedDate() == null) ? 0 : getCreatedDate().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getDisableSchemaValidation() == null) ? 0 : getDisableSchemaValidation().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getProtocolType() == null) ? 0 : getProtocolType().hashCode()); hashCode = prime * hashCode + ((getRouteSelectionExpression() == null) ? 0 : getRouteSelectionExpression().hashCode()); hashCode = prime * hashCode + ((getVersion() == null) ? 0 : getVersion().hashCode()); hashCode = prime * hashCode + ((getWarnings() == null) ? 0 : getWarnings().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public GetApiResult clone() { try { return (GetApiResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", 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 nginx.unit.websocket; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; /** * Wraps the {@link AsynchronousSocketChannel} with SSL/TLS. This needs a lot * more testing before it can be considered robust. */ public class AsyncChannelWrapperSecure implements AsyncChannelWrapper { private final Log log = LogFactory.getLog(AsyncChannelWrapperSecure.class); private static final StringManager sm = StringManager.getManager(AsyncChannelWrapperSecure.class); private static final ByteBuffer DUMMY = ByteBuffer.allocate(16921); private final AsynchronousSocketChannel socketChannel; private final SSLEngine sslEngine; private final ByteBuffer socketReadBuffer; private final ByteBuffer socketWriteBuffer; // One thread for read, one for write private final ExecutorService executor = Executors.newFixedThreadPool(2, new SecureIOThreadFactory()); private AtomicBoolean writing = new AtomicBoolean(false); private AtomicBoolean reading = new AtomicBoolean(false); public AsyncChannelWrapperSecure(AsynchronousSocketChannel socketChannel, SSLEngine sslEngine) { this.socketChannel = socketChannel; this.sslEngine = sslEngine; int socketBufferSize = sslEngine.getSession().getPacketBufferSize(); socketReadBuffer = ByteBuffer.allocateDirect(socketBufferSize); socketWriteBuffer = ByteBuffer.allocateDirect(socketBufferSize); } @Override public Future<Integer> read(ByteBuffer dst) { WrapperFuture<Integer,Void> future = new WrapperFuture<>(); if (!reading.compareAndSet(false, true)) { throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.concurrentRead")); } ReadTask readTask = new ReadTask(dst, future); executor.execute(readTask); return future; } @Override public <B,A extends B> void read(ByteBuffer dst, A attachment, CompletionHandler<Integer,B> handler) { WrapperFuture<Integer,B> future = new WrapperFuture<>(handler, attachment); if (!reading.compareAndSet(false, true)) { throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.concurrentRead")); } ReadTask readTask = new ReadTask(dst, future); executor.execute(readTask); } @Override public Future<Integer> write(ByteBuffer src) { WrapperFuture<Long,Void> inner = new WrapperFuture<>(); if (!writing.compareAndSet(false, true)) { throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.concurrentWrite")); } WriteTask writeTask = new WriteTask(new ByteBuffer[] {src}, 0, 1, inner); executor.execute(writeTask); Future<Integer> future = new LongToIntegerFuture(inner); return future; } @Override public <B,A extends B> void write(ByteBuffer[] srcs, int offset, int length, long timeout, TimeUnit unit, A attachment, CompletionHandler<Long,B> handler) { WrapperFuture<Long,B> future = new WrapperFuture<>(handler, attachment); if (!writing.compareAndSet(false, true)) { throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.concurrentWrite")); } WriteTask writeTask = new WriteTask(srcs, offset, length, future); executor.execute(writeTask); } @Override public void close() { try { socketChannel.close(); } catch (IOException e) { log.info(sm.getString("asyncChannelWrapperSecure.closeFail")); } executor.shutdownNow(); } @Override public Future<Void> handshake() throws SSLException { WrapperFuture<Void,Void> wFuture = new WrapperFuture<>(); Thread t = new WebSocketSslHandshakeThread(wFuture); t.start(); return wFuture; } private class WriteTask implements Runnable { private final ByteBuffer[] srcs; private final int offset; private final int length; private final WrapperFuture<Long,?> future; public WriteTask(ByteBuffer[] srcs, int offset, int length, WrapperFuture<Long,?> future) { this.srcs = srcs; this.future = future; this.offset = offset; this.length = length; } @Override public void run() { long written = 0; try { for (int i = offset; i < offset + length; i++) { ByteBuffer src = srcs[i]; while (src.hasRemaining()) { socketWriteBuffer.clear(); // Encrypt the data SSLEngineResult r = sslEngine.wrap(src, socketWriteBuffer); written += r.bytesConsumed(); Status s = r.getStatus(); if (s == Status.OK || s == Status.BUFFER_OVERFLOW) { // Need to write out the bytes and may need to read from // the source again to empty it } else { // Status.BUFFER_UNDERFLOW - only happens on unwrap // Status.CLOSED - unexpected throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.statusWrap")); } // Check for tasks if (r.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable = sslEngine.getDelegatedTask(); while (runnable != null) { runnable.run(); runnable = sslEngine.getDelegatedTask(); } } socketWriteBuffer.flip(); // Do the write int toWrite = r.bytesProduced(); while (toWrite > 0) { Future<Integer> f = socketChannel.write(socketWriteBuffer); Integer socketWrite = f.get(); toWrite -= socketWrite.intValue(); } } } if (writing.compareAndSet(true, false)) { future.complete(Long.valueOf(written)); } else { future.fail(new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.wrongStateWrite"))); } } catch (Exception e) { writing.set(false); future.fail(e); } } } private class ReadTask implements Runnable { private final ByteBuffer dest; private final WrapperFuture<Integer,?> future; public ReadTask(ByteBuffer dest, WrapperFuture<Integer,?> future) { this.dest = dest; this.future = future; } @Override public void run() { int read = 0; boolean forceRead = false; try { while (read == 0) { socketReadBuffer.compact(); if (forceRead) { forceRead = false; Future<Integer> f = socketChannel.read(socketReadBuffer); Integer socketRead = f.get(); if (socketRead.intValue() == -1) { throw new EOFException(sm.getString("asyncChannelWrapperSecure.eof")); } } socketReadBuffer.flip(); if (socketReadBuffer.hasRemaining()) { // Decrypt the data in the buffer SSLEngineResult r = sslEngine.unwrap(socketReadBuffer, dest); read += r.bytesProduced(); Status s = r.getStatus(); if (s == Status.OK) { // Bytes available for reading and there may be // sufficient data in the socketReadBuffer to // support further reads without reading from the // socket } else if (s == Status.BUFFER_UNDERFLOW) { // There is partial data in the socketReadBuffer if (read == 0) { // Need more data before the partial data can be // processed and some output generated forceRead = true; } // else return the data we have and deal with the // partial data on the next read } else if (s == Status.BUFFER_OVERFLOW) { // Not enough space in the destination buffer to // store all of the data. We could use a bytes read // value of -bufferSizeRequired to signal the new // buffer size required but an explicit exception is // clearer. if (reading.compareAndSet(true, false)) { throw new ReadBufferOverflowException(sslEngine. getSession().getApplicationBufferSize()); } else { future.fail(new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.wrongStateRead"))); } } else { // Status.CLOSED - unexpected throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.statusUnwrap")); } // Check for tasks if (r.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable = sslEngine.getDelegatedTask(); while (runnable != null) { runnable.run(); runnable = sslEngine.getDelegatedTask(); } } } else { forceRead = true; } } if (reading.compareAndSet(true, false)) { future.complete(Integer.valueOf(read)); } else { future.fail(new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.wrongStateRead"))); } } catch (RuntimeException | ReadBufferOverflowException | SSLException | EOFException | ExecutionException | InterruptedException e) { reading.set(false); future.fail(e); } } } private class WebSocketSslHandshakeThread extends Thread { private final WrapperFuture<Void,Void> hFuture; private HandshakeStatus handshakeStatus; private Status resultStatus; public WebSocketSslHandshakeThread(WrapperFuture<Void,Void> hFuture) { this.hFuture = hFuture; } @Override public void run() { try { sslEngine.beginHandshake(); // So the first compact does the right thing socketReadBuffer.position(socketReadBuffer.limit()); handshakeStatus = sslEngine.getHandshakeStatus(); resultStatus = Status.OK; boolean handshaking = true; while(handshaking) { switch (handshakeStatus) { case NEED_WRAP: { socketWriteBuffer.clear(); SSLEngineResult r = sslEngine.wrap(DUMMY, socketWriteBuffer); checkResult(r, true); socketWriteBuffer.flip(); Future<Integer> fWrite = socketChannel.write(socketWriteBuffer); fWrite.get(); break; } case NEED_UNWRAP: { socketReadBuffer.compact(); if (socketReadBuffer.position() == 0 || resultStatus == Status.BUFFER_UNDERFLOW) { Future<Integer> fRead = socketChannel.read(socketReadBuffer); fRead.get(); } socketReadBuffer.flip(); SSLEngineResult r = sslEngine.unwrap(socketReadBuffer, DUMMY); checkResult(r, false); break; } case NEED_TASK: { Runnable r = null; while ((r = sslEngine.getDelegatedTask()) != null) { r.run(); } handshakeStatus = sslEngine.getHandshakeStatus(); break; } case FINISHED: { handshaking = false; break; } case NOT_HANDSHAKING: { throw new SSLException( sm.getString("asyncChannelWrapperSecure.notHandshaking")); } } } } catch (Exception e) { hFuture.fail(e); return; } hFuture.complete(null); } private void checkResult(SSLEngineResult result, boolean wrap) throws SSLException { handshakeStatus = result.getHandshakeStatus(); resultStatus = result.getStatus(); if (resultStatus != Status.OK && (wrap || resultStatus != Status.BUFFER_UNDERFLOW)) { throw new SSLException( sm.getString("asyncChannelWrapperSecure.check.notOk", resultStatus)); } if (wrap && result.bytesConsumed() != 0) { throw new SSLException(sm.getString("asyncChannelWrapperSecure.check.wrap")); } if (!wrap && result.bytesProduced() != 0) { throw new SSLException(sm.getString("asyncChannelWrapperSecure.check.unwrap")); } } } private static class WrapperFuture<T,A> implements Future<T> { private final CompletionHandler<T,A> handler; private final A attachment; private volatile T result = null; private volatile Throwable throwable = null; private CountDownLatch completionLatch = new CountDownLatch(1); public WrapperFuture() { this(null, null); } public WrapperFuture(CompletionHandler<T,A> handler, A attachment) { this.handler = handler; this.attachment = attachment; } public void complete(T result) { this.result = result; completionLatch.countDown(); if (handler != null) { handler.completed(result, attachment); } } public void fail(Throwable t) { throwable = t; completionLatch.countDown(); if (handler != null) { handler.failed(throwable, attachment); } } @Override public final boolean cancel(boolean mayInterruptIfRunning) { // Could support cancellation by closing the connection return false; } @Override public final boolean isCancelled() { // Could support cancellation by closing the connection return false; } @Override public final boolean isDone() { return completionLatch.getCount() > 0; } @Override public T get() throws InterruptedException, ExecutionException { completionLatch.await(); if (throwable != null) { throw new ExecutionException(throwable); } return result; } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { boolean latchResult = completionLatch.await(timeout, unit); if (latchResult == false) { throw new TimeoutException(); } if (throwable != null) { throw new ExecutionException(throwable); } return result; } } private static final class LongToIntegerFuture implements Future<Integer> { private final Future<Long> wrapped; public LongToIntegerFuture(Future<Long> wrapped) { this.wrapped = wrapped; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return wrapped.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return wrapped.isCancelled(); } @Override public boolean isDone() { return wrapped.isDone(); } @Override public Integer get() throws InterruptedException, ExecutionException { Long result = wrapped.get(); if (result.longValue() > Integer.MAX_VALUE) { throw new ExecutionException(sm.getString( "asyncChannelWrapperSecure.tooBig", result), null); } return Integer.valueOf(result.intValue()); } @Override public Integer get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Long result = wrapped.get(timeout, unit); if (result.longValue() > Integer.MAX_VALUE) { throw new ExecutionException(sm.getString( "asyncChannelWrapperSecure.tooBig", result), null); } return Integer.valueOf(result.intValue()); } } private static class SecureIOThreadFactory implements ThreadFactory { private AtomicInteger count = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("WebSocketClient-SecureIO-" + count.incrementAndGet()); // No need to set the context class loader. The threads will be // cleaned up when the connection is closed. t.setDaemon(true); return t; } } }
/* * 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.planner.index; import org.apache.drill.shaded.guava.com.google.common.collect.ImmutableList; import org.apache.drill.shaded.guava.com.google.common.collect.Lists; import org.apache.drill.shaded.guava.com.google.common.collect.Maps; import org.apache.drill.shaded.guava.com.google.common.collect.Sets; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexUtil; import org.apache.drill.common.expression.LogicalExpression; import org.apache.drill.exec.planner.logical.DrillScanRel; import org.apache.drill.exec.planner.logical.partition.RewriteCombineBinaryOperators; import org.apache.calcite.rel.RelNode; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class IndexConditionInfo { public final RexNode indexCondition; public final RexNode remainderCondition; public final boolean hasIndexCol; public IndexConditionInfo(RexNode indexCondition, RexNode remainderCondition, boolean hasIndexCol) { this.indexCondition = indexCondition; this.remainderCondition = remainderCondition; this.hasIndexCol = hasIndexCol; } public static Builder newBuilder(RexNode condition, Iterable<IndexDescriptor> indexes, RexBuilder builder, RelNode scan) { return new Builder(condition, indexes, builder, scan); } public static class Builder { final RexBuilder builder; final RelNode scan; final Iterable<IndexDescriptor> indexes; private RexNode condition; public Builder(RexNode condition, Iterable<IndexDescriptor> indexes, RexBuilder builder, RelNode scan) { this.condition = condition; this.builder = builder; this.scan = scan; this.indexes = indexes; } public Builder(RexNode condition, IndexDescriptor index, RexBuilder builder, DrillScanRel scan) { this.condition = condition; this.builder = builder; this.scan = scan; this.indexes = Lists.newArrayList(index); } /** * Get a single IndexConditionInfo in which indexCondition has field on all indexes in this.indexes * @return */ public IndexConditionInfo getCollectiveInfo(IndexLogicalPlanCallContext indexContext) { Set<LogicalExpression> paths = Sets.newLinkedHashSet(); for (IndexDescriptor index : indexes ) { paths.addAll(index.getIndexColumns()); //paths.addAll(index.getNonIndexColumns()); } return indexConditionRelatedToFields(Lists.newArrayList(paths), condition); } /* * A utility function to check whether the given index hint is valid. */ public boolean isValidIndexHint(IndexLogicalPlanCallContext indexContext) { if (indexContext.indexHint.equals("")) { return false; } for (IndexDescriptor index: indexes ) { if (indexContext.indexHint.equals(index.getIndexName())) { return true; } } return false; } /** * Get a map of Index=>IndexConditionInfo, each IndexConditionInfo has the separated condition and remainder condition. * The map is ordered, so the last IndexDescriptor will have the final remainderCondition after separating conditions * that are relevant to this.indexes. The conditions are separated on LEADING index columns. * @return Map containing index{@link IndexDescriptor} and condition {@link IndexConditionInfo} pairs */ public Map<IndexDescriptor, IndexConditionInfo> getFirstKeyIndexConditionMap() { Map<IndexDescriptor, IndexConditionInfo> indexInfoMap = Maps.newLinkedHashMap(); RexNode initCondition = condition; for (IndexDescriptor index : indexes) { List<LogicalExpression> leadingColumns = new ArrayList<>(); if (initCondition.isAlwaysTrue()) { break; } // TODO: Ensure we dont get NULL pointer exceptions leadingColumns.add(index.getIndexColumns().get(0)); IndexConditionInfo info = indexConditionRelatedToFields(leadingColumns, initCondition); if (info == null || info.hasIndexCol == false) { // No info found, based on remaining condition. Check if the leading columns are same as another index IndexConditionInfo origInfo = indexConditionRelatedToFields(leadingColumns, condition); if (origInfo == null || origInfo.hasIndexCol == false) { // do nothing } else { indexInfoMap.put(index, origInfo); // Leave the initCondition as-is, since this is a duplicate condition } continue; } indexInfoMap.put(index, info); initCondition = info.remainderCondition; } return indexInfoMap; } /** * Given a RexNode corresponding to the condition expression tree and the index descriptor, * check if one or more columns involved in the condition tree form a prefix of the columns in the * index keys. * @param indexDesc * @param initCondition * @return True if prefix, False if not */ public boolean isConditionPrefix(IndexDescriptor indexDesc, RexNode initCondition) { List<LogicalExpression> indexCols = indexDesc.getIndexColumns(); boolean prefix = true; int numPrefix = 0; if (indexCols.size() > 0 && initCondition != null) { int i = 0; while (prefix && i < indexCols.size()) { LogicalExpression p = indexCols.get(i++); List<LogicalExpression> prefixCol = ImmutableList.of(p); IndexConditionInfo info = indexConditionRelatedToFields(prefixCol, initCondition); if (info != null && info.hasIndexCol) { numPrefix++; initCondition = info.remainderCondition; if (initCondition.isAlwaysTrue()) { // all filter conditions are accounted for break; } } else { prefix = false; } } } return numPrefix > 0; } /** * Get a map of Index=>IndexConditionInfo, each IndexConditionInfo has the separated condition and remainder condition. * The map is ordered, so the last IndexDescriptor will have the final remainderCondition after separating conditions * that are relevant to the indexList. The conditions are separated based on index columns. * @return Map containing index{@link IndexDescriptor} and condition {@link IndexConditionInfo} pairs */ public Map<IndexDescriptor, IndexConditionInfo> getIndexConditionMap(List<IndexDescriptor> indexList) { return getIndexConditionMapInternal(indexList); } /** * Get a map of Index=>IndexConditionInfo, each IndexConditionInfo has the separated condition and remainder condition. * The map is ordered, so the last IndexDescriptor will have the final remainderCondition after separating conditions * that are relevant to this.indexes. The conditions are separated based on index columns. * @return Map containing index{@link IndexDescriptor} and condition {@link IndexConditionInfo} pairs */ public Map<IndexDescriptor, IndexConditionInfo> getIndexConditionMap() { return getIndexConditionMapInternal(Lists.newArrayList(indexes)); } private Map<IndexDescriptor, IndexConditionInfo> getIndexConditionMapInternal(List<IndexDescriptor> indexes) { Map<IndexDescriptor, IndexConditionInfo> indexInfoMap = Maps.newLinkedHashMap(); RexNode initCondition = condition; for (IndexDescriptor index : indexes) { if (initCondition.isAlwaysTrue()) { break; } if (!isConditionPrefix(index, initCondition)) { continue; } IndexConditionInfo info = indexConditionRelatedToFields(index.getIndexColumns(), initCondition); if (info == null || info.hasIndexCol == false) { continue; } initCondition = info.remainderCondition; indexInfoMap.put(index, info); } return indexInfoMap; } /** * Given a list of Index Expressions(usually indexed fields/functions from one or a set of indexes), * separate a filter condition into * 1), relevant subset of conditions (by relevant, it means at least one given index Expression was found) and, * 2), the rest in remainderCondition * @param relevantPaths * @param condition * @return */ public IndexConditionInfo indexConditionRelatedToFields(List<LogicalExpression> relevantPaths, RexNode condition) { // Use the same filter analyzer that is used for partitioning columns RewriteCombineBinaryOperators reverseVisitor = new RewriteCombineBinaryOperators(true, builder); condition = condition.accept(reverseVisitor); RexSeparator separator = new RexSeparator(relevantPaths, scan, builder); RexNode indexCondition = separator.getSeparatedCondition(condition); if (indexCondition == null) { return new IndexConditionInfo(null, null, false); } List<RexNode> conjuncts = RelOptUtil.conjunctions(condition); List<RexNode> indexConjuncts = RelOptUtil.conjunctions(indexCondition); for (RexNode indexConjunction: indexConjuncts) { RexUtil.removeAll(conjuncts, indexConjunction); } RexNode remainderCondition = RexUtil.composeConjunction(builder, conjuncts, false); indexCondition = indexCondition.accept(reverseVisitor); return new IndexConditionInfo(indexCondition, remainderCondition, true); } } }
// Copyright 2012 Cloudera 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.cloudera.impala.analysis; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cloudera.impala.catalog.Catalog; import com.cloudera.impala.catalog.Function; import com.cloudera.impala.catalog.Function.CompareMode; import com.cloudera.impala.catalog.PrimitiveType; import com.cloudera.impala.catalog.ScalarType; import com.cloudera.impala.catalog.Type; import com.cloudera.impala.common.AnalysisException; import com.cloudera.impala.common.TreeNode; import com.cloudera.impala.thrift.TExpr; import com.cloudera.impala.thrift.TExprNode; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.Lists; import com.google.common.collect.Sets; /** * Root of the expr node hierarchy. * */ abstract public class Expr extends TreeNode<Expr> implements ParseNode, Cloneable { private final static Logger LOG = LoggerFactory.getLogger(Expr.class); // Limits on the number of expr children and the depth of an expr tree. These maximum // values guard against crashes due to stack overflows (IMPALA-432) and were // experimentally determined to be safe. public final static int EXPR_CHILDREN_LIMIT = 10000; // The expr depth limit is mostly due to our recursive implementation of clone(). public final static int EXPR_DEPTH_LIMIT = 1500; // Name of the function that needs to be implemented by every Expr that // supports negation. private final static String NEGATE_FN = "negate"; // to be used where we can't come up with a better estimate protected static double DEFAULT_SELECTIVITY = 0.1; // returns true if an Expr is a non-analytic aggregate. private final static com.google.common.base.Predicate<Expr> isAggregatePredicate_ = new com.google.common.base.Predicate<Expr>() { public boolean apply(Expr arg) { return arg instanceof FunctionCallExpr && ((FunctionCallExpr)arg).isAggregateFunction(); } }; // Returns true if an Expr is a NOT CompoundPredicate. public final static com.google.common.base.Predicate<Expr> IS_NOT_PREDICATE = new com.google.common.base.Predicate<Expr>() { @Override public boolean apply(Expr arg) { return arg instanceof CompoundPredicate && ((CompoundPredicate)arg).getOp() == CompoundPredicate.Operator.NOT; } }; // Returns true if an Expr is an OR CompoundPredicate. public final static com.google.common.base.Predicate<Expr> IS_OR_PREDICATE = new com.google.common.base.Predicate<Expr>() { @Override public boolean apply(Expr arg) { return arg instanceof CompoundPredicate && ((CompoundPredicate)arg).getOp() == CompoundPredicate.Operator.OR; } }; // Returns true if an Expr is a scalar subquery public final static com.google.common.base.Predicate<Expr> IS_SCALAR_SUBQUERY = new com.google.common.base.Predicate<Expr>() { @Override public boolean apply(Expr arg) { return arg.isScalarSubquery(); } }; // Returns true if an Expr is an aggregate function that returns non-null on // an empty set (e.g. count). public final static com.google.common.base.Predicate<Expr> NON_NULL_EMPTY_AGG = new com.google.common.base.Predicate<Expr>() { @Override public boolean apply(Expr arg) { return arg instanceof FunctionCallExpr && ((FunctionCallExpr)arg).returnsNonNullOnEmpty(); } }; // Returns true if an Expr is a builtin aggregate function. public final static com.google.common.base.Predicate<Expr> IS_BUILTIN_AGG_FN = new com.google.common.base.Predicate<Expr>() { @Override public boolean apply(Expr arg) { return arg instanceof FunctionCallExpr && ((FunctionCallExpr)arg).getFnName().isBuiltin(); } }; public final static com.google.common.base.Predicate<Expr> IS_TRUE_LITERAL = new com.google.common.base.Predicate<Expr>() { @Override public boolean apply(Expr arg) { return arg instanceof BoolLiteral && ((BoolLiteral)arg).getValue(); } }; // id that's unique across the entire query statement and is assigned by // Analyzer.registerConjuncts(); only assigned for the top-level terms of a // conjunction, and therefore null for most Exprs protected ExprId id_; // true if Expr is an auxiliary predicate that was generated by the plan generation // process to facilitate predicate propagation; // false if Expr originated with a query stmt directly private boolean isAuxExpr_ = false; protected Type type_; // result of analysis protected boolean isAnalyzed_; // true after analyze() has been called protected boolean isWhereClauseConjunct_; // set by analyzer // Flag to indicate whether to wrap this expr's toSql() in parenthesis. Set by parser. // Needed for properly capturing expr precedences in the SQL string. protected boolean printSqlInParens_ = false; // estimated probability of a predicate evaluating to true; // set during analysis; // between 0 and 1 if valid: invalid: -1 protected double selectivity_; // estimated number of distinct values produced by Expr; invalid: -1 // set during analysis protected long numDistinctValues_; // The function to call. This can either be a scalar or aggregate function. // Set in analyze(). protected Function fn_; protected Expr() { super(); type_ = Type.INVALID; selectivity_ = -1.0; numDistinctValues_ = -1; } /** * Copy c'tor used in clone(). */ protected Expr(Expr other) { id_ = other.id_; isAuxExpr_ = other.isAuxExpr_; type_ = other.type_; isAnalyzed_ = other.isAnalyzed_; isWhereClauseConjunct_ = other.isWhereClauseConjunct_; printSqlInParens_ = other.printSqlInParens_; selectivity_ = other.selectivity_; numDistinctValues_ = other.numDistinctValues_; fn_ = other.fn_; children_ = Expr.cloneList(other.children_); } public ExprId getId() { return id_; } protected void setId(ExprId id) { this.id_ = id; } public Type getType() { return type_; } public double getSelectivity() { return selectivity_; } public long getNumDistinctValues() { return numDistinctValues_; } public void setPrintSqlInParens(boolean b) { printSqlInParens_ = b; } public boolean isWhereClauseConjunct() { return isWhereClauseConjunct_; } public void setIsWhereClauseConjunct() { isWhereClauseConjunct_ = true; } public boolean isAuxExpr() { return isAuxExpr_; } public void setIsAuxExpr() { isAuxExpr_ = true; } public Function getFn() { return fn_; } /** * Perform semantic analysis of node and all of its children. * Throws exception if any errors found. * @see com.cloudera.impala.parser.ParseNode#analyze(com.cloudera.impala.parser.Analyzer) */ public void analyze(Analyzer analyzer) throws AnalysisException { // Check the expr child limit. if (children_.size() > EXPR_CHILDREN_LIMIT) { String sql = toSql(); String sqlSubstr = sql.substring(0, Math.min(80, sql.length())); throw new AnalysisException(String.format("Exceeded the maximum number of child " + "expressions (%s).\nExpression has %s children:\n%s...", EXPR_CHILDREN_LIMIT, children_.size(), sqlSubstr)); } // analyzer may be null for certain literal constructions (e.g. IntLiteral). if (analyzer != null) { analyzer.incrementCallDepth(); // Check the expr depth limit. Do not print the toSql() to not overflow the stack. if (analyzer.getCallDepth() > EXPR_DEPTH_LIMIT) { throw new AnalysisException(String.format("Exceeded the maximum depth of an " + "expression tree (%s).", EXPR_DEPTH_LIMIT)); } } for (Expr child: children_) { child.analyze(analyzer); } isAnalyzed_ = true; computeNumDistinctValues(); if (analyzer != null) analyzer.decrementCallDepth(); } /** * Helper function to analyze this expr and assert that the analysis was successful. * TODO: This function could be used in many more places to clean up. Consider * adding an IAnalyzable interface or similar to and move this helper into Analyzer * such that non-Expr things can use the helper also. */ public void analyzeNoThrow(Analyzer analyzer) { try { analyze(analyzer); } catch (AnalysisException e) { throw new IllegalStateException(e); } } protected void computeNumDistinctValues() { if (isConstant()) { numDistinctValues_ = 1; } else { // if this Expr contains slotrefs, we estimate the # of distinct values // to be the maximum such number for any of the slotrefs; // the subclass analyze() function may well want to override this, if it // knows better List<SlotRef> slotRefs = Lists.newArrayList(); this.collect(Predicates.instanceOf(SlotRef.class), slotRefs); numDistinctValues_ = -1; for (SlotRef slotRef: slotRefs) { numDistinctValues_ = Math.max(numDistinctValues_, slotRef.numDistinctValues_); } } } /** * Collects the returns types of the child nodes in an array. */ protected Type[] collectChildReturnTypes() { Type[] childTypes = new Type[children_.size()]; for (int i = 0; i < children_.size(); ++i) { childTypes[i] = children_.get(i).type_; } return childTypes; } /** * Looks up in the catalog the builtin for 'name' and 'argTypes'. * Returns null if the function is not found. */ protected Function getBuiltinFunction(Analyzer analyzer, String name, Type[] argTypes, CompareMode mode) throws AnalysisException { FunctionName fnName = new FunctionName(Catalog.BUILTINS_DB, name); Function searchDesc = new Function(fnName, argTypes, Type.INVALID, false); return analyzer.getCatalog().getFunction(searchDesc, mode); } /** * Generates the necessary casts for the children of this expr to call fn_. * child(0) is cast to the function's first argument, child(1) to the second etc. * This does not do any validation and the casts are assumed to be safe. * * If ignoreWildcardDecimals is true, the function will not cast arguments that * are wildcard decimals. This is used for builtins where the cast is done within * the BE function. * Otherwise, if the function signature contains wildcard decimals, each wildcard child * argument will be cast to the highest resolution that can contain all of the child * wildcard arguments. * e.g. fn(decimal(*), decimal(*)) * called with fn(decimal(10,2), decimal(5,3)) * both children will be cast to (11, 3). */ protected void castForFunctionCall(boolean ignoreWildcardDecimals) throws AnalysisException { Preconditions.checkState(fn_ != null); Type[] fnArgs = fn_.getArgs(); Type resolvedWildcardType = getResolvedWildCardType(); for (int i = 0; i < children_.size(); ++i) { // For varargs, we must compare with the last type in fnArgs.argTypes. int ix = Math.min(fnArgs.length - 1, i); if (fnArgs[ix].isWildcardDecimal()) { if (children_.get(i).type_.isDecimal() && ignoreWildcardDecimals) continue; Preconditions.checkState(resolvedWildcardType != null); if (!children_.get(i).type_.equals(resolvedWildcardType)) { castChild(resolvedWildcardType, i); } } else if (!children_.get(i).type_.matchesType(fnArgs[ix])) { castChild(fnArgs[ix], i); } } } /** * Returns the max resolution type of all the wild card decimal types. * Returns null if there are no wild card types. */ Type getResolvedWildCardType() throws AnalysisException { Type result = null; Type[] fnArgs = fn_.getArgs(); for (int i = 0; i < children_.size(); ++i) { // For varargs, we must compare with the last type in fnArgs.argTypes. int ix = Math.min(fnArgs.length - 1, i); if (!fnArgs[ix].isWildcardDecimal()) continue; Type childType = children_.get(i).type_; Preconditions.checkState(!childType.isWildcardDecimal(), "Child expr should have been resolved."); Preconditions.checkState(childType.isScalarType(), "Function should not have resolved with a non-scalar child type."); ScalarType decimalType = (ScalarType) childType; if (result == null) { result = decimalType.getMinResolutionDecimal(); } else { result = Type.getAssignmentCompatibleType(result, childType); } } if (result != null) { if (result.isNull()) { throw new AnalysisException( "Cannot resolve DECIMAL precision and scale from NULL type."); } Preconditions.checkState(result.isDecimal() && !result.isWildcardDecimal()); } return result; } /** * Returns true if e is a CastExpr and the target type is a decimal. */ private boolean isExplicitCastToDecimal(Expr e) { if (!(e instanceof CastExpr)) return false; CastExpr c = (CastExpr)e; return !c.isImplicit() && c.getType().isDecimal(); } /** * Returns a clone of child with all NumericLiterals in it explicitly * cast to targetType. */ private Expr convertNumericLiteralsToFloat(Analyzer analyzer, Expr child, Type targetType) throws AnalysisException { if (!targetType.isFloatingPointType() && !targetType.isIntegerType()) return child; if (targetType.isIntegerType()) targetType = Type.DOUBLE; List<NumericLiteral> literals = Lists.newArrayList(); child.collectAll(Predicates.instanceOf(NumericLiteral.class), literals); ExprSubstitutionMap smap = new ExprSubstitutionMap(); for (NumericLiteral l: literals) { NumericLiteral castLiteral = (NumericLiteral) l.clone(); castLiteral.explicitlyCastToFloat(targetType); smap.put(l, castLiteral); } return child.substitute(smap, analyzer); } /** * Converts numeric literal in the expr tree rooted at this expr to return floating * point types instead of decimals, if possible. * * Decimal has a higher processing cost than floating point and we should not pay * the cost if the user does not require the accuracy. For example: * "select float_col + 1.1" would start out with 1.1 as a decimal(2,1) and the * float_col would be promoted to a high accuracy decimal. This function will identify * this case and treat 1.1 as a float. * In the case of "decimal_col + 1.1", 1.1 would remain a decimal. * In the case of "float_col + cast(1.1 as decimal(2,1))", the result would be a * decimal. * * Another way to think about it is that DecimalLiterals are analyzed as returning * decimals (of the narrowest precision/scale) and we later convert them to a floating * point type when it is consistent with the user's intent. * * TODO: another option is to do constant folding in the FE and then apply this rule. */ protected void convertNumericLiteralsFromDecimal(Analyzer analyzer) throws AnalysisException { Preconditions.checkState(this instanceof ArithmeticExpr || this instanceof BinaryPredicate); Preconditions.checkState(children_.size() == 2); Type t0 = getChild(0).getType(); Type t1 = getChild(1).getType(); boolean c0IsConstantDecimal = getChild(0).isConstant() && t0.isDecimal(); boolean c1IsConstantDecimal = getChild(1).isConstant() && t1.isDecimal(); if (c0IsConstantDecimal && c1IsConstantDecimal) return; if (!c0IsConstantDecimal && !c1IsConstantDecimal) return; // Only child(0) or child(1) is a const decimal. See if we can cast it to // the type of the other child. if (c0IsConstantDecimal && !isExplicitCastToDecimal(getChild(0))) { Expr c0 = convertNumericLiteralsToFloat(analyzer, getChild(0), t1); setChild(0, c0); } if (c1IsConstantDecimal && !isExplicitCastToDecimal(getChild(1))) { Expr c1 = convertNumericLiteralsToFloat(analyzer, getChild(1), t0); setChild(1, c1); } } /** * Helper function: analyze list of exprs */ public static void analyze(List<? extends Expr> exprs, Analyzer analyzer) throws AnalysisException { if (exprs == null) return; for (Expr expr: exprs) { expr.analyze(analyzer); } } @Override public String toSql() { return (printSqlInParens_) ? "(" + toSqlImpl() + ")" : toSqlImpl(); } /** * Returns a SQL string representing this expr. Subclasses should override this method * instead of toSql() to ensure that parenthesis are properly added around the toSql(). */ protected abstract String toSqlImpl(); // Convert this expr, including all children, to its Thrift representation. public TExpr treeToThrift() { if (type_.isNull()) { // Hack to ensure BE never sees TYPE_NULL. If an expr makes it this far without // being cast to a non-NULL type, the type doesn't matter and we can cast it // arbitrarily. Preconditions.checkState(this instanceof NullLiteral || this instanceof SlotRef); return NullLiteral.create(ScalarType.BOOLEAN).treeToThrift(); } TExpr result = new TExpr(); treeToThriftHelper(result); return result; } // Append a flattened version of this expr, including all children, to 'container'. protected void treeToThriftHelper(TExpr container) { Preconditions.checkState(isAnalyzed_, "Must be analyzed before serializing to thrift. %s", this); Preconditions.checkState(!type_.isWildcardDecimal()); // The BE should never see TYPE_NULL Preconditions.checkState(!type_.isNull(), "Expr has type null!"); TExprNode msg = new TExprNode(); msg.type = type_.toThrift(); msg.num_children = children_.size(); if (fn_ != null) { msg.setFn(fn_.toThrift()); if (fn_.hasVarArgs()) msg.setVararg_start_idx(fn_.getNumArgs() - 1); } toThrift(msg); container.addToNodes(msg); for (Expr child: children_) { child.treeToThriftHelper(container); } } // Convert this expr into msg (excluding children), which requires setting // msg.op as well as the expr-specific field. protected abstract void toThrift(TExprNode msg); /** * Returns the product of the given exprs' number of distinct values or -1 if any of * the exprs have an invalid number of distinct values. */ public static long getNumDistinctValues(List<Expr> exprs) { long numDistinctValues = 1; for (Expr expr: exprs) { if (expr.getNumDistinctValues() == -1) { numDistinctValues = -1; break; } numDistinctValues *= expr.getNumDistinctValues(); } return numDistinctValues; } public static List<TExpr> treesToThrift(List<? extends Expr> exprs) { List<TExpr> result = Lists.newArrayList(); for (Expr expr: exprs) { result.add(expr.treeToThrift()); } return result; } public static com.google.common.base.Predicate<Expr> isAggregatePredicate() { return isAggregatePredicate_; } public boolean isAggregate() { return isAggregatePredicate_.apply(this); } public List<String> childrenToSql() { List<String> result = Lists.newArrayList(); for (Expr child: children_) { result.add(child.toSql()); } return result; } public String debugString() { return (id_ != null ? "exprid=" + id_.toString() + " " : "") + debugString(children_); } public static String debugString(List<? extends Expr> exprs) { if (exprs == null || exprs.isEmpty()) return ""; List<String> strings = Lists.newArrayList(); for (Expr expr: exprs) { strings.add(expr.debugString()); } return Joiner.on(" ").join(strings); } public static String toSql(List<? extends Expr> exprs) { if (exprs == null || exprs.isEmpty()) return ""; List<String> strings = Lists.newArrayList(); for (Expr expr: exprs) { strings.add(expr.toSql()); } return Joiner.on(", ").join(strings); } /** * Returns true if two expressions are equal. The equality comparison works on analyzed * as well as unanalyzed exprs by ignoring implicit casts (see CastExpr.equals()). */ @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj.getClass() != this.getClass()) return false; // don't compare type, this could be called pre-analysis Expr expr = (Expr) obj; if (children_.size() != expr.children_.size()) return false; for (int i = 0; i < children_.size(); ++i) { if (!children_.get(i).equals(expr.children_.get(i))) return false; } if (fn_ == null && expr.fn_ == null) return true; if (fn_ == null || expr.fn_ == null) return false; // One null, one not // Both fn_'s are not null return fn_.equals(expr.fn_); } /** * Return true if l1[i].equals(l2[i]) for all i. */ public static <C extends Expr> boolean equalLists(List<C> l1, List<C> l2) { if (l1.size() != l2.size()) return false; Iterator<C> l1Iter = l1.iterator(); Iterator<C> l2Iter = l2.iterator(); while (l1Iter.hasNext()) { if (!l1Iter.next().equals(l2Iter.next())) return false; } return true; } /** * Return true if l1 equals l2 when both lists are interpreted as sets. * TODO: come up with something better than O(n^2)? */ public static <C extends Expr> boolean equalSets(List<C> l1, List<C> l2) { if (l1.size() != l2.size()) return false; return l1.containsAll(l2) && l2.containsAll(l1); } /** * Return true if l1 is a subset of l2. */ public static <C extends Expr> boolean isSubset(List<C> l1, List<C> l2) { if (l1.size() > l2.size()) return false; return l2.containsAll(l1); } @Override public int hashCode() { if (id_ == null) { throw new UnsupportedOperationException("Expr.hashCode() is not implemented"); } else { return id_.asInt(); } } /** * Gather conjuncts from this expr and return them in a list. * A conjunct is an expr that returns a boolean, e.g., Predicates, function calls, * SlotRefs, etc. Hence, this method is placed here and not in Predicate. */ public List<Expr> getConjuncts() { List<Expr> list = Lists.newArrayList(); if (this instanceof CompoundPredicate && ((CompoundPredicate) this).getOp() == CompoundPredicate.Operator.AND) { // TODO: we have to convert CompoundPredicate.AND to two expr trees for // conjuncts because NULLs are handled differently for CompoundPredicate.AND // and conjunct evaluation. This is not optimal for jitted exprs because it // will result in two functions instead of one. Create a new CompoundPredicate // Operator (i.e. CONJUNCT_AND) with the right NULL semantics and use that // instead list.addAll((getChild(0)).getConjuncts()); list.addAll((getChild(1)).getConjuncts()); } else { list.add(this); } return list; } /** * Returns an analyzed clone of 'this' with exprs substituted according to smap. * Removes implicit casts and analysis state while cloning/substituting exprs within * this tree, such that the returned result has minimal implicit casts and types. * Throws if analyzing the post-substitution expr tree failed. * If smap is null, this function is equivalent to clone(). */ public Expr trySubstitute(ExprSubstitutionMap smap, Analyzer analyzer) throws AnalysisException { Expr result = clone(); // Return clone to avoid removing casts. if (smap == null) return result; result = result.substituteImpl(smap, analyzer); result.analyze(analyzer); return result; } /** * Returns an analyzed clone of 'this' with exprs substituted according to smap. * Removes implicit casts and analysis state while cloning/substituting exprs within * this tree, such that the returned result has minimal implicit casts and types. * Expects the analysis of the post-substitution expr to succeed. * If smap is null, this function is equivalent to clone(). */ public Expr substitute(ExprSubstitutionMap smap, Analyzer analyzer) { try { return trySubstitute(smap, analyzer); } catch (Exception e) { throw new IllegalStateException("Failed analysis after expr substitution.", e); } } public static ArrayList<Expr> trySubstituteList(Iterable<? extends Expr> exprs, ExprSubstitutionMap smap, Analyzer analyzer) throws AnalysisException { if (exprs == null) return null; ArrayList<Expr> result = new ArrayList<Expr>(); for (Expr e: exprs) { result.add(e.trySubstitute(smap, analyzer)); } return result; } public static ArrayList<Expr> substituteList(Iterable<? extends Expr> exprs, ExprSubstitutionMap smap, Analyzer analyzer) { try { return trySubstituteList(exprs, smap, analyzer); } catch (Exception e) { throw new IllegalStateException("Failed analysis after expr substitution.", e); } } /** * Recursive method that performs the actual substitution for try/substitute() while * removing implicit casts. Resets the analysis state in all non-SlotRef expressions. * Exprs that have non-child exprs which should be affected by substitutions must * override this method and apply the substitution to such exprs as well. */ protected Expr substituteImpl(ExprSubstitutionMap smap, Analyzer analyzer) throws AnalysisException { if (isImplicitCast()) return getChild(0).substituteImpl(smap, analyzer); if (smap != null) { Expr substExpr = smap.get(this); if (substExpr != null) return substExpr.clone(); } for (int i = 0; i < children_.size(); ++i) { children_.set(i, children_.get(i).substituteImpl(smap, analyzer)); } // SlotRefs must remain analyzed to support substitution across query blocks. All // other exprs must be analyzed again after the substitution to add implicit casts // and for resolving their correct function signature. if (!(this instanceof SlotRef)) resetAnalysisState(); return this; } /** * Resets the internal state of this expr produced by analyze(). * Only modifies this expr, and not its child exprs. */ protected void resetAnalysisState() { isAnalyzed_ = false; } /** * Resets the internal analysis state of this expr tree. Removes implicit casts. */ public Expr reset() { if (isImplicitCast()) return getChild(0).reset(); for (int i = 0; i < children_.size(); ++i) { children_.set(i, children_.get(i).reset()); } resetAnalysisState(); return this; } public static ArrayList<Expr> resetList(ArrayList<Expr> l) { for (int i = 0; i < l.size(); ++i) { l.set(i, l.get(i).reset()); } return l; } /** * Creates a deep copy of this expr including its analysis state. The method is * abstract in this class to force new Exprs to implement it. */ @Override public abstract Expr clone(); /** * Create a deep copy of 'l'. The elements of the returned list are of the same * type as the input list. */ public static <C extends Expr> ArrayList<C> cloneList(Iterable<C> l) { Preconditions.checkNotNull(l); ArrayList<C> result = new ArrayList<C>(); for (Expr element: l) { result.add((C) element.clone()); } return result; } /** * Removes duplicate exprs (according to equals()). */ public static <C extends Expr> void removeDuplicates(List<C> l) { if (l == null) return; ListIterator<C> it1 = l.listIterator(); while (it1.hasNext()) { C e1 = it1.next(); ListIterator<C> it2 = l.listIterator(); boolean duplicate = false; while (it2.hasNext()) { C e2 = it2.next(); // only check up to but excluding e1 if (e1 == e2) break; if (e1.equals(e2)) { duplicate = true; break; } } if (duplicate) it1.remove(); } } /** * Removes constant exprs */ public static <C extends Expr> void removeConstants(List<C> l) { if (l == null) return; ListIterator<C> it = l.listIterator(); while (it.hasNext()) { C e = it.next(); if (e.isConstant()) it.remove(); } } /** * Returns true if expr is fully bound by tid, otherwise false. */ public boolean isBound(TupleId tid) { return isBoundByTupleIds(Lists.newArrayList(tid)); } /** * Returns true if expr is fully bound by tids, otherwise false. */ public boolean isBoundByTupleIds(List<TupleId> tids) { for (Expr child: children_) { if (!child.isBoundByTupleIds(tids)) return false; } return true; } /** * Returns true if expr is fully bound by slotId, otherwise false. */ public boolean isBound(SlotId slotId) { return isBoundBySlotIds(Lists.newArrayList(slotId)); } /** * Returns true if expr is fully bound by slotIds, otherwise false. */ public boolean isBoundBySlotIds(List<SlotId> slotIds) { for (Expr child: children_) { if (!child.isBoundBySlotIds(slotIds)) return false; } return true; } public static boolean isBound(List<? extends Expr> exprs, List<TupleId> tids) { for (Expr expr: exprs) { if (!expr.isBoundByTupleIds(tids)) return false; } return true; } public void getIds(List<TupleId> tupleIds, List<SlotId> slotIds) { Set<TupleId> tupleIdSet = Sets.newHashSet(); Set<SlotId> slotIdSet = Sets.newHashSet(); getIdsHelper(tupleIdSet, slotIdSet); if (tupleIds != null) tupleIds.addAll(tupleIdSet); if (slotIds != null) slotIds.addAll(slotIdSet); } protected void getIdsHelper(Set<TupleId> tupleIds, Set<SlotId> slotIds) { for (Expr child: children_) { child.getIdsHelper(tupleIds, slotIds); } } public static <C extends Expr> void getIds(List<? extends Expr> exprs, List<TupleId> tupleIds, List<SlotId> slotIds) { if (exprs == null) return; for (Expr e: exprs) { e.getIds(tupleIds, slotIds); } } /** * @return true if this is an instance of LiteralExpr */ public boolean isLiteral() { return this instanceof LiteralExpr; } /** * @return true if this expr can be evaluated with Expr::GetValue(NULL), * ie, if it doesn't contain any references to runtime variables (which * at the moment are only slotrefs and subqueries). */ public boolean isConstant() { return !contains(Predicates.instanceOf(SlotRef.class)) && !contains(Predicates.instanceOf(Subquery.class)); } /** * @return true if this expr is either a null literal or a cast from * a null literal. */ public boolean isNullLiteral() { if (this instanceof NullLiteral) return true; if (!(this instanceof CastExpr)) return false; Preconditions.checkState(children_.size() == 1); return children_.get(0).isNullLiteral(); } /** * Return true if this expr is a scalar subquery. */ public boolean isScalarSubquery() { Preconditions.checkState(isAnalyzed_); return this instanceof Subquery && getType().isScalarType(); } /** * Checks whether this expr returns a boolean type or NULL type. * If not, throws an AnalysisException with an appropriate error message using * 'name' as a prefix. For example, 'name' could be "WHERE clause". * The error message only contains this.toSql() if printExpr is true. */ public void checkReturnsBool(String name, boolean printExpr) throws AnalysisException { if (!type_.isBoolean() && !type_.isNull()) { throw new AnalysisException( String.format("%s%s requires return type 'BOOLEAN'. " + "Actual type is '%s'.", name, (printExpr) ? " '" + toSql() + "'" : "", type_.toString())); } } /** * Checks validity of cast, and * calls uncheckedCastTo() to * create a cast expression that casts * this to a specific type. * @param targetType * type to be cast to * @return cast expression, or converted literal, * should never return null * @throws AnalysisException * when an invalid cast is asked for, for example, * failure to convert a string literal to a date literal */ public final Expr castTo(Type targetType) throws AnalysisException { Type type = Type.getAssignmentCompatibleType(this.type_, targetType); Preconditions.checkState(type.isValid(), "cast %s to %s", this.type_, targetType); // If the targetType is NULL_TYPE then ignore the cast because NULL_TYPE // is compatible with all types and no cast is necessary. if (targetType.isNull()) return this; if (!targetType.isDecimal()) { // requested cast must be to assignment-compatible type // (which implies no loss of precision) Preconditions.checkArgument(targetType.equals(type), "targetType=" + targetType + " type=" + type); } return uncheckedCastTo(targetType); } /** * Create an expression equivalent to 'this' but returning targetType; * possibly by inserting an implicit cast, * or by returning an altogether new expression * or by returning 'this' with a modified return type'. * @param targetType * type to be cast to * @return cast expression, or converted literal, * should never return null * @throws AnalysisException * when an invalid cast is asked for, for example, * failure to convert a string literal to a date literal */ protected Expr uncheckedCastTo(Type targetType) throws AnalysisException { return new CastExpr(targetType, this, true); } /** * Add a cast expression above child. * If child is a literal expression, we attempt to * convert the value of the child directly, and not insert a cast node. * @param targetType * type to be cast to * @param childIndex * index of child to be cast */ public void castChild(Type targetType, int childIndex) throws AnalysisException { Expr child = getChild(childIndex); Expr newChild = child.castTo(targetType); setChild(childIndex, newChild); } /** * Convert child to to targetType, possibly by inserting an implicit cast, or by * returning an altogether new expression, or by returning 'this' with a modified * return type'. * @param targetType * type to be cast to * @param childIndex * index of child to be cast */ protected void uncheckedCastChild(Type targetType, int childIndex) throws AnalysisException { Expr child = getChild(childIndex); Expr newChild = child.uncheckedCastTo(targetType); setChild(childIndex, newChild); } /** * Returns child expr if this expr is an implicit cast, otherwise returns 'this'. */ public Expr ignoreImplicitCast() { if (isImplicitCast()) return getChild(0).ignoreImplicitCast(); return this; } /** * Returns true if 'this' is an implicit cast expr. */ public boolean isImplicitCast() { return this instanceof CastExpr && ((CastExpr) this).isImplicit(); } @Override public String toString() { return Objects.toStringHelper(this.getClass()) .add("id", id_) .add("type", type_) .add("sel", selectivity_) .add("#distinct", numDistinctValues_) .toString(); } /** * If 'this' is a SlotRef or a Cast that wraps a SlotRef, returns that SlotRef. * Otherwise returns null. */ public SlotRef unwrapSlotRef(boolean implicitOnly) { if (this instanceof SlotRef) { return (SlotRef) this; } else if (this instanceof CastExpr && (!implicitOnly || ((CastExpr) this).isImplicit()) && getChild(0) instanceof SlotRef) { return (SlotRef) getChild(0); } else { return null; } } /** * Pushes negation to the individual operands of a predicate * tree rooted at 'root'. */ public static Expr pushNegationToOperands(Expr root) { Preconditions.checkNotNull(root); if (Expr.IS_NOT_PREDICATE.apply(root)) { try { // Make sure we call function 'negate' only on classes that support it, // otherwise we may recurse infinitely. Method m = root.getChild(0).getClass().getDeclaredMethod(NEGATE_FN); return pushNegationToOperands(root.getChild(0).negate()); } catch (NoSuchMethodException e) { // The 'negate' function is not implemented. Break the recursion. return root; } } if (root instanceof CompoundPredicate) { Expr left = pushNegationToOperands(root.getChild(0)); Expr right = pushNegationToOperands(root.getChild(1)); return new CompoundPredicate(((CompoundPredicate)root).getOp(), left, right); } return root; } /** * Negates a boolean Expr. */ public Expr negate() { Preconditions.checkState(type_.getPrimitiveType() == PrimitiveType.BOOLEAN); return new CompoundPredicate(CompoundPredicate.Operator.NOT, this, null); } /** * Returns the subquery of an expr. Returns null if this expr does not contain * a subquery. * * TODO: Support predicates with more that one subqueries when we implement * the independent subquery evaluation. */ public Subquery getSubquery() { if (!contains(Subquery.class)) return null; List<Subquery> subqueries = Lists.newArrayList(); collect(Subquery.class, subqueries); Preconditions.checkState(subqueries.size() == 1); return subqueries.get(0); } }
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.apache.axis.message; import javax.xml.namespace.QName; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.SOAPPart; import org.apache.axis.utils.Mapping; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.SOAPException; /** * SOAPDcoumentImpl implements the Document API for SOAPPART. At the moment, it * again delgate the XERCES DOM Implementation Here is my argument on it: I * guess that there is 3 way to implement this. - fully implement the DOM API * here myself. => This is too much and duplicated work. - extends XERCES * Implementation => this makes we are fixed to one Implementation - choose * delgate depends on the user's parser preference => This is the practically * best solution I have now * * @author Heejune Ahn (cityboy@tmax.co.kr) * */ public class SOAPDocumentImpl implements org.w3c.dom.Document, java.io.Serializable { // Depending on the user's parser preference protected Document delegate = null; protected SOAPPart soapPart = null; /** * Construct the Document * * @param sp the soap part */ public SOAPDocumentImpl(SOAPPart sp) { try { delegate = XMLUtils.newDocument(); } catch (ParserConfigurationException e) { // Do nothing } soapPart = sp; } /** * @todo : link with SOAP * * @return */ public DocumentType getDoctype() { return delegate.getDoctype(); } public DOMImplementation getImplementation() { return delegate.getImplementation(); } /** * should not be called, the method will be handled in SOAPPart * * @return */ public Element getDocumentElement() { return soapPart.getDocumentElement(); } /** * based on the tagName, we will make different kind SOAP Elements Instance * Is really we can determine the Type by the Tagname??? * * @todo : verify this method * * @param tagName * @return @throws * DOMException */ public org.w3c.dom.Element createElement(String tagName) throws DOMException { int index = tagName.indexOf(":"); String prefix, localname; if (index < 0) { prefix = ""; localname = tagName; } else { prefix = tagName.substring(0, index); localname = tagName.substring(index + 1); } try { SOAPEnvelope soapenv = (org.apache.axis.message.SOAPEnvelope) soapPart.getEnvelope(); if (soapenv != null) { if (tagName.equalsIgnoreCase(Constants.ELEM_ENVELOPE)) new SOAPEnvelope(); if (tagName.equalsIgnoreCase(Constants.ELEM_HEADER)) return new SOAPHeader(soapenv, soapenv.getSOAPConstants()); if (tagName.equalsIgnoreCase(Constants.ELEM_BODY)) return new SOAPBody(soapenv, soapenv.getSOAPConstants()); if (tagName.equalsIgnoreCase(Constants.ELEM_FAULT)) return new SOAPEnvelope(); if (tagName.equalsIgnoreCase(Constants.ELEM_FAULT_DETAIL)) return new SOAPFault(new AxisFault(tagName)); else { return new MessageElement("", prefix, localname); } } else { return new MessageElement("", prefix, localname); } } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * * Creates an empty <code>DocumentFragment</code> object. @todo not * implemented yet * * @return A new <code>DocumentFragment</code>. */ public DocumentFragment createDocumentFragment() { return delegate.createDocumentFragment(); } /** * Creates a <code>Text</code> node given the specified string. * * @param data * The data for the node. * @return The new <code>Text</code> object. */ public org.w3c.dom.Text createTextNode(String data) { org.apache.axis.message.Text me = new org.apache.axis.message.Text(delegate.createTextNode(data)); me.setOwnerDocument(soapPart); return me; } /** * Creates a <code>Comment</code> node given the specified string. * * @param data * The data for the node. * @return The new <code>Comment</code> object. */ public Comment createComment(String data) { return new org.apache.axis.message.CommentImpl(data); } /** * Creates a <code>CDATASection</code> node whose value is the specified * string. * * @param data * The data for the <code>CDATASection</code> contents. * @return The new <code>CDATASection</code> object. * @exception DOMException * NOT_SUPPORTED_ERR: Raised if this document is an HTML * document. */ public CDATASection createCDATASection(String data) throws DOMException { return new CDATAImpl(data); } /** * Creates a <code>ProcessingInstruction</code> node given the specified * name and data strings. * * @param target * The target part of the processing instruction. * @param data * The data for the node. * @return The new <code>ProcessingInstruction</code> object. * @exception DOMException * INVALID_CHARACTER_ERR: Raised if the specified target * contains an illegal character. <br>NOT_SUPPORTED_ERR: * Raised if this document is an HTML document. */ public ProcessingInstruction createProcessingInstruction( String target, String data) throws DOMException { throw new java.lang.UnsupportedOperationException( "createProcessingInstruction"); } /** * @todo: How Axis will maintain the Attribute representation ? */ public Attr createAttribute(String name) throws DOMException { return delegate.createAttribute(name); } /** * @param name * @return @throws * DOMException */ public EntityReference createEntityReference(String name) throws DOMException { throw new java.lang.UnsupportedOperationException( "createEntityReference"); } // implemented by yoonforh 2004-07-30 02:48:50 public Node importNode(Node importedNode, boolean deep) throws DOMException { Node targetNode = null; int type = importedNode.getNodeType(); switch (type) { case ELEMENT_NODE : Element el = (Element) importedNode; if (deep) { targetNode = new SOAPBodyElement(el); break; } SOAPBodyElement target = new SOAPBodyElement(); org.w3c.dom.NamedNodeMap attrs = el.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { org.w3c.dom.Node att = attrs.item(i); if (att.getNamespaceURI() != null && att.getPrefix() != null && att.getNamespaceURI().equals(Constants.NS_URI_XMLNS) && att.getPrefix().equals("xmlns")) { Mapping map = new Mapping(att.getNodeValue(), att.getLocalName()); target.addMapping(map); } if (att.getLocalName() != null) { target.addAttribute(att.getPrefix(), att.getNamespaceURI(), att.getLocalName(), att.getNodeValue()); } else if (att.getNodeName() != null) { target.addAttribute(att.getPrefix(), att.getNamespaceURI(), att.getNodeName(), att.getNodeValue()); } } if (el.getLocalName() == null) { target.setName(el.getNodeName()); } else { target.setQName(new QName(el.getNamespaceURI(), el.getLocalName())); } targetNode = target; break; case ATTRIBUTE_NODE : if (importedNode.getLocalName() == null) { targetNode = createAttribute(importedNode.getNodeName()); } else { targetNode = createAttributeNS(importedNode.getNamespaceURI(), importedNode.getLocalName()); } break; case TEXT_NODE : targetNode = createTextNode(importedNode.getNodeValue()); break; case CDATA_SECTION_NODE : targetNode = createCDATASection(importedNode.getNodeValue()); break; case COMMENT_NODE : targetNode = createComment(importedNode.getNodeValue()); break; case DOCUMENT_FRAGMENT_NODE : targetNode = createDocumentFragment(); if (deep) { org.w3c.dom.NodeList children = importedNode.getChildNodes(); for (int i = 0; i < children.getLength(); i++){ targetNode.appendChild(importNode(children.item(i), true)); } } break; case ENTITY_REFERENCE_NODE : targetNode = createEntityReference(importedNode.getNodeName()); break; case PROCESSING_INSTRUCTION_NODE : ProcessingInstruction pi = (ProcessingInstruction) importedNode; targetNode = createProcessingInstruction(pi.getTarget(), pi.getData()); break; case ENTITY_NODE : // TODO : ... throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Entity nodes are not supported."); case NOTATION_NODE : // TODO : any idea? throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Notation nodes are not supported."); case DOCUMENT_TYPE_NODE : throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "DocumentType nodes cannot be imported."); case DOCUMENT_NODE : throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Document nodes cannot be imported."); default : throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Node type (" + type + ") cannot be imported."); } return targetNode; } /** * Return SOAPElements (what if they want SOAPEnvelope or Header/Body?) * * @param namespaceURI * @param qualifiedName * @return @throws * DOMException */ public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException { org.apache.axis.soap.SOAPConstants soapConstants = null; if (Constants.URI_SOAP11_ENV.equals(namespaceURI)) { soapConstants = org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS; } else if (Constants.URI_SOAP12_ENV.equals(namespaceURI)) { soapConstants = org.apache.axis.soap.SOAPConstants.SOAP12_CONSTANTS; } // For special SOAP Element MessageElement me = null; if (soapConstants != null) { if (qualifiedName.equals(Constants.ELEM_ENVELOPE)) { // TODO: confirm SOAP 1.1! me = new SOAPEnvelope(soapConstants); } else if (qualifiedName.equals(Constants.ELEM_HEADER)) { me = new SOAPHeader(null, soapConstants); // Dummy SOAPEnv required? } else if (qualifiedName.equals(Constants.ELEM_BODY)) { me = new SOAPBody(null, soapConstants); } else if (qualifiedName.equals(Constants.ELEM_FAULT)) { me = null; } else if (qualifiedName.equals(Constants.ELEM_FAULT_DETAIL)) { // TODO: me = null; } else { throw new DOMException( DOMException.INVALID_STATE_ERR, "No such Localname for SOAP URI"); } // TODO: return null; // general Elements } else { me = new MessageElement(namespaceURI, qualifiedName); } if (me != null) me.setOwnerDocument(soapPart); return me; } /** * Attribute is not particularly dealt with in SAAJ. * */ public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException { return delegate.createAttributeNS(namespaceURI, qualifiedName); } /** * search the SOAPPart in order of SOAPHeader and SOAPBody for the * requested Element name * */ public NodeList getElementsByTagNameNS( String namespaceURI, String localName) { try { NodeListImpl list = new NodeListImpl(); if (soapPart != null) { SOAPEnvelope soapEnv = (org.apache.axis.message.SOAPEnvelope) soapPart .getEnvelope(); SOAPHeader header = (org.apache.axis.message.SOAPHeader) soapEnv.getHeader(); if (header != null) { list.addNodeList(header.getElementsByTagNameNS( namespaceURI, localName)); } SOAPBody body = (org.apache.axis.message.SOAPBody) soapEnv.getBody(); if (body != null) { list.addNodeList(body.getElementsByTagNameNS( namespaceURI, localName)); } } return list; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * search the SOAPPart in order of SOAPHeader and SOAPBody for the * requested Element name * */ public NodeList getElementsByTagName(String localName) { try { NodeListImpl list = new NodeListImpl(); if (soapPart != null) { SOAPEnvelope soapEnv = (org.apache.axis.message.SOAPEnvelope) soapPart .getEnvelope(); SOAPHeader header = (org.apache.axis.message.SOAPHeader) soapEnv.getHeader(); if (header != null) { list.addNodeList(header.getElementsByTagName(localName)); } SOAPBody body = (org.apache.axis.message.SOAPBody) soapEnv.getBody(); if (body != null) { list.addNodeList(body.getElementsByTagName(localName)); } } return list; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * Returns the <code>Element</code> whose <code>ID</code> is given by * <code>elementId</code>. If no such element exists, returns <code>null</code>. * Behavior is not defined if more than one element has this <code>ID</code>. * The DOM implementation must have information that says which attributes * are of type ID. Attributes with the name "ID" are not of type ID unless * so defined. Implementations that do not know whether attributes are of * type ID or not are expected to return <code>null</code>. * * @param elementId * The unique <code>id</code> value for an element. * @return The matching element. * @since DOM Level 2 */ public Element getElementById(String elementId) { return delegate.getElementById(elementId); } /** * Node Implementation * */ public String getNodeName() { return null; } public String getNodeValue() throws DOMException { throw new DOMException( DOMException.NO_DATA_ALLOWED_ERR, "Cannot use TextNode.get in " + this); } public void setNodeValue(String nodeValue) throws DOMException { throw new DOMException( DOMException.NO_DATA_ALLOWED_ERR, "Cannot use TextNode.set in " + this); } /** * override it in sub-classes * * @return */ public short getNodeType() { return Node.DOCUMENT_NODE; } public Node getParentNode() { return null; } public NodeList getChildNodes() { try { if (soapPart != null) { NodeListImpl children = new NodeListImpl(); children.addNode(soapPart.getEnvelope()); return children; } else { return NodeListImpl.EMPTY_NODELIST; } } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * Do we have to count the Attributes as node ???? * * @return */ public Node getFirstChild() { try { if (soapPart != null) return (org.apache.axis.message.SOAPEnvelope) soapPart .getEnvelope(); else return null; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * @return */ public Node getLastChild() { try { if (soapPart != null) return (org.apache.axis.message.SOAPEnvelope) soapPart .getEnvelope(); else return null; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } public Node getPreviousSibling() { return null; } public Node getNextSibling() { return null; } public NamedNodeMap getAttributes() { return null; } /** * * we have to have a link to them... */ public Document getOwnerDocument() { return null; } /** */ public Node insertBefore(Node newChild, Node refChild) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public Node replaceChild(Node newChild, Node oldChild) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public Node removeChild(Node oldChild) throws DOMException { try { Node envNode; if (soapPart != null) { envNode = soapPart.getEnvelope(); if (envNode.equals(oldChild)) { return envNode; } } throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } public Node appendChild(Node newChild) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public boolean hasChildNodes() { try { if (soapPart != null) { if (soapPart.getEnvelope() != null) { return true; } } return false; } catch (SOAPException se) { throw new DOMException(DOMException.INVALID_STATE_ERR, ""); } } /** * @todo: Study it more.... to implement the deep mode correctly. * */ public Node cloneNode(boolean deep) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } /** * @todo: is it OK to simply call the superclass? * */ public void normalize() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } // TODO: fill appropriate features private String[] features = { "foo", "bar" }; private String version = "version 2.0"; public boolean isSupported(String feature, String version) { if (!version.equalsIgnoreCase(version)) return false; else return true; } public String getPrefix() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public void setPrefix(String prefix) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public String getNamespaceURI() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public void setNamespaceURI(String nsURI) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public String getLocalName() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } public boolean hasAttributes() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, ""); } }
/************************************************************************** * copyright file="ConversationSchema.java" company="Microsoft" * Copyright (c) Microsoft Corporation. All rights reserved. * * Defines the ConversationSchema.java. **************************************************************************/ package microsoft.exchange.webservices.data; import java.util.EnumSet; /** * Represents the schema for Conversation. */ @Schema public class ConversationSchema extends ServiceObjectSchema { /** * Field URIs for Item. */ private static class FieldUris { /** The Constant ConversationId. */ public static final String ConversationId = "conversation:ConversationId"; /** The Constant ConversationTopic. */ public static final String ConversationTopic = "conversation:ConversationTopic"; /** The Constant UniqueRecipients. */ public static final String UniqueRecipients = "conversation:UniqueRecipients"; /** The Constant GlobalUniqueRecipients. */ public static final String GlobalUniqueRecipients = "conversation:GlobalUniqueRecipients"; /** The Constant UniqueUnreadSenders. */ public static final String UniqueUnreadSenders = "conversation:UniqueUnreadSenders"; /** The Constant GlobalUniqueUnreadSenders. */ public static final String GlobalUniqueUnreadSenders = "conversation:GlobalUniqueUnreadSenders"; /** The Constant UniqueSenders. */ public static final String UniqueSenders = "conversation:UniqueSenders"; /** The Constant GlobalUniqueSenders. */ public static final String GlobalUniqueSenders = "conversation:GlobalUniqueSenders"; /** The Constant LastDeliveryTime. */ public static final String LastDeliveryTime = "conversation:LastDeliveryTime"; /** The Constant GlobalLastDeliveryTime. */ public static final String GlobalLastDeliveryTime = "conversation:GlobalLastDeliveryTime"; /** The Constant Categories. */ public static final String Categories = "conversation:Categories"; /** The Constant GlobalCategories. */ public static final String GlobalCategories = "conversation:GlobalCategories"; /** The Constant FlagStatus. */ public static final String FlagStatus = "conversation:FlagStatus"; /** The Constant GlobalFlagStatus. */ public static final String GlobalFlagStatus = "conversation:GlobalFlagStatus"; /** The Constant HasAttachments. */ public static final String HasAttachments = "conversation:HasAttachments"; /** The Constant GlobalHasAttachments. */ public static final String GlobalHasAttachments = "conversation:GlobalHasAttachments"; /** The Constant MessageCount. */ public static final String MessageCount = "conversation:MessageCount"; /** The Constant GlobalMessageCount. */ public static final String GlobalMessageCount = "conversation:GlobalMessageCount"; /** The Constant UnreadCount. */ public static final String UnreadCount = "conversation:UnreadCount"; /** The Constant GlobalUnreadCount. */ public static final String GlobalUnreadCount = "conversation:GlobalUnreadCount"; /** The Constant Size. */ public static final String Size = "conversation:Size"; /** The Constant GlobalSize. */ public static final String GlobalSize = "conversation:GlobalSize"; /** The Constant ItemClasses. */ public static final String ItemClasses = "conversation:ItemClasses"; /** The Constant GlobalItemClasses. */ public static final String GlobalItemClasses = "conversation:GlobalItemClasses"; /** The Constant Importance. */ public static final String Importance = "conversation:Importance"; /** The Constant GlobalImportance. */ public static final String GlobalImportance = "conversation:GlobalImportance"; /** The Constant ItemIds. */ public static final String ItemIds = "conversation:ItemIds"; /** The Constant GlobalItemIds. */ public static final String GlobalItemIds = "conversation:GlobalItemIds"; public static String ItemId; } /** * Defines the Id property. */ public static final PropertyDefinition Id = new ComplexPropertyDefinition<ConversationId>( ConversationId.class, XmlElementNames.ConversationId, FieldUris.ConversationId, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<ConversationId>() { public ConversationId createComplexProperty() { return new ConversationId(); }; }); /** * Defines the Topic property. */ public static final PropertyDefinition Topic = new StringPropertyDefinition( XmlElementNames.ConversationTopic, FieldUris.ConversationTopic, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the UniqueRecipients property. */ public static final PropertyDefinition UniqueRecipients = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.UniqueRecipients, FieldUris.UniqueRecipients, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(); }; }); /** * Defines the GlobalUniqueRecipients property. */ public static final PropertyDefinition GlobalUniqueRecipients = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.GlobalUniqueRecipients, FieldUris.GlobalUniqueRecipients, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(); }; }); /** * Defines the UniqueUnreadSenders property. */ public static final PropertyDefinition UniqueUnreadSenders = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.UniqueUnreadSenders, FieldUris.UniqueUnreadSenders, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(); }; }); /** * Defines the GlobalUniqueUnreadSenders property. */ public static final PropertyDefinition GlobalUniqueUnreadSenders = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.GlobalUniqueUnreadSenders, FieldUris.GlobalUniqueUnreadSenders, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(); }; }); /** * Defines the UniqueSenders property. */ public static final PropertyDefinition UniqueSenders = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.UniqueSenders, FieldUris.UniqueSenders, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(); }; }); /** * Defines the GlobalUniqueSenders property. */ public static final PropertyDefinition GlobalUniqueSenders = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.GlobalUniqueSenders, FieldUris.GlobalUniqueSenders, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(); }; }); /** * Defines the LastDeliveryTime property. */ public static final PropertyDefinition LastDeliveryTime = new DateTimePropertyDefinition( XmlElementNames.LastDeliveryTime, FieldUris.LastDeliveryTime, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the GlobalLastDeliveryTime property. */ public static final PropertyDefinition GlobalLastDeliveryTime = new DateTimePropertyDefinition( XmlElementNames.GlobalLastDeliveryTime, FieldUris.GlobalLastDeliveryTime, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the Categories property. */ public static final PropertyDefinition Categories = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.Categories, FieldUris.Categories, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(); }; }); /** * Defines the GlobalCategories property. */ public static final PropertyDefinition GlobalCategories = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.GlobalCategories, FieldUris.GlobalCategories, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(); }; }); /** * Defines the FlagStatus property. */ public static final PropertyDefinition FlagStatus = new GenericPropertyDefinition<ConversationFlagStatus>( ConversationFlagStatus.class, XmlElementNames.FlagStatus, FieldUris.FlagStatus, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the GlobalFlagStatus property. */ public static final PropertyDefinition GlobalFlagStatus = new GenericPropertyDefinition<ConversationFlagStatus>( ConversationFlagStatus.class, XmlElementNames.GlobalFlagStatus, FieldUris.GlobalFlagStatus, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the HasAttachments property. */ public static final PropertyDefinition HasAttachments = new BoolPropertyDefinition( XmlElementNames.HasAttachments, FieldUris.HasAttachments, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the GlobalHasAttachments property. */ public static final PropertyDefinition GlobalHasAttachments = new BoolPropertyDefinition( XmlElementNames.GlobalHasAttachments, FieldUris.GlobalHasAttachments, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the MessageCount property. */ public static final PropertyDefinition MessageCount = new IntPropertyDefinition( XmlElementNames.MessageCount, FieldUris.MessageCount, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the GlobalMessageCount property. */ public static final PropertyDefinition GlobalMessageCount = new IntPropertyDefinition( XmlElementNames.GlobalMessageCount, FieldUris.GlobalMessageCount, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the UnreadCount property. */ public static final PropertyDefinition UnreadCount = new IntPropertyDefinition( XmlElementNames.UnreadCount, FieldUris.UnreadCount, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the GlobalUnreadCount property. */ public static final PropertyDefinition GlobalUnreadCount = new IntPropertyDefinition( XmlElementNames.GlobalUnreadCount, FieldUris.GlobalUnreadCount, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the Size property. */ public static final PropertyDefinition Size = new IntPropertyDefinition( XmlElementNames.Size, FieldUris.Size, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the GlobalSize property. */ public static final PropertyDefinition GlobalSize = new IntPropertyDefinition( XmlElementNames.GlobalSize, FieldUris.GlobalSize, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the ItemClasses property. */ public static final PropertyDefinition ItemClasses = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.ItemClasses, FieldUris.ItemClasses, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(XmlElementNames. ItemClass); }; }); /** * Defines the GlobalItemClasses property. */ public static final PropertyDefinition GlobalItemClasses = new ComplexPropertyDefinition<StringList>( StringList.class, XmlElementNames.GlobalItemClasses, FieldUris.GlobalItemClasses, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<StringList>() { public StringList createComplexProperty() { return new StringList(XmlElementNames. ItemClass); }; }); /** * Defines the Importance property. */ public static final PropertyDefinition Importance = new GenericPropertyDefinition<Importance>( Importance.class, XmlElementNames.Importance, FieldUris.Importance, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the GlobalImportance property. */ public static final PropertyDefinition GlobalImportance = new GenericPropertyDefinition<Importance>( Importance.class, XmlElementNames.GlobalImportance, FieldUris.GlobalImportance, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1); /** * Defines the ItemIds property. */ public static final PropertyDefinition ItemIds = new ComplexPropertyDefinition<ItemIdCollection>( ItemIdCollection.class, XmlElementNames.ItemIds, FieldUris.ItemIds, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<ItemIdCollection>() { public ItemIdCollection createComplexProperty() { return new ItemIdCollection(); }; }); /** * Defines the GlobalItemIds property. */ public static final PropertyDefinition GlobalItemIds = new ComplexPropertyDefinition<ItemIdCollection>( ItemIdCollection.class, XmlElementNames.GlobalItemIds, FieldUris.GlobalItemIds, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2010_SP1, new ICreateComplexPropertyDelegate<ItemIdCollection>() { public ItemIdCollection createComplexProperty() { return new ItemIdCollection(); }; }); /** * This must be declared after the property definitions */ protected static final ConversationSchema Instance = new ConversationSchema(); /** * Registers properties. */ @Override protected void registerProperties() { super.registerProperties(); this.registerProperty(Id); this.registerProperty(Topic); this.registerProperty(UniqueRecipients); this.registerProperty(GlobalUniqueRecipients); this.registerProperty(UniqueUnreadSenders); this.registerProperty(GlobalUniqueUnreadSenders); this.registerProperty(UniqueSenders); this.registerProperty(GlobalUniqueSenders); this.registerProperty(LastDeliveryTime); this.registerProperty(GlobalLastDeliveryTime); this.registerProperty(Categories); this.registerProperty(GlobalCategories); this.registerProperty(FlagStatus); this.registerProperty(GlobalFlagStatus); this.registerProperty(HasAttachments); this.registerProperty(GlobalHasAttachments); this.registerProperty(MessageCount); this.registerProperty(GlobalMessageCount); this.registerProperty(UnreadCount); this.registerProperty(GlobalUnreadCount); this.registerProperty(Size); this.registerProperty(GlobalSize); this.registerProperty(ItemClasses); this.registerProperty(GlobalItemClasses); this.registerProperty(Importance); this.registerProperty(GlobalImportance); this.registerProperty(ItemIds); this.registerProperty(GlobalItemIds); } /** * Initializes a new instance of * the ConversationSchema class. */ protected ConversationSchema() { super(); } }
package fi.solita.utils.functional; public class Tuple32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> extends Tuple implements Tuple.Tailable<Tuple31<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19,T20,T21,T22,T23,T24,T25,T26,T27,T28,T29,T30,T31,T32>>, Tuple._1<T1>, Tuple._2<T2>, Tuple._3<T3>, Tuple._4<T4>, Tuple._5<T5>, Tuple._6<T6>, Tuple._7<T7>, Tuple._8<T8>, Tuple._9<T9>, Tuple._10<T10>, Tuple._11<T11>, Tuple._12<T12>, Tuple._13<T13>, Tuple._14<T14>, Tuple._15<T15>, Tuple._16<T16>, Tuple._17<T17>, Tuple._18<T18>, Tuple._19<T19>, Tuple._20<T20>, Tuple._21<T21>, Tuple._22<T22>, Tuple._23<T23>, Tuple._24<T24>, Tuple._25<T25>, Tuple._26<T26>, Tuple._27<T27>, Tuple._28<T28>, Tuple._29<T29>, Tuple._30<T30>, Tuple._31<T31>, Tuple._32<T32> { public final T1 _1; public final T2 _2; public final T3 _3; public final T4 _4; public final T5 _5; public final T6 _6; public final T7 _7; public final T8 _8; public final T9 _9; public final T10 _10; public final T11 _11; public final T12 _12; public final T13 _13; public final T14 _14; public final T15 _15; public final T16 _16; public final T17 _17; public final T18 _18; public final T19 _19; public final T20 _20; public final T21 _21; public final T22 _22; public final T23 _23; public final T24 _24; public final T25 _25; public final T26 _26; public final T27 _27; public final T28 _28; public final T29 _29; public final T30 _30; public final T31 _31; public final T32 _32; public Tuple32(T1 _1, T2 _2, T3 _3, T4 _4, T5 _5, T6 _6, T7 _7, T8 _8, T9 _9, T10 _10, T11 _11, T12 _12, T13 _13, T14 _14, T15 _15, T16 _16, T17 _17, T18 _18, T19 _19, T20 _20, T21 _21, T22 _22, T23 _23, T24 _24, T25 _25, T26 _26, T27 _27, T28 _28, T29 _29, T30 _30, T31 _31, T32 _32) { this._1 = _1; this._2 = _2; this._3 = _3; this._4 = _4; this._5 = _5; this._6 = _6; this._7 = _7; this._8 = _8; this._9 = _9; this._10 = _10; this._11 = _11; this._12 = _12; this._13 = _13; this._14 = _14; this._15 = _15; this._16 = _16; this._17 = _17; this._18 = _18; this._19 = _19; this._20 = _20; this._21 = _21; this._22 = _22; this._23 = _23; this._24 = _24; this._25 = _25; this._26 = _26; this._27 = _27; this._28 = _28; this._29 = _29; this._30 = _30; this._31 = _31; this._32 = _32; } /** * @return a prefix of this tuple. */ public Tuple1<T1> take1() { return Tuple.of(_1); } /** * @return a prefix of this tuple. */ public Pair<T1, T2> take2() { return Pair.of(_1, _2); } /** * @return a prefix of this tuple. */ public Tuple3<T1, T2, T3> take3() { return Tuple.of(_1, _2, _3); } /** * @return a prefix of this tuple. */ public Tuple4<T1, T2, T3, T4> take4() { return Tuple.of(_1, _2, _3, _4); } /** * @return a prefix of this tuple. */ public Tuple5<T1, T2, T3, T4, T5> take5() { return Tuple.of(_1, _2, _3, _4, _5); } /** * @return a prefix of this tuple. */ public Tuple6<T1, T2, T3, T4, T5, T6> take6() { return Tuple.of(_1, _2, _3, _4, _5, _6); } /** * @return a prefix of this tuple. */ public Tuple7<T1, T2, T3, T4, T5, T6, T7> take7() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7); } /** * @return a prefix of this tuple. */ public Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> take8() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8); } /** * @return a prefix of this tuple. */ public Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9> take9() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9); } /** * @return a prefix of this tuple. */ public Tuple10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> take10() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10); } /** * @return a prefix of this tuple. */ public Tuple11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> take11() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11); } /** * @return a prefix of this tuple. */ public Tuple12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> take12() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12); } /** * @return a prefix of this tuple. */ public Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> take13() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13); } /** * @return a prefix of this tuple. */ public Tuple14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> take14() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14); } /** * @return a prefix of this tuple. */ public Tuple15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> take15() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15); } /** * @return a prefix of this tuple. */ public Tuple16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> take16() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16); } /** * @return a prefix of this tuple. */ public Tuple17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> take17() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17); } /** * @return a prefix of this tuple. */ public Tuple18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> take18() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18); } /** * @return a prefix of this tuple. */ public Tuple19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> take19() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19); } /** * @return a prefix of this tuple. */ public Tuple20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> take20() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20); } /** * @return a prefix of this tuple. */ public Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> take21() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21); } /** * @return a prefix of this tuple. */ public Tuple22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> take22() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22); } /** * @return a prefix of this tuple. */ public Tuple23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> take23() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23); } /** * @return a prefix of this tuple. */ public Tuple24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> take24() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24); } /** * @return a prefix of this tuple. */ public Tuple25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> take25() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25); } /** * @return a prefix of this tuple. */ public Tuple26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> take26() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25 ,_26); } /** * @return a prefix of this tuple. */ public Tuple27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> take27() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25 ,_26, _27); } /** * @return a prefix of this tuple. */ public Tuple28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28> take28() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25 ,_26, _27, _28); } /** * @return a prefix of this tuple. */ public Tuple29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29> take29() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25 ,_26, _27, _28, _29); } /** * @return a prefix of this tuple. */ public Tuple30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30> take30() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25 ,_26, _27, _28, _29, _30); } /** * @return a prefix of this tuple. */ public Tuple31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31> take31() { return Tuple.of(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25 ,_26, _27, _28, _29, _30, _31); } /** * @return a suffix of this tuple. */ public Tuple31<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop1() { return Tuple.of(_2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple30<T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop2() { return Tuple.of(_3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple29<T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop3() { return Tuple.of(_4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple28<T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop4() { return Tuple.of(_5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple27<T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop5() { return Tuple.of(_6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple26<T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop6() { return Tuple.of(_7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple25<T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop7() { return Tuple.of(_8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple24<T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop8() { return Tuple.of(_9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple23<T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop9() { return Tuple.of(_10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple22<T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop10() { return Tuple.of(_11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple21<T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop11() { return Tuple.of(_12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple20<T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop12() { return Tuple.of(_13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple19<T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop13() { return Tuple.of(_14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple18<T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop14() { return Tuple.of(_15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple17<T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop15() { return Tuple.of(_16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple16<T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop16() { return Tuple.of(_17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple15<T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop17() { return Tuple.of(_18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple14<T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop18() { return Tuple.of(_19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple13<T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop19() { return Tuple.of(_20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple12<T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop20() { return Tuple.of(_21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple11<T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop21() { return Tuple.of(_22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple10<T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> drop22() { return Tuple.of(_23, _24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple9<T24, T25, T26, T27, T28, T29, T30, T31, T32> drop23() { return Tuple.of(_24, _25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple8<T25, T26, T27, T28, T29, T30, T31, T32> drop24() { return Tuple.of(_25, _26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple7<T26, T27, T28, T29, T30, T31, T32> drop25() { return Tuple.of(_26, _27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple6<T27, T28, T29, T30, T31, T32> drop26() { return Tuple.of(_27, _28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple5<T28, T29, T30, T31, T32> drop27() { return Tuple.of(_28, _29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple4<T29, T30, T31, T32> drop28() { return Tuple.of(_29, _30, _31, _32); } /** * @return a suffix of this tuple. */ public Tuple3<T30, T31, T32> drop29() { return Tuple.of(_30, _31, _32); } /** * @return a suffix of this tuple. */ public Pair<T31, T32> drop30() { return Pair.of(_31, _32); } /** * @return a suffix of this tuple. */ public Tuple1<T32> drop31() { return Tuple.of(_32); } public T1 get_1() { return _1; } public T2 get_2() { return _2; } public T3 get_3() { return _3; } public T4 get_4() { return _4; } public T5 get_5() { return _5; } public T6 get_6() { return _6; } public T7 get_7() { return _7; } public T8 get_8() { return _8; } public T9 get_9() { return _9; } public T10 get_10() { return _10; } public T11 get_11() { return _11; } public T12 get_12() { return _12; } public T13 get_13() { return _13; } public T14 get_14() { return _14; } public T15 get_15() { return _15; } public T16 get_16() { return _16; } public T17 get_17() { return _17; } public T18 get_18() { return _18; } public T19 get_19() { return _19; } public T20 get_20() { return _20; } public T21 get_21() { return _21; } public T22 get_22() { return _22; } public T23 get_23() { return _23; } public T24 get_24() { return _24; } public T25 get_25() { return _25; } public T26 get_26() { return _26; } public T27 get_27() { return _27; } public T28 get_28() { return _28; } public T29 get_29() { return _29; } public T30 get_30() { return _30; } public T31 get_31() { return _31; } public T32 get_32() { return _32; } public Object[] toArray() { return new Object[]{_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32}; } }
package de.unibamberg.minf.dme.controller.editors; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; 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.ResponseBody; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.BooleanNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import de.unibamberg.minf.dme.controller.base.BaseMainEditorController; import de.unibamberg.minf.dme.exception.GenericScheregException; import de.unibamberg.minf.dme.exporter.DatamodelExporter; import de.unibamberg.minf.dme.importer.DatamodelImportWorker; import de.unibamberg.minf.dme.importer.datamodel.DatamodelImporter; import de.unibamberg.minf.dme.model.PersistedSession; import de.unibamberg.minf.dme.model.RightsContainer; import de.unibamberg.minf.dme.model.base.Element; import de.unibamberg.minf.dme.model.base.Identifiable; import de.unibamberg.minf.dme.model.base.ModelElement; import de.unibamberg.minf.dme.model.base.Nonterminal; import de.unibamberg.minf.dme.model.base.Terminal; import de.unibamberg.minf.dme.model.datamodel.NonterminalImpl; import de.unibamberg.minf.dme.model.datamodel.base.Datamodel; import de.unibamberg.minf.dme.model.datamodel.base.DatamodelNature; import de.unibamberg.minf.dme.model.datamodel.natures.XmlDatamodelNature; import de.unibamberg.minf.dme.model.grammar.GrammarImpl; import de.unibamberg.minf.dme.model.mapping.base.Mapping; import de.unibamberg.minf.dme.model.serialization.DatamodelReferenceContainer; import de.unibamberg.minf.dme.pojo.converter.AuthWrappedPojoConverter; import de.unibamberg.minf.dme.pojo.converter.ModelElementPojoConverter; import de.unibamberg.minf.dme.service.ElementServiceImpl; import de.unibamberg.minf.dme.service.base.BaseEntityService; import de.unibamberg.minf.dme.service.interfaces.IdentifiableService; import eu.dariah.de.dariahsp.model.web.AuthPojo; import de.unibamberg.minf.core.web.pojo.ModelActionPojo; import de.unibamberg.minf.core.web.pojo.MessagePojo; @Controller @RequestMapping(value="/model/editor/{entityId}/") public class SchemaEditorController extends BaseMainEditorController implements InitializingBean { @Autowired private DatamodelImportWorker importWorker; @Autowired private AuthWrappedPojoConverter authPojoConverter; @Autowired private IdentifiableService identifiableService; @Autowired private DatamodelExporter datamodelExporter; @Override protected String getPrefix() { return "/model/editor/"; } @Override protected DatamodelImportWorker getImportWorker() { return this.importWorker; } @Override protected BaseEntityService getMainEntityService() { return this.schemaService; } public SchemaEditorController() { super("schemaEditor"); } @Override public void afterPropertiesSet() throws Exception { super.afterPropertiesSet(); Files.createDirectories(Paths.get(tmpUploadDirPath)); } @RequestMapping(value="/query/{query}", method=RequestMethod.GET) public @ResponseBody List<Identifiable> queryElements(@PathVariable String entityId, @PathVariable String query) { return identifiableService.findByNameAndSchemaId(query, entityId, new Class<?>[] { Nonterminal.class, GrammarImpl.class }); } @RequestMapping(method=GET, value="") public String getEditor(@PathVariable String entityId, Model model, @ModelAttribute String sample, Locale locale, HttpServletRequest request, HttpServletResponse response) throws IOException { AuthPojo auth = authInfoHelper.getAuth(request); RightsContainer<Datamodel> schema = schemaService.findByIdAndAuth(entityId, auth); if (schema==null) { response.sendRedirect("/registry/"); return null; } boolean oversized = false; model.addAttribute("schema", authPojoConverter.convert(schema, auth.getUserId())); List<RightsContainer<Mapping>> mappings = mappingService.getMappings(entityId); model.addAttribute("mapped", mappings!=null && mappings.size()>0); try { PersistedSession s = sessionService.accessOrCreate(entityId, request.getSession().getId(), auth.getUserId()); model.addAttribute("session", s); /*if (s.getSampleInput()!=null) { if (s.getSampleInput().getBytes().length>this.maxTravelSize) {*/ oversized = true; /*} else { model.addAttribute("sampleInput", s.getSampleInput()); } }*/ } catch (Exception e) { logger.error("Failed to load/initialize persisted session", e); } model.addAttribute("sampleInputOversize", oversized); return "schemaEditor"; } @PreAuthorize("isAuthenticated()") @RequestMapping(method=GET, value={"/forms/edit"}) public String getEditForm(@PathVariable String entityId, Model model, Locale locale, HttpServletRequest request, HttpServletResponse response) { if (!schemaService.getUserCanWriteEntity(entityId, authInfoHelper.getAuth(request).getUserId())) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } RightsContainer<Datamodel> schema = schemaService.findByIdAndAuth(entityId, authInfoHelper.getAuth(request)); model.addAttribute("actionPath", "/model/async/save"); model.addAttribute("datamodelImpl", schema.getElement()); model.addAttribute("readOnly", schema.isReadOnly()); return "schema/form/edit"; } @PreAuthorize("isAuthenticated()") @RequestMapping(method=GET, value={"/async/delete"}, produces = "application/json; charset=utf-8") public @ResponseBody ModelActionPojo deleteSchema(@PathVariable String entityId, HttpServletRequest request, HttpServletResponse response) { if (!schemaService.getUserCanWriteEntity(entityId, authInfoHelper.getAuth(request).getUserId())) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return new ModelActionPojo(false); } ModelActionPojo result; if (entityId!=null && !entityId.isEmpty()) { schemaService.deleteSchemaById(entityId, authInfoHelper.getAuth(request)); result = new ModelActionPojo(true); } else { result = new ModelActionPojo(false); } return result; } @PreAuthorize("isAuthenticated()") @RequestMapping(method=GET, value={"/forms/import"}) public String getImportForm(@PathVariable String entityId, @RequestParam(required=false) String elementId, Model model, Locale locale, HttpServletRequest request, HttpServletResponse response) { AuthPojo auth = authInfoHelper.getAuth(request); if(!schemaService.getUserCanWriteEntity(entityId, auth.getUserId())) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } model.addAttribute("actionPath", "/model/editor/" + entityId + "/async/import"); model.addAttribute("schema", schemaService.findSchemaById(entityId)); if (elementId!=null){ model.addAttribute("elementId", elementId); } return "schemaEditor/form/import"; } @PreAuthorize("isAuthenticated()") @RequestMapping(method = RequestMethod.GET, value = "/form/createRoot") public String getNewNonterminalForm(@PathVariable String entityId, Model model, Locale locale, HttpServletRequest request, HttpServletResponse response) { AuthPojo auth = authInfoHelper.getAuth(request); if(!schemaService.getUserCanWriteEntity(entityId, auth.getUserId())) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } model.addAttribute("element", new NonterminalImpl()); model.addAttribute("availableTerminals", schemaService.getAvailableTerminals(entityId)); model.addAttribute("actionPath", "/model/editor/" + entityId + "/async/saveNewRoot"); return "elementEditor/form/edit_nonterminal"; } @PreAuthorize("isAuthenticated()") @RequestMapping(method = RequestMethod.POST, value = "/async/saveNewRoot") public @ResponseBody ModelActionPojo saveNonterminal(@PathVariable String entityId, @Valid NonterminalImpl element, BindingResult bindingResult, Locale locale, HttpServletRequest request, HttpServletResponse response) { AuthPojo auth = authInfoHelper.getAuth(request); if(!schemaService.getUserCanWriteEntity(entityId, auth.getUserId())) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return new ModelActionPojo(false); } ModelActionPojo result = this.getActionResult(bindingResult, locale); if (result.isSuccess()) { element.setEntityId(entityId); elementService.saveOrReplaceRoot(entityId, element, authInfoHelper.getAuth(request)); } return result; } @PreAuthorize("isAuthenticated()") @RequestMapping(method=POST, value={"/async/import"}, produces = "application/json; charset=utf-8") public @ResponseBody ModelActionPojo importSchemaElements(@PathVariable String entityId, @RequestParam(value="file.id") String fileId, @RequestParam(required=false, value="elementId") String elementId, @RequestParam(value="schema_root_qn") String schemaRoot, @RequestParam(required=false, value="schema_root_type") String schemaRootType, @RequestParam(required=false, value="schema_root_id") String schemaRootId, @RequestParam(defaultValue="false", value="keep-imported-ids") boolean keepImportedIds, Locale locale, HttpServletRequest request, HttpServletResponse response) { AuthPojo auth = authInfoHelper.getAuth(request); if(!schemaService.getUserCanWriteEntity(entityId, auth.getUserId())) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return new ModelActionPojo(false); } if (schemaRootId!=null && schemaRootId.isEmpty()) { schemaRootId = null; } ModelActionPojo result = new ModelActionPojo(); try { if (temporaryFilesMap.containsKey(fileId)) { if (schemaRoot.isEmpty()) { result.setSuccess(false); result.addFieldError("schema_root", messageSource.getMessage("~de.unibamberg.minf.dme.notification.import.root_missing", null, locale)); return result; } if (elementId!=null) { importWorker.importSubtree(temporaryFilesMap.remove(fileId), entityId, elementId, (schemaRootId!=null ? schemaRootId : schemaRoot), schemaRootType, keepImportedIds, authInfoHelper.getAuth(request)); } else { Datamodel m = schemaService.findByIdAndAuth(entityId, auth).getElement(); m.setNatures(null); elementService.clearElementTree(entityId, auth); schemaService.saveSchema(m, auth); importWorker.importSchema(temporaryFilesMap.remove(fileId), entityId, (schemaRootId!=null ? schemaRootId : schemaRoot), keepImportedIds, authInfoHelper.getAuth(request)); } result.setSuccess(true); return result; } } catch (Exception e) { MessagePojo msg = new MessagePojo("danger", messageSource.getMessage("~de.unibamberg.minf.common.view.forms.file.generalerror.head", null, locale), messageSource.getMessage("~de.unibamberg.minf.common.view.forms.file.generalerror.body", new Object[] {e.getLocalizedMessage()}, locale)); result.setMessage(msg); } result.setSuccess(false); return result; } @RequestMapping(method = RequestMethod.GET, value = "/async/export") public @ResponseBody ModelActionPojo exportSchema(@PathVariable String entityId, Model model, HttpServletRequest request, Locale locale) { DatamodelReferenceContainer container = datamodelExporter.exportDatamodel(entityId, authInfoHelper.getAuth(request)); if (container==null) { return new ModelActionPojo(false); } ModelActionPojo result = new ModelActionPojo(true); result.setPojo(container); return result; } @RequestMapping(method = RequestMethod.GET, value = "/async/exportSubtree") public @ResponseBody ModelActionPojo exportSubtree(@PathVariable String entityId, @RequestParam String elementId, Model model, HttpServletRequest request, Locale locale) { AuthPojo auth = authInfoHelper.getAuth(request); ModelActionPojo result = new ModelActionPojo(true); result.setPojo(datamodelExporter.exportDatamodelSubtree(entityId, elementId, auth)); return result; } @RequestMapping(method = RequestMethod.GET, value = "/async/getHierarchy") public @ResponseBody ModelActionPojo getHierarchy(@PathVariable String entityId, @RequestParam(defaultValue="false") boolean staticElementsOnly, @RequestParam(defaultValue="false") boolean collectNatureClasses, @RequestParam(defaultValue="logical_model", name="model") String modelClass, Model model, Locale locale, HttpServletRequest request, HttpServletResponse response) throws IOException, GenericScheregException { ModelActionPojo rPojo = new ModelActionPojo(true); AuthPojo auth = authInfoHelper.getAuth(request); Element result = elementService.findRootBySchemaId(entityId, true); if (result==null) { response.getWriter().print("null"); response.setContentType("application/json"); return null; } Map<String, List<String>> nonterminalNatureClassesMap = new HashMap<String, List<String>>(); Datamodel m = schemaService.findByIdAndAuth(entityId, auth).getElement(); if (modelClass.equals("logical_model")) { if (m.getNatures()!=null) { for (DatamodelNature n : m.getNatures()) { if (n.getNonterminalTerminalIdMap()!=null) { for (String nId : n.getNonterminalTerminalIdMap().keySet()) { List<String> natureClasses = nonterminalNatureClassesMap.get(nId); if (natureClasses==null) { natureClasses = new ArrayList<String>(); } natureClasses.add(n.getClass().getName()); nonterminalNatureClassesMap.put(nId, natureClasses); } } } } rPojo.setPojo(ModelElementPojoConverter.convertModelElement(result, nonterminalNatureClassesMap, staticElementsOnly)); } else { try { @SuppressWarnings("unchecked") Class<? extends DatamodelNature> modelClazz = (Class<? extends DatamodelNature>)Class.forName(modelClass); DatamodelNature n = schemaService.findByIdAndAuth(entityId, auth).getElement().getNature(modelClazz); rPojo.setPojo(ModelElementPojoConverter.convertModelElementTerminal(result, n)); } catch (Exception e) { logger.error(String.format("Failed to retrieve model of class %s for datamodel %s", modelClass, entityId), e); } } ObjectNode statusNode = objectMapper.createObjectNode(); boolean headers = false; Nonterminal processingRoot = ElementServiceImpl.findProcessingRoot((Nonterminal)result); if (processingRoot==null || processingRoot.isIncludeHeader()) { headers = true; } statusNode.put("includeHeaders", headers); rPojo.setStatusInfo(statusNode); return rPojo; } @RequestMapping(method = RequestMethod.GET, value = "/async/getTerminals") public @ResponseBody List<? extends Terminal> getTerminals(@PathVariable String entityId) { Datamodel s = schemaService.findSchemaById(entityId); if (s.getNature(XmlDatamodelNature.class)!=null) { return s.getNature(XmlDatamodelNature.class).getTerminals(); } return null; } @Override protected ModelActionPojo validateImportedFile(String entityId, String fileId, String elementId, Locale locale) { JsonNode rootNodes; ModelActionPojo result = new ModelActionPojo(); DatamodelImporter importer = importWorker.getSupportingImporter(temporaryFilesMap.get(fileId)); if (elementId==null) { rootNodes = objectMapper.valueToTree(importer.getPossibleRootElements()); } else { List<Class<? extends ModelElement>> allowedSubtreeRoots = identifiableService.getAllowedSubelementTypes(elementId); rootNodes = objectMapper.valueToTree(importer.getElementsByTypes(allowedSubtreeRoots)); } if (rootNodes!=null) { result.setSuccess(true); MessagePojo msg = new MessagePojo("success", messageSource.getMessage("~de.unibamberg.minf.common.view.forms.file.validationsucceeded.head", null, locale), messageSource.getMessage("~de.unibamberg.minf.common.view.forms.file.validationsucceeded.body", null, locale)); result.setMessage(msg); ObjectNode pojoNode = objectMapper.createObjectNode(); pojoNode.set("elements", rootNodes); pojoNode.set("keepIdsAllowed", BooleanNode.valueOf(importer.isKeepImportedIdsSupported())); pojoNode.set("importerMainType", TextNode.valueOf(importer.getMainImporterType())); pojoNode.set("importerSubtype", TextNode.valueOf(importer.getImporterSubtype())); result.setPojo(pojoNode); } return result; } }
/* * 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.geode.internal.cache.tx; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.anyLong; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.concurrent.ExecutorService; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.apache.geode.cache.CacheClosedException; import org.apache.geode.cache.RegionDestroyedException; import org.apache.geode.cache.TransactionException; import org.apache.geode.distributed.DistributedSystemDisconnectedException; import org.apache.geode.distributed.internal.ClusterDistributionManager; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.distributed.internal.OperationExecutors; import org.apache.geode.distributed.internal.ReplyException; import org.apache.geode.distributed.internal.ReplyProcessor21; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.cache.GemFireCacheImpl; import org.apache.geode.internal.cache.LocalRegion; import org.apache.geode.internal.cache.RemoteOperationException; import org.apache.geode.internal.cache.TXManagerImpl; import org.apache.geode.internal.cache.TXStateProxy; import org.apache.geode.internal.cache.TXStateProxyImpl; import org.apache.geode.test.fake.Fakes; public class RemoteOperationMessageTest { private TestableRemoteOperationMessage msg; // the class under test private InternalDistributedMember sender; private final String regionPath = "regionPath"; private GemFireCacheImpl cache; private InternalDistributedSystem system; private ClusterDistributionManager dm; private LocalRegion r; private TXManagerImpl txMgr; private long startTime = 0; private TXStateProxy tx; @Before public void setUp() throws Exception { cache = Fakes.cache(); system = cache.getSystem(); dm = (ClusterDistributionManager) system.getDistributionManager(); r = mock(LocalRegion.class); txMgr = mock(TXManagerImpl.class); tx = mock(TXStateProxyImpl.class); OperationExecutors executors = mock(OperationExecutors.class); ExecutorService executorService = mock(ExecutorService.class); when(cache.getRegionByPathForProcessing(regionPath)).thenReturn(r); when(cache.getTxManager()).thenReturn(txMgr); when(dm.getExecutors()).thenReturn(executors); when(executors.getWaitingThreadPool()).thenReturn(executorService); sender = mock(InternalDistributedMember.class); InternalDistributedMember recipient = mock(InternalDistributedMember.class); ReplyProcessor21 processor = mock(ReplyProcessor21.class); // make it a spy to aid verification msg = spy(new TestableRemoteOperationMessage(recipient, regionPath, processor)); } @Test public void messageWithNoTXPerformsOnRegion() throws Exception { when(txMgr.masqueradeAs(msg)).thenReturn(null); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(msg, times(1)).operateOnRegion(dm, r, startTime); verify(dm, times(1)).putOutgoing(any()); } @Test public void messageForNotFinishedTXPerformsOnRegion() throws Exception { when(txMgr.masqueradeAs(msg)).thenReturn(tx); when(tx.isInProgress()).thenReturn(true); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(msg, times(1)).operateOnRegion(dm, r, startTime); verify(dm, times(1)).putOutgoing(any()); } @Test public void messageForFinishedTXDoesNotPerformOnRegion() throws Exception { when(txMgr.masqueradeAs(msg)).thenReturn(tx); when(tx.isInProgress()).thenReturn(false); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(msg, times(0)).operateOnRegion(dm, r, startTime); // A reply is sent even though we do not call operationOnRegion verify(dm, times(1)).putOutgoing(any()); } @Test public void messageForFinishedTXRepliesWithException() throws Exception { when(txMgr.masqueradeAs(msg)).thenReturn(tx); when(tx.isInProgress()).thenReturn(false); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(msg, times(1)).sendReply( eq(sender), eq(0), eq(dm), argThat(ex -> ex != null && ex.getCause() instanceof TransactionException), eq(r), eq(startTime)); } @Test public void noNewTxProcessingAfterTXManagerImplClosed() throws Exception { when(txMgr.masqueradeAs(msg)).thenReturn(tx); when(txMgr.isClosed()).thenReturn(true); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(msg, times(0)).operateOnRegion(dm, r, startTime); // If we do not respond what prevents the sender from waiting forever? verify(dm, times(0)).putOutgoing(any()); } @Test public void processWithNullCacheSendsReplyContainingCacheClosedException() throws Exception { when(dm.getExistingCache()).thenReturn(null); msg.setSender(sender); msg.process(dm); verify(msg, times(0)).operateOnRegion(dm, r, startTime); verify(dm, times(1)).putOutgoing(any()); ArgumentCaptor<ReplyException> captor = ArgumentCaptor.forClass(ReplyException.class); verify(msg, times(1)).sendReply(any(), anyInt(), eq(dm), captor.capture(), any(), eq(startTime)); assertThat(captor.getValue().getCause()).isInstanceOf(CacheClosedException.class); } @Test public void processWithDisconnectingDSAndClosedCacheSendsReplyContainingCachesClosedException() throws Exception { CacheClosedException reasonCacheWasClosed = mock(CacheClosedException.class); when(system.isDisconnecting()).thenReturn(true); when(cache.getCacheClosedException(any())).thenReturn(reasonCacheWasClosed); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(msg, times(0)).operateOnRegion(dm, r, startTime); verify(dm, times(1)).putOutgoing(any()); ArgumentCaptor<ReplyException> captor = ArgumentCaptor.forClass(ReplyException.class); verify(msg, times(1)).sendReply(any(), anyInt(), eq(dm), captor.capture(), any(), eq(startTime)); assertThat(captor.getValue().getCause()).isSameAs(reasonCacheWasClosed); } @Test public void processWithNullPointerExceptionFromOperationOnRegionWithNoSystemFailureSendsReplyWithNPE() throws Exception { when(msg.operateOnRegion(dm, r, startTime)).thenThrow(NullPointerException.class); doNothing().when(msg).checkForSystemFailure(); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(dm, times(1)).putOutgoing(any()); ArgumentCaptor<ReplyException> captor = ArgumentCaptor.forClass(ReplyException.class); verify(msg, times(1)).sendReply(any(), anyInt(), eq(dm), captor.capture(), eq(r), eq(startTime)); assertThat(captor.getValue().getCause()).isInstanceOf(NullPointerException.class); } @Test public void processWithNullPointerExceptionFromOperationOnRegionWithNoSystemFailureAndIsDisconnectingSendsReplyWithRemoteOperationException() throws Exception { when(msg.operateOnRegion(dm, r, startTime)).thenThrow(NullPointerException.class); doNothing().when(msg).checkForSystemFailure(); when(system.isDisconnecting()).thenReturn(false).thenReturn(true); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(dm, times(1)).putOutgoing(any()); ArgumentCaptor<ReplyException> captor = ArgumentCaptor.forClass(ReplyException.class); verify(msg, times(1)).sendReply(any(), anyInt(), eq(dm), captor.capture(), eq(r), eq(startTime)); assertThat(captor.getValue().getCause()).isInstanceOf(RemoteOperationException.class); } @Test public void processWithRegionDestroyedExceptionFromOperationOnRegionSendsReplyWithSameRegionDestroyedException() throws Exception { RegionDestroyedException ex = mock(RegionDestroyedException.class); when(msg.operateOnRegion(dm, r, startTime)).thenThrow(ex); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(dm, times(1)).putOutgoing(any()); ArgumentCaptor<ReplyException> captor = ArgumentCaptor.forClass(ReplyException.class); verify(msg, times(1)).sendReply(any(), anyInt(), eq(dm), captor.capture(), eq(r), eq(startTime)); assertThat(captor.getValue().getCause()).isSameAs(ex); } @Test public void processWithRegionDoesNotExistSendsReplyWithRegionDestroyedExceptionReply() throws Exception { when(cache.getRegionByPathForProcessing(regionPath)).thenReturn(null); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(msg, never()).operateOnRegion(any(), any(), anyLong()); verify(dm, times(1)).putOutgoing(any()); ArgumentCaptor<ReplyException> captor = ArgumentCaptor.forClass(ReplyException.class); verify(msg, times(1)).sendReply(any(), anyInt(), eq(dm), captor.capture(), eq(null), eq(startTime)); assertThat(captor.getValue().getCause()).isInstanceOf(RegionDestroyedException.class); } @Test public void processWithDistributedSystemDisconnectedExceptionFromOperationOnRegionDoesNotSendReply() throws Exception { when(msg.operateOnRegion(dm, r, startTime)) .thenThrow(DistributedSystemDisconnectedException.class); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(dm, never()).putOutgoing(any()); } @Test public void processWithOperateOnRegionReturningFalseDoesNotSendReply() { msg.setOperationOnRegionResult(false); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(dm, never()).putOutgoing(any()); } @Test public void processWithRemoteOperationExceptionFromOperationOnRegionSendsReplyWithSameRemoteOperationException() throws Exception { RemoteOperationException theException = mock(RemoteOperationException.class); when(msg.operateOnRegion(dm, r, startTime)).thenThrow(theException); msg.setSender(sender); msg.doRemoteOperation(dm, cache); verify(dm, times(1)).putOutgoing(any()); ArgumentCaptor<ReplyException> captor = ArgumentCaptor.forClass(ReplyException.class); verify(msg, times(1)).sendReply(any(), anyInt(), eq(dm), captor.capture(), eq(r), eq(startTime)); assertThat(captor.getValue().getCause()).isSameAs(theException); } @Test public void processWithNullPointerExceptionFromOperationOnRegionWithSystemFailureSendsReplyWithRemoteOperationException() throws Exception { when(msg.operateOnRegion(dm, r, startTime)).thenThrow(NullPointerException.class); doThrow(new RuntimeException("SystemFailure")).when(msg).checkForSystemFailure(); msg.setSender(sender); assertThatThrownBy(() -> msg.doRemoteOperation(dm, cache)).isInstanceOf(RuntimeException.class) .hasMessage("SystemFailure"); verify(dm, times(1)).putOutgoing(any()); ArgumentCaptor<ReplyException> captor = ArgumentCaptor.forClass(ReplyException.class); verify(msg, times(1)).sendReply(any(), anyInt(), eq(dm), captor.capture(), eq(r), eq(startTime)); assertThat(captor.getValue().getCause()).isInstanceOf(RemoteOperationException.class) .hasMessageContaining("system failure"); } @Test public void processInvokesDoRemoteOperationIfThreadOwnsResources() { when(system.threadOwnsResources()).thenReturn(true); doNothing().when(msg).doRemoteOperation(dm, cache); msg.process(dm); verify(msg).doRemoteOperation(dm, cache); verify(msg, never()).isTransactional(); } @Test public void processInvokesDoRemoteOperationIfThreadDoesNotOwnResourcesAndNotTransactional() { when(system.threadOwnsResources()).thenReturn(false); doReturn(false).when(msg).isTransactional(); doNothing().when(msg).doRemoteOperation(dm, cache); msg.process(dm); verify(msg).doRemoteOperation(dm, cache); verify(msg).isTransactional(); } @Test public void isTransactionalReturnsFalseIfTXUniqueIdIsNOTX() { assertThat(msg.getTXUniqId()).isEqualTo(TXManagerImpl.NOTX); assertThat(msg.isTransactional()).isFalse(); } @Test public void isTransactionalReturnsFalseIfCannotParticipateInTransaction() { doReturn(1).when(msg).getTXUniqId(); doReturn(false).when(msg).canParticipateInTransaction(); assertThat(msg.isTransactional()).isFalse(); } @Test public void isTransactionalReturnsTrueIfHasTXUniqueIdAndCanParticipateInTransaction() { doReturn(1).when(msg).getTXUniqId(); assertThat(msg.canParticipateInTransaction()).isTrue(); assertThat(msg.isTransactional()).isTrue(); } private static class TestableRemoteOperationMessage extends RemoteOperationMessage { private boolean operationOnRegionResult = true; TestableRemoteOperationMessage(InternalDistributedMember recipient, String regionPath, ReplyProcessor21 processor) { super(recipient, regionPath, processor); } @Override public int getDSFID() { return 0; } @Override protected boolean operateOnRegion(ClusterDistributionManager dm, LocalRegion r, long startTime) throws RemoteOperationException { return operationOnRegionResult; } void setOperationOnRegionResult(boolean v) { this.operationOnRegionResult = v; } } }
package openexplorer.preferences; /** * Copyright (c) 2011 Samson Wu * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ import java.io.File; import java.util.ArrayList; import openexplorer.Activator; import openexplorer.util.IFileManagerExecutables; import openexplorer.util.Messages; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** * @author <a href="mailto:samson959@gmail.com">Samson Wu</a> * @version 1.4.0 */ public class FMPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private ArrayList<Button> fileManagerButtons = new ArrayList<Button>(); private Label fullPathLabel; private Text fileManagerPath; private Button browseButton; private String selectedFileManager; private String fileManagerPathString; /* * (non-Javadoc) * * @see * org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { IPreferenceStore store = getPreferenceStore(); selectedFileManager = store .getString(IPreferenceConstants.LINUX_FILE_MANAGER); fileManagerPathString = store .getString(IPreferenceConstants.LINUX_FILE_MANAGER_PATH); setDescription(Messages.System_File_Manager_Preferences); } @Override protected Control createContents(Composite parent) { Composite composite = createComposite(parent); createMacOSXFMGroup(composite); createWindowsFMGroup(composite); createLinuxFMGroup(composite); return composite; } protected Composite createComposite(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginWidth = 0; layout.marginHeight = 0; composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL)); return composite; } private Group createGroup(Composite composite, String title) { Group groupComposite = new Group(composite, SWT.LEFT); GridLayout layout = new GridLayout(); groupComposite.setLayout(layout); GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); groupComposite.setLayoutData(data); groupComposite.setText(title); return groupComposite; } protected void createMacOSXFMGroup(Composite composite) { Group groupComposite = createGroup(composite, Messages.MAC_OS_X); Button macOSXFMButton = createRadioButton(groupComposite, Messages.Finder, IFileManagerExecutables.FINDER); macOSXFMButton.setSelection(true); } protected void createWindowsFMGroup(Composite composite) { Group groupComposite = createGroup(composite, Messages.WINDOWS); Button windowsFMButton = createRadioButton(groupComposite, Messages.Windows_Explorer, IFileManagerExecutables.EXPLORER); windowsFMButton.setSelection(true); } protected void createLinuxFMGroup(Composite composite) { Group groupComposite = createGroup(composite, Messages.LINUX); String label = Messages.Nautilus; String value = IFileManagerExecutables.NAUTILUS; createRadioButtonWithSelectionListener(groupComposite, label, value, false); label = Messages.Dolphin; value = IFileManagerExecutables.DOLPHIN; createRadioButtonWithSelectionListener(groupComposite, label, value, false); label = Messages.Thunar; value = IFileManagerExecutables.THUNAR; createRadioButtonWithSelectionListener(groupComposite, label, value, false); label = Messages.PCManFM; value = IFileManagerExecutables.PCMANFM; createRadioButtonWithSelectionListener(groupComposite, label, value, false); label = Messages.ROX; value = IFileManagerExecutables.ROX; createRadioButtonWithSelectionListener(groupComposite, label, value, false); label = Messages.Xdg_open; value = IFileManagerExecutables.XDG_OPEN; createRadioButtonWithSelectionListener(groupComposite, label, value, false); label = Messages.Other; value = IFileManagerExecutables.OTHER; createRadioButtonWithSelectionListener(groupComposite, label, value, true); Composite c = new Composite(groupComposite, SWT.NONE); c.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout layout = new GridLayout(3, false); layout.marginWidth = 0; c.setLayout(layout); fullPathLabel = new Label(c, SWT.NONE); fullPathLabel.setText(Messages.Full_Path_Label_Text); fileManagerPath = new Text(c, SWT.BORDER); if (fileManagerPathString != null) { fileManagerPath.setText(fileManagerPathString); } fileManagerPath.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fileManagerPath.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (fileManagerPath.isEnabled()) { String path = fileManagerPath.getText(); if (path == null || path.equals("")) { setValid(false); setErrorMessage(Messages.Error_Path_Cant_be_blank); return; } File f = new File(path); if (!f.exists() || !f.isFile()) { setValid(false); setErrorMessage(Messages.Erorr_Path_Not_Exist_or_Not_a_File); return; } setErrorMessage(null); setValid(true); } } }); browseButton = new Button(c, SWT.PUSH); browseButton.setText(Messages.Browse_Button_Text); browseButton.setFont(composite.getFont()); browseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent evt) { String newValue = browsePressed(); if (newValue != null) { setFileManagerPath(newValue); } } }); browseButton.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { browseButton = null; } }); if (!IFileManagerExecutables.OTHER.equals(selectedFileManager)) { fullPathLabel.setEnabled(false); fileManagerPath.setEnabled(false); browseButton.setEnabled(false); } createNoteComposite(composite.getFont(), groupComposite, Messages.Preference_note, Messages.FileManager_need_to_be_installed); } private void setFileManagerPath(String value) { if (fileManagerPath != null) { if (value == null) { value = ""; } fileManagerPath.setText(value); } } private String browsePressed() { File f = new File(fileManagerPath.getText()); if (!f.exists()) { f = null; } File filePath = getFilePath(f); if (filePath == null) { return null; } return filePath.getAbsolutePath(); } private File getFilePath(File startingDirectory) { FileDialog fileDialog = new FileDialog(getShell(), SWT.OPEN | SWT.SHEET); if (startingDirectory != null) { fileDialog.setFilterPath(startingDirectory.getPath()); } String filePath = fileDialog.open(); if (filePath != null) { filePath = filePath.trim(); if (filePath.length() > 0) { return new File(filePath); } } return null; } private void toggleOtherTextField(boolean enabled) { fullPathLabel.setEnabled(enabled); fileManagerPath.setEnabled(enabled); browseButton.setEnabled(enabled); } private Button createRadioButton(Composite parent, String label, String value) { Button button = new Button(parent, SWT.RADIO | SWT.LEFT); button.setText(label); button.setData(value); return button; } private Button createRadioButtonWithSelectionListener(Composite parent, String label, final String value, final boolean enableOtherTextFieldIfClick) { Button button = createRadioButton(parent, label, value); if (value != null && value.equals(selectedFileManager)) { button.setSelection(true); } button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { selectedFileManager = (String) e.widget.getData(); toggleOtherTextField(enableOtherTextFieldIfClick); if (IFileManagerExecutables.OTHER.equals(value)) { fileManagerPath.notifyListeners(SWT.Modify, new Event()); } else { setValid(true); setErrorMessage(null); } } }); fileManagerButtons.add(button); return button; } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() */ @Override protected IPreferenceStore doGetPreferenceStore() { return Activator.getDefault().getPreferenceStore(); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.PreferencePage#performDefaults() */ @Override protected void performDefaults() { IPreferenceStore store = getPreferenceStore(); for (Button button : fileManagerButtons) { if (store.getDefaultString(IPreferenceConstants.LINUX_FILE_MANAGER) .equals((String) button.getData())) { button.setSelection(true); selectedFileManager = (String) button.getData(); } else { button.setSelection(false); } } fileManagerPath .setText(store .getDefaultString(IPreferenceConstants.LINUX_FILE_MANAGER_PATH)); super.performDefaults(); } /* * (non-Javadoc) * * @see org.eclipse.jface.preference.PreferencePage#performOk() */ @Override public boolean performOk() { IPreferenceStore store = getPreferenceStore(); store.setValue(IPreferenceConstants.LINUX_FILE_MANAGER, selectedFileManager); store.setValue(IPreferenceConstants.LINUX_FILE_MANAGER_PATH, fileManagerPath.getText()); return super.performOk(); } }
/* * 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.geode.internal.cache.snapshot; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.List; import java.util.Map.Entry; import java.util.UUID; import org.apache.geode.cache.EntryDestroyedException; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.cache.CachedDeserializable; import org.apache.geode.internal.cache.EntrySnapshot; import org.apache.geode.internal.cache.LocalRegion; import org.apache.geode.internal.cache.NonTXEntry; import org.apache.geode.internal.cache.Token; import org.apache.geode.internal.offheap.OffHeapHelper; import org.apache.geode.internal.offheap.annotations.Released; import org.apache.geode.internal.serialization.DataSerializableFixedID; import org.apache.geode.internal.serialization.DeserializationContext; import org.apache.geode.internal.serialization.KnownVersion; import org.apache.geode.internal.serialization.SerializationContext; import org.apache.geode.internal.util.BlobHelper; /** * Provides an envelope for transmitting a collection of <code>SnapshotRecord</code>s during export. * */ public class SnapshotPacket implements DataSerializableFixedID { /** * Captures the key/value data from a cache entry for import or export. */ public static class SnapshotRecord implements DataSerializableFixedID { /** the serialized key */ private byte[] key; /** the serialized value */ private byte[] value; /** for deserialization */ public SnapshotRecord() {} public SnapshotRecord(byte[] key, byte[] value) { this.key = key; this.value = value; } public <K, V> SnapshotRecord(K keyObj, V valObj) throws IOException { key = BlobHelper.serializeToBlob(keyObj); value = convertToBytes(valObj); } public <K, V> SnapshotRecord(LocalRegion region, Entry<K, V> entry) throws IOException { key = BlobHelper.serializeToBlob(entry.getKey()); if (entry instanceof NonTXEntry && region != null) { @Released Object v = ((NonTXEntry) entry).getRegionEntry().getValueOffHeapOrDiskWithoutFaultIn(region); try { value = convertToBytes(v); } finally { OffHeapHelper.release(v); } } else if (entry instanceof EntrySnapshot) { EntrySnapshot entrySnapshot = (EntrySnapshot) entry; Object entryValue = entrySnapshot.getValuePreferringCachedDeserializable(); value = convertToBytes(entryValue); } else { value = convertToBytes(entry.getValue()); } } /** * Returns the serialized key. * * @return the key */ public byte[] getKey() { return key; } /** * Returns the serialized value. * * @return the value */ public byte[] getValue() { return value; } /** * Returns the deserialized key object. * * @return the key * * @throws IOException error deserializing key * @throws ClassNotFoundException unable to deserialize key */ public <K> K getKeyObject() throws IOException, ClassNotFoundException { return (K) BlobHelper.deserializeBlob(key); } /** * Returns the deserialized value object. * * @return the value * * @throws IOException error deserializing value * @throws ClassNotFoundException unable to deserialize value */ public <V> V getValueObject() throws IOException, ClassNotFoundException { return value == null ? null : (V) BlobHelper.deserializeBlob(value); } /** * Returns true if the record has a value. * * @return the value, or null */ public boolean hasValue() { return value != null; } /** * Returns the size in bytes of the serialized key and value. * * @return the record size */ public int getSize() { return key.length + (value == null ? 0 : value.length); } @Override public void toData(DataOutput out, SerializationContext context) throws IOException { InternalDataSerializer.writeByteArray(key, out); InternalDataSerializer.writeByteArray(value, out); } @Override public int getDSFID() { return SNAPSHOT_RECORD; } @Override public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { key = InternalDataSerializer.readByteArray(in); value = InternalDataSerializer.readByteArray(in); } private byte[] convertToBytes(Object val) throws IOException { if (Token.isRemoved(val)) { throw new EntryDestroyedException(); } else if (Token.isInvalid(val)) { return null; } else if (val instanceof CachedDeserializable) { byte[] bytes = ((CachedDeserializable) val).getSerializedValue(); return bytes; } else if (val != null) { return BlobHelper.serializeToBlob(val); } return null; } @Override public KnownVersion[] getSerializationVersions() { return null; } } /** the window id for responses */ private int windowId; /** the packet id */ private String packetId; /** the member sending the packet */ private DistributedMember sender; /** the snapshot data */ private SnapshotRecord[] records; /** for deserialization */ public SnapshotPacket() {} public SnapshotPacket(int windowId, DistributedMember sender, List<SnapshotRecord> recs) { this.windowId = windowId; this.packetId = UUID.randomUUID().toString(); this.sender = sender; records = recs.toArray(new SnapshotRecord[0]); } /** * Returns the window id for sending responses. * * @return the window id */ public int getWindowId() { return windowId; } /** * Returns the packet id. * * @return the packet id */ public String getPacketId() { return packetId; } /** * Returns the member that sent the packet. * * @return the sender */ public DistributedMember getSender() { return sender; } /** * Returns the snapshot data * * @return the records */ public SnapshotRecord[] getRecords() { return records; } @Override public int getDSFID() { return SNAPSHOT_PACKET; } @Override public void toData(DataOutput out, SerializationContext context) throws IOException { out.writeInt(windowId); InternalDataSerializer.writeString(packetId, out); context.getSerializer().writeObject(sender, out); InternalDataSerializer.writeArrayLength(records.length, out); for (SnapshotRecord rec : records) { InternalDataSerializer.invokeToData(rec, out); } } @Override public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { windowId = in.readInt(); packetId = InternalDataSerializer.readString(in); sender = context.getDeserializer().readObject(in); int count = InternalDataSerializer.readArrayLength(in); records = new SnapshotRecord[count]; for (int i = 0; i < count; i++) { SnapshotRecord rec = new SnapshotRecord(); InternalDataSerializer.invokeFromData(rec, in); records[i] = rec; } } @Override public KnownVersion[] getSerializationVersions() { 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.eagle.executor; import com.codahale.metrics.MetricRegistry; import com.sun.jersey.client.impl.CopyOnWriteHashMap; import com.typesafe.config.Config; import org.apache.commons.lang3.time.DateUtils; import org.apache.eagle.alert.common.AlertConstants; import org.apache.eagle.alert.config.AbstractPolicyDefinition; import org.apache.eagle.alert.dao.AlertDefinitionDAO; import org.apache.eagle.alert.dao.AlertStreamSchemaDAO; import org.apache.eagle.alert.dao.AlertStreamSchemaDAOImpl; import org.apache.eagle.alert.entity.AlertAPIEntity; import org.apache.eagle.alert.entity.AlertDefinitionAPIEntity; import org.apache.eagle.alert.policy.*; import org.apache.eagle.alert.siddhi.EagleAlertContext; import org.apache.eagle.alert.siddhi.SiddhiAlertHandler; import org.apache.eagle.alert.siddhi.StreamMetadataManager; import org.apache.eagle.common.config.EagleConfigConstants; import org.apache.eagle.dataproc.core.JsonSerDeserUtils; import org.apache.eagle.dataproc.core.ValuesArray; import org.apache.eagle.datastream.Collector; import org.apache.eagle.datastream.JavaStormStreamExecutor2; import org.apache.eagle.datastream.Tuple2; import org.apache.eagle.metric.reportor.EagleCounterMetric; import org.apache.eagle.metric.reportor.EagleMetricListener; import org.apache.eagle.metric.reportor.EagleServiceReporterMetricListener; import org.apache.eagle.metric.reportor.MetricKeyCodeDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.ManagementFactory; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class AlertExecutor extends JavaStormStreamExecutor2<String, AlertAPIEntity> implements PolicyLifecycleMethods, SiddhiAlertHandler, PolicyDistributionReportMethods { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(AlertExecutor.class); private String alertExecutorId; private volatile CopyOnWriteHashMap<String, PolicyEvaluator> policyEvaluators; private PolicyPartitioner partitioner; private int numPartitions; private int partitionSeq; private Config config; private Map<String, Map<String, AlertDefinitionAPIEntity>> initialAlertDefs; private AlertDefinitionDAO alertDefinitionDao; private String[] sourceStreams; private static String EAGLE_EVENT_COUNT = "eagle.event.count"; private static String EAGLE_POLICY_EVAL_COUNT = "eagle.policy.eval.count"; private static String EAGLE_POLICY_EVAL_FAIL_COUNT = "eagle.policy.eval.fail.count"; private static String EAGLE_ALERT_COUNT = "eagle.alert.count"; private static String EAGLE_ALERT_FAIL_COUNT = "eagle.alert.fail.count"; private static long MERITE_GRANULARITY = DateUtils.MILLIS_PER_MINUTE; private Map<String, Map<String, String>> dimensionsMap; // cache it for performance private Map<String, String> baseDimensions; private MetricRegistry registry; private EagleMetricListener listener; public AlertExecutor(String alertExecutorId, PolicyPartitioner partitioner, int numPartitions, int partitionSeq, AlertDefinitionDAO alertDefinitionDao, String[] sourceStreams){ this.alertExecutorId = alertExecutorId; this.partitioner = partitioner; this.numPartitions = numPartitions; this.partitionSeq = partitionSeq; this.alertDefinitionDao = alertDefinitionDao; this.sourceStreams = sourceStreams; } public String getAlertExecutorId(){ return this.alertExecutorId; } public int getNumPartitions() { return this.numPartitions; } public int getPartitionSeq(){ return this.partitionSeq; } public PolicyPartitioner getPolicyPartitioner() { return this.partitioner; } public Map<String, Map<String, AlertDefinitionAPIEntity>> getInitialAlertDefs() { return this.initialAlertDefs; } public AlertDefinitionDAO getAlertDefinitionDao() { return alertDefinitionDao; } public Map<String, PolicyEvaluator> getPolicyEvaluators(){ return policyEvaluators; } @Override public void prepareConfig(Config config) { this.config = config; } public void initMetricReportor() { String host = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.HOST); int port = config.getInt(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PORT); String username = config.hasPath(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.USERNAME) ? config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.USERNAME) : null; String password = config.hasPath(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PASSWORD) ? config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PASSWORD) : null; //TODO: need to it replace it with batch flush listener registry = new MetricRegistry(); listener = new EagleServiceReporterMetricListener(host, port, username, password); baseDimensions = new HashMap<>(); baseDimensions.put(AlertConstants.ALERT_EXECUTOR_ID, alertExecutorId); baseDimensions.put(AlertConstants.PARTITIONSEQ, String.valueOf(partitionSeq)); baseDimensions.put(AlertConstants.SOURCE, ManagementFactory.getRuntimeMXBean().getName()); baseDimensions.put(EagleConfigConstants.DATA_SOURCE, config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.DATA_SOURCE)); baseDimensions.put(EagleConfigConstants.SITE, config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.SITE)); dimensionsMap = new HashMap<>(); } /** * for unit test purpose only * @param config * @return */ public AlertStreamSchemaDAO getAlertStreamSchemaDAO(Config config){ return new AlertStreamSchemaDAOImpl(config); } @Override public void init() { // initialize StreamMetadataManager before it is used StreamMetadataManager.getInstance().init(config, getAlertStreamSchemaDAO(config)); // for each AlertDefinition, to create a PolicyEvaluator Map<String, PolicyEvaluator> tmpPolicyEvaluators = new HashMap<String, PolicyEvaluator>(); String site = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.SITE); String dataSource = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.DATA_SOURCE); try { initialAlertDefs = alertDefinitionDao.findActiveAlertDefsGroupbyAlertExecutorId(site, dataSource); } catch (Exception ex) { LOG.error("fail to initialize initialAlertDefs: ", ex); throw new IllegalStateException("fail to initialize initialAlertDefs: ", ex); } if(initialAlertDefs == null || initialAlertDefs.isEmpty()){ LOG.warn("No alert definitions was found for site: " + site + ", dataSource: " + dataSource); } else if (initialAlertDefs.get(alertExecutorId) != null) { for(AlertDefinitionAPIEntity alertDef : initialAlertDefs.get(alertExecutorId).values()){ int part = partitioner.partition(numPartitions, alertDef.getTags().get(AlertConstants.POLICY_TYPE), alertDef.getTags().get(AlertConstants.POLICY_ID)); if (part == partitionSeq) { tmpPolicyEvaluators.put(alertDef.getTags().get(AlertConstants.POLICY_ID), createPolicyEvaluator(alertDef)); } } } policyEvaluators = new CopyOnWriteHashMap<>(); // for efficiency, we don't put single policy evaluator policyEvaluators.putAll(tmpPolicyEvaluators); DynamicPolicyLoader policyLoader = DynamicPolicyLoader.getInstance(); policyLoader.init(initialAlertDefs, alertDefinitionDao, config); String fullQualifiedAlertExecutorId = alertExecutorId + "_" + partitionSeq; policyLoader.addPolicyChangeListener(fullQualifiedAlertExecutorId, this); policyLoader.addPolicyDistributionReporter(fullQualifiedAlertExecutorId, this); LOG.info("Alert Executor created, partitionSeq: " + partitionSeq + " , numPartitions: " + numPartitions); LOG.info("All policy evaluators: " + policyEvaluators); initMetricReportor(); } /** * Create PolicyEvaluator instance according to policyType-mapped policy evaluator class * * @param alertDef alert definition * @return PolicyEvaluator instance */ private PolicyEvaluator createPolicyEvaluator(AlertDefinitionAPIEntity alertDef){ String policyType = alertDef.getTags().get(AlertConstants.POLICY_TYPE); Class<? extends PolicyEvaluator> evalCls = PolicyManager.getInstance().getPolicyEvaluator(policyType); if(evalCls == null){ String msg = "No policy evaluator defined for policy type : " + policyType; LOG.error(msg); throw new IllegalStateException(msg); } // check out whether strong incoming data validation is necessary String needValidationConfigKey= AlertConstants.ALERT_EXECUTOR_CONFIGS + "." + alertExecutorId + ".needValidation"; // Default: true boolean needValidation = !config.hasPath(needValidationConfigKey) || config.getBoolean(needValidationConfigKey); AbstractPolicyDefinition policyDef = null; try { policyDef = JsonSerDeserUtils.deserialize(alertDef.getPolicyDef(), AbstractPolicyDefinition.class, PolicyManager.getInstance().getPolicyModules(policyType)); } catch (Exception ex) { LOG.error("Fail initial alert policy def: "+alertDef.getPolicyDef(), ex); } PolicyEvaluator pe; try{ // Create evaluator instances pe = evalCls.getConstructor(Config.class, String.class, AbstractPolicyDefinition.class, String[].class, boolean.class).newInstance(config, alertDef.getTags().get("policyId"), policyDef, sourceStreams, needValidation); }catch(Exception ex){ LOG.error("Fail creating new policyEvaluator", ex); LOG.warn("Broken policy definition and stop running : " + alertDef.getPolicyDef()); throw new IllegalStateException(ex); } return pe; } /** * verify both alertExecutor logic name and partition id * @param alertDef alert definition * * @return whether accept the alert definition */ private boolean accept(AlertDefinitionAPIEntity alertDef){ if(!alertDef.getTags().get("alertExecutorId").equals(alertExecutorId)) { if(LOG.isDebugEnabled()){ LOG.debug("alertDef does not belong to this alertExecutorId : " + alertExecutorId + ", alertDef : " + alertDef); } return false; } int targetPartitionSeq = partitioner.partition(numPartitions, alertDef.getTags().get(AlertConstants.POLICY_TYPE), alertDef.getTags().get(AlertConstants.POLICY_ID)); if(targetPartitionSeq == partitionSeq) return true; return false; } public long trim(long value, long granularity) { return value / granularity * granularity; } public void updateCounter(String name, Map<String, String> dimensions, double value) { long current = System.currentTimeMillis(); String metricName = MetricKeyCodeDecoder.codeMetricKey(name, dimensions); if (registry.getMetrics().get(metricName) == null) { EagleCounterMetric metric = new EagleCounterMetric(current, metricName, value, MERITE_GRANULARITY); metric.registerListener(listener); registry.register(metricName, metric); } else { EagleCounterMetric metric = (EagleCounterMetric) registry.getMetrics().get(metricName); metric.update(value, current); //TODO: need remove unused metric from registry } } public void updateCounter(String name, Map<String, String> dimensions) { updateCounter(name, dimensions, 1.0); } public Map<String, String> getDimensions(String policyId) { if (dimensionsMap.get(policyId) == null) { Map<String, String> newDimensions = new HashMap<String, String>(baseDimensions); newDimensions.put(AlertConstants.POLICY_ID, policyId); dimensionsMap.put(policyId, newDimensions); } return dimensionsMap.get(policyId); } /** * within this single executor, execute all PolicyEvaluator sequentially * the contract for input: * 1. total # of fields for input is 3, which is fixed * 2. the first field is key * 3. the second field is stream name * 4. the third field is value which is java SortedMap */ @Override public void flatMap(java.util.List<Object> input, Collector<Tuple2<String, AlertAPIEntity>> outputCollector){ if(input.size() != 3) throw new IllegalStateException("AlertExecutor always consumes exactly 3 fields: key, stream name and value(SortedMap)"); if(LOG.isDebugEnabled()) LOG.debug("Msg is coming " + input.get(2)); if(LOG.isDebugEnabled()) LOG.debug("Current policyEvaluators: " + policyEvaluators.keySet().toString()); updateCounter(EAGLE_EVENT_COUNT, baseDimensions); try{ synchronized(this.policyEvaluators) { for(Entry<String, PolicyEvaluator> entry : policyEvaluators.entrySet()){ String policyId = entry.getKey(); PolicyEvaluator evaluator = entry.getValue(); updateCounter(EAGLE_POLICY_EVAL_COUNT, getDimensions(policyId)); try { EagleAlertContext siddhiAlertContext = new EagleAlertContext(); siddhiAlertContext.alertExecutor = this; siddhiAlertContext.policyId = policyId; siddhiAlertContext.evaluator = evaluator; siddhiAlertContext.outputCollector = outputCollector; evaluator.evaluate(new ValuesArray(siddhiAlertContext, input.get(1), input.get(2))); } catch (Exception ex) { LOG.error("Got an exception, but continue to run " + input.get(2).toString(), ex); updateCounter(EAGLE_POLICY_EVAL_FAIL_COUNT, getDimensions(policyId)); } } } } catch(Exception ex){ LOG.error(alertExecutorId + ", partition " + partitionSeq + ", error fetching alerts, but continue to run", ex); updateCounter(EAGLE_ALERT_FAIL_COUNT, baseDimensions); } } @Override public void onPolicyCreated(Map<String, AlertDefinitionAPIEntity> added) { if(LOG.isDebugEnabled()) LOG.debug(alertExecutorId + ", partition " + partitionSeq + " policy added : " + added + " policyEvaluators " + policyEvaluators); for(AlertDefinitionAPIEntity alertDef : added.values()){ if(!accept(alertDef)) continue; LOG.info(alertExecutorId + ", partition " + partitionSeq + " policy really added " + alertDef); PolicyEvaluator newEvaluator = createPolicyEvaluator(alertDef); if(newEvaluator != null){ synchronized(this.policyEvaluators) { policyEvaluators.put(alertDef.getTags().get(AlertConstants.POLICY_ID), newEvaluator); } } } } @Override public void onPolicyChanged(Map<String, AlertDefinitionAPIEntity> changed) { if(LOG.isDebugEnabled()) LOG.debug(alertExecutorId + ", partition " + partitionSeq + " policy changed : " + changed); for(AlertDefinitionAPIEntity alertDef : changed.values()){ if(!accept(alertDef)) continue; LOG.info(alertExecutorId + ", partition " + partitionSeq + " policy really changed " + alertDef); synchronized(this.policyEvaluators) { PolicyEvaluator pe = policyEvaluators.get(alertDef.getTags().get(AlertConstants.POLICY_ID)); pe.onPolicyUpdate(alertDef); } } } @Override public void onPolicyDeleted(Map<String, AlertDefinitionAPIEntity> deleted) { if(LOG.isDebugEnabled()) LOG.debug(alertExecutorId + ", partition " + partitionSeq + " policy deleted : " + deleted); for(AlertDefinitionAPIEntity alertDef : deleted.values()){ if(!accept(alertDef)) continue; LOG.info(alertExecutorId + ", partition " + partitionSeq + " policy really deleted " + alertDef); String policyId = alertDef.getTags().get(AlertConstants.POLICY_ID); synchronized(this.policyEvaluators) { if (policyEvaluators.containsKey(policyId)) { PolicyEvaluator pe = policyEvaluators.remove(alertDef.getTags().get(AlertConstants.POLICY_ID)); pe.onPolicyDelete(); } } } } @Override public void onAlerts(EagleAlertContext context, List<AlertAPIEntity> alerts) { if(alerts != null && !alerts.isEmpty()){ String policyId = context.policyId; LOG.info(String.format("Detected %s alerts for policy %s",alerts.size(),policyId)); Collector outputCollector = context.outputCollector; PolicyEvaluator evaluator = context.evaluator; updateCounter(EAGLE_ALERT_COUNT, getDimensions(policyId), alerts.size()); for (AlertAPIEntity entity : alerts) { synchronized(this) { outputCollector.collect(new Tuple2(policyId, entity)); } if(LOG.isDebugEnabled()) LOG.debug("A new alert is triggered: "+alertExecutorId + ", partition " + partitionSeq + ", Got an alert with output context: " + entity.getAlertContext() + ", for policy " + evaluator); } } } @Override public void report() { PolicyDistroStatsLogReporter appender = new PolicyDistroStatsLogReporter(); appender.reportPolicyMembership(alertExecutorId + "_" + partitionSeq, policyEvaluators.keySet()); } }
/* * 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.hyracks.algebricks.core.algebra.metadata; import java.util.List; import java.util.Map; import org.apache.hyracks.algebricks.common.constraints.AlgebricksPartitionConstraint; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.common.utils.Pair; import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression; import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable; import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment; import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import org.apache.hyracks.algebricks.core.algebra.functions.IFunctionInfo; import org.apache.hyracks.algebricks.core.algebra.operators.logical.IOperatorSchema; import org.apache.hyracks.algebricks.core.jobgen.impl.JobGenContext; import org.apache.hyracks.algebricks.data.IPrinterFactory; import org.apache.hyracks.algebricks.runtime.base.IPushRuntimeFactory; import org.apache.hyracks.api.dataflow.IOperatorDescriptor; import org.apache.hyracks.api.dataflow.value.RecordDescriptor; import org.apache.hyracks.api.job.JobSpecification; public interface IMetadataProvider<S, I> { public IDataSource<S> findDataSource(S id) throws AlgebricksException; /** * Obs: A scanner may choose to contribute a null * AlgebricksPartitionConstraint and implement * contributeSchedulingConstraints instead. */ public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getScannerRuntime(IDataSource<S> dataSource, List<LogicalVariable> scanVariables, List<LogicalVariable> projectVariables, boolean projectPushed, List<LogicalVariable> minFilterVars, List<LogicalVariable> maxFilterVars, IOperatorSchema opSchema, IVariableTypeEnvironment typeEnv, JobGenContext context, JobSpecification jobSpec, Object implConfig) throws AlgebricksException; public Pair<IPushRuntimeFactory, AlgebricksPartitionConstraint> getWriteFileRuntime(IDataSink sink, int[] printColumns, IPrinterFactory[] printerFactories, RecordDescriptor inputDesc) throws AlgebricksException; public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getResultHandleRuntime(IDataSink sink, int[] printColumns, IPrinterFactory[] printerFactories, RecordDescriptor inputDesc, boolean ordered, JobSpecification spec) throws AlgebricksException; public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getWriteResultRuntime(IDataSource<S> dataSource, IOperatorSchema propagatedSchema, List<LogicalVariable> keys, LogicalVariable payLoadVar, List<LogicalVariable> additionalNonKeyFields, JobGenContext context, JobSpecification jobSpec) throws AlgebricksException; public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getInsertRuntime(IDataSource<S> dataSource, IOperatorSchema propagatedSchema, IVariableTypeEnvironment typeEnv, List<LogicalVariable> keys, LogicalVariable payLoadVar, List<LogicalVariable> additionalFilterKeyFields, List<LogicalVariable> additionalNonFilteringFields, RecordDescriptor recordDesc, JobGenContext context, JobSpecification jobSpec, boolean bulkload) throws AlgebricksException; public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getDeleteRuntime(IDataSource<S> dataSource, IOperatorSchema propagatedSchema, IVariableTypeEnvironment typeEnv, List<LogicalVariable> keys, LogicalVariable payLoadVar, List<LogicalVariable> additionalNonKeyFields, RecordDescriptor recordDesc, JobGenContext context, JobSpecification jobSpec) throws AlgebricksException; /** * Creates the insert runtime of IndexInsertDeletePOperator, which models * insert/delete operations into a secondary index. * * @param dataSource * Target secondary index. * @param propagatedSchema * Output schema of the insert/delete operator to be created. * @param inputSchemas * Output schemas of the insert/delete operator to be created. * @param typeEnv * Type environment of the original IndexInsertDeleteOperator operator. * @param primaryKeys * Variables for the dataset's primary keys that the dataSource secondary index belongs to. * @param secondaryKeys * Variables for the secondary-index keys. * @param additionalNonKeyFields * Additional variables that can be passed to the secondary index as payload. * This can be useful when creating a second filter on a non-primary and non-secondary * fields for additional pruning power. * @param filterExpr * Filtering expression to be pushed inside the runtime op. * Such a filter may, e.g., exclude NULLs from being inserted/deleted. * @param recordDesc * Output record descriptor of the runtime op to be created. * @param context * Job generation context. * @param spec * Target job specification. * @return * A Hyracks IOperatorDescriptor and its partition constraint. * @throws AlgebricksException */ public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getIndexInsertRuntime( IDataSourceIndex<I, S> dataSource, IOperatorSchema propagatedSchema, IOperatorSchema[] inputSchemas, IVariableTypeEnvironment typeEnv, List<LogicalVariable> primaryKeys, List<LogicalVariable> secondaryKeys, List<LogicalVariable> additionalNonKeyFields, ILogicalExpression filterExpr, RecordDescriptor recordDesc, JobGenContext context, JobSpecification spec, boolean bulkload) throws AlgebricksException; /** * Creates the delete runtime of IndexInsertDeletePOperator, which models * insert/delete operations into a secondary index. * * @param dataSource * Target secondary index. * @param propagatedSchema * Output schema of the insert/delete operator to be created. * @param inputSchemas * Output schemas of the insert/delete operator to be created. * @param typeEnv * Type environment of the original IndexInsertDeleteOperator operator. * @param primaryKeys * Variables for the dataset's primary keys that the dataSource secondary index belongs to. * @param secondaryKeys * Variables for the secondary-index keys. * @param additionalNonKeyFields * Additional variables that can be passed to the secondary index as payload. * This can be useful when creating a second filter on a non-primary and non-secondary * fields for additional pruning power. * @param filterExpr * Filtering expression to be pushed inside the runtime op. * Such a filter may, e.g., exclude NULLs from being inserted/deleted. * @param recordDesc * Output record descriptor of the runtime op to be created. * @param context * Job generation context. * @param spec * Target job specification. * @return * A Hyracks IOperatorDescriptor and its partition constraint. * @throws AlgebricksException */ public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getIndexDeleteRuntime( IDataSourceIndex<I, S> dataSource, IOperatorSchema propagatedSchema, IOperatorSchema[] inputSchemas, IVariableTypeEnvironment typeEnv, List<LogicalVariable> primaryKeys, List<LogicalVariable> secondaryKeys, List<LogicalVariable> additionalNonKeyFields, ILogicalExpression filterExpr, RecordDescriptor recordDesc, JobGenContext context, JobSpecification spec) throws AlgebricksException; /** * Creates the TokenizeOperator for IndexInsertDeletePOperator, which tokenizes * secondary key into [token, number of token] pair in a length-partitioned index. * In case of non length-partitioned index, it tokenizes secondary key into [token]. * * @param dataSource * Target secondary index. * @param propagatedSchema * Output schema of the insert/delete operator to be created. * @param inputSchemas * Output schemas of the insert/delete operator to be created. * @param typeEnv * Type environment of the original IndexInsertDeleteOperator operator. * @param primaryKeys * Variables for the dataset's primary keys that the dataSource secondary index belongs to. * @param secondaryKeys * Variables for the secondary-index keys. * @param filterExpr * Filtering expression to be pushed inside the runtime op. * Such a filter may, e.g., exclude NULLs from being inserted/deleted. * @param recordDesc * Output record descriptor of the runtime op to be created. * @param context * Job generation context. * @param spec * Target job specification. * @return * A Hyracks IOperatorDescriptor and its partition constraint. * @throws AlgebricksException */ public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getTokenizerRuntime( IDataSourceIndex<I, S> dataSource, IOperatorSchema propagatedSchema, IOperatorSchema[] inputSchemas, IVariableTypeEnvironment typeEnv, List<LogicalVariable> primaryKeys, List<LogicalVariable> secondaryKeys, ILogicalExpression filterExpr, RecordDescriptor recordDesc, JobGenContext context, JobSpecification spec, boolean bulkload) throws AlgebricksException; public IDataSourceIndex<I, S> findDataSourceIndex(I indexId, S dataSourceId) throws AlgebricksException; public IFunctionInfo lookupFunction(FunctionIdentifier fid); public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getUpsertRuntime(IDataSource<S> dataSource, IOperatorSchema inputSchema, IVariableTypeEnvironment typeEnv, List<LogicalVariable> keys, LogicalVariable payLoadVar, List<LogicalVariable> additionalFilterFields, List<LogicalVariable> additionalNonFilteringFields, RecordDescriptor recordDesc, JobGenContext context, JobSpecification jobSpec) throws AlgebricksException; public Pair<IOperatorDescriptor, AlgebricksPartitionConstraint> getIndexUpsertRuntime( IDataSourceIndex<I, S> dataSourceIndex, IOperatorSchema propagatedSchema, IOperatorSchema[] inputSchemas, IVariableTypeEnvironment typeEnv, List<LogicalVariable> primaryKeys, List<LogicalVariable> secondaryKeys, List<LogicalVariable> additionalFilteringKeys, ILogicalExpression filterExpr, List<LogicalVariable> prevSecondaryKeys, LogicalVariable prevAdditionalFilteringKeys, RecordDescriptor inputDesc, JobGenContext context, JobSpecification spec) throws AlgebricksException; public Map<String, String> getConfig(); }
/* * 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.processors.hadoop.taskexecutor.external.child; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.hadoop.HadoopCommonUtils; import org.apache.ignite.internal.processors.hadoop.HadoopHelperImpl; import org.apache.ignite.internal.processors.hadoop.HadoopJobEx; import org.apache.ignite.internal.processors.hadoop.HadoopTaskContext; import org.apache.ignite.internal.processors.hadoop.HadoopTaskInfo; import org.apache.ignite.internal.processors.hadoop.HadoopTaskInput; import org.apache.ignite.internal.processors.hadoop.HadoopTaskOutput; import org.apache.ignite.internal.processors.hadoop.message.HadoopMessage; import org.apache.ignite.internal.processors.hadoop.shuffle.HadoopShuffleAck; import org.apache.ignite.internal.processors.hadoop.shuffle.HadoopShuffleJob; import org.apache.ignite.internal.processors.hadoop.shuffle.HadoopShuffleMessage; import org.apache.ignite.internal.processors.hadoop.taskexecutor.HadoopExecutorService; import org.apache.ignite.internal.processors.hadoop.taskexecutor.HadoopRunnableTask; import org.apache.ignite.internal.processors.hadoop.taskexecutor.HadoopTaskState; import org.apache.ignite.internal.processors.hadoop.taskexecutor.HadoopTaskStatus; import org.apache.ignite.internal.processors.hadoop.taskexecutor.external.HadoopJobInfoUpdateRequest; import org.apache.ignite.internal.processors.hadoop.taskexecutor.external.HadoopPrepareForJobRequest; import org.apache.ignite.internal.processors.hadoop.taskexecutor.external.HadoopProcessDescriptor; import org.apache.ignite.internal.processors.hadoop.taskexecutor.external.HadoopProcessStartedAck; import org.apache.ignite.internal.processors.hadoop.taskexecutor.external.HadoopTaskExecutionRequest; import org.apache.ignite.internal.processors.hadoop.taskexecutor.external.HadoopTaskFinishedMessage; import org.apache.ignite.internal.processors.hadoop.taskexecutor.external.communication.HadoopExternalCommunication; import org.apache.ignite.internal.processors.hadoop.taskexecutor.external.communication.HadoopMessageListener; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.lang.IgniteInClosure2X; import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMemory; import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.U; import static org.apache.ignite.internal.processors.hadoop.HadoopTaskType.MAP; import static org.apache.ignite.internal.processors.hadoop.HadoopTaskType.REDUCE; /** * Hadoop process base. */ @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") public class HadoopChildProcessRunner { /** Node process descriptor. */ private HadoopProcessDescriptor nodeDesc; /** Message processing executor service. */ private ExecutorService msgExecSvc; /** Task executor service. */ private HadoopExecutorService execSvc; /** */ protected GridUnsafeMemory mem = new GridUnsafeMemory(0); /** External communication. */ private HadoopExternalCommunication comm; /** Logger. */ private IgniteLogger log; /** Init guard. */ private final AtomicBoolean initGuard = new AtomicBoolean(); /** Start time. */ private long startTime; /** Init future. */ private final GridFutureAdapter<?> initFut = new GridFutureAdapter<>(); /** Job instance. */ private HadoopJobEx job; /** Number of uncompleted tasks. */ private final AtomicInteger pendingTasks = new AtomicInteger(); /** Shuffle job. */ private HadoopShuffleJob<HadoopProcessDescriptor> shuffleJob; /** Concurrent mappers. */ private int concMappers; /** Concurrent reducers. */ private int concReducers; /** * Starts child process runner. */ public void start(HadoopExternalCommunication comm, HadoopProcessDescriptor nodeDesc, ExecutorService msgExecSvc, IgniteLogger parentLog) throws IgniteCheckedException { this.comm = comm; this.nodeDesc = nodeDesc; this.msgExecSvc = msgExecSvc; comm.setListener(new MessageListener()); log = parentLog.getLogger(HadoopChildProcessRunner.class); startTime = U.currentTimeMillis(); // At this point node knows that this process has started. comm.sendMessage(this.nodeDesc, new HadoopProcessStartedAck()); } /** * Initializes process for task execution. * * @param req Initialization request. */ @SuppressWarnings("unchecked") private void prepareProcess(HadoopPrepareForJobRequest req) { if (initGuard.compareAndSet(false, true)) { try { if (log.isDebugEnabled()) log.debug("Initializing external hadoop task: " + req); assert job == null; Class jobCls; try { jobCls = Class.forName(HadoopCommonUtils.JOB_CLS_NAME); } catch (ClassNotFoundException e) { throw new IgniteException("Failed to load job class: " + HadoopCommonUtils.JOB_CLS_NAME, e); } job = req.jobInfo().createJob(jobCls, req.jobId(), log, null, new HadoopHelperImpl()); job.initialize(true, nodeDesc.processId()); shuffleJob = new HadoopShuffleJob<>(comm.localProcessDescriptor(), log, job, mem, req.totalReducerCount(), req.localReducers(), 0, false); initializeExecutors(); if (log.isDebugEnabled()) log.debug("External process initialized [initWaitTime=" + (U.currentTimeMillis() - startTime) + ']'); initFut.onDone(); } catch (IgniteCheckedException e) { U.error(log, "Failed to initialize process: " + req, e); initFut.onDone(e); } } else log.warning("Duplicate initialize process request received (will ignore): " + req); } /** * @param req Task execution request. */ private void runTasks(final HadoopTaskExecutionRequest req) { if (!initFut.isDone() && log.isDebugEnabled()) log.debug("Will wait for process initialization future completion: " + req); initFut.listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> f) { try { // Make sure init was successful. f.get(); boolean set = pendingTasks.compareAndSet(0, req.tasks().size()); assert set; HadoopTaskInfo info = F.first(req.tasks()); assert info != null; int size = info.type() == MAP ? concMappers : concReducers; // execSvc.setCorePoolSize(size); // execSvc.setMaximumPoolSize(size); if (log.isDebugEnabled()) log.debug("Set executor service size for task type [type=" + info.type() + ", size=" + size + ']'); for (HadoopTaskInfo taskInfo : req.tasks()) { if (log.isDebugEnabled()) log.debug("Submitted task for external execution: " + taskInfo); execSvc.submit(new HadoopRunnableTask(log, job, mem, taskInfo, nodeDesc.parentNodeId()) { @Override protected void onTaskFinished(HadoopTaskStatus status) { onTaskFinished0(this, status); } @Override protected HadoopTaskInput createInput(HadoopTaskContext ctx) throws IgniteCheckedException { return shuffleJob.input(ctx); } @Override protected HadoopTaskOutput createOutput(HadoopTaskContext ctx) throws IgniteCheckedException { return shuffleJob.output(ctx); } }); } } catch (IgniteCheckedException e) { for (HadoopTaskInfo info : req.tasks()) notifyTaskFinished(info, new HadoopTaskStatus(HadoopTaskState.FAILED, e), false); } } }); } /** * Creates executor services. * */ private void initializeExecutors() { int cpus = Runtime.getRuntime().availableProcessors(); execSvc = new HadoopExecutorService(log, "", cpus * 2, 1024); } /** * Updates external process map so that shuffle can proceed with sending messages to reducers. * * @param req Update request. */ private void updateTasks(final HadoopJobInfoUpdateRequest req) { initFut.listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> gridFut) { assert initGuard.get(); assert req.jobId().equals(job.id()); if (req.reducersAddresses() != null) { if (shuffleJob.initializeReduceAddresses(req.reducersAddresses())) { shuffleJob.startSending("external", new IgniteInClosure2X<HadoopProcessDescriptor, HadoopMessage>() { @Override public void applyx(HadoopProcessDescriptor dest, HadoopMessage msg) throws IgniteCheckedException { comm.sendMessage(dest, msg); } }); } } } }); } /** * Stops all executors and running tasks. */ private void shutdown() { if (execSvc != null) execSvc.shutdown(5000); if (msgExecSvc != null) msgExecSvc.shutdownNow(); try { job.dispose(true); } catch (IgniteCheckedException e) { U.error(log, "Failed to dispose job.", e); } } /** * Notifies node about task finish. * * @param run Finished task runnable. * @param status Task status. */ private void onTaskFinished0(HadoopRunnableTask run, HadoopTaskStatus status) { HadoopTaskInfo info = run.taskInfo(); int pendingTasks0 = pendingTasks.decrementAndGet(); if (log.isDebugEnabled()) log.debug("Hadoop task execution finished [info=" + info + ", state=" + status.state() + ", waitTime=" + run.waitTime() + ", execTime=" + run.executionTime() + ", pendingTasks=" + pendingTasks0 + ", err=" + status.failCause() + ']'); assert info.type() == MAP || info.type() == REDUCE : "Only MAP or REDUCE tasks are supported."; boolean flush = pendingTasks0 == 0 && info.type() == MAP; notifyTaskFinished(info, status, flush); } /** * @param taskInfo Finished task info. * @param status Task status. */ private void notifyTaskFinished(final HadoopTaskInfo taskInfo, final HadoopTaskStatus status, boolean flush) { final HadoopTaskState state = status.state(); final Throwable err = status.failCause(); if (!flush) { try { if (log.isDebugEnabled()) log.debug("Sending notification to parent node [taskInfo=" + taskInfo + ", state=" + state + ", err=" + err + ']'); comm.sendMessage(nodeDesc, new HadoopTaskFinishedMessage(taskInfo, status)); } catch (IgniteCheckedException e) { log.error("Failed to send message to parent node (will terminate child process).", e); shutdown(); terminate(); } } else { if (log.isDebugEnabled()) log.debug("Flushing shuffle messages before sending last task completion notification [taskInfo=" + taskInfo + ", state=" + state + ", err=" + err + ']'); final long start = U.currentTimeMillis(); try { shuffleJob.flush().listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> f) { long end = U.currentTimeMillis(); if (log.isDebugEnabled()) log.debug("Finished flushing shuffle messages [taskInfo=" + taskInfo + ", flushTime=" + (end - start) + ']'); try { // Check for errors on shuffle. f.get(); notifyTaskFinished(taskInfo, status, false); } catch (IgniteCheckedException e) { log.error("Failed to flush shuffle messages (will fail the task) [taskInfo=" + taskInfo + ", state=" + state + ", err=" + err + ']', e); notifyTaskFinished(taskInfo, new HadoopTaskStatus(HadoopTaskState.FAILED, e), false); } } }); } catch (IgniteCheckedException e) { log.error("Failed to flush shuffle messages (will fail the task) [taskInfo=" + taskInfo + ", state=" + state + ", err=" + err + ']', e); notifyTaskFinished(taskInfo, new HadoopTaskStatus(HadoopTaskState.FAILED, e), false); } } } /** * Checks if message was received from parent node and prints warning if not. * * @param desc Sender process ID. * @param msg Received message. * @return {@code True} if received from parent node. */ private boolean validateNodeMessage(HadoopProcessDescriptor desc, HadoopMessage msg) { if (!nodeDesc.processId().equals(desc.processId())) { log.warning("Received process control request from unknown process (will ignore) [desc=" + desc + ", msg=" + msg + ']'); return false; } return true; } /** * Stops execution of this process. */ private void terminate() { System.exit(1); } /** * Message listener. */ private class MessageListener implements HadoopMessageListener { /** {@inheritDoc} */ @Override public void onMessageReceived(final HadoopProcessDescriptor desc, final HadoopMessage msg) { if (msg instanceof HadoopTaskExecutionRequest) { if (validateNodeMessage(desc, msg)) runTasks((HadoopTaskExecutionRequest)msg); } else if (msg instanceof HadoopJobInfoUpdateRequest) { if (validateNodeMessage(desc, msg)) updateTasks((HadoopJobInfoUpdateRequest)msg); } else if (msg instanceof HadoopPrepareForJobRequest) { if (validateNodeMessage(desc, msg)) prepareProcess((HadoopPrepareForJobRequest)msg); } else if (msg instanceof HadoopShuffleMessage) { if (log.isTraceEnabled()) log.trace("Received shuffle message [desc=" + desc + ", msg=" + msg + ']'); initFut.listen(new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> f) { try { HadoopShuffleMessage m = (HadoopShuffleMessage)msg; shuffleJob.onShuffleMessage(desc, m); } catch (IgniteCheckedException e) { U.error(log, "Failed to process hadoop shuffle message [desc=" + desc + ", msg=" + msg + ']', e); } } }); } else if (msg instanceof HadoopShuffleAck) { if (log.isTraceEnabled()) log.trace("Received shuffle ack [desc=" + desc + ", msg=" + msg + ']'); shuffleJob.onShuffleAck((HadoopShuffleAck)msg); } else log.warning("Unknown message received (will ignore) [desc=" + desc + ", msg=" + msg + ']'); } /** {@inheritDoc} */ @Override public void onConnectionLost(HadoopProcessDescriptor desc) { if (log.isDebugEnabled()) log.debug("Lost connection with remote process: " + desc); if (desc == null) U.warn(log, "Handshake failed."); else if (desc.processId().equals(nodeDesc.processId())) { log.warning("Child process lost connection with parent node (will terminate child process)."); shutdown(); terminate(); } } } }
package graphene.model.extracted; import java.util.HashMap; import java.util.Map; public class ExtractedData { private Map<String, String[]> metadata; private String absolutePath; private String containingPath; private String md5Hash; private String filename; private String encodedFile; private String extractionDateISO; private String fileExtension; private Map<String, Object> customMetadata; private long extractionDateMillis; /** * Something like Excel files, or PDFs or 'Files From USB' */ private String documentClass; /** * The entirety of the non meta-data that was able to be extracted with * Tika, etc. */ private String body; /** * A place for text about the file that the integrator can supply. */ private String note; public ExtractedData() { // TODO Auto-generated constructor stub } public ExtractedData(final long millis, final String dateISO) { extractionDateISO = dateISO; extractionDateMillis = millis; customMetadata = new HashMap<String, Object>(); metadata = new HashMap<String, String[]>(10); } /** * @return the absolutePath */ public String getAbsolutePath() { return absolutePath; } public String getBody() { return body; } /** * @return the containingPath */ public String getContainingPath() { return containingPath; } /** * @return the customMetadata */ public Map<String, Object> getCustomMetadata() { return customMetadata; } /** * @return the documentClass */ public String getDocumentClass() { return documentClass; } /** * @return the encodedFile */ public String getEncodedFile() { return encodedFile; } /** * @return the extractionDateISO */ public String getExtractionDateISO() { return extractionDateISO; } /** * @return the extractionDateMillis */ public long getExtractionDateMillis() { return extractionDateMillis; } /** * @return the fileExtension */ public String getFileExtension() { return fileExtension; } /** * @return the filename */ public String getFilename() { return filename; } /** * @return the md5Hash */ public String getMd5Hash() { return md5Hash; } /** * @return the metadata */ public Map<String, String[]> getMetadata() { return metadata; } /** * @return the note */ public String getNote() { return note; } /** * @param absolutePath * the absolutePath to set */ public void setAbsolutePath(final String absolutePath) { this.absolutePath = absolutePath; } public void setBody(final String body) { this.body = body; } /** * @param containingPath * the containingPath to set */ public void setContainingPath(final String containingPath) { this.containingPath = containingPath; } /** * @param customMetadata * the customMetadata to set */ public void setCustomMetadata(final Map<String, Object> customMetadata) { this.customMetadata = customMetadata; } /** * @param documentClass * the documentClass to set */ public void setDocumentClass(final String documentClass) { this.documentClass = documentClass; } /** * @param encodedFile * the encodedFile to set */ public void setEncodedFile(final String encodedFile) { this.encodedFile = encodedFile; } /** * @param extractionDateISO * the extractionDateISO to set */ public void setExtractionDateISO(final String extractionDateISO) { this.extractionDateISO = extractionDateISO; } /** * @param extractionDateMillis * the extractionDateMillis to set */ public void setExtractionDateMillis(final long extractionDateMillis) { this.extractionDateMillis = extractionDateMillis; } /** * @param fileExtension * the fileExtension to set */ public void setFileExtension(final String fileExtension) { this.fileExtension = fileExtension; } /** * @param filename * the filename to set */ public void setFilename(final String filename) { this.filename = filename; } /** * @param md5Hash * the md5Hash to set */ public void setMd5Hash(final String md5Hash) { this.md5Hash = md5Hash; } /** * @param metadata * the metadata to set */ public void setMetadata(final Map<String, String[]> metadata) { this.metadata = metadata; } /** * @param note * the note to set */ public void setNote(final String note) { this.note = note; } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.recoveryservices.v2016_06_01.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.CloudException; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.Validator; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.PATCH; import retrofit2.http.Path; import retrofit2.http.PUT; import retrofit2.http.Query; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in VaultExtendedInfos. */ public class VaultExtendedInfosInner { /** The Retrofit service to perform REST calls. */ private VaultExtendedInfosService service; /** The service client containing this operation class. */ private RecoveryServicesClientImpl client; /** * Initializes an instance of VaultExtendedInfosInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public VaultExtendedInfosInner(Retrofit retrofit, RecoveryServicesClientImpl client) { this.service = retrofit.create(VaultExtendedInfosService.class); this.client = client; } /** * The interface defining all the services for VaultExtendedInfos to be * used by Retrofit to perform actually REST calls. */ interface VaultExtendedInfosService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.v2016_06_01.VaultExtendedInfos get" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/extendedInformation/vaultExtendedInfo") Observable<Response<ResponseBody>> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.v2016_06_01.VaultExtendedInfos createOrUpdate" }) @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/extendedInformation/vaultExtendedInfo") Observable<Response<ResponseBody>> createOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Query("api-version") String apiVersion, @Body VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.v2016_06_01.VaultExtendedInfos update" }) @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/extendedInformation/vaultExtendedInfo") Observable<Response<ResponseBody>> update(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Query("api-version") String apiVersion, @Body VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Get the vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VaultExtendedInfoResourceInner object if successful. */ public VaultExtendedInfoResourceInner get(String resourceGroupName, String vaultName) { return getWithServiceResponseAsync(resourceGroupName, vaultName).toBlocking().single().body(); } /** * Get the vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VaultExtendedInfoResourceInner> getAsync(String resourceGroupName, String vaultName, final ServiceCallback<VaultExtendedInfoResourceInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, vaultName), serviceCallback); } /** * Get the vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VaultExtendedInfoResourceInner object */ public Observable<VaultExtendedInfoResourceInner> getAsync(String resourceGroupName, String vaultName) { return getWithServiceResponseAsync(resourceGroupName, vaultName).map(new Func1<ServiceResponse<VaultExtendedInfoResourceInner>, VaultExtendedInfoResourceInner>() { @Override public VaultExtendedInfoResourceInner call(ServiceResponse<VaultExtendedInfoResourceInner> response) { return response.body(); } }); } /** * Get the vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VaultExtendedInfoResourceInner object */ public Observable<ServiceResponse<VaultExtendedInfoResourceInner>> getWithServiceResponseAsync(String resourceGroupName, String vaultName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (vaultName == null) { throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.get(this.client.subscriptionId(), resourceGroupName, vaultName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VaultExtendedInfoResourceInner>>>() { @Override public Observable<ServiceResponse<VaultExtendedInfoResourceInner>> call(Response<ResponseBody> response) { try { ServiceResponse<VaultExtendedInfoResourceInner> clientResponse = getDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<VaultExtendedInfoResourceInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<VaultExtendedInfoResourceInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<VaultExtendedInfoResourceInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Create vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @param resourceResourceExtendedInfoDetails Details of ResourceExtendedInfo * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VaultExtendedInfoResourceInner object if successful. */ public VaultExtendedInfoResourceInner createOrUpdate(String resourceGroupName, String vaultName, VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, resourceResourceExtendedInfoDetails).toBlocking().single().body(); } /** * Create vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @param resourceResourceExtendedInfoDetails Details of ResourceExtendedInfo * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VaultExtendedInfoResourceInner> createOrUpdateAsync(String resourceGroupName, String vaultName, VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails, final ServiceCallback<VaultExtendedInfoResourceInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, resourceResourceExtendedInfoDetails), serviceCallback); } /** * Create vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @param resourceResourceExtendedInfoDetails Details of ResourceExtendedInfo * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VaultExtendedInfoResourceInner object */ public Observable<VaultExtendedInfoResourceInner> createOrUpdateAsync(String resourceGroupName, String vaultName, VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, resourceResourceExtendedInfoDetails).map(new Func1<ServiceResponse<VaultExtendedInfoResourceInner>, VaultExtendedInfoResourceInner>() { @Override public VaultExtendedInfoResourceInner call(ServiceResponse<VaultExtendedInfoResourceInner> response) { return response.body(); } }); } /** * Create vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @param resourceResourceExtendedInfoDetails Details of ResourceExtendedInfo * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VaultExtendedInfoResourceInner object */ public Observable<ServiceResponse<VaultExtendedInfoResourceInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String vaultName, VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (vaultName == null) { throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (resourceResourceExtendedInfoDetails == null) { throw new IllegalArgumentException("Parameter resourceResourceExtendedInfoDetails is required and cannot be null."); } Validator.validate(resourceResourceExtendedInfoDetails); return service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, vaultName, this.client.apiVersion(), resourceResourceExtendedInfoDetails, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VaultExtendedInfoResourceInner>>>() { @Override public Observable<ServiceResponse<VaultExtendedInfoResourceInner>> call(Response<ResponseBody> response) { try { ServiceResponse<VaultExtendedInfoResourceInner> clientResponse = createOrUpdateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<VaultExtendedInfoResourceInner> createOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<VaultExtendedInfoResourceInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<VaultExtendedInfoResourceInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Update vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @param resourceResourceExtendedInfoDetails Details of ResourceExtendedInfo * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VaultExtendedInfoResourceInner object if successful. */ public VaultExtendedInfoResourceInner update(String resourceGroupName, String vaultName, VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails) { return updateWithServiceResponseAsync(resourceGroupName, vaultName, resourceResourceExtendedInfoDetails).toBlocking().single().body(); } /** * Update vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @param resourceResourceExtendedInfoDetails Details of ResourceExtendedInfo * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VaultExtendedInfoResourceInner> updateAsync(String resourceGroupName, String vaultName, VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails, final ServiceCallback<VaultExtendedInfoResourceInner> serviceCallback) { return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, vaultName, resourceResourceExtendedInfoDetails), serviceCallback); } /** * Update vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @param resourceResourceExtendedInfoDetails Details of ResourceExtendedInfo * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VaultExtendedInfoResourceInner object */ public Observable<VaultExtendedInfoResourceInner> updateAsync(String resourceGroupName, String vaultName, VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails) { return updateWithServiceResponseAsync(resourceGroupName, vaultName, resourceResourceExtendedInfoDetails).map(new Func1<ServiceResponse<VaultExtendedInfoResourceInner>, VaultExtendedInfoResourceInner>() { @Override public VaultExtendedInfoResourceInner call(ServiceResponse<VaultExtendedInfoResourceInner> response) { return response.body(); } }); } /** * Update vault extended info. * * @param resourceGroupName The name of the resource group where the recovery services vault is present. * @param vaultName The name of the recovery services vault. * @param resourceResourceExtendedInfoDetails Details of ResourceExtendedInfo * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VaultExtendedInfoResourceInner object */ public Observable<ServiceResponse<VaultExtendedInfoResourceInner>> updateWithServiceResponseAsync(String resourceGroupName, String vaultName, VaultExtendedInfoResourceInner resourceResourceExtendedInfoDetails) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (vaultName == null) { throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (resourceResourceExtendedInfoDetails == null) { throw new IllegalArgumentException("Parameter resourceResourceExtendedInfoDetails is required and cannot be null."); } Validator.validate(resourceResourceExtendedInfoDetails); return service.update(this.client.subscriptionId(), resourceGroupName, vaultName, this.client.apiVersion(), resourceResourceExtendedInfoDetails, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VaultExtendedInfoResourceInner>>>() { @Override public Observable<ServiceResponse<VaultExtendedInfoResourceInner>> call(Response<ResponseBody> response) { try { ServiceResponse<VaultExtendedInfoResourceInner> clientResponse = updateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<VaultExtendedInfoResourceInner> updateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<VaultExtendedInfoResourceInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<VaultExtendedInfoResourceInner>() { }.getType()) .registerError(CloudException.class) .build(response); } }
/* * 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.asterix.app.replication; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import org.apache.asterix.app.nc.task.BindMetadataNodeTask; import org.apache.asterix.app.nc.task.CheckpointTask; import org.apache.asterix.app.nc.task.ExternalLibrarySetupTask; import org.apache.asterix.app.nc.task.LocalRecoveryTask; import org.apache.asterix.app.nc.task.MetadataBootstrapTask; import org.apache.asterix.app.nc.task.RemoteRecoveryTask; import org.apache.asterix.app.nc.task.ReportMaxResourceIdTask; import org.apache.asterix.app.nc.task.StartLifecycleComponentsTask; import org.apache.asterix.app.nc.task.StartReplicationServiceTask; import org.apache.asterix.app.replication.message.NCLifecycleTaskReportMessage; import org.apache.asterix.app.replication.message.ReplayPartitionLogsRequestMessage; import org.apache.asterix.app.replication.message.ReplayPartitionLogsResponseMessage; import org.apache.asterix.app.replication.message.StartupTaskRequestMessage; import org.apache.asterix.app.replication.message.StartupTaskResponseMessage; import org.apache.asterix.common.api.INCLifecycleTask; import org.apache.asterix.common.cluster.ClusterPartition; import org.apache.asterix.common.cluster.IClusterStateManager; import org.apache.asterix.common.exceptions.ExceptionUtils; import org.apache.asterix.common.messaging.api.ICCMessageBroker; import org.apache.asterix.common.replication.IFaultToleranceStrategy; import org.apache.asterix.common.replication.INCLifecycleMessage; import org.apache.asterix.common.replication.IReplicationStrategy; import org.apache.asterix.common.replication.Replica; import org.apache.asterix.common.transactions.IRecoveryManager.SystemState; import org.apache.asterix.runtime.utils.AppContextInfo; import org.apache.asterix.util.FaultToleranceUtil; import org.apache.hyracks.api.application.IClusterLifecycleListener.ClusterEventType; import org.apache.hyracks.api.exceptions.HyracksDataException; public class MetadataNodeFaultToleranceStrategy implements IFaultToleranceStrategy { private static final Logger LOGGER = Logger.getLogger(MetadataNodeFaultToleranceStrategy.class.getName()); private IClusterStateManager clusterManager; private String metadataNodeId; private IReplicationStrategy replicationStrategy; private ICCMessageBroker messageBroker; private final Set<String> hotStandbyMetadataReplica = new HashSet<>(); private final Set<String> failedNodes = new HashSet<>(); private Set<String> pendingStartupCompletionNodes = new HashSet<>(); @Override public synchronized void notifyNodeJoin(String nodeId) throws HyracksDataException { pendingStartupCompletionNodes.add(nodeId); } @Override public synchronized void notifyNodeFailure(String nodeId) throws HyracksDataException { failedNodes.add(nodeId); hotStandbyMetadataReplica.remove(nodeId); clusterManager.updateNodePartitions(nodeId, false); if (nodeId.equals(metadataNodeId)) { clusterManager.updateMetadataNode(metadataNodeId, false); } clusterManager.refreshState(); if (replicationStrategy.isParticipant(nodeId)) { // Notify impacted replica FaultToleranceUtil.notifyImpactedReplicas(nodeId, ClusterEventType.NODE_FAILURE, clusterManager, messageBroker, replicationStrategy); } // If the failed node is the metadata node, ask its replicas to replay any committed jobs if (nodeId.equals(metadataNodeId)) { int metadataPartitionId = AppContextInfo.INSTANCE.getMetadataProperties().getMetadataPartition() .getPartitionId(); Set<Integer> metadataPartition = new HashSet<>(Arrays.asList(metadataPartitionId)); Set<Replica> activeRemoteReplicas = replicationStrategy.getRemoteReplicas(metadataNodeId).stream() .filter(replica -> !failedNodes.contains(replica.getId())).collect(Collectors.toSet()); //TODO Do election to identity the node with latest state for (Replica replica : activeRemoteReplicas) { ReplayPartitionLogsRequestMessage msg = new ReplayPartitionLogsRequestMessage(metadataPartition); try { messageBroker.sendApplicationMessageToNC(msg, replica.getId()); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed sending an application message to an NC", e); continue; } } } } @Override public IFaultToleranceStrategy from(IReplicationStrategy replicationStrategy, ICCMessageBroker messageBroker) { MetadataNodeFaultToleranceStrategy ft = new MetadataNodeFaultToleranceStrategy(); ft.replicationStrategy = replicationStrategy; ft.messageBroker = messageBroker; return ft; } @Override public synchronized void process(INCLifecycleMessage message) throws HyracksDataException { switch (message.getType()) { case STARTUP_TASK_REQUEST: process((StartupTaskRequestMessage) message); break; case STARTUP_TASK_RESULT: process((NCLifecycleTaskReportMessage) message); break; case REPLAY_LOGS_RESPONSE: process((ReplayPartitionLogsResponseMessage) message); break; default: throw new HyracksDataException("Unsupported message type: " + message.getType().name()); } } @Override public synchronized void bindTo(IClusterStateManager clusterManager) { this.clusterManager = clusterManager; this.metadataNodeId = clusterManager.getCurrentMetadataNodeId(); } private synchronized void process(ReplayPartitionLogsResponseMessage msg) { hotStandbyMetadataReplica.add(msg.getNodeId()); LOGGER.log(Level.INFO, "Hot Standby Metadata Replicas: " + hotStandbyMetadataReplica); } private synchronized void process(StartupTaskRequestMessage msg) throws HyracksDataException { final String nodeId = msg.getNodeId(); final SystemState state = msg.getState(); final boolean isParticipant = replicationStrategy.isParticipant(nodeId); List<INCLifecycleTask> tasks; if (!isParticipant) { tasks = buildNonParticipantStartupSequence(nodeId, state); } else { tasks = buildParticipantStartupSequence(nodeId, state); } StartupTaskResponseMessage response = new StartupTaskResponseMessage(nodeId, tasks); try { messageBroker.sendApplicationMessageToNC(response, msg.getNodeId()); } catch (Exception e) { throw ExceptionUtils.convertToHyracksDataException(e); } } private synchronized void process(NCLifecycleTaskReportMessage msg) throws HyracksDataException { final String nodeId = msg.getNodeId(); pendingStartupCompletionNodes.remove(nodeId); if (msg.isSuccess()) { // If this node failed and recovered, notify impacted replicas to reconnect to it if (replicationStrategy.isParticipant(nodeId) && failedNodes.remove(nodeId)) { FaultToleranceUtil.notifyImpactedReplicas(nodeId, ClusterEventType.NODE_JOIN, clusterManager, messageBroker, replicationStrategy); } clusterManager.updateNodePartitions(msg.getNodeId(), true); if (msg.getNodeId().equals(metadataNodeId)) { clusterManager.updateMetadataNode(metadataNodeId, true); // When metadata node is active, it is the only hot standby replica hotStandbyMetadataReplica.clear(); hotStandbyMetadataReplica.add(metadataNodeId); } clusterManager.refreshState(); } else { LOGGER.log(Level.SEVERE, msg.getNodeId() + " failed to complete startup. ", msg.getException()); } } private List<INCLifecycleTask> buildNonParticipantStartupSequence(String nodeId, SystemState state) { final List<INCLifecycleTask> tasks = new ArrayList<>(); if (state == SystemState.CORRUPTED) { //need to perform local recovery for node partitions LocalRecoveryTask rt = new LocalRecoveryTask(Arrays.asList(clusterManager.getNodePartitions(nodeId)) .stream().map(ClusterPartition::getPartitionId).collect(Collectors.toSet())); tasks.add(rt); } tasks.add(new ExternalLibrarySetupTask(false)); tasks.add(new ReportMaxResourceIdTask()); tasks.add(new CheckpointTask()); tasks.add(new StartLifecycleComponentsTask()); return tasks; } private List<INCLifecycleTask> buildParticipantStartupSequence(String nodeId, SystemState state) { final List<INCLifecycleTask> tasks = new ArrayList<>(); switch (state) { case NEW_UNIVERSE: // If the metadata node (or replica) failed and lost its data // => Metadata Remote Recovery from standby replica tasks.add(getMetadataPartitionRecoveryPlan()); // Checkpoint after remote recovery to move node to HEALTHY state tasks.add(new CheckpointTask()); break; case CORRUPTED: // If the metadata node (or replica) failed and started again without losing data => Local Recovery LocalRecoveryTask rt = new LocalRecoveryTask(Arrays.asList(clusterManager.getNodePartitions(nodeId)) .stream().map(ClusterPartition::getPartitionId).collect(Collectors.toSet())); tasks.add(rt); break; case INITIAL_RUN: case HEALTHY: case RECOVERING: break; default: break; } tasks.add(new StartReplicationServiceTask()); final boolean isMetadataNode = nodeId.equals(metadataNodeId); if (isMetadataNode) { tasks.add(new MetadataBootstrapTask()); } tasks.add(new ExternalLibrarySetupTask(isMetadataNode)); tasks.add(new ReportMaxResourceIdTask()); tasks.add(new CheckpointTask()); tasks.add(new StartLifecycleComponentsTask()); if (isMetadataNode) { tasks.add(new BindMetadataNodeTask(true)); } return tasks; } private RemoteRecoveryTask getMetadataPartitionRecoveryPlan() { if (hotStandbyMetadataReplica.isEmpty()) { throw new IllegalStateException("No metadata replicas to recover from"); } // Construct recovery plan: Node => Set of partitions to recover from it Map<String, Set<Integer>> recoveryPlan = new HashMap<>(); // Recover metadata partition from any metadata hot standby replica int metadataPartitionId = AppContextInfo.INSTANCE.getMetadataProperties().getMetadataPartition() .getPartitionId(); Set<Integer> metadataPartition = new HashSet<>(Arrays.asList(metadataPartitionId)); recoveryPlan.put(hotStandbyMetadataReplica.iterator().next(), metadataPartition); return new RemoteRecoveryTask(recoveryPlan); } }
package com.greenpepper.runner.repository; import com.greenpepper.document.Document; import com.greenpepper.repository.DocumentRepository; import static com.greenpepper.util.CollectionUtil.toVector; import com.greenpepper.util.TestCase; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.xmlrpc.WebServer; import org.apache.xmlrpc.XmlRpcException; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; import java.util.Vector; public class GreenPepperRepositoryTest extends TestCase { private static WebServer ws; private Mockery context = new JUnit4Mockery(); private Handler handler; private String dummySpec; public static Test suite() { return new TestSetup(new TestSuite(GreenPepperRepositoryTest.class)) { @Override protected void setUp() throws Exception { ws = new WebServer( 9005 ); ws.start(); } @Override protected void tearDown() throws Exception { ws.shutdown(); } }; } protected void setUp() { handler = context.mock( Handler.class ); ws.removeHandler( "greenpepper1" ); ws.addHandler( "greenpepper1", handler ); dummySpec = TestStringSpecifications.SimpleAlternateCalculatorTest; } @SuppressWarnings("unchecked") public void testCanProvideAListOfSpecificationsGivenASutAndARepository() throws Exception { final Vector<String> page1 = pageDefinition(1); final Vector<String> page2 = pageDefinition(2); final Vector<String> page3 = pageDefinition(3); List<String> expected = toVector( "REPO/PAGE 1", "REPO/PAGE 2", "REPO/PAGE 3" ); context.checking(new Expectations() {{ one(handler).getListOfSpecificationLocations("REPO", "SUT"); will(returnValue(toVector(page1, page2, page3))); }}); DocumentRepository repo = new GreenPepperRepository("http://localhost:9005/rpc/xmlrpc?handler=greenpepper1&sut=SUT"); List<String> actual = repo.listDocuments( "REPO" ); assertEquals( expected, actual ); } @SuppressWarnings("unchecked") public void testCanDownloadPageContentFromConfluence() throws Exception { final Vector<String> page1 = confPageDefinition(); final Vector<?> expected = toVector( "SPACE%20KEY", "PAGE TITLE", Boolean.TRUE, Boolean.TRUE ); context.checking(new Expectations() {{ one(handler).getListOfSpecificationLocations("REPO", "SUT"); will(returnValue(toVector(page1))); one(handler).getRenderedSpecification("user", "pwd", expected); will(returnValue(dummySpec)); }}); DocumentRepository repo = new GreenPepperRepository("http://localhost:9005/rpc/xmlrpc?handler=greenpepper1&sut=SUT"); Document document = repo.loadDocument( "REPO/PAGE TITLE" ); assertEquals("html", document.getType()); assertSpecification( dummySpec, document ); } @SuppressWarnings("unchecked") public void testhandlesImplementedVersionAttribute() throws Exception { final Vector<String> page1 = confPageDefinition(); final Vector<?> expected = toVector( "SPACE%20KEY", "PAGE TITLE", Boolean.TRUE, Boolean.FALSE ); context.checking(new Expectations() {{ one(handler).getListOfSpecificationLocations("REPO", "SUT"); will(returnValue(toVector(page1))); one(handler).getRenderedSpecification("user", "pwd", expected); will(returnValue(dummySpec)); }}); DocumentRepository repo = new GreenPepperRepository("http://localhost:9005/rpc/xmlrpc?implemented=false&handler=greenpepper1&sut=SUT"); Document document = repo.loadDocument( "REPO/PAGE TITLE" ); assertEquals("html", document.getType()); assertSpecification( dummySpec, document ); } @SuppressWarnings("unchecked") public void testHandlesPostBackExecutionResult() throws Exception { final Vector<String> page1 = confPageDefinition(); final Vector<?> expected1 = toVector( "SPACE%20KEY", "PAGE TITLE", Boolean.TRUE, Boolean.TRUE ); final Vector<?> expected2 = toVector( "SPACE%20KEY", "PAGE TITLE", "SUT", TestStringSpecifications.SimpleAlternateCalculatorXmlReport ); context.checking(new Expectations() {{ one(handler).getListOfSpecificationLocations("REPO", "SUT"); will(returnValue(toVector(page1))); one(handler).getRenderedSpecification("user", "pwd", expected1); will(returnValue(dummySpec)); one(handler).saveExecutionResult("user", "pwd", expected2); will(returnValue("<success>")); }}); DocumentRepository repo = new GreenPepperRepository("http://localhost:9005/rpc/xmlrpc?handler=greenpepper1&sut=SUT&postExecutionResult=true"); Document document = repo.loadDocument( "REPO/PAGE TITLE" ); assertEquals("html", document.getType()); assertSpecification( dummySpec, document ); document.done(); } @SuppressWarnings("unchecked") public void testHandlesNoSuchMethodPostBackExecutionResultQuietly() throws Exception { final Vector<String> page1 = confPageDefinition(); final Vector<?> expected1 = toVector( "SPACE%20KEY", "PAGE TITLE", Boolean.TRUE, Boolean.TRUE ); final RuntimeException noSuchMethodException = new RuntimeException(new NoSuchMethodException()); final Vector<?> expected2 = toVector( "SPACE%20KEY", "PAGE TITLE", "SUT", TestStringSpecifications.SimpleAlternateCalculatorXmlReport ); context.checking(new Expectations() {{ one(handler).getListOfSpecificationLocations("REPO", "SUT"); will(returnValue(toVector(page1))); one(handler).getRenderedSpecification("user", "pwd", expected1); will(returnValue(dummySpec)); one(handler).saveExecutionResult("user", "pwd", expected2); will(throwException(noSuchMethodException)); }}); DocumentRepository repo = new GreenPepperRepository("http://localhost:9005/rpc/xmlrpc?handler=greenpepper1&sut=SUT&postExecutionResult=true"); Document document = repo.loadDocument( "REPO/PAGE TITLE" ); assertEquals("html", document.getType()); assertSpecification( dummySpec, document ); document.done(); } @SuppressWarnings("unchecked") public void testHandlesOtherXmlRpcExceptionPostBackExecutionResult() throws Exception { final Vector<String> page1 = confPageDefinition(); final Vector<?> expected1 = toVector( "SPACE%20KEY", "PAGE TITLE", Boolean.TRUE, Boolean.TRUE ); final XmlRpcException noSuchMethodException = new XmlRpcException(0, "junit"); final Vector<?> expected2 = toVector( "SPACE%20KEY", "PAGE TITLE", "SUT", TestStringSpecifications.SimpleAlternateCalculatorXmlReport ); context.checking(new Expectations() {{ one(handler).getListOfSpecificationLocations("REPO", "SUT"); will(returnValue(toVector(page1))); one(handler).getRenderedSpecification("user", "pwd", expected1); will(returnValue(dummySpec)); one(handler).saveExecutionResult("user", "pwd", expected2); will(throwException( noSuchMethodException )); }}); DocumentRepository repo = new GreenPepperRepository("http://localhost:9005/rpc/xmlrpc?handler=greenpepper1&sut=SUT&postExecutionResult=true"); Document document = repo.loadDocument( "REPO/PAGE TITLE" ); assertEquals("html", document.getType()); assertSpecification( dummySpec, document ); try { document.done(); fail(); } catch (Exception e) { // ok } } @SuppressWarnings("unchecked") public void testHandlesUnsuccessfullPostBackExecutionResult() throws Exception { final Vector<String> page1 = confPageDefinition(); final Vector<?> expected1 = toVector( "SPACE%20KEY", "PAGE TITLE", Boolean.TRUE, Boolean.TRUE ); final Vector<?> expected2 = toVector( "SPACE%20KEY", "PAGE TITLE", "SUT", TestStringSpecifications.SimpleAlternateCalculatorXmlReport ); context.checking(new Expectations() {{ one(handler).getListOfSpecificationLocations("REPO", "SUT"); will(returnValue(toVector(page1))); one(handler).getRenderedSpecification("user", "pwd", expected1); will(returnValue(dummySpec)); one(handler).saveExecutionResult("user", "pwd", expected2); will(returnValue("<failure>")); }}); DocumentRepository repo = new GreenPepperRepository("http://localhost:9005/rpc/xmlrpc?handler=greenpepper1&sut=SUT&postExecutionResult=true"); Document document = repo.loadDocument( "REPO/PAGE TITLE" ); assertEquals("html", document.getType()); assertSpecification( dummySpec, document ); try { document.done(); fail(); } catch (Exception e) { // ok } } public void testComplainsIfArgumentsAreMissing() throws Exception { try { DocumentRepository repo = new GreenPepperRepository("http://localhost:9005/rpc/xmlrpc?handler=greenpepper1"); repo.listDocuments( "REPO" ); fail(); } catch (IllegalArgumentException expected) { assertTrue(true); } try { DocumentRepository repo = new GreenPepperRepository("http://localhost:9005/rpc/xmlrpc?handler=greenpepper1"); repo.listDocuments( "http://localhost:9005/rpc/xmlrpc?sut=SUT&includeStyle=true" ); fail(); } catch (IllegalArgumentException expected) { assertTrue(true); } } private void assertSpecification( String expectedSpec, Document actualDoc) { assertNotNull( actualDoc ); StringWriter buffer = new StringWriter(); actualDoc.print( new PrintWriter( buffer ) ); assertEquals( expectedSpec, buffer.toString() ); } private Vector<String> confPageDefinition() { Vector<String> def = new Vector<String>(); def.add(AtlassianRepository.class.getName()); def.add("http://localhost:9005/rpc/xmlrpc?handler=greenpepper1#SPACE%20KEY"); def.add("user"); def.add("pwd"); def.add("PAGE TITLE"); return def; } private Vector<String> pageDefinition(int identifier) { Vector<String> def = new Vector<String>(); def.add("repoClass"); def.add("testUrl"+identifier); def.add("user"+identifier); def.add("pwd"+identifier); def.add("PAGE "+identifier); return def; } public static interface Handler { Vector<Vector<String>> getListOfSpecificationLocations(String repoUID, String sutName); String getRenderedSpecification(String username, String password, Vector<?> args); String saveExecutionResult(String username, String password, Vector<?> args); } }
/* * 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.pig.test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import org.apache.pig.ExecType; import org.apache.pig.PigServer; import org.apache.pig.builtin.COUNT; import org.apache.pig.builtin.SIZE; import org.apache.pig.impl.PigContext; import org.apache.pig.newplan.Operator; import org.apache.pig.newplan.OperatorPlan; import org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer; import org.apache.pig.newplan.logical.relational.LOFilter; import org.apache.pig.newplan.logical.relational.LOForEach; import org.apache.pig.newplan.logical.relational.LOLoad; import org.apache.pig.newplan.logical.relational.LOStore; import org.apache.pig.newplan.logical.relational.LogicalPlan; import org.apache.pig.newplan.logical.rules.FilterAboveForeach; import org.apache.pig.newplan.logical.rules.LoadTypeCastInserter; import org.apache.pig.newplan.optimizer.PlanOptimizer; import org.apache.pig.newplan.optimizer.PlanTransformListener; import org.apache.pig.newplan.optimizer.Rule; import org.apache.pig.test.TestNewPlanPushDownForeachFlatten.MyFilterFunc; import org.junit.Assert; import org.junit.Test; public class TestNewPlanFilterAboveForeach { PigContext pc = new PigContext(ExecType.LOCAL, new Properties()); @Test public void testSimple() throws Exception { String query = "A =LOAD 'file.txt' AS (name, cuisines:bag{ t : ( cuisine ) } );" + "B = FOREACH A GENERATE name, flatten(cuisines);" + "C = FILTER B BY name == 'joe';" + "D = STORE C INTO 'empty';" ; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe1 = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); } @Test public void testSimpleNotPossible() throws Exception { String query = "A =LOAD 'file.txt' AS (name, cuisines:bag{ t : ( cuisine ) } );" + "B = FOREACH A GENERATE name, flatten(cuisines) as cuisines;" + "C = FILTER B BY cuisines == 'pizza';" + "D = STORE C INTO 'empty';" ; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator fe1 = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); Operator filter = newLogicalPlan.getSuccessors( fe2 ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); } /** * Non-deterministic filters should not be pushed up (see PIG-2014). * In the example below, if Filter gets pushed above flatten, we might remove * whole bags of cuisines of random gets pushed up, while the intent is to sample from each bag. * @throws Exception */ @Test public void testNondeterministicFilter() throws Exception { String query = "A =LOAD 'file.txt' AS (name, cuisines:bag{ t : ( cuisine ) }, num:int );" + "B = FOREACH A GENERATE name, flatten(cuisines), num;" + "C = FILTER B BY RANDOM(num) > 5;" + "D = STORE C INTO 'empty';" ; LogicalPlan newLogicalPlan = buildPlan( query ); newLogicalPlan.explain(System.out, "text", true); // Expect Filter to not be pushed, so it should be load->foreach-> filter Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator fe1 = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); Operator filter = newLogicalPlan.getSuccessors( fe2 ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); } @Test public void testMultipleFilter() throws Exception { String query = "A =LOAD 'file.txt' AS (name, cuisines : bag{ t : ( cuisine ) } );" + "B = FOREACH A GENERATE name, flatten(cuisines);" + "C = FILTER B BY $1 == 'french';" + "D = FILTER C BY name == 'joe';" + "E = STORE D INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe1 = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); Operator filter2 = newLogicalPlan.getSuccessors( fe2 ).get( 0 ); Assert.assertTrue( filter2 instanceof LOFilter ); } @Test public void testMultipleFilter2() throws Exception { String query = "A =LOAD 'file.txt' AS (name, age, cuisines : bag{ t : ( cuisine ) } );" + "B = FOREACH A GENERATE name, age, flatten(cuisines);" + "C = FILTER B BY name == 'joe';" + "D = FILTER C BY age == 30;" + "E = STORE D INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator filter2 = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( filter2 instanceof LOFilter ); Operator fe1 = newLogicalPlan.getSuccessors( filter2 ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); } @Test public void testMultipleFilterNotPossible() throws Exception { String query = "A =LOAD 'file.txt' AS (name, cuisines : bag{ t : ( cuisine, region ) } );" + "B = FOREACH A GENERATE name, flatten(cuisines);" + "C = FILTER B BY $1 == 'French';" + "D = FILTER C BY $2 == 'Europe';" + "E = STORE D INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator fe1 = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); Operator filter = newLogicalPlan.getSuccessors( fe2 ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator filter2 = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( filter2 instanceof LOFilter ); } @Test public void testNotPossibleFilter() throws Exception { String query = "A =LOAD 'file.txt' AS (name, cuisines:bag{ t : ( cuisine ) } );" + "B = FOREACH A GENERATE name, flatten(cuisines);" + "C = FILTER B BY cuisine == 'French';" + "D = STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator fe1 = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); Operator filter = newLogicalPlan.getSuccessors( fe2 ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); } @Test public void testSimple2() throws Exception { String query = "A =LOAD 'file.txt' AS (name, cuisines:bag{ t : ( cuisine ) } );" + "B = FOREACH A GENERATE name, cuisines;" + "C = FILTER B BY name == 'joe';" + "D = STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe1 = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); } /** * Normal test case: all fields from Foreach are used by exhaustive list. * Optimization should kick in. * @throws Exception */ @Test public void test1() throws Exception { String query = "A =LOAD 'file.txt' AS (a:bag{(u,v)}, b, c);" + "B = FOREACH A GENERATE $0, b;" + "C = FILTER B BY " + COUNT.class.getName() +"($0) > 5;" + "STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator fe1 = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator filter = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe2 = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); } /** * Identical to test1() except that it use project *. * @throws Exception */ @Test public void test2() throws Exception { String query = "A =LOAD 'file.txt' AS (a:(u,v), b, c);" + "B = FOREACH A GENERATE $0, b;" + "C = FILTER B BY " + SIZE.class.getName() +"(TOTUPLE(*)) > 5;" + "STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator fe1 = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator filter = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe2 = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); } /** * No fields are used in filter condition at all. * @throws Exception */ @Test public void test3() throws Exception { String query = "A =LOAD 'file.txt' AS (a:(u,v), b, c);" + "B = FOREACH A GENERATE $0, b;" + "C = FILTER B BY 8 > 5;" + "STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe1 = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); } /** * Similar to test2, but not all fields are available from the operator before foreach. * Optimziation doesn't kick in. * @throws Exception */ @Test public void test4() throws Exception { String query = "A =LOAD 'file.txt' AS (a:(u,v), b, c);" + "B = FOREACH A GENERATE $0, b, flatten(1);" + "C = FILTER B BY " + SIZE.class.getName() +"(TOTUPLE(*)) > 5;" + "STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator fe1 = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( fe1 instanceof LOForEach ); Operator fe2 = newLogicalPlan.getSuccessors( fe1 ).get( 0 ); Assert.assertTrue( fe2 instanceof LOForEach ); Operator filter = newLogicalPlan.getSuccessors( fe2 ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); } @Test public void testFilterForeach() throws Exception { String query = "A =load 'myfile' as (name, age, gpa);" + "B = foreach A generate $1, $2;" + "C = filter B by $0 < 18;" + "D = STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); fe = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); Operator store = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( store instanceof LOStore ); } @Test public void testFilterForeachAddedField() throws Exception { String query = "A =load 'myfile' as (name, age, gpa);" + "B = foreach A generate $1, $2, COUNT({(1)});" + "C = filter B by $2 < 18;" + "D = STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator fe = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); fe = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); Operator filter = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator store = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( store instanceof LOStore ); } @Test public void testFilterForeachCast() throws Exception { String query = "A =load 'myfile' as (name, age, gpa);" + "B = foreach A generate (int)$1, $2;" + "C = filter B by $0 < 18;" + "D = STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator fe = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); fe = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); Operator filter = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator store = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( store instanceof LOStore ); } @Test public void testFilterCastForeach() throws Exception { String query = "A =load 'myfile' as (name, age, gpa);" + "B = foreach A generate $1, $2;" + "C = filter B by (int)$0 < 18;" + "D = STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); fe = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); Operator store = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( store instanceof LOStore ); } @Test public void testFilterConstantConditionForeach() throws Exception { String query = "A =load 'myfile' as (name, age, gpa);" + "B = foreach A generate $1, $2;" + "C = filter B by 1 == 1;" + "D = STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); fe = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); Operator store = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( store instanceof LOStore ); } @Test public void testFilterUDFForeach() throws Exception { String query = "A =load 'myfile' as (name, age, gpa);" + "B = foreach A generate $1, $2;" + "C = filter B by " + MyFilterFunc.class.getName() + "($1) ;" + "D = STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); fe = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); Operator store = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( store instanceof LOStore ); } @Test public void testFilterForeachFlatten() throws Exception { String query = "A =load 'myfile' as (name, age, gpa);" + "B = foreach A generate $1, flatten($2);" + "C = filter B by $0 < 18;" + "D = STORE C INTO 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator load = newLogicalPlan.getSources().get( 0 ); Assert.assertTrue( load instanceof LOLoad ); Operator filter = newLogicalPlan.getSuccessors( load ).get( 0 ); Assert.assertTrue( filter instanceof LOFilter ); Operator fe = newLogicalPlan.getSuccessors( filter ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); fe = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( fe instanceof LOForEach ); Operator store = newLogicalPlan.getSuccessors( fe ).get( 0 ); Assert.assertTrue( store instanceof LOStore ); } // See PIG-1669 @Test public void testPushUpFilterWithScalar() throws Exception { String query = "a = load 'studenttab10k' as (name, age, gpa);" + "b = group a all;" + "c = foreach b generate AVG(a.age) as age;" + "d = foreach a generate name, age;" + "e = filter d by age > c.age;" + "f = store e into 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator store = newLogicalPlan.getSinks().get( 0 ); Operator foreach = newLogicalPlan.getPredecessors(store).get(0); Assert.assertTrue( foreach instanceof LOForEach ); } // See PIG-1935 @Test public void testPushUpFilterAboveBinCond() throws Exception { String query = "data = LOAD 'data.txt' as (referrer:chararray, canonical_url:chararray, ip:chararray);" + "best_url = FOREACH data GENERATE ((canonical_url != '' and canonical_url is not null) ? canonical_url : referrer) AS url, ip;" + "filtered = FILTER best_url BY url == 'badsite.com';" + "store filtered into 'empty';"; LogicalPlan newLogicalPlan = buildPlan( query ); Operator store = newLogicalPlan.getSinks().get( 0 ); Operator filter = newLogicalPlan.getPredecessors(store).get(0); Assert.assertTrue( filter instanceof LOFilter ); } private LogicalPlan buildPlan(String query) throws Exception { PigServer pigServer = new PigServer( pc ); LogicalPlan newLogicalPlan = Util.buildLp(pigServer, query); PlanOptimizer optimizer = new MyPlanOptimizer( newLogicalPlan, 3 ); optimizer.optimize(); return newLogicalPlan; } public class MyPlanOptimizer extends LogicalPlanOptimizer { protected MyPlanOptimizer(OperatorPlan p, int iterations) { super(p, iterations, new HashSet<String>()); } @Override public void addPlanTransformListener(PlanTransformListener listener) { super.addPlanTransformListener(listener); } @Override protected List<Set<Rule>> buildRuleSets() { List<Set<Rule>> ls = new ArrayList<Set<Rule>>(); Set<Rule> s = new HashSet<Rule>(); // add split filter rule Rule r = new LoadTypeCastInserter( "TypeCastInserter" ); s.add(r); ls.add(s); s = new HashSet<Rule>(); r = new FilterAboveForeach( "FilterAboveForeach" ); s.add(r); ls.add(s); return ls; } } }
/* * 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.ambari.server.api.services; import static org.easymock.EasyMock.createNiceMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.Assert.fail; import java.io.File; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.persistence.EntityManager; import org.apache.ambari.server.AmbariException; import org.apache.ambari.server.configuration.Configuration; import org.apache.ambari.server.events.publishers.AmbariEventPublisher; import org.apache.ambari.server.metadata.ActionMetadata; import org.apache.ambari.server.orm.GuiceJpaInitializer; import org.apache.ambari.server.orm.InMemoryDefaultTestModule; import org.apache.ambari.server.orm.dao.AlertDefinitionDAO; import org.apache.ambari.server.orm.dao.MetainfoDAO; import org.apache.ambari.server.stack.StackManager; import org.apache.ambari.server.stack.StackManagerFactory; import org.apache.ambari.server.state.AutoDeployInfo; import org.apache.ambari.server.state.ComponentInfo; import org.apache.ambari.server.state.DependencyInfo; import org.apache.ambari.server.state.ServiceInfo; import org.apache.ambari.server.state.alert.AlertDefinitionFactory; import org.apache.ambari.server.state.stack.OsFamily; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.util.Modules; import junit.framework.Assert; public class KerberosServiceMetaInfoTest { private final static Logger LOG = LoggerFactory.getLogger(KerberosServiceMetaInfoTest.class); private ServiceInfo serviceInfo = null; /* ******************************************************************************************** * In the event we want to create a superclass that can be used to execute tests on service * metainfo data, the following methods may be useful * ******************************************************************************************** */ private void testAutoDeploy(Map<String, AutoDeployInfo> expectedAutoDeployMap) throws AmbariException { Assert.assertNotNull(serviceInfo); List<ComponentInfo> componentList = serviceInfo.getComponents(); Assert.assertNotNull(componentList); Assert.assertEquals(expectedAutoDeployMap.size(), componentList.size()); for (ComponentInfo component : componentList) { Assert.assertTrue(expectedAutoDeployMap.containsKey(component.getName())); AutoDeployInfo expectedAutoDeploy = expectedAutoDeployMap.get(component.getName()); AutoDeployInfo componentAutoDeploy = component.getAutoDeploy(); if (expectedAutoDeploy == null) { Assert.assertNull(componentAutoDeploy); } else { Assert.assertNotNull(componentAutoDeploy); Assert.assertEquals(expectedAutoDeploy.isEnabled(), componentAutoDeploy.isEnabled()); Assert.assertEquals(expectedAutoDeploy.getCoLocate(), componentAutoDeploy.getCoLocate()); } } } private void testCardinality(HashMap<String, String> expectedCardinalityMap) throws AmbariException { Assert.assertNotNull(serviceInfo); List<ComponentInfo> componentList = serviceInfo.getComponents(); Assert.assertNotNull(componentList); Assert.assertEquals(expectedCardinalityMap.size(), componentList.size()); for (ComponentInfo component : componentList) { Assert.assertTrue(expectedCardinalityMap.containsKey(component.getName())); Assert.assertEquals(expectedCardinalityMap.get(component.getName()), component.getCardinality()); } } protected void testDependencies(Map<String, Map<String, DependencyInfo>> expectedDependenciesMap) throws AmbariException { Assert.assertNotNull(serviceInfo); List<ComponentInfo> componentList = serviceInfo.getComponents(); Assert.assertNotNull(componentList); Assert.assertEquals(expectedDependenciesMap.size(), componentList.size()); for (ComponentInfo component : componentList) { Assert.assertTrue(expectedDependenciesMap.containsKey(component.getName())); Map<String, ? extends DependencyInfo> expectedDependencyMap = expectedDependenciesMap.get(component.getName()); List<DependencyInfo> componentDependencies = component.getDependencies(); if (expectedDependencyMap == null) { Assert.assertNull(componentDependencies); } else { Assert.assertEquals(expectedDependencyMap.size(), componentDependencies.size()); for (DependencyInfo componentDependency : componentDependencies) { DependencyInfo expectedDependency = expectedDependencyMap.get(componentDependency.getComponentName()); Assert.assertNotNull(expectedDependency); AutoDeployInfo expectedDependencyAutoDeploy = expectedDependency.getAutoDeploy(); AutoDeployInfo componentDependencyAutoDeploy = componentDependency.getAutoDeploy(); Assert.assertEquals(expectedDependency.getName(), componentDependency.getName()); Assert.assertEquals(expectedDependency.getServiceName(), componentDependency.getServiceName()); Assert.assertEquals(expectedDependency.getComponentName(), componentDependency.getComponentName()); Assert.assertEquals(expectedDependency.getScope(), componentDependency.getScope()); if (expectedDependencyAutoDeploy == null) { Assert.assertNull(componentDependencyAutoDeploy); } else { Assert.assertNotNull(componentDependencyAutoDeploy); Assert.assertEquals(expectedDependencyAutoDeploy.isEnabled(), componentDependencyAutoDeploy.isEnabled()); Assert.assertEquals(expectedDependencyAutoDeploy.getCoLocate(), componentDependencyAutoDeploy.getCoLocate()); } } } } } @Before public void before() throws Exception { File stackRoot = new File("src/main/resources/stacks"); File commonServicesRoot = new File("src/main/resources/common-services"); LOG.info("Stacks file " + stackRoot.getAbsolutePath()); LOG.info("Common Services file " + commonServicesRoot.getAbsolutePath()); AmbariMetaInfo metaInfo = createAmbariMetaInfo(stackRoot, commonServicesRoot, new File("src/test/resources/version"), true); metaInfo.init(); serviceInfo = metaInfo.getService("HDP", "2.2", "KERBEROS"); } /* ******************************************************************************************* */ @Test public void test220Cardinality() throws Exception { testCardinality(new HashMap<String, String>() { { put("KERBEROS_CLIENT", "ALL"); } }); } @Test public void test220AutoDeploy() throws Exception { testAutoDeploy(new HashMap<String, AutoDeployInfo>() { { put("KERBEROS_CLIENT", new AutoDeployInfo() {{ setEnabled(true); setCoLocate(null); }}); } }); } @Test public void test220Dependencies() throws Exception { testDependencies(new HashMap<String, Map<String, DependencyInfo>>() { { put("KERBEROS_CLIENT", new HashMap<>()); } }); } private TestAmbariMetaInfo createAmbariMetaInfo(File stackRoot, File commonServicesRoot, File versionFile, boolean replayMocks) throws Exception { Properties properties = new Properties(); properties.setProperty(Configuration.METADATA_DIR_PATH.getKey(), stackRoot.getPath()); properties.setProperty(Configuration.COMMON_SERVICES_DIR_PATH.getKey(), commonServicesRoot.getPath()); properties.setProperty(Configuration.SERVER_VERSION_FILE.getKey(), versionFile.getPath()); Configuration configuration = new Configuration(properties); TestAmbariMetaInfo metaInfo = new TestAmbariMetaInfo(configuration); if (replayMocks) { metaInfo.replayAllMocks(); try { metaInfo.init(); } catch(Exception e) { LOG.info("Error in initializing ", e); throw e; } waitForAllReposToBeResolved(metaInfo); } return metaInfo; } private void waitForAllReposToBeResolved(AmbariMetaInfo metaInfo) throws Exception { int maxWait = 45000; int waitTime = 0; StackManager sm = metaInfo.getStackManager(); while (waitTime < maxWait && ! sm.haveAllRepoUrlsBeenResolved()) { Thread.sleep(5); waitTime += 5; } if (waitTime >= maxWait) { fail("Latest Repo tasks did not complete"); } } private static class TestAmbariMetaInfo extends AmbariMetaInfo { MetainfoDAO metaInfoDAO; AlertDefinitionDAO alertDefinitionDAO; AlertDefinitionFactory alertDefinitionFactory; OsFamily osFamily; public TestAmbariMetaInfo(Configuration configuration) throws Exception { super(configuration); Injector injector = Guice.createInjector(Modules.override( new InMemoryDefaultTestModule()).with(new MockModule())); injector.getInstance(GuiceJpaInitializer.class); injector.getInstance(EntityManager.class); Class<?> c = getClass().getSuperclass(); // MetainfoDAO metaInfoDAO = injector.getInstance(MetainfoDAO.class); Field f = c.getDeclaredField("metaInfoDAO"); f.setAccessible(true); f.set(this, metaInfoDAO); // StackManagerFactory StackManagerFactory stackManagerFactory = injector.getInstance(StackManagerFactory.class); f = c.getDeclaredField("stackManagerFactory"); f.setAccessible(true); f.set(this, stackManagerFactory); //AlertDefinitionDAO alertDefinitionDAO = createNiceMock(AlertDefinitionDAO.class); f = c.getDeclaredField("alertDefinitionDao"); f.setAccessible(true); f.set(this, alertDefinitionDAO); //AlertDefinitionFactory //alertDefinitionFactory = createNiceMock(AlertDefinitionFactory.class); alertDefinitionFactory = new AlertDefinitionFactory(); f = c.getDeclaredField("alertDefinitionFactory"); f.setAccessible(true); f.set(this, alertDefinitionFactory); //AmbariEventPublisher AmbariEventPublisher ambariEventPublisher = new AmbariEventPublisher(); f = c.getDeclaredField("eventPublisher"); f.setAccessible(true); f.set(this, ambariEventPublisher); //OSFamily Configuration config = createNiceMock(Configuration.class); expect(config.getSharedResourcesDirPath()).andReturn("./src/test/resources").anyTimes(); replay(config); osFamily = new OsFamily(config); f = c.getDeclaredField("osFamily"); f.setAccessible(true); f.set(this, osFamily); } public void replayAllMocks() { replay(metaInfoDAO, alertDefinitionDAO); } public class MockModule extends AbstractModule { @Override protected void configure() { bind(ActionMetadata.class); // create a mock metainfo DAO for the entire system so that injectables // can use the mock as well bind(MetainfoDAO.class).toInstance(createNiceMock(MetainfoDAO.class)); } } } }
/* * Copyright (c) 2008-2017, Hazelcast, Inc. 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.hazelcast.query.impl.extractor.specification; import com.hazelcast.config.Config; import com.hazelcast.config.InMemoryFormat; import com.hazelcast.query.Predicates; import com.hazelcast.query.QueryException; import com.hazelcast.query.impl.extractor.AbstractExtractionTest; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Collection; import static com.hazelcast.config.InMemoryFormat.BINARY; import static com.hazelcast.config.InMemoryFormat.OBJECT; import static com.hazelcast.query.impl.extractor.AbstractExtractionSpecification.Index.NO_INDEX; import static com.hazelcast.query.impl.extractor.AbstractExtractionSpecification.Index.ORDERED; import static com.hazelcast.query.impl.extractor.AbstractExtractionSpecification.Index.UNORDERED; import static com.hazelcast.query.impl.extractor.AbstractExtractionSpecification.Multivalue.ARRAY; import static com.hazelcast.query.impl.extractor.AbstractExtractionSpecification.Multivalue.PORTABLE; import static com.hazelcast.query.impl.extractor.specification.ComplexTestDataStructure.Finger; import static com.hazelcast.query.impl.extractor.specification.ComplexTestDataStructure.Person; import static com.hazelcast.query.impl.extractor.specification.ComplexTestDataStructure.finger; import static com.hazelcast.query.impl.extractor.specification.ComplexTestDataStructure.limb; import static com.hazelcast.query.impl.extractor.specification.ComplexTestDataStructure.person; import static com.hazelcast.query.impl.extractor.specification.ComplexTestDataStructure.tattoos; import static java.util.Arrays.asList; /** * Specification test that verifies the behavior of corner-cases extraction in arrays ONLY. * <p/> * Extraction mechanism: IN-BUILT REFLECTION EXTRACTION * <p/> * This test is parametrised on two axes (see the parametrisationData() method): * - in memory format * - indexing */ @RunWith(Parameterized.class) @Category({QuickTest.class, ParallelTest.class}) public class ExtractionInArraySpecTest extends AbstractExtractionTest { private static final Person BOND = person("Bond", limb("left-hand", tattoos(), finger("thumb"), finger(null)), limb("right-hand", tattoos("knife"), finger("middle"), finger("index")) ); private static final Person KRUEGER = person("Krueger", limb("linke-hand", tattoos("bratwurst"), finger("Zeigefinger"), finger("Mittelfinger")), limb("rechte-hand", tattoos(), finger("Ringfinger"), finger("Daumen")) ); private static final Person HUNT_NULL_TATTOOS = person("Hunt", limb("left", null, new Finger[]{}) ); private static final Person HUNT_NULL_LIMB = person("Hunt"); protected Configurator getInstanceConfigurator() { return new Configurator() { @Override public void doWithConfig(Config config, Multivalue mv) { config.getSerializationConfig().addPortableFactory(ComplexTestDataStructure.PersonPortableFactory.ID, new ComplexTestDataStructure.PersonPortableFactory()); } }; } public ExtractionInArraySpecTest(InMemoryFormat inMemoryFormat, Index index, Multivalue multivalue) { super(inMemoryFormat, index, multivalue); } @Test @Ignore("Checking array's length does not work for now") public void length_property() { execute(Input.of(BOND, KRUEGER), Query.of(Predicates.equal("limbs_.length", 2), mv), Expected.of(BOND, KRUEGER)); } @Test @Ignore("Checking array's length does not work for now") public void length_property_atLeaf() { execute(Input.of(BOND, KRUEGER), Query.of(Predicates.equal("limbs_[0].tattoos_.length", 1), mv), Expected.of(KRUEGER)); } @Test @Ignore("Checking array's length does not work for now") public void null_collection_length() { execute(Input.of(HUNT_NULL_LIMB), Query.of(Predicates.equal("limbs_[0].fingers_.length", 1), mv), Expected.empty()); } @Test @Ignore("Checking array's length does not work for now") public void null_collection_length_compared_to_null() { execute(Input.of(HUNT_NULL_LIMB), Query.of(Predicates.equal("limbs_[0].fingers_.length", null), mv), Expected.of(HUNT_NULL_LIMB)); } @Test @Ignore("Checking array's length does not work for now") public void null_collection_length_reduced() { execute(Input.of(HUNT_NULL_LIMB), Query.of(Predicates.equal("limbs_[any].fingers_.length", 1), mv), Expected.empty()); } @Test @Ignore("Checking array's length does not work for now") public void null_collection_length_reduced_compared_to_null() { execute(Input.of(HUNT_NULL_LIMB), Query.of(Predicates.equal("limbs_[any].fingers_.length", null), mv), Expected.of(HUNT_NULL_LIMB)); } @Test @Ignore("Checking array's length does not work for now") public void null_collection_length_atLeaf() { execute(Input.of(HUNT_NULL_TATTOOS), Query.of(Predicates.equal("limbs_[0].tattoos_.length", 1), mv), Expected.empty()); } @Test @Ignore("Checking array's length does not work for now") public void null_collection_length_atLeaf_compared_to_null() { execute(Input.of(HUNT_NULL_TATTOOS), Query.of(Predicates.equal("limbs_[0].tattoos_.length", null), mv), Expected.of(HUNT_NULL_TATTOOS)); } @Test @Ignore("Checking array's length does not work for now") public void null_collection_length_atLeaf_reduced() { execute(Input.of(HUNT_NULL_TATTOOS), Query.of(Predicates.equal("limbs_[any].tattoos_.length", 1), mv), Expected.empty()); } @Test @Ignore("Checking array's length does not work for now") public void null_collection_length_atLeaf_reduced_compared_to_null() { execute(Input.of(HUNT_NULL_TATTOOS), Query.of(Predicates.equal("limbs_[any].tattoos_.length", null), mv), Expected.of(HUNT_NULL_TATTOOS)); } @Test public void indexOutOfBound_notExistingProperty() { execute(Input.of(BOND, KRUEGER), Query.of(equal("limbs_[100].sdafasdf", "knife"), mv), Expected.of(QueryException.class)); } @Test public void indexOutOfBound_notExistingProperty_notAtLeaf() { execute(Input.of(BOND, KRUEGER), Query.of(equal("limbs_[100].sdafasdf.zxcvzxcv", "knife"), mv), Expected.of(QueryException.class)); } @Test public void indexOutOfBound_atLeaf_notExistingProperty() { execute(Input.of(BOND, KRUEGER), Query.of(equal("limbs_[0].tattoos_[100].asdfas", "knife"), mv), Expected.of(QueryException.class)); } @Parameterized.Parameters(name = "{index}: {0}, {1}, {2}") public static Collection<Object[]> parametrisationData() { return axes( asList(BINARY, OBJECT), asList(NO_INDEX, ORDERED, UNORDERED), asList(ARRAY, PORTABLE) ); } }
/* * 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.jena.sdb.core.sqlnode; import java.util.List ; import java.util.Set ; import org.apache.jena.atlas.io.IndentedWriter ; import org.apache.jena.atlas.iterator.Iter ; import org.apache.jena.atlas.lib.Lib ; import org.apache.jena.sdb.SDB ; import org.apache.jena.sdb.core.Annotations ; import org.apache.jena.sdb.core.sqlexpr.S_Equal ; import org.apache.jena.sdb.core.sqlexpr.SqlColumn ; import org.apache.jena.sdb.core.sqlexpr.SqlExpr ; import org.apache.jena.sdb.core.sqlexpr.SqlExprList ; import org.apache.jena.sdb.shared.SDBInternalError ; import org.apache.jena.sdb.shared.SDBNotImplemented ; import org.apache.jena.sparql.core.Var ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ; // This is not a general purpose SQL writer - it needs only work with the // SQL node trees that the SDB compiler generate. // // It just writes out the tree - it does not optimize it in anyway (that // happens before this stage). public class GenerateSQLVisitor implements SqlNodeVisitor { // Annotate should ensureEndofLine ? private static Logger log = LoggerFactory.getLogger(GenerateSQLVisitor.class) ; protected IndentedWriter out ; int levelSelectBlock = 0 ; // Per Generator public boolean outputAnnotations = SDB.getContext().isTrueOrUndef(SDB.annotateGeneratedSQL) ; private static final int annotationColumn = 40 ; private static boolean commentSQLStyle = true ; public GenerateSQLVisitor(IndentedWriter out) { this.out = out ; } public void visit(SqlProject sqlNode) { shouldNotSee(sqlNode) ; } public void visit(SqlDistinct sqlNode) { shouldNotSee(sqlNode) ; } public void visit(SqlRestrict sqlNode) { shouldNotSee(sqlNode) ; } public void visit(SqlSlice sqlNode) { shouldNotSee(sqlNode) ; } public void visit(SqlRename sqlNode) { shouldNotSee(sqlNode) ; } private void shouldNotSee(SqlNode sqlNode) { throw new SDBInternalError("Didn't expect: "+Lib.className(sqlNode)) ; } // If nested (subquery) @Override public void visit(SqlSelectBlock sqlSelectBlock) { // Need a rename and alias if: // Not top // Not merely a table inside. levelSelectBlock++ ; if ( levelSelectBlock > 1 ) { // Alias needed. // SqlRename rename = SqlRename.view("X", sqlSelectBlock) ; // rename.visit(this) ; // levelSelectBlock-- ; // return ; } genPrefix(sqlSelectBlock) ; out.print("SELECT ") ; if ( sqlSelectBlock.getDistinct() ) out.print("DISTINCT ") ; if ( annotate(sqlSelectBlock) ) out.ensureStartOfLine() ; out.incIndent() ; genColumnPrefix(sqlSelectBlock) ; print(sqlSelectBlock.getCols()) ; out.decIndent() ; out.ensureStartOfLine() ; // FROM out.print("FROM") ; if ( ! sqlSelectBlock.getSubNode().isTable() ) out.println(); else out.print(" "); out.incIndent() ; outputNode(sqlSelectBlock.getSubNode(), true) ; //sqlSelectBlock.getSubNode().visit(this) ; out.decIndent() ; out.ensureStartOfLine() ; // WHERE if ( sqlSelectBlock.getConditions().size() > 0 ) genWHERE(sqlSelectBlock.getConditions()) ; // LIMIT/OFFSET out.ensureStartOfLine() ; genLimitOffset(sqlSelectBlock) ; genSuffix(sqlSelectBlock) ; levelSelectBlock-- ; } /** * Generate anything that needs to appear before the core SELECT. */ protected void genPrefix(SqlSelectBlock sqlSelectBlock) { // By default, NOP. } /** * Generate any additional columns. */ protected void genColumnPrefix(SqlSelectBlock sqlSelectBlock) { // By default, NOP. } /** * Generate anything that needs to appear after the core SELECT. */ protected void genSuffix(SqlSelectBlock sqlSelectBlock) { // By default, NOP. } protected void genLimitOffset(SqlSelectBlock sqlSelectBlock) { if ( sqlSelectBlock.getLength() >= 0 ) out.println("LIMIT "+sqlSelectBlock.getLength()) ; if ( sqlSelectBlock.getStart() >= 0 ) out.println("OFFSET "+sqlSelectBlock.getStart()) ; } private void print(List<ColAlias> cols) { String sep = "" ; if ( cols.size() == 0 ) { // Can happen - e.g. query with no variables. //log.info("No SELECT columns") ; out.print("*") ; } // Put common prefix on same line String currentPrefix = null ; String splitMarker = "." ; for ( ColAlias c : cols ) { out.print(sep) ; // Choose split points. String cn = c.getColumn().getFullColumnName() ; int j = cn.lastIndexOf(splitMarker) ; if ( j == -1 ) currentPrefix = null ; else { String x = cn.substring(0, j) ; if ( currentPrefix != null && ! x.equals(currentPrefix) ) out.println() ; currentPrefix = x ; } sep = ", " ; out.print(c.getColumn().getFullColumnName()) ; if ( c.getAlias() != null ) { out.print(aliasToken()) ; out.print(c.getAlias().getColumnName()) ; } } } private void genWHERE(SqlExprList conditions) { out.print("WHERE") ; out.print(" ") ; out.incIndent() ; conditionList(conditions) ; out.decIndent() ; } @Override public void visit(SqlTable table) { out.print(table.getTableName()) ; out.print(aliasToken()) ; out.print(table.getAliasName()) ; annotate(table) ; } @Override public void visit(SqlJoinInner join) { join = rewrite(join) ; visitJoin(join) ; } public SqlJoinInner rewrite(SqlJoinInner join) { if ( ! join.getRight().isInnerJoin() ) return join ; // if ( join(A, join(B, C)) ) rewrite as join(join(A,B),C) // this then is written without brackets (and so scope changing) // TODO abstract as organiseJoin(List<join elements>) // and remember to do top down to find maximal join trees SqlJoinInner right = join.getRight().asInnerJoin() ; String alias1 = join.getAliasName() ; String alias2 = right.getAliasName() ; SqlNode sn_a = join.getLeft() ; SqlNode sn_b = right.getLeft() ; SqlNode sn_c = right.getRight() ; SqlExprList conditions = new SqlExprList(join.getConditions()) ; conditions.addAll(right.getConditions()) ; Set<SqlTable> tables_ab = sn_a.tablesInvolved() ; tables_ab.addAll(sn_b.tablesInvolved()) ; SqlExprList newCond_ab = new SqlExprList() ; // Goes to new join(A,B) SqlExprList newCond_c = new SqlExprList() ; // Goes to new join(,C) // Place conditions for ( SqlExpr e : conditions ) { Set<SqlColumn> cols = e.getColumnsNeeded() ; // columns to tables. Set<SqlTable> tables = tables(cols) ; // Are the tables contained in tables_ab? tables.removeAll(tables_ab) ; if ( tables.size() == 0 ) newCond_ab.add(e) ; else newCond_c.add(e) ; } if ( newCond_ab.size()+newCond_c.size() != conditions.size() ) log.error(String.format("Conditions mismatch: (%d,%d,%d)", newCond_ab.size(), newCond_c.size(), conditions.size())) ; SqlJoinInner join2 = new SqlJoinInner(sn_a, sn_b) ; join2.addConditions(newCond_ab) ; join2 = new SqlJoinInner(join2, sn_c) ; join2.addConditions(newCond_c) ; return join2 ; } private static Set<SqlTable> tables(Set<SqlColumn> cols) { return Iter.toSet(Iter.map(cols.iterator(), SqlColumn::getTable)) ; } @Override public void visit(SqlJoinLeftOuter join) { visitJoin(join) ; } @Override public void visit(SqlCoalesce sqlNode) { out.print("SELECT ") ; boolean first = true ; SqlJoin join = sqlNode.getJoinNode() ; // Rough draft code. for ( Var v : sqlNode.getCoalesceVars() ) { if ( ! first ) out.print(", ") ; SqlColumn col = sqlNode.getIdScope().findScopeForVar(v).getColumn() ; SqlColumn leftCol = join.getLeft().getIdScope().findScopeForVar(v).getColumn() ; SqlColumn rightCol = join.getRight().getIdScope().findScopeForVar(v).getColumn() ; out.print("COALESCE(") ; out.print(leftCol.getFullColumnName()) ; out.print(", ") ; out.print(rightCol.getFullColumnName()) ; out.print(")") ; out.print(aliasToken()) ; out.print(col.getColumnName()) ; first = false ; } // And other vars we want. for ( Var v : sqlNode.getNonCoalesceVars() ) { if ( ! first ) out.print(", ") ; first = false ; // Need generated names. SqlColumn colSub = join.getIdScope().findScopeForVar(v).getColumn() ; SqlColumn col = sqlNode.getIdScope().findScopeForVar(v).getColumn() ; out.print(colSub.getFullColumnName()) ; out.print(aliasToken()) ; out.print(col.getColumnName()) ; } out.ensureStartOfLine() ; out.incIndent() ; // INC out.println("FROM") ; join.visit(this) ; out.ensureStartOfLine() ; // Alias and annotations handled by outputNode } @Override public void visit(SqlUnion sqlUnion) { throw new SDBNotImplemented("SQL generation of SqlUnion") ; } protected void visitJoin(SqlJoin join) { visitJoin(join, join.getJoinType().sqlOperator()) ; } protected void visitJoin(SqlJoin join, String joinOperatorName) { // TODO revisit this code. Is it now needless complex? // Check brackets for more general SQL generation (safe mode - i.e. always bracketted?) SqlNode left = join.getLeft() ; SqlNode right = join.getRight() ; // Appearance: stop nesting too much. // Can we linearise the format? (drop indentation) if ( left.isJoin() && left.getAliasName() == null ) outputNode(left, false) ; else { out.incIndent() ; outputNode(left, true) ; out.decIndent() ; } out.println() ; //out.print(" ") ; out.print(joinOperatorName) ; annotate(join) ; out.println() ; // Aliasing and scoping - may need sub-SELECT - or just don't generate // such SqlNode structures, leaving only COALESCE as the sub-SELECT case boolean bracketsRight = true ; // if ( right.isInnerJoin() && join.isInnerJoin() && no conditions ) // bracketsRight = false ; if ( bracketsRight ) // Why? out.incIndent() ; outputNode(right, bracketsRight) ; if ( bracketsRight ) out.decIndent() ; out.println() ; out.print("ON ") ; if ( join.getConditions().size() > 0 ) conditionList(join.getConditions()) ; else { out.print(" ( ") ; out.print(leftJoinNoConditionsString()) ; out.print(" )") ; } } // -------- Extension points for various SQL differences protected String aliasToken() { return " AS " ; } protected String leftJoinNoConditionsString() { return "1 = 1" ; } // -------- // Interaction with annotations static boolean allOnOneLine = false ; public void conditionList(SqlExprList conditions) { if ( conditions.size() == 0 ) return ; out.print("( ") ; String sep = " AND " ; boolean first = true ; boolean lastAnnotated = false ; for ( SqlExpr c : conditions ) { if ( ! first ) { if ( ! allOnOneLine ) out.println(); out.print(sep) ; } boolean needsParens = ! ( c instanceof S_Equal ) ; // TODO Interact with SqlExpr precedence printing if ( needsParens ) out.print("( ") ; out.print(c.asSQL()) ; if ( needsParens ) out.print(" )") ; if ( ! allOnOneLine ) lastAnnotated = annotate(c) ; first = false ; } if ( ! allOnOneLine && lastAnnotated ) out.println("") ; out.print(" )") ; first = true ; if ( allOnOneLine ) { for ( SqlExpr c : conditions ) { if ( c.hasNotes() ) { if ( !first ) out.println() ; annotate(c) ; first = false ; } } } } private void outputNode(SqlNode sqlNode, boolean mayNeedBrackets) { if ( sqlNode.isTable() ) { sqlNode.visit(this) ; return ; } //boolean brackets = ( mayNeedBrackets && ( sqlNode.isSelectBlock() || sqlNode.isCoalesce() ) ) ; boolean brackets = false ; brackets = brackets || (mayNeedBrackets && sqlNode.isCoalesce()) ; // Work harder? ready for a better test. brackets = brackets || ( mayNeedBrackets && sqlNode.isSelectBlock()) ; // Need brackets if the subpart is a SELECT if ( brackets ) { out.print("( ") ; out.incIndent() ; } sqlNode.visit(this) ; if ( brackets ) { out.decIndent() ; out.ensureStartOfLine() ; out.print(")") ; } // Every derived table (SELECT ...) must have an alias. // Is there a more principled way to do this? .isDerived? // if ( sqlNode.isRestrict() || sqlNode.isProject()) // out.print(+sqlNode.getAliasName()) ; if ( sqlNode.getAliasName() != null ) { out.print(aliasToken()) ; out.print(sqlNode.getAliasName()) ; } annotate(sqlNode) ; } private boolean annotate(Annotations sqlNode) { return annotate(sqlNode, annotationColumn) ; } // return true if annotation was output and it runs to end-of-line private boolean annotate(Annotations sqlNode, int indentationColumn) { if ( ! outputAnnotations ) return false ; boolean first = true ; for ( String s : sqlNode.getNotes() ) { if ( !first ) out.println(); first = false; out.pad(indentationColumn, true) ; if ( commentSQLStyle ) { out.print(" -- ") ; out.print(s) ; }else{ out.print(" /* ") ; out.print(s) ; out.print(" */") ; } } return !commentSQLStyle || !first ; } }
package info.tregmine.listeners; import info.tregmine.Tregmine; import info.tregmine.api.GenericPlayer; import info.tregmine.api.Notification; import info.tregmine.database.DAOException; import info.tregmine.database.IBlessedBlockDAO; import info.tregmine.database.IContext; import info.tregmine.database.IWalletDAO; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Zombie; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityBreakDoorEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.util.Vector; import java.util.EnumSet; import java.util.Map; import java.util.Set; public class BlessedBlockListener implements Listener { public final static Set<Material> ALLOWED_MATERIALS = EnumSet.of(Material.CHEST, Material.TRAPPED_CHEST, Material.FURNACE, Material.BURNING_FURNACE, Material.BREWING_STAND, Material.WOOD_DOOR, Material.WOODEN_DOOR, Material.LEVER, Material.STONE_BUTTON, Material.STONE_PLATE, Material.WOOD_PLATE, Material.WORKBENCH, Material.SIGN_POST, Material.DIODE, Material.DIODE_BLOCK_OFF, Material.TRAP_DOOR, Material.DIODE_BLOCK_ON, Material.JUKEBOX, Material.SIGN, Material.FENCE_GATE, Material.DISPENSER, Material.WOOD_BUTTON, Material.NOTE_BLOCK, Material.REDSTONE_COMPARATOR, Material.REDSTONE_COMPARATOR_OFF, Material.REDSTONE_COMPARATOR_ON, Material.HOPPER, Material.DROPPER); private Tregmine plugin; public BlessedBlockListener(Tregmine instance) { plugin = instance; } @EventHandler public void onBlockBreak(BlockBreakEvent event) { Location loc = event.getBlock().getLocation(); Player player = event.getPlayer(); Map<Location, Integer> blessedBlocks = plugin.getBlessedBlocks(); if (blessedBlocks.get(loc) != null) { player.sendMessage(ChatColor.RED + "You can't destroy a blessed item."); event.setCancelled(true); return; } } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { Block block = event.getBlockPlaced(); Map<Location, Integer> blessedBlocks = plugin.getBlessedBlocks(); if (block.getType() == Material.CHEST) { Player player = event.getPlayer(); Location loc = block.getLocation(); Location loc1 = loc.add(new Vector(1, 0, 0)); Location loc2 = loc.subtract(new Vector(1, 0, 0)); Location loc3 = loc.add(new Vector(0, 0, 1)); Location loc4 = loc.subtract(new Vector(0, 0, 1)); if (blessedBlocks.get(loc1) != null || blessedBlocks.get(loc2) != null || blessedBlocks.get(loc3) != null || blessedBlocks.get(loc4) != null) { player.sendMessage(ChatColor.RED + "You can't place a chest next to one that is already blessed."); event.setCancelled(true); return; } } else if (block.getType() == Material.HOPPER) { GenericPlayer player = plugin.getPlayer(event.getPlayer()); Location loc = block.getLocation(); Location loc1 = loc.subtract(new Vector(0, 1, 0)); if (blessedBlocks.get(loc) != null || blessedBlocks.get(loc1) != null) { player.sendMessage(ChatColor.RED + "You can't place a hopper under a blessed chest."); event.setCancelled(true); } } } @EventHandler public void onDoorBreak(EntityBreakDoorEvent event) { Location l = event.getBlock().getLocation(); Entity e = event.getEntity(); Map<Location, Integer> b = plugin.getBlessedBlocks(); if (b.get(l) != null) { if (e instanceof Zombie) { event.setCancelled(true); } } } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { Block block = event.getClickedBlock(); GenericPlayer player = plugin.getPlayer(event.getPlayer()); if (event.getAction() == Action.RIGHT_CLICK_BLOCK && player.getItemInHand().getType() == Material.FEATHER && player.getRank().canUnbless() && ALLOWED_MATERIALS.contains(block.getType())) { Location loc = block.getLocation(); try (IContext ctx = plugin.createContext()) { IBlessedBlockDAO blessDAO = ctx.getBlessedBlockDAO(); int owner = blessDAO.owner(loc); if (owner == -1) { return; } GenericPlayer blockOwner = plugin.getPlayer(owner); if (blockOwner.isOnline()) { blockOwner.sendMessage( new TextComponent(ChatColor.AQUA + "One of your blocks at X" + loc.getBlockX() + " Y" + loc.getBlockY() + " Z" + loc.getBlockZ() + " has been unblessed by "), player.getChatName()); } IWalletDAO walletDAO = ctx.getWalletDAO(); walletDAO.add(blockOwner, 25000); blessDAO.delete(loc); player.sendMessage(ChatColor.AQUA + "You unblessed a block at X" + loc.getBlockX() + " Y" + loc.getBlockY() + " Z" + loc.getBlockZ() + ""); Map<Location, Integer> blessedBlocks = plugin.getBlessedBlocks(); blessedBlocks.remove(loc); event.setCancelled(true); } catch (DAOException e) { throw new RuntimeException(e); } } if (event.getAction() == Action.RIGHT_CLICK_BLOCK && player.getItemInHand().getType() == Material.BONE && player.getRank().canBless() && ALLOWED_MATERIALS.contains(block.getType())) { int targetId = player.getBlessTarget(); if (targetId == 0) { player.sendMessage(ChatColor.RED + "Use /bless [name] first!"); return; } GenericPlayer target = plugin.getPlayerOffline(targetId); if (target == null) { player.sendMessage(ChatColor.RED + "Use /bless [name] first!"); return; } int amount = player.getRank().getBlessCost(block); if (amount > 0) { try (IContext ctx = plugin.createContext()) { IWalletDAO walletDAO = ctx.getWalletDAO(); if (walletDAO.take(player, amount)) { player.sendMessage(ChatColor.LIGHT_PURPLE + (amount + " tregs was taken from you")); } else { player.sendMessage(ChatColor.RED + "You need " + amount + " tregs"); return; } } catch (DAOException e) { throw new RuntimeException(e); } } Location loc = block.getLocation(); if (target.isOnline()) { target.sendNotification(Notification.BLESS, new TextComponent(ChatColor.AQUA + "Your god blessed it in your name!")); } player.sendMessage(new TextComponent(ChatColor.AQUA + "You blessed for "), target.getChatNameStaff(), new TextComponent(".")); Tregmine.LOGGER.info(player.getName() + " Blessed a block " + loc + " to " + target.getName() + "."); Map<Location, Integer> blessedBlocks = plugin.getBlessedBlocks(); blessedBlocks.put(loc, targetId); try (IContext ctx = plugin.createContext()) { IBlessedBlockDAO blessDAO = ctx.getBlessedBlockDAO(); blessDAO.insert(target, loc); } catch (DAOException e) { throw new RuntimeException(e); } event.setCancelled(true); return; } if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK) && ALLOWED_MATERIALS.contains(block.getType())) { Location loc = block.getLocation(); Map<Location, Integer> blessedBlocks = plugin.getBlessedBlocks(); if (blessedBlocks.get(loc) != null) { int id = blessedBlocks.get(loc); GenericPlayer target = plugin.getPlayerOffline(id); if (id != player.getId()) { player.sendMessage(new TextComponent(ChatColor.YELLOW + "Blessed to: "), target.getChatName(), new TextComponent(".")); if (!player.getRank().canInspectInventories()) { event.setCancelled(true); } } else { player.sendMessage(ChatColor.AQUA + "Blessed to you."); } } } } }
// Copyright 2020 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. package org.chromium.chrome.browser.autofill_assistant.header; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import androidx.annotation.ColorInt; import androidx.core.content.ContextCompat; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.autofill_assistant.AssistantTagsForTesting; import org.chromium.chrome.browser.autofill_assistant.drawable.AssistantDrawableIcon; import org.chromium.chrome.browser.autofill_assistant.generic_ui.AssistantDrawable; import org.chromium.components.browser_ui.styles.SemanticColorUtils; import org.chromium.components.browser_ui.widget.animation.Interpolators; import org.chromium.ui.widget.ChromeImageView; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Handles construction and state changes on a progress bar with steps. */ public class AssistantStepProgressBar { private static final int ANIMATION_DELAY_MS = 1_000; private static final int ICON_ENABLED_ANIMATION_DURATION_MS = 300; private static final int LINE_ANIMATION_DURATION_MS = 1_000; private static final int PULSING_DURATION_MS = 1_000; // This controls the delay between the scaling of the pulsating and the alpha change. I.e. the // animation starts scaling and after a while the alpha changes. private static final int PULSING_ALPHA_CHANGE_DELAY_MS = 300; private static final int PULSING_RESTART_DELAY_MS = 2_000; private static final int COLOR_LIST = R.color.blue_when_enabled; private static final int ERROR_COLOR_LIST = R.color.default_red; private static class IconViewHolder { private final RelativeLayout mView; private final Context mContext; private final View mPulsor; private final ChromeImageView mIcon; private final ValueAnimator mPulseAnimation; private boolean mShouldRunAnimation; private boolean mDisableAnimations; private boolean mFirstAnimation; IconViewHolder(ViewGroup view, Context context) { mContext = context; mView = addContainer(view, mContext); mPulsor = addPulsor(mView, mContext); mIcon = addIcon(mView, mContext); mPulseAnimation = createPulseAnimation(); } void setTag(String tag) { mView.setTag(tag); } void disableAnimations(boolean disable) { mDisableAnimations = disable; } private RelativeLayout addContainer(ViewGroup view, Context context) { RelativeLayout container = new RelativeLayout(context); view.addView(container); int size = context.getResources().getDimensionPixelSize( R.dimen.autofill_assistant_progress_icon_background_size); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size); container.setLayoutParams(params); return container; } private View addPulsor(RelativeLayout view, Context context) { View pulsor = new View(context); view.addView(pulsor); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); pulsor.setLayoutParams(params); pulsor.setBackground(ApiCompatibilityUtils.getDrawable( context.getResources(), R.drawable.autofill_assistant_circle_background)); pulsor.setVisibility(View.GONE); return pulsor; } private ChromeImageView addIcon(RelativeLayout view, Context context) { ChromeImageView icon = new ChromeImageView(context); view.addView(icon); int size = context.getResources().getDimensionPixelSize( R.dimen.autofill_assistant_progress_icon_size); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(size, size); params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); icon.setLayoutParams(params); ApiCompatibilityUtils.setImageTintList( icon, ContextCompat.getColorStateList(context, COLOR_LIST)); icon.setEnabled(false); return icon; } private ValueAnimator createPulseAnimation() { ValueAnimator pulseAnimation = ValueAnimator.ofFloat(0f, PULSING_DURATION_MS); pulseAnimation.setDuration(PULSING_DURATION_MS); pulseAnimation.setInterpolator(Interpolators.LINEAR_INTERPOLATOR); pulseAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animator) { if (mShouldRunAnimation) { mPulsor.setScaleX(0f); mPulsor.setScaleY(0f); mPulsor.setAlpha(1f); mPulsor.setVisibility(View.VISIBLE); } } @Override public void onAnimationEnd(Animator animator) { mPulsor.setVisibility(View.GONE); mFirstAnimation = false; if (mShouldRunAnimation) { pulseAnimation.setStartDelay(PULSING_RESTART_DELAY_MS); pulseAnimation.start(); } } }); pulseAnimation.addUpdateListener(animation -> { float time = (float) animation.getAnimatedValue(); float scale = time / PULSING_DURATION_MS; mPulsor.setScaleX(scale); mPulsor.setScaleY(scale); float alpha = time < PULSING_ALPHA_CHANGE_DELAY_MS ? 1 : 1 - ((time - PULSING_ALPHA_CHANGE_DELAY_MS) / (float) (PULSING_DURATION_MS - PULSING_ALPHA_CHANGE_DELAY_MS)); mPulsor.setAlpha(alpha); }); return pulseAnimation; } void setIcon(AssistantDrawable drawable) { drawable.getDrawable(mContext, mIcon::setImageDrawable); } void setEnabled(boolean enabled) { mIcon.setEnabled(enabled); } void startEnabledAnimation() { if (mDisableAnimations) { setEnabled(true); return; } ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f); animator.setStartDelay(ANIMATION_DELAY_MS); animator.setDuration(ICON_ENABLED_ANIMATION_DURATION_MS); animator.setInterpolator(Interpolators.LINEAR_INTERPOLATOR); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animator) { mIcon.setScaleX(0f); mIcon.setScaleY(0f); mIcon.setEnabled(true); } @Override public void onAnimationEnd(Animator animator) { mIcon.setScaleX(1f); mIcon.setScaleY(1f); } }); animator.addUpdateListener(animation -> { float animatedValue = (float) animation.getAnimatedValue(); mIcon.setScaleX(animatedValue); mIcon.setScaleY(animatedValue); }); animator.start(); } void setPulsingAnimationEnabled(boolean pulsate) { if (pulsate) { startPulsingAnimation(/* delayed= */ false); } else { stopPulsingAnimation(); } } void startPulsingAnimation(boolean delayed) { if (mDisableAnimations) { return; } mFirstAnimation = true; mShouldRunAnimation = true; mPulseAnimation.setStartDelay(delayed ? ANIMATION_DELAY_MS + ICON_ENABLED_ANIMATION_DURATION_MS + LINE_ANIMATION_DURATION_MS : 0); mPulseAnimation.start(); } private void stopPulsingAnimation() { mShouldRunAnimation = false; } void setError(boolean error) { if (mIcon.isEnabled() || !error) { ApiCompatibilityUtils.setImageTintList(mIcon, ContextCompat.getColorStateList( mContext, error ? ERROR_COLOR_LIST : COLOR_LIST)); } else if ((!mPulseAnimation.isStarted() || mFirstAnimation) && !mDisableAnimations) { // This is in case when the blue line is animating towards the icon that we need to // set in error state. We want to wait for the line to reach the icon before turning // the icon red. mPulseAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animator) { mPulseAnimation.removeListener(this); ApiCompatibilityUtils.setImageTintList( mIcon, ContextCompat.getColorStateList(mContext, ERROR_COLOR_LIST)); } }); } else { mPulseAnimation.cancel(); ApiCompatibilityUtils.setImageTintList( mIcon, ContextCompat.getColorStateList(mContext, ERROR_COLOR_LIST)); } } } private static class LineViewHolder { private final Context mContext; private final LinearLayout mView; private final View mLineForeground; private boolean mDisableAnimations; LineViewHolder(ViewGroup view, Context context) { mContext = context; mView = addMainContainer(view, context); RelativeLayout relativeContainer = addRelativeContainer(mView, context); addBackgroundLine(relativeContainer, context); mLineForeground = addForegroundLine(relativeContainer, context); } void setTag(String tag) { mView.setTag(tag); } void disableAnimations(boolean disable) { mDisableAnimations = disable; } private LinearLayout addMainContainer(ViewGroup view, Context context) { LinearLayout container = new LinearLayout(context); view.addView(container); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, context.getResources().getDimensionPixelSize( R.dimen.autofill_assistant_progress_line_height)); params.weight = 1.0f; container.setLayoutParams(params); int padding = context.getResources().getDimensionPixelSize( R.dimen.autofill_assistant_progress_padding); container.setPadding(padding, 0, padding, 0); return container; } private RelativeLayout addRelativeContainer(ViewGroup view, Context context) { RelativeLayout container = new RelativeLayout(context); view.addView(container); return container; } private void addBackgroundLine(ViewGroup view, Context context) { View line = new View(context); view.addView(line); line.setBackground(ApiCompatibilityUtils.getDrawable(context.getResources(), R.drawable.autofill_assistant_rounded_corner_background)); line.setEnabled(false); } private View addForegroundLine(ViewGroup view, Context context) { View line = new View(context); view.addView(line); line.setBackground(ApiCompatibilityUtils.getDrawable(context.getResources(), R.drawable.autofill_assistant_rounded_corner_background)); line.setTag(AssistantTagsForTesting.PROGRESSBAR_LINE_FOREGROUND_TAG); line.setEnabled(true); line.setScaleX(0f); return line; } void setEnabled(boolean enabled) { mLineForeground.setScaleX(enabled ? 1f : 0f); } void startAnimation() { if (mDisableAnimations) { setEnabled(true); return; } ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f); animator.setStartDelay(ANIMATION_DELAY_MS + ICON_ENABLED_ANIMATION_DURATION_MS); animator.setDuration(LINE_ANIMATION_DURATION_MS); animator.setInterpolator(Interpolators.LINEAR_INTERPOLATOR); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animator) { mLineForeground.setScaleX(0f); mLineForeground.setPivotX(0f); } @Override public void onAnimationEnd(Animator animator) { mLineForeground.setScaleX(1f); mLineForeground.setPivotX(0f); } }); animator.addUpdateListener(animation -> { float animatedValue = (float) animation.getAnimatedValue(); mLineForeground.setScaleX(animatedValue); mLineForeground.setPivotX(-mLineForeground.getWidth()); }); animator.start(); } void setError(boolean error) { final @ColorInt int color = error ? ContextCompat.getColor(mContext, R.color.default_red) : SemanticColorUtils.getDefaultIconColorAccent1(mContext); mLineForeground.setBackgroundColor(color); } } private final ViewGroup mView; private int mNumberOfSteps; private IconViewHolder[] mIcons; private LineViewHolder[] mLines; private int mCurrentStep = -1; AssistantStepProgressBar(ViewGroup view) { mView = view; setSteps(new ArrayList<AssistantDrawable>() { { add(AssistantDrawable.createFromIcon( AssistantDrawableIcon.PROGRESSBAR_DEFAULT_INITIAL_STEP)); add(AssistantDrawable.createFromIcon( AssistantDrawableIcon.PROGRESSBAR_DEFAULT_FINAL_STEP)); } }); } public void setSteps(List<AssistantDrawable> icons) { assert icons.size() >= 2; // NOTE: instead of immediately removing the old icons, we first add the new ones. This // prevents a change of the bottom sheet height, which was the cause for animation glitches // (see b/174014637). int oldNumChilds = mView.getChildCount(); mNumberOfSteps = icons.size(); mCurrentStep = -1; mIcons = new IconViewHolder[mNumberOfSteps]; mLines = new LineViewHolder[mNumberOfSteps - 1]; for (int i = 0; i < mNumberOfSteps; ++i) { mIcons[i] = new IconViewHolder(mView, mView.getContext()); mIcons[i].setIcon(icons.get(i)); mIcons[i].setTag(String.format( Locale.getDefault(), AssistantTagsForTesting.PROGRESSBAR_ICON_TAG, i)); if (i < mNumberOfSteps - 1) { mLines[i] = new LineViewHolder(mView, mView.getContext()); mLines[i].setTag(String.format( Locale.getDefault(), AssistantTagsForTesting.PROGRESSBAR_LINE_TAG, i)); } } mView.removeViews(0, oldNumChilds); } public void setVisible(boolean visible) { mView.setVisibility(visible ? View.VISIBLE : View.GONE); } public void disableAnimations(boolean disable) { for (IconViewHolder icon : mIcons) { icon.disableAnimations(disable); } for (LineViewHolder line : mLines) { line.disableAnimations(disable); } } public void setActiveStep(int step) { assert step >= 0 && step <= mNumberOfSteps; assert step >= mCurrentStep; if (step == mCurrentStep) { return; } for (int i = 0; i < mNumberOfSteps; ++i) { if (i == mCurrentStep && step == mCurrentStep + 1) { mIcons[i].startEnabledAnimation(); } else { mIcons[i].setEnabled(i < step); } if (i == step && step == mCurrentStep + 1 && mCurrentStep != -1) { // In case we advance to a new step, start the enable animation on the current // icon. If not for the first step, start the pulsating animation with a delay such // that it only starts after the other animations have run. mIcons[i].startPulsingAnimation(/* delayed= */ true); } else { mIcons[i].setPulsingAnimationEnabled(i == step); } if (i < mNumberOfSteps - 1) { if (i == step - 1 && step == mCurrentStep + 1) { mLines[i].startAnimation(); } else { mLines[i].setEnabled(i < step); } } } mCurrentStep = step; } public void setError(boolean error) { boolean errorAfterCompletion = error && mCurrentStep >= mNumberOfSteps; for (int i = 0; i < mNumberOfSteps; ++i) { mIcons[i].setError(errorAfterCompletion || (error && i == mCurrentStep)); mIcons[i].setPulsingAnimationEnabled(!error && i == mCurrentStep); } for (LineViewHolder line : mLines) { line.setError(errorAfterCompletion); } } }
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.slaves; import hudson.AbortException; import hudson.FilePath; import hudson.Functions; import hudson.Main; import hudson.RestrictedSince; import hudson.Util; import hudson.console.ConsoleLogFilter; import hudson.model.Computer; import hudson.model.Executor; import hudson.model.ExecutorListener; import hudson.model.Node; import hudson.model.Queue; import hudson.model.Slave; import hudson.model.TaskListener; import hudson.model.User; import hudson.remoting.Channel; import hudson.remoting.ChannelBuilder; import hudson.remoting.ChannelClosedException; import hudson.remoting.CommandTransport; import hudson.remoting.Launcher; import hudson.remoting.VirtualChannel; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.slaves.OfflineCause.ChannelTermination; import hudson.util.Futures; import hudson.util.NullStream; import hudson.util.RingBufferLogHandler; import hudson.util.StreamTaskListener; import hudson.util.VersionNumber; import hudson.util.io.RewindableFileOutputStream; import hudson.util.io.RewindableRotatingFileOutputStream; import jenkins.agents.AgentComputerUtil; import jenkins.model.Jenkins; import jenkins.security.ChannelConfigurator; import jenkins.security.MasterToSlaveCallable; import jenkins.slaves.EncryptedSlaveAgentJnlpFile; import jenkins.slaves.JnlpAgentReceiver; import jenkins.slaves.RemotingVersionInfo; import jenkins.slaves.systemInfo.SlaveSystemInfo; import jenkins.util.SystemProperties; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.Beta; import org.kohsuke.accmod.restrictions.DoNotUse; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.interceptor.RequirePOST; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.CheckReturnValue; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.OverrideMustInvoke; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.nio.charset.Charset; import java.security.Security; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Future; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import static hudson.slaves.SlaveComputer.LogHolder.SLAVE_LOG_HANDLER; import org.jenkinsci.remoting.util.LoggingChannelListener; /** * {@link Computer} for {@link Slave}s. * * @author Kohsuke Kawaguchi */ public class SlaveComputer extends Computer { private volatile Channel channel; private volatile transient boolean acceptingTasks = true; private Charset defaultCharset; private Boolean isUnix; /** * Effective {@link ComputerLauncher} that hides the details of * how we launch a agent agent on this computer. * * <p> * This is normally the same as {@link Slave#getLauncher()} but * can be different. See {@link #grabLauncher(Node)}. */ private ComputerLauncher launcher; /** * Perpetually writable log file. */ private final RewindableFileOutputStream log; /** * {@link StreamTaskListener} that wraps {@link #log}, hence perpetually writable. */ private final TaskListener taskListener; /** * Number of failed attempts to reconnect to this node * (so that if we keep failing to reconnect, we can stop * trying.) */ private transient int numRetryAttempt; /** * Tracks the status of the last launch operation, which is always asynchronous. * This can be used to wait for the completion, or cancel the launch activity. */ private volatile Future<?> lastConnectActivity = null; private Object constructed = new Object(); private transient volatile String absoluteRemoteFs; public SlaveComputer(Slave slave) { super(slave); this.log = new RewindableRotatingFileOutputStream(getLogFile(), 10); this.taskListener = new StreamTaskListener(decorate(this.log)); assert slave.getNumExecutors()!=0 : "Computer created with 0 executors"; } /** * Uses {@link ConsoleLogFilter} to decorate logger. */ private OutputStream decorate(OutputStream os) { for (ConsoleLogFilter f : ConsoleLogFilter.all()) { try { os = f.decorateLogger(this,os); } catch (IOException|InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to filter log with "+f, e); } } return os; } @Override @OverrideMustInvoke public boolean isAcceptingTasks() { // our boolean flag is an override on any additional programmatic reasons why this agent might not be // accepting tasks. return acceptingTasks && super.isAcceptingTasks(); } /** * @since 1.498 */ public String getJnlpMac() { return JnlpAgentReceiver.SLAVE_SECRET.mac(getName()); } /** * Allows suspension of tasks being accepted by the agent computer. While this could be called by a * {@linkplain hudson.slaves.ComputerLauncher} or a {@linkplain hudson.slaves.RetentionStrategy}, such usage * can result in fights between multiple actors calling setting differential values. A better approach * is to override {@link hudson.slaves.RetentionStrategy#isAcceptingTasks(hudson.model.Computer)} if the * {@link hudson.slaves.RetentionStrategy} needs to control availability. * * @param acceptingTasks {@code true} if the agent can accept tasks. */ public void setAcceptingTasks(boolean acceptingTasks) { this.acceptingTasks = acceptingTasks; } @Override public Boolean isUnix() { return isUnix; } @CheckForNull @Override public Slave getNode() { Node node = super.getNode(); if (node == null || node instanceof Slave) { return (Slave)node; } else { logger.log(Level.WARNING, "found an unexpected kind of node {0} from {1} with nodeName={2}", new Object[] {node, this, nodeName}); return null; } } /** * Return the {@link TaskListener} for this SlaveComputer. Never null * @since 2.9 */ public TaskListener getListener() { return taskListener; } @Override public String getIcon() { Future<?> l = lastConnectActivity; if(l!=null && !l.isDone()) return "computer-flash.gif"; return super.getIcon(); } /** * @deprecated since 2008-05-20. */ @Deprecated @Override public boolean isJnlpAgent() { return launcher instanceof JNLPLauncher; } @Override public boolean isLaunchSupported() { return launcher.isLaunchSupported(); } /** * Return the {@link ComputerLauncher} for this SlaveComputer. * @since 1.312 */ public ComputerLauncher getLauncher() { return launcher; } /** * Return the {@link ComputerLauncher} for this SlaveComputer, strips off * any {@link DelegatingComputerLauncher}s or {@link ComputerLauncherFilter}s. * @since 2.83 */ public ComputerLauncher getDelegatedLauncher() { ComputerLauncher l = launcher; while (true) { if (l instanceof DelegatingComputerLauncher) { l = ((DelegatingComputerLauncher) l).getLauncher(); } else if (l instanceof ComputerLauncherFilter) { l = ((ComputerLauncherFilter) l).getCore(); } else { break; } } return l; } protected Future<?> _connect(boolean forceReconnect) { if(channel!=null) return Futures.precomputed(null); if(!forceReconnect && isConnecting()) return lastConnectActivity; if(forceReconnect && isConnecting()) logger.fine("Forcing a reconnect on "+getName()); closeChannel(); Throwable threadInfo = new Throwable("launched here"); return lastConnectActivity = Computer.threadPoolForRemoting.submit(() -> { // do this on another thread so that the lengthy launch operation // (which is typical) won't block UI thread. try (ACLContext ctx = ACL.as2(ACL.SYSTEM2)) {// background activity should run like a super user log.rewind(); try { for (ComputerListener cl : ComputerListener.all()) cl.preLaunch(SlaveComputer.this, taskListener); offlineCause = null; launcher.launch(SlaveComputer.this, taskListener); } catch (AbortException e) { e.addSuppressed(threadInfo); taskListener.error(e.getMessage()); throw e; } catch (IOException e) { e.addSuppressed(threadInfo); Util.displayIOException(e,taskListener); Functions.printStackTrace(e, taskListener.error(Messages.ComputerLauncher_unexpectedError())); throw e; } catch (InterruptedException e) { e.addSuppressed(threadInfo); Functions.printStackTrace(e, taskListener.error(Messages.ComputerLauncher_abortedLaunch())); throw e; } catch (Exception e) { e.addSuppressed(threadInfo); Functions.printStackTrace(e, taskListener.error(Messages.ComputerLauncher_unexpectedError())); throw e; } } finally { if (channel==null && offlineCause == null) { offlineCause = new OfflineCause.LaunchFailed(); for (ComputerListener cl : ComputerListener.all()) cl.onLaunchFailure(SlaveComputer.this, taskListener); } } if (channel==null) throw new IOException("Agent failed to connect, even though the launcher didn't report it. See the log output for details."); return null; }); } @Override public void taskAccepted(Executor executor, Queue.Task task) { super.taskAccepted(executor, task); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskAccepted(executor, task); } //getNode() can return null at indeterminate times when nodes go offline Slave node = getNode(); if (node != null && node.getRetentionStrategy() instanceof ExecutorListener) { ((ExecutorListener)node.getRetentionStrategy()).taskAccepted(executor, task); } } @Override public void taskCompleted(Executor executor, Queue.Task task, long durationMS) { super.taskCompleted(executor, task, durationMS); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskCompleted(executor, task, durationMS); } RetentionStrategy r = getRetentionStrategy(); if (r instanceof ExecutorListener) { ((ExecutorListener) r).taskCompleted(executor, task, durationMS); } } @Override public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) { super.taskCompletedWithProblems(executor, task, durationMS, problems); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskCompletedWithProblems(executor, task, durationMS, problems); } RetentionStrategy r = getRetentionStrategy(); if (r instanceof ExecutorListener) { ((ExecutorListener) r).taskCompletedWithProblems(executor, task, durationMS, problems); } } @Override public boolean isConnecting() { Future<?> l = lastConnectActivity; return isOffline() && l!=null && !l.isDone(); } public OutputStream openLogFile() { try { log.rewind(); return log; } catch (IOException e) { logger.log(Level.SEVERE, "Failed to create log file "+getLogFile(),e); return new NullStream(); } } private final Object channelLock = new Object(); /** * Creates a {@link Channel} from the given stream and sets that to this agent. * * Same as {@link #setChannel(InputStream, OutputStream, OutputStream, Channel.Listener)}, but for * {@link TaskListener}. */ public void setChannel(@NonNull InputStream in, @NonNull OutputStream out, @NonNull TaskListener taskListener, @CheckForNull Channel.Listener listener) throws IOException, InterruptedException { setChannel(in,out,taskListener.getLogger(),listener); } /** * Creates a {@link Channel} from the given stream and sets that to this agent. * * @param in * Stream connected to the remote agent. It's the caller's responsibility to do * buffering on this stream, if that's necessary. * @param out * Stream connected to the remote peer. It's the caller's responsibility to do * buffering on this stream, if that's necessary. * @param launchLog * If non-null, receive the portion of data in {@code is} before * the data goes into the "binary mode". This is useful * when the established communication channel might include some data that might * be useful for debugging/trouble-shooting. * @param listener * Gets a notification when the channel closes, to perform clean up. Can be null. * By the time this method is called, the cause of the termination is reported to the user, * so the implementation of the listener doesn't need to do that again. */ public void setChannel(@NonNull InputStream in, @NonNull OutputStream out, @CheckForNull OutputStream launchLog, @CheckForNull Channel.Listener listener) throws IOException, InterruptedException { ChannelBuilder cb = new ChannelBuilder(nodeName,threadPoolForRemoting) .withMode(Channel.Mode.NEGOTIATE) .withHeaderStream(launchLog); for (ChannelConfigurator cc : ChannelConfigurator.all()) { cc.onChannelBuilding(cb,this); } Channel channel = cb.build(in,out); setChannel(channel,launchLog,listener); } /** * Creates a {@link Channel} from the given Channel Builder and Command Transport. * This method can be used to allow {@link ComputerLauncher}s to create channels not based on I/O streams. * * @param cb * Channel Builder. * To print launch logs this channel builder should have a Header Stream defined * (see {@link ChannelBuilder#getHeaderStream()}) in this argument or by one of {@link ChannelConfigurator}s. * @param commandTransport * Command Transport * @param listener * Gets a notification when the channel closes, to perform clean up. Can be {@code null}. * By the time this method is called, the cause of the termination is reported to the user, * so the implementation of the listener doesn't need to do that again. * @since 2.127 */ @Restricted(Beta.class) public void setChannel(@NonNull ChannelBuilder cb, @NonNull CommandTransport commandTransport, @CheckForNull Channel.Listener listener) throws IOException, InterruptedException { for (ChannelConfigurator cc : ChannelConfigurator.all()) { cc.onChannelBuilding(cb,this); } OutputStream headerStream = cb.getHeaderStream(); if (headerStream == null) { LOGGER.log(Level.WARNING, "No header stream defined when setting channel for computer {0}. " + "Launch log won't be printed", this); } Channel channel = cb.build(commandTransport); setChannel(channel, headerStream, listener); } /** * Shows {@link Channel#classLoadingCount}. * @return Requested value or {@code -1} if the agent is offline. * @since 1.495 */ @CheckReturnValue public int getClassLoadingCount() throws IOException, InterruptedException { if (channel == null) { return -1; } return channel.call(new LoadingCount(false)); } /** * Shows {@link Channel#classLoadingPrefetchCacheCount}. * @return Requested value or {@code -1} in case that capability is not supported or if the agent is offline. * @since 1.519 */ @CheckReturnValue public int getClassLoadingPrefetchCacheCount() throws IOException, InterruptedException { if (channel == null) { return -1; } if (!channel.remoteCapability.supportsPrefetch()) { return -1; } return channel.call(new LoadingPrefetchCacheCount()); } /** * Shows {@link Channel#resourceLoadingCount}. * @return Requested value or {@code -1} if the agent is offline. * @since 1.495 */ @CheckReturnValue public int getResourceLoadingCount() throws IOException, InterruptedException { if (channel == null) { return -1; } return channel.call(new LoadingCount(true)); } /** * Shows {@link Channel#classLoadingTime}. * @return Requested value or {@code -1} if the agent is offline. * @since 1.495 */ @CheckReturnValue public long getClassLoadingTime() throws IOException, InterruptedException { if (channel == null) { return -1; } return channel.call(new LoadingTime(false)); } /** * Shows {@link Channel#resourceLoadingTime}. * @return Requested value or {@code -1} if the agent is offline. * @since 1.495 */ @CheckReturnValue public long getResourceLoadingTime() throws IOException, InterruptedException { if (channel == null) { return -1; } return channel.call(new LoadingTime(true)); } /** * Returns the remote FS root absolute path or {@code null} if the agent is off-line. The absolute path may change * between connections if the connection method does not provide a consistent working directory and the node's * remote FS is specified as a relative path. * * @return the remote FS root absolute path or {@code null} if the agent is off-line. * @since 1.606 */ @CheckForNull public String getAbsoluteRemoteFs() { return channel == null ? null : absoluteRemoteFs; } /** * Just for restFul api. * Returns the remote FS root absolute path or {@code null} if the agent is off-line. The absolute path may change * between connections if the connection method does not provide a consistent working directory and the node's * remote FS is specified as a relative path. * @see #getAbsoluteRemoteFs() * @return the remote FS root absolute path or {@code null} if the agent is off-line or don't have connect permission. * @since 2.125 */ @Exported @Restricted(DoNotUse.class) @CheckForNull public String getAbsoluteRemotePath() { if(hasPermission(CONNECT)) { return getAbsoluteRemoteFs(); } else { return null; } } static class LoadingCount extends MasterToSlaveCallable<Integer,RuntimeException> { private final boolean resource; LoadingCount(boolean resource) { this.resource = resource; } @Override public Integer call() { Channel c = Channel.current(); if (c == null) { return -1; } return resource ? c.resourceLoadingCount.get() : c.classLoadingCount.get(); } } static class LoadingPrefetchCacheCount extends MasterToSlaveCallable<Integer,RuntimeException> { @Override public Integer call() { Channel c = Channel.current(); if (c == null) { return -1; } return c.classLoadingPrefetchCacheCount.get(); } } static class LoadingTime extends MasterToSlaveCallable<Long,RuntimeException> { private final boolean resource; LoadingTime(boolean resource) { this.resource = resource; } @Override public Long call() { Channel c = Channel.current(); if (c == null) { return -1L; } return resource ? c.resourceLoadingTime.get() : c.classLoadingTime.get(); } } /** * Sets up the connection through an existing channel. * @param channel the channel to use; <strong>warning:</strong> callers are expected to have called {@link ChannelConfigurator} already. * @param launchLog Launch log. If not {@code null}, will receive launch log messages * @param listener Channel event listener to be attached (if not {@code null}) * @since 1.444 */ public void setChannel(@NonNull Channel channel, @CheckForNull OutputStream launchLog, @CheckForNull Channel.Listener listener) throws IOException, InterruptedException { if(this.channel!=null) throw new IllegalStateException("Already connected"); final TaskListener taskListener = launchLog != null ? new StreamTaskListener(launchLog) : TaskListener.NULL; PrintStream log = taskListener.getLogger(); channel.setProperty(SlaveComputer.class, this); channel.addListener(new LoggingChannelListener(logger, Level.FINEST) { @Override public void onClosed(Channel c, IOException cause) { // Orderly shutdown will have null exception if (cause!=null) { offlineCause = new ChannelTermination(cause); Functions.printStackTrace(cause, taskListener.error("Connection terminated")); } else { taskListener.getLogger().println("Connection terminated"); } closeChannel(); try { launcher.afterDisconnect(SlaveComputer.this, taskListener); } catch (Throwable t) { LogRecord lr = new LogRecord(Level.SEVERE, "Launcher {0}'s afterDisconnect method propagated an exception when {1}'s connection was closed: {2}"); lr.setThrown(t); lr.setParameters(new Object[]{launcher, SlaveComputer.this.getName(), t.getMessage()}); logger.log(lr); } } }); if(listener!=null) channel.addListener(listener); String slaveVersion = channel.call(new SlaveVersion()); log.println("Remoting version: " + slaveVersion); VersionNumber agentVersion = new VersionNumber(slaveVersion); if (agentVersion.isOlderThan(RemotingVersionInfo.getMinimumSupportedVersion())) { log.printf("WARNING: Remoting version is older than a minimum required one (%s). " + "Connection will not be rejected, but the compatibility is NOT guaranteed%n", RemotingVersionInfo.getMinimumSupportedVersion()); } boolean _isUnix = channel.call(new DetectOS()); log.println(_isUnix? hudson.model.Messages.Slave_UnixSlave():hudson.model.Messages.Slave_WindowsSlave()); String defaultCharsetName = channel.call(new DetectDefaultCharset()); Slave node = getNode(); if (node == null) { // Node has been disabled/removed during the connection throw new IOException("Node "+nodeName+" has been deleted during the channel setup"); } String remoteFS = node.getRemoteFS(); if (Util.isRelativePath(remoteFS)) { remoteFS = channel.call(new AbsolutePath(remoteFS)); log.println("NOTE: Relative remote path resolved to: "+remoteFS); } if(_isUnix && !remoteFS.contains("/") && remoteFS.contains("\\")) log.println("WARNING: "+remoteFS +" looks suspiciously like Windows path. Maybe you meant "+remoteFS.replace('\\','/')+"?"); FilePath root = new FilePath(channel,remoteFS); // reference counting problem is known to happen, such as JENKINS-9017, and so as a preventive measure // we pin the base classloader so that it'll never get GCed. When this classloader gets released, // it'll have a catastrophic impact on the communication. channel.pinClassLoader(getClass().getClassLoader()); channel.call(new SlaveInitializer(DEFAULT_RING_BUFFER_SIZE)); try (ACLContext ctx = ACL.as2(ACL.SYSTEM2)) { for (ComputerListener cl : ComputerListener.all()) { cl.preOnline(this,channel,root,taskListener); } } offlineCause = null; // update the data structure atomically to prevent others from seeing a channel that's not properly initialized yet synchronized(channelLock) { if(this.channel!=null) { // check again. we used to have this entire method in a big synchronization block, // but Channel constructor blocks for an external process to do the connection // if CommandLauncher is used, and that cannot be interrupted because it blocks at InputStream. // so if the process hangs, it hangs the thread in a lock, and since Hudson will try to relaunch, // we'll end up queuing the lot of threads in a pseudo deadlock. // This implementation prevents that by avoiding a lock. HUDSON-1705 is likely a manifestation of this. channel.close(); throw new IllegalStateException("Already connected"); } isUnix = _isUnix; numRetryAttempt = 0; this.channel = channel; this.absoluteRemoteFs = remoteFS; defaultCharset = Charset.forName(defaultCharsetName); synchronized (statusChangeLock) { statusChangeLock.notifyAll(); } } try (ACLContext ctx = ACL.as2(ACL.SYSTEM2)) { for (ComputerListener cl : ComputerListener.all()) { try { cl.onOnline(this,taskListener); } catch (Exception e) { // Per Javadoc log exceptions but still go online. // NOTE: this does not include Errors, which indicate a fatal problem taskListener.getLogger().format( "onOnline: %s reported an exception: %s%n", cl.getClass(), e.toString()); } catch (Throwable e) { closeChannel(); throw e; } } } log.println("Agent successfully connected and online"); Jenkins.get().getQueue().scheduleMaintenance(); } @Override public Channel getChannel() { return channel; } public Charset getDefaultCharset() { return defaultCharset; } public List<LogRecord> getLogRecords() throws IOException, InterruptedException { if(channel==null) return Collections.emptyList(); else return channel.call(new SlaveLogFetcher()); } @RequirePOST public HttpResponse doDoDisconnect(@QueryParameter String offlineMessage) { if (channel!=null) { //does nothing in case computer is already disconnected checkPermission(DISCONNECT); offlineMessage = Util.fixEmptyAndTrim(offlineMessage); disconnect(new OfflineCause.UserCause(User.current(), offlineMessage)); } return new HttpRedirect("."); } @Override public Future<?> disconnect(OfflineCause cause) { super.disconnect(cause); return Computer.threadPoolForRemoting.submit(new Runnable() { public void run() { // do this on another thread so that any lengthy disconnect operation // (which could be typical) won't block UI thread. launcher.beforeDisconnect(SlaveComputer.this, taskListener); closeChannel(); launcher.afterDisconnect(SlaveComputer.this, taskListener); } }); } @RequirePOST @Override public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException { checkPermission(CONNECT); if(channel!=null) { try { req.getView(this, "already-launched.jelly").forward(req, rsp); } catch (IOException x) { throw x; } catch (/*Servlet*/Exception x) { throw new IOException(x); } return; } connect(true); // TODO: would be nice to redirect the user to "launching..." wait page, // then spend a few seconds there and poll for the completion periodically. rsp.sendRedirect("log"); } public void tryReconnect() { numRetryAttempt++; if(numRetryAttempt<6 || (numRetryAttempt%12)==0) { // initially retry several times quickly, and after that, do it infrequently. logger.info("Attempting to reconnect "+nodeName); connect(true); } } /** * Serves jar files for inbound agents. * * @deprecated since 2008-08-18. * This URL binding is no longer used and moved up directly under to {@link jenkins.model.Jenkins}, * but it's left here for now just in case some old inbound agents request it. */ @Deprecated public Slave.JnlpJar getJnlpJars(String fileName) { return new Slave.JnlpJar(fileName); } @WebMethod(name="slave-agent.jnlp") public HttpResponse doSlaveAgentJnlp(StaplerRequest req, StaplerResponse res) { return doJenkinsAgentJnlp(req, res); } @WebMethod(name="jenkins-agent.jnlp") public HttpResponse doJenkinsAgentJnlp(StaplerRequest req, StaplerResponse res) { return new EncryptedSlaveAgentJnlpFile(this, "jenkins-agent.jnlp.jelly", getName(), CONNECT); } class LowPermissionResponse { @WebMethod(name="jenkins-agent.jnlp") public HttpResponse doJenkinsAgentJnlp(StaplerRequest req, StaplerResponse res) { return SlaveComputer.this.doJenkinsAgentJnlp(req, res); } @WebMethod(name="slave-agent.jnlp") public HttpResponse doSlaveAgentJnlp(StaplerRequest req, StaplerResponse res) { return SlaveComputer.this.doJenkinsAgentJnlp(req, res); } } @Override @Restricted(NoExternalUse.class) public Object getTarget() { if (!SKIP_PERMISSION_CHECK) { if (!Jenkins.get().hasPermission(Jenkins.READ)) { return new LowPermissionResponse(); } } return this; } @Override protected void kill() { super.kill(); closeChannel(); try { log.close(); } catch (IOException x) { LOGGER.log(Level.WARNING, "Failed to close agent log", x); } try { Util.deleteRecursive(getLogDir()); } catch (IOException ex) { logger.log(Level.WARNING, "Unable to delete agent logs", ex); } } public RetentionStrategy getRetentionStrategy() { Slave n = getNode(); return n==null ? RetentionStrategy.NOOP : n.getRetentionStrategy(); } /** * If still connected, disconnect. */ private void closeChannel() { // TODO: race condition between this and the setChannel method. Channel c; synchronized (channelLock) { c = channel; channel = null; absoluteRemoteFs = null; isUnix = null; } if (c != null) { try { c.close(); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to terminate channel to " + getDisplayName(), e); } for (ComputerListener cl : ComputerListener.all()) cl.onOffline(this, offlineCause); } } @Override protected void setNode(final Node node) { super.setNode(node); launcher = grabLauncher(node); // maybe the configuration was changed to relaunch the agent, so try to re-launch now. // "constructed==null" test is an ugly hack to avoid launching before the object is fully // constructed. if(constructed!=null) { if (node instanceof Slave) { Queue.withLock(new Runnable() { @Override public void run() { ((Slave)node).getRetentionStrategy().check(SlaveComputer.this); } }); } else { connect(false); } } } /** * Grabs a {@link ComputerLauncher} out of {@link Node} to keep it in this {@link Computer}. * The returned launcher will be set to {@link #launcher} and used to carry out the actual launch operation. * * <p> * Subtypes that needs to decorate {@link ComputerLauncher} can do so by overriding this method. * This is useful for {@link SlaveComputer}s for clouds for example, where one normally needs * additional pre-launch step (such as waiting for the provisioned node to become available) * before the user specified launch step (like SSH connection) kicks in. * * @see ComputerLauncherFilter */ protected ComputerLauncher grabLauncher(Node node) { return ((Slave)node).getLauncher(); } /** * Get the agent version */ @CheckReturnValue public String getSlaveVersion() throws IOException, InterruptedException { if (channel == null) { return "Unknown (agent is offline)"; } return channel.call(new SlaveVersion()); } /** * Get the OS description. */ @CheckReturnValue public String getOSDescription() throws IOException, InterruptedException { if (channel == null) { return "Unknown (agent is offline)"; } return channel.call(new DetectOS()) ? "Unix" : "Windows"; } /** * Expose real full env vars map from agent for UI presentation */ @CheckReturnValue public Map<String,String> getEnvVarsFull() throws IOException, InterruptedException { if (channel == null) { Map<String, String> env = new TreeMap<> (); env.put("N/A","N/A"); return env; } else { return channel.call(new ListFullEnvironment()); } } private static class ListFullEnvironment extends MasterToSlaveCallable<Map<String,String>,IOException> { public Map<String,String> call() throws IOException { Map<String, String> env = new TreeMap<>(System.getenv()); if(Main.isUnitTest || Main.isDevelopmentMode) { // if unit test is launched with maven debug switch, // we need to prevent forked Maven processes from seeing it, or else // they'll hang env.remove("MAVEN_OPTS"); } return env; } } private static final Logger logger = Logger.getLogger(SlaveComputer.class.getName()); private static final class SlaveVersion extends MasterToSlaveCallable<String,IOException> { public String call() throws IOException { try { return Launcher.VERSION; } catch (Throwable ex) { return "< 1.335"; } // Older agent.jar won't have VERSION } } private static final class DetectOS extends MasterToSlaveCallable<Boolean,IOException> { public Boolean call() throws IOException { return File.pathSeparatorChar==':'; } } private static final class AbsolutePath extends MasterToSlaveCallable<String,IOException> { private static final long serialVersionUID = 1L; private final String relativePath; private AbsolutePath(String relativePath) { this.relativePath = relativePath; } public String call() throws IOException { return new File(relativePath).getAbsolutePath(); } } private static final class DetectDefaultCharset extends MasterToSlaveCallable<String,IOException> { public String call() throws IOException { return Charset.defaultCharset().name(); } } /** * Puts the {@link #SLAVE_LOG_HANDLER} into a separate class so that loading this class * in JVM doesn't end up loading tons of additional classes. */ static final class LogHolder { /** * This field is used on each agent to record logs on the agent. */ static RingBufferLogHandler SLAVE_LOG_HANDLER; } private static class SlaveInitializer extends MasterToSlaveCallable<Void,RuntimeException> { final int ringBufferSize; public SlaveInitializer(int ringBufferSize) { this.ringBufferSize = ringBufferSize; } public Void call() { SLAVE_LOG_HANDLER = new RingBufferLogHandler(ringBufferSize); // avoid double installation of the handler. Inbound agents can reconnect to the master multiple times // and each connection gets a different RemoteClassLoader, so we need to evict them by class name, // not by their identity. for (Handler h : LOGGER.getHandlers()) { if (h.getClass().getName().equals(SLAVE_LOG_HANDLER.getClass().getName())) LOGGER.removeHandler(h); } LOGGER.addHandler(SLAVE_LOG_HANDLER); // remove Sun PKCS11 provider if present. See http://wiki.jenkins-ci.org/display/JENKINS/Solaris+Issue+6276483 try { Security.removeProvider("SunPKCS11-Solaris"); } catch (SecurityException e) { // ignore this error. } try { getChannelOrFail().setProperty("slave",Boolean.TRUE); // indicate that this side of the channel is the agent side. } catch (ChannelClosedException e) { throw new IllegalStateException(e); } return null; } private static final long serialVersionUID = 1L; private static final Logger LOGGER = Logger.getLogger(""); } /** * Obtains a {@link VirtualChannel} that allows some computation to be performed on the master. * This method can be called from any thread on the master, or from agent (more precisely, * it only works from the remoting request-handling thread in agents, which means if you've started * separate thread on agents, that'll fail.) * * @return null if the calling thread doesn't have any trace of where its master is. * @since 1.362 * @deprecated Use {@link AgentComputerUtil#getChannelToMaster()} instead. */ @Deprecated public static VirtualChannel getChannelToMaster() { return AgentComputerUtil.getChannelToMaster(); } /** * Helper method for Jelly. */ @Restricted(DoNotUse.class) @RestrictedSince("TODO") public static List<SlaveSystemInfo> getSystemInfoExtensions() { return SlaveSystemInfo.all(); } private static class SlaveLogFetcher extends MasterToSlaveCallable<List<LogRecord>,RuntimeException> { public List<LogRecord> call() { return new ArrayList<>(SLAVE_LOG_HANDLER.getView()); } } // use RingBufferLogHandler class name to configure for backward compatibility private static final int DEFAULT_RING_BUFFER_SIZE = SystemProperties.getInteger(RingBufferLogHandler.class.getName() + ".defaultSize", 256); private static final Logger LOGGER = Logger.getLogger(SlaveComputer.class.getName()); }
/* Copyright 2004 The Apache Software Foundation * * 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 compile.scomp.detailed; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.Assert; import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; import java.io.File; import java.util.*; import compile.scomp.common.CompileCommon; import javax.xml.namespace.QName; public class DetailedCompTests extends TestCase { public DetailedCompTests(String name) { super(name); } public static Test suite() { return new TestSuite(DetailedCompTests.class); } /** * This test requires laxDoc.xsd to be compiled and * on the classpath ahead of time, otherwise documentation * element processing would not occur * @throws Exception */ public void testLaxDocProcessing() throws Exception { QName q = new QName("urn:lax.Doc.Compilation", "ItemRequest"); ArrayList err = new ArrayList(); XmlOptions xm_opt = new XmlOptions().setErrorListener(err); xm_opt.setSavePrettyPrint(); XmlObject xObj = XmlObject.Factory.parse( new File(CompileCommon.fileLocation+"/detailed/laxDoc.xsd")); XmlObject[] schemas = new XmlObject[]{xObj}; // ensure exception is thrown when // xmloptions flag is not set boolean valDocEx = false; try{ SchemaTypeSystem sts = XmlBeans.compileXmlBeans(null, null, schemas, null, XmlBeans.getBuiltinTypeSystem(), null, xm_opt); Assert.assertTrue("STS was null", sts != null); }catch(XmlException xmlEx){ valDocEx = true; System.err.println("Expected Error: "+xmlEx.getMessage()); } catch(Exception e){ throw e; } //check exception was thrown if(!valDocEx) throw new Exception("Documentation processing " + "should have thrown and error"); // validate error code valDocEx = false; for (Iterator iterator = err.iterator(); iterator.hasNext();) { XmlError xErr = (XmlError)iterator.next(); //System.out.println("ERROR: '"+ xErr+"'"); //any one of these are possible if(xErr.getErrorCode().compareTo("cvc-complex-type.4") == 0 || xErr.getErrorCode().compareTo("cvc-complex-type.2.3") == 0 || xErr.getErrorCode().compareTo("cvc-complex-type.2.4c") == 0) valDocEx = true; } if (!valDocEx) throw new Exception("Expected Error code did not validate"); //reset errors err.clear(); //ensure no exception when error xm_opt = xm_opt.setCompileNoValidation(); try { SchemaTypeSystem sts = XmlBeans.compileXmlBeans(null, null, schemas, null, XmlBeans.getBuiltinTypeSystem(), null, xm_opt); if(!err.isEmpty()) throw new Exception("Error listener should be empty"); for (Iterator iterator = err.iterator(); iterator.hasNext();) { System.out.println(iterator.next()); } SchemaGlobalElement sge = sts.findElement(q); System.out.println("QName: " + sge.getName()); System.out.println("Type: " + sge.getType()); } catch (Exception e) { throw e; } } private static final String schema_begin = "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n"; private static final String root_decl = "<xs:element name=\"root\">\n <xs:complexType>\n"; private static final String att_decl = " <xs:attribute name=\"att\" type=\"simpleNotType\"/>\n"; private static final String root_end = " </xs:complexType>\n</xs:element>\n"; private static final String schema_end = "</xs:schema>\n"; private static final String notation1 = " <xs:attribute name=\"att\" type=\"xs:NOTATION\"/>\n"; private static final String notation2 = "<xs:simpleType name=\"simpleNotType\">\n" + " <xs:restriction base=\"xs:NOTATION\">\n" + " <xs:pattern value=\"ns:.*\"/>\n" + " </xs:restriction>\n</xs:simpleType>\n"; private static final String notation3 = " <xs:sequence>\n " + "<xs:element name=\"elem\" type=\"xs:ID\"/>\n" + " </xs:sequence>\n"; private static final String notation4 = " targetNamespace=\"scomp.detailed.CompilationTests\" " + "xmlns=\"scomp.detailed.CompilationTests\">\n"; private static final String simpleTypeDef= "<xs:simpleType name=\"simpleNotType\">\n" + " <xs:restriction base=\"enumDef\">\n"; private static final String notation6 = " <xs:pattern value=\"ns:.*\"/>\n"; private static final String notation5 = " <xs:length value=\"6\"/>\n"; private static final String enumDef = " </xs:restriction>\n</xs:simpleType>\n" + "<xs:simpleType name=\"enumDef\">\n" + " <xs:restriction base=\"xs:NOTATION\" xmlns:ns=\"namespace.notation\">\n" + " <xs:enumeration value=\"ns:app1\"/>\n" + " <xs:enumeration value=\"ns:app2\"/>\n" + " </xs:restriction>\n</xs:simpleType>\n"; private static final String doc_begin = "<root xmlns:ns=\"namespace.notation\" " + "xmlns:app=\"namespace.notation\" att=\""; private static final String doc_end = "\"/>"; private static final String notation7 = "ns1:app1"; private static final String notation8 = "ns:app"; private static final String notation9 = "app:app1"; private static final String notation10 = "ns:app1"; /** * This tests usage of the xs:NOTATION type * @throws Exception */ public void testNotation() throws Exception { String schema; String xml; SchemaTypeSystem typeSystem; XmlObject[] parsedSchema = new XmlObject[1]; XmlObject parsedDoc; XmlOptions opts = new XmlOptions(); ArrayList errors = new ArrayList(); opts.setErrorListener(errors); opts.put("COMPILE_PARTIAL_TYPESYSTEM"); // 1. Negative test - Error if xs:NOTATION used directly schema = schema_begin + root_decl + notation1 + root_end + schema_end; // System.out.println(schema); parsedSchema[0] = SchemaDocument.Factory.parse(schema); errors.clear(); XmlBeans.compileXsd(parsedSchema, null, opts); assertTrue("Expected error: NOTATION type cannot be used directly", errors.size() == 1); assertEquals("Expected error: NOTATION type cannot be used directly", XmlErrorCodes.ATTR_NOTATION_TYPE_FORBIDDEN, ((XmlError)errors.get(0)).getErrorCode()); assertEquals(XmlError.SEVERITY_ERROR, ((XmlError)errors.get(0)).getSeverity()); // 2. Negative test - Error if xs:NOTATION restricted without enumeration schema = schema_begin + root_decl + att_decl + root_end + notation2 + schema_end; // System.out.println(schema); parsedSchema[0] = SchemaDocument.Factory.parse(schema); errors.clear(); XmlBeans.compileXsd(parsedSchema, null, opts); assertTrue("Expected error: restriction of NOTATION must use enumeration facet", errors.size() == 1); assertEquals("Expected error: restriction of NOTATION must use enumeration facet", XmlErrorCodes.DATATYPE_ENUM_NOTATION, ((XmlError)errors.get(0)).getErrorCode()); assertEquals(XmlError.SEVERITY_ERROR, ((XmlError)errors.get(0)).getSeverity()); // 3. Warning if xs:NOTATION used as type of an element final String correctTypes = simpleTypeDef + notation6 + enumDef; schema = schema_begin + root_decl + notation3 + root_end + correctTypes + schema_end; // System.out.println(schema); parsedSchema[0] = SchemaDocument.Factory.parse(schema); errors.clear(); XmlBeans.compileXsd(parsedSchema, null, opts); assertTrue("Expected warning: NOTATION-derived type should not be used on elements", errors.size() == 1); assertEquals("Expected warning: NOTATION-derived type should not be used on elements", XmlErrorCodes.ELEM_COMPATIBILITY_TYPE, ((XmlError)errors.get(0)).getErrorCode()); assertEquals(XmlError.SEVERITY_WARNING, ((XmlError)errors.get(0)).getSeverity()); // 4. Warning if xs:NOTATION is used in a Schema with target namespace schema = schema_begin.substring(0, schema_begin.length() - 2) + notation4 + root_decl + att_decl + root_end + correctTypes + schema_end; // System.out.println(schema); parsedSchema[0] = SchemaDocument.Factory.parse(schema); errors.clear(); XmlBeans.compileXsd(parsedSchema, null, opts); assertTrue("Expected warning: NOTATION-derived type should not be used in a Schema with target namespace", errors.size() == 1); assertEquals("Expected warning: NOTATION-derived type should not be used in a Schema with target namespace", XmlErrorCodes.ATTR_COMPATIBILITY_TARGETNS, ((XmlError)errors.get(0)).getErrorCode()); assertEquals(XmlError.SEVERITY_WARNING, ((XmlError)errors.get(0)).getSeverity()); // 5. Warning - Deprecation of minLength, maxLength and length facets schema = schema_begin + root_decl + att_decl + root_end + simpleTypeDef + notation5 + enumDef + schema_end; // System.out.println(schema); parsedSchema[0] = SchemaDocument.Factory.parse(schema); errors.clear(); XmlBeans.compileXsd(parsedSchema, null, opts); assertTrue("Expected warning: length facet cannot be used on a type derived from NOTATION", errors.size() == 1); assertEquals("Expected warning: length facet cannot be used on a type derived from NOTATION", XmlErrorCodes.FACETS_DEPRECATED_NOTATION, ((XmlError)errors.get(0)).getErrorCode()); assertEquals(XmlError.SEVERITY_WARNING, ((XmlError)errors.get(0)).getSeverity()); // 6. Positive test - Test restriction via enumeration, then same as 2 schema = schema_begin + root_decl + att_decl + root_end + correctTypes + schema_end; // System.out.println(schema); parsedSchema[0] = SchemaDocument.Factory.parse(schema); errors.clear(); typeSystem = XmlBeans.compileXsd(parsedSchema, null, opts); assertTrue("Expected no errors or warnings", errors.size() == 0); SchemaType docType = typeSystem.findDocumentType(new QName("", "root")); SchemaType type = docType.getElementProperty(new QName("", "root")).getType(). getAttributeProperty(new QName("", "att")).getType(); assertEquals(type.getPrimitiveType().getBuiltinTypeCode(), SchemaType.BTC_NOTATION); SchemaTypeLoader loader = XmlBeans.typeLoaderUnion(new SchemaTypeLoader[] {typeSystem, XmlBeans.getBuiltinTypeSystem()}); // 7. Validation negative - Test error if QName has bad prefix xml = doc_begin + notation7 + doc_end; parsedDoc = loader.parse(xml, null, opts); assertEquals("Did not find the root element in the Schema", docType, parsedDoc.schemaType()); errors.clear(); parsedDoc.validate(opts); // Both "prefix not found" and "pattern doesn't match" errors assertTrue("Expected validation errors", errors.size() == 2); // Unfortunately, can't get the error code because it is logged via an intermediate exception assertTrue("Expected prefix not found error", ((XmlError) errors.get(0)).getMessage(). indexOf("Invalid QName") >= 0); assertEquals(XmlError.SEVERITY_ERROR, ((XmlError) errors.get(0)).getSeverity()); // System.out.println(xml); // 8. Validation negative - Test error if QName has correct prefix but not in enumeration xml = doc_begin + notation8 + doc_end; parsedDoc = loader.parse(xml, null, opts); assertEquals("Did not find the root element in the Schema", docType, parsedDoc.schemaType()); errors.clear(); parsedDoc.validate(opts); assertTrue("Expected validation errors", errors.size() == 1); assertEquals("Expected prefix not found error", XmlErrorCodes.DATATYPE_ENUM_VALID, ((XmlError) errors.get(0)).getErrorCode()); assertEquals(XmlError.SEVERITY_ERROR, ((XmlError) errors.get(0)).getSeverity()); // System.out.println(xml); // 9. Validation negative - Test error if QName doesn't match the extra facet xml = doc_begin + notation9 + doc_end; parsedDoc = loader.parse(xml, null, opts); assertEquals("Did not find the root element in the Schema", docType, parsedDoc.schemaType()); errors.clear(); parsedDoc.validate(opts); assertTrue("Expected validation errors", errors.size() == 1); assertEquals("Expected prefix not found error", XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, ((XmlError) errors.get(0)).getErrorCode()); assertEquals(XmlError.SEVERITY_ERROR, ((XmlError) errors.get(0)).getSeverity()); // System.out.println(xml); // 10. Validation positive - Test that validation can be performed correctly xml = doc_begin + notation10 + doc_end; parsedDoc = loader.parse(xml, null, opts); assertEquals("Did not find the root element in the Schema", docType, parsedDoc.schemaType()); errors.clear(); parsedDoc.validate(opts); assertTrue("Expected no validation errors", errors.size() == 0); // System.out.println(xml); } }
package fi.aalto.trafficsense.trafficsense.backend.backend_util; import android.app.AlarmManager; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import com.google.firebase.messaging.RemoteMessage; import fi.aalto.trafficsense.trafficsense.R; import fi.aalto.trafficsense.trafficsense.TrafficSenseApplication; import fi.aalto.trafficsense.trafficsense.ui.MainActivity; import fi.aalto.trafficsense.trafficsense.util.EnvInfo; import fi.aalto.trafficsense.trafficsense.util.TSBootReceiver; import timber.log.Timber; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import static android.app.AlarmManager.RTC; /** * Created by mikko.rinne@aalto.fi on 16/12/16. * * Store notifications coming from the server * (Currently implemented with Firebase messaging) */ public class ServerNotification { private String uriString; private String messageTitle; private String messageBody; private int notificationType = NOTIFICATION_TYPE_UNKNOWN; private boolean shouldCreateNotification = true; public static final String FB_TOPIC_SURVEY = "surveys"; public static final String FB_TOPIC_BROADCAST = "broadcast"; private static final String FB_TOPIC_PREFIX = "/topics/"; public static final String KEY_NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; public static final String KEY_NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; public static final String KEY_NOTIFICATION_URI = "NOTIFICATION_URI"; public static final String KEY_NOTIFICATION_TYPE = "NOTIFICATION_TYPE"; public static final String KEY_NOTIFICATION_TITLE_FI = "NOTIFICATION_TITLE_FI"; public static final String KEY_NOTIFICATION_MESSAGE_FI = "NOTIFICATION_MESSAGE_FI"; public static final String KEY_NOTIFICATION_URI_FI = "NOTIFICATION_URI_FI"; public static final String KEY_PTP_ALERT_TITLE = "PTP_ALERT_TITLE"; public static final String KEY_PTP_ALERT_MESSAGE = "PTP_ALERT_MESSAGE"; public static final String KEY_PTP_ALERT_LAT = "PTP_ALERT_LAT"; public static final String KEY_PTP_ALERT_LNG = "PTP_ALERT_LNG"; public static final int SERVER_NOTIFICATION_ID = 1213; public static final String PTP_ALERT_END_ACTION = "fi.aalto.trafficsense.action.PTP_ALERT_END"; public static final int NOTIFICATION_TYPE_UNKNOWN = 0; public static final int NOTIFICATION_TYPE_SURVEY = 1; public static final int NOTIFICATION_TYPE_BROADCASTMESSAGE = 2; public static final int NOTIFICATION_TYPE_FERRY = 3; public static final int NOTIFICATION_TYPE_SUBWAY = 4; public static final int NOTIFICATION_TYPE_TRAIN = 5; public static final int NOTIFICATION_TYPE_TRAM = 6; public static final int NOTIFICATION_TYPE_BUS = 7; public static final int NOTIFICATION_TYPE_DIGITRAFFIC = 8; private static final String PTP_ALERT_PUBTRANS = "PTP_ALERT_PUBTRANS"; private static final String PTP_ALERT_TRAFFIC = "PTP_ALERT_TRAFFIC"; private static final String PTP_ALERT_END = "PTP_ALERT_END"; private static final String PTP_ALERT_TYPE = "PTP_ALERT_TYPE"; private static final String PTP_NOTIFICATION = "PTP_NOTIFICATION"; public static final String NOTIFICATION_PREFS_FILE_NAME = "SurveyPrefs"; private static String CHANNEL_ID = "trafficsense_server"; private SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); public ServerNotification(String mUri, String mTitle, String mBody) { uriString = mUri; messageTitle = mTitle; messageBody = mBody; } public ServerNotification(RemoteMessage remoteMessage) { // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { String from = remoteMessage.getFrom(); Timber.d("From: %s", from); Map<String, String> msgPayload = remoteMessage.getData(); // All messages currently may have a title, message and uri. if (msgPayload.containsKey(KEY_NOTIFICATION_TITLE)) { messageTitle = msgPayload.get(KEY_NOTIFICATION_TITLE); } else { shouldCreateNotification = false; } if (msgPayload.containsKey(KEY_NOTIFICATION_MESSAGE)) { messageBody = msgPayload.get(KEY_NOTIFICATION_MESSAGE); } else { shouldCreateNotification = false; } if (msgPayload.containsKey(KEY_NOTIFICATION_URI)) { uriString = msgPayload.get(KEY_NOTIFICATION_URI); } else { uriString = ""; } // If terminal locale is set to Finnish and there is Finnish content => replace String loc = Locale.getDefault().getLanguage(); // Timber.d("ServerNotification got language as: %s", loc); if (loc.equalsIgnoreCase("fi")) { if (msgPayload.containsKey(KEY_NOTIFICATION_TITLE_FI)) { messageTitle = msgPayload.get(KEY_NOTIFICATION_TITLE_FI); } if (msgPayload.containsKey(KEY_NOTIFICATION_MESSAGE_FI)) { messageBody = msgPayload.get(KEY_NOTIFICATION_MESSAGE_FI); } if (msgPayload.containsKey(KEY_NOTIFICATION_URI_FI)) { uriString = msgPayload.get(KEY_NOTIFICATION_URI_FI); } else { uriString = ""; } } if (from.startsWith(FB_TOPIC_PREFIX)) { // Broadcast topic message if (from.endsWith(FB_TOPIC_SURVEY)) { Timber.d("Survey received"); notificationType = NOTIFICATION_TYPE_SURVEY; } else if (from.endsWith(FB_TOPIC_BROADCAST)) { Timber.d("Generic Broadcast received"); notificationType = NOTIFICATION_TYPE_BROADCASTMESSAGE; } // Store without field replacements -> Survey should get the latest numbers, when launched SharedPreferences mPref = TrafficSenseApplication.getContext().getSharedPreferences(NOTIFICATION_PREFS_FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor mPrefEditor = mPref.edit(); if (uriString.length()>5) { mPrefEditor.putString(KEY_NOTIFICATION_URI, uriString); Timber.d("Survey URI String stored as: %s", uriString); mPrefEditor.putString(KEY_NOTIFICATION_MESSAGE, messageBody); Timber.d("Message Notification Body: %s", messageBody); mPrefEditor.putInt(KEY_NOTIFICATION_TYPE, notificationType); } else { mPrefEditor.remove(KEY_NOTIFICATION_URI); mPrefEditor.remove(KEY_NOTIFICATION_MESSAGE); mPrefEditor.remove(KEY_NOTIFICATION_TYPE); } mPrefEditor.apply(); } else { // No topic - point-to-point message Timber.d("ServerNotification received a point-to-point"); // Only Traffic Alerts currently contain a location: if (msgPayload.containsKey(PTP_ALERT_TRAFFIC)) { SharedPreferences mPref = TrafficSenseApplication.getContext().getSharedPreferences(NOTIFICATION_PREFS_FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor mPrefEditor = mPref.edit(); if (msgPayload.containsKey(KEY_PTP_ALERT_LAT) && msgPayload.containsKey(KEY_PTP_ALERT_LNG)) { mPrefEditor.putFloat(KEY_PTP_ALERT_LAT, Float.parseFloat(msgPayload.get(KEY_PTP_ALERT_LAT))); mPrefEditor.putFloat(KEY_PTP_ALERT_LNG, Float.parseFloat(msgPayload.get(KEY_PTP_ALERT_LNG))); mPrefEditor.putString(KEY_PTP_ALERT_TITLE, addLinebreaks(messageTitle, 30)); mPrefEditor.putString(KEY_PTP_ALERT_MESSAGE, addLinebreaks(messageBody, 30)); Timber.d("Saved PTP Traffic alert position."); } else { Timber.d("Clearing a PTP Traffic alert position."); mPrefEditor.remove(KEY_PTP_ALERT_LAT); mPrefEditor.remove(KEY_PTP_ALERT_LNG); mPrefEditor.remove(KEY_PTP_ALERT_MESSAGE); } mPrefEditor.apply(); } // Common processing for public transport and traffic alerts if (msgPayload.containsKey(PTP_ALERT_PUBTRANS) || msgPayload.containsKey(PTP_ALERT_TRAFFIC)) { long now = System.currentTimeMillis(); long alertEndMillis = now + (15 * 60 * 1000); // Default 15 minutes if (msgPayload.containsKey(PTP_ALERT_END)) { // Alert expiration time specified Date alertEndDate = new Date(); Timber.d("PTP Alert End is: %s", msgPayload.get(PTP_ALERT_END)); try { alertEndDate = dateTimeFormat.parse(msgPayload.get(PTP_ALERT_END)); } catch (ParseException e) { Timber.d("ServerNotification failed to parse PTP_ALERT_END: %s", e.getMessage()); e.printStackTrace(); } Timber.d("Now is: %d Alert End is: %d", now, alertEndMillis); if (alertEndDate.getTime() > now) { alertEndMillis = alertEndDate.getTime(); } } Timber.d("ServerNotification set alert duration as %d ms.", alertEndMillis - now); // Set up an alarm for the alert end time Context ctx = TrafficSenseApplication.getContext(); AlarmManager alarmManager = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(ctx, TSBootReceiver.class); intent.setAction(PTP_ALERT_END_ACTION); intent.putExtra("notification_id", SERVER_NOTIFICATION_ID); PendingIntent pi = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.set(RTC, alertEndMillis, pi); if (msgPayload.containsKey(PTP_ALERT_TYPE)) { switch (msgPayload.get(PTP_ALERT_TYPE)) { case "TRAIN": notificationType = NOTIFICATION_TYPE_TRAIN; break; case "TRAM": notificationType = NOTIFICATION_TYPE_TRAM; break; case "SUBWAY": notificationType = NOTIFICATION_TYPE_SUBWAY; break; case "BUS": notificationType = NOTIFICATION_TYPE_BUS; break; case "FERRY": notificationType = NOTIFICATION_TYPE_FERRY; break; case "DIGITRAFFIC": notificationType = NOTIFICATION_TYPE_DIGITRAFFIC; break; default: notificationType = NOTIFICATION_TYPE_UNKNOWN; } } } else if (msgPayload.containsKey(PTP_NOTIFICATION)) { notificationType = NOTIFICATION_TYPE_BROADCASTMESSAGE; } else { // Unknown PTP - do not post shouldCreateNotification = false; } } } } /** * Post the server notification */ public void postNotification() { int notificationIcon; switch (notificationType) { case NOTIFICATION_TYPE_SURVEY: notificationIcon = R.drawable.md_survey; break; case NOTIFICATION_TYPE_BROADCASTMESSAGE: notificationIcon = R.drawable.ic_info_outline_24dp; break; case NOTIFICATION_TYPE_FERRY: notificationIcon = R.drawable.md_activity_ferry_24dp; break; case NOTIFICATION_TYPE_SUBWAY: notificationIcon = R.drawable.md_activity_subway_24dp; break; case NOTIFICATION_TYPE_TRAIN: notificationIcon = R.drawable.md_activity_train_24dp; break; case NOTIFICATION_TYPE_TRAM: notificationIcon = R.drawable.md_activity_subway_24dp; break; case NOTIFICATION_TYPE_BUS: notificationIcon = R.drawable.md_activity_bus_24dp; break; case NOTIFICATION_TYPE_DIGITRAFFIC: notificationIcon = R.drawable.md_activity_vehicle_24dp; break; default: notificationIcon = R.mipmap.ic_launcher; } Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Context ctx = TrafficSenseApplication.getContext(); // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = ctx.getText(R.string.app_name) + " " + ctx.getText(R.string.notif_chan_service_name); NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT); channel.setDescription(ctx.getString(R.string.notif_chan_service_desc)); NotificationManager notificationManager = ctx.getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(TrafficSenseApplication.getContext(), CHANNEL_ID) .setSmallIcon(notificationIcon) .setColor(ContextCompat.getColor(TrafficSenseApplication.getContext(),R.color.colorTilting)) .setContentTitle(messageTitle) .setContentText(messageBody) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setSound(defaultSoundUri) // Notifications from 4.1 onwards .setStyle(new NotificationCompat.BigTextStyle() .bigText(messageBody)); // Set notification click behavior Intent notificationIntent; if (uriString.length()>5) { // If we have a URI, clicking will open it notificationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(EnvInfo.replaceUriFields(uriString))); } else { // Otherwise click will open MainActivity notificationIntent = new Intent(TrafficSenseApplication.getContext(), MainActivity.class); } PendingIntent pendingIntent = PendingIntent.getActivity(TrafficSenseApplication.getContext(), 0 /* Request code */, notificationIntent, PendingIntent.FLAG_ONE_SHOT); notificationBuilder.setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) TrafficSenseApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(SERVER_NOTIFICATION_ID /* ID of notification */, notificationBuilder.build()); } public boolean shouldCreateNotification() { return shouldCreateNotification; } // From http://stackoverflow.com/a/7528259/5528498 private String addLinebreaks(String input, int maxLineLength) { StringTokenizer tok = new StringTokenizer(input, " "); StringBuilder output = new StringBuilder(input.length()); int lineLen = 0; while (tok.hasMoreTokens()) { String word = tok.nextToken()+" "; if (lineLen + word.length() > maxLineLength) { output.append("\n"); lineLen = 0; } output.append(word); lineLen += word.length(); } return output.toString(); } }
/* * 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.uima.caseditor.ide; import org.apache.uima.caseditor.CasEditorPlugin; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.dialogs.PropertyPage; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; /** * Type System Property Page to set the default type system location of a project. */ public class TypeSystemLocationPropertyPage extends PropertyPage { public final static String TYPE_SYSTEM_PROPERTY = "UimaCasEditorTypeSystemPath"; private static final String DEFAULT_TYPE_SYSTEM_PATH = "TypeSystem.xml"; private Text typeSystemText; IProject getProject() { return (IProject) getElement().getAdapter(IProject.class); } String getDefaultTypeSystemLocation() { IProject project = getProject(); if (project != null) { return project.getFile(DEFAULT_TYPE_SYSTEM_PATH).getFullPath().toString(); } else { return ""; } } @Override protected Control createContents(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(); data.verticalAlignment = GridData.FILL; data.horizontalAlignment = GridData.FILL; composite.setLayoutData(data); Label instructions = new Label(composite, SWT.WRAP); instructions.setText("Select the default type system which is used to open CASes:"); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; gd.grabExcessHorizontalSpace = true; instructions.setLayoutData(gd); typeSystemText = new Text(composite, SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); typeSystemText.setLayoutData(gd); typeSystemText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent event) { updateApplyButton(); } }); try { String typeSystemPath = ((IResource) getElement()) .getPersistentProperty(new QualifiedName("", TYPE_SYSTEM_PROPERTY)); typeSystemText .setText((typeSystemPath != null) ? typeSystemPath : getDefaultTypeSystemLocation()); } catch (CoreException e) { typeSystemText.setText(DEFAULT_TYPE_SYSTEM_PATH); } Button browseButton = new Button(composite, SWT.PUSH); browseButton.setText("Browse ..."); browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider()); dialog.setTitle("Select descriptor"); dialog.setMessage("Select descriptor"); dialog.setInput(ResourcesPlugin.getWorkspace().getRoot()); dialog.setInitialSelection( ResourcesPlugin.getWorkspace().getRoot().findMember(typeSystemText.getText())); if (dialog.open() == IDialogConstants.OK_ID) { IResource resource = (IResource) dialog.getFirstResult(); if (resource != null) { String fileLoc = resource.getFullPath().toString(); typeSystemText.setText(fileLoc); } } } }); return composite; } @Override protected void performDefaults() { typeSystemText.setText(getDefaultTypeSystemLocation()); } @Override public boolean performOk() { // have check, so performOk is only done when ts file is a valid file string // store the value in the owner text field try { ((IResource) getElement()).setPersistentProperty(new QualifiedName("", TYPE_SYSTEM_PROPERTY), typeSystemText.getText()); } catch (CoreException e) { return false; } return true; } /** * Retrieves the type system or null if its not set. * * @param project * - * @return the type system location or null if its not set */ public static IFile getTypeSystemLocation(IProject project) { IFile defaultTypeSystemFile = project.getFile(DEFAULT_TYPE_SYSTEM_PATH); String typeSystemLocation; try { typeSystemLocation = project .getPersistentProperty(new QualifiedName("", TYPE_SYSTEM_PROPERTY)); } catch (CoreException e) { typeSystemLocation = null; } IFile typeSystemFile = null; // Type system location is null when it was never set it anyway, if (typeSystemLocation != null) { if (typeSystemLocation.length() > 0) { IResource potentialTypeSystemResource = ResourcesPlugin.getWorkspace().getRoot() .findMember(typeSystemLocation); if (potentialTypeSystemResource instanceof IFile) { typeSystemFile = (IFile) potentialTypeSystemResource; } } // Empty string means user does not want a type system to be set else { return null; } } if (typeSystemFile == null) { typeSystemFile = defaultTypeSystemFile; } return typeSystemFile; } public static void setTypeSystemLocation(IProject project, String typeSystemLocation) { try { project.setPersistentProperty(new QualifiedName("", TYPE_SYSTEM_PROPERTY), typeSystemLocation); } catch (CoreException e) { CasEditorPlugin.log(e); } } }
// Copyright 2018 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.sandbox; import build.bazel.remote.execution.v2.Platform; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.MoreCollectors; import com.google.common.eventbus.Subscribe; import com.google.common.io.ByteStreams; import com.google.devtools.build.lib.actions.ExecException; import com.google.devtools.build.lib.actions.Spawn; import com.google.devtools.build.lib.actions.Spawns; import com.google.devtools.build.lib.actions.UserExecException; import com.google.devtools.build.lib.analysis.platform.PlatformUtils; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.Reporter; import com.google.devtools.build.lib.exec.TreeDeleter; import com.google.devtools.build.lib.exec.local.LocalEnvProvider; import com.google.devtools.build.lib.remote.options.RemoteOptions; import com.google.devtools.build.lib.runtime.CommandCompleteEvent; import com.google.devtools.build.lib.runtime.CommandEnvironment; import com.google.devtools.build.lib.runtime.ProcessWrapper; import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxInputs; import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxOutputs; import com.google.devtools.build.lib.server.FailureDetails.Sandbox.Code; import com.google.devtools.build.lib.shell.Command; import com.google.devtools.build.lib.shell.CommandException; import com.google.devtools.build.lib.util.OS; import com.google.devtools.build.lib.util.ProcessUtils; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; /** Spawn runner that uses Docker to execute a local subprocess. */ final class DockerSandboxedSpawnRunner extends AbstractSandboxSpawnRunner { // The name of the container image entry in the Platform proto // (see third_party/googleapis/devtools/remoteexecution/*/remote_execution.proto and // remote_default_exec_properties in // src/main/java/com/google/devtools/build/lib/remote/RemoteOptions.java) private static final String CONTAINER_IMAGE_ENTRY_NAME = "container-image"; private static final String DOCKER_IMAGE_PREFIX = "docker://"; /** * Returns whether the darwin sandbox is supported on the local machine by running docker info. * This is expensive, and we have also reports of docker hanging for a long time! */ public static boolean isSupported(CommandEnvironment cmdEnv, Path dockerClient) throws InterruptedException { boolean verbose = cmdEnv.getOptions().getOptions(SandboxOptions.class).dockerVerbose; if (ProcessWrapper.fromCommandEnvironment(cmdEnv) == null) { if (verbose) { cmdEnv .getReporter() .handle( Event.error( "Docker sandboxing is disabled because ProcessWrapper is not supported. " + "This should never happen - is your Bazel binary corrupted?")); } return false; } // On Linux we need to know the UID and GID that we're running as, because otherwise Docker will // create files as 'root' and we can't move them to the execRoot. if (OS.getCurrent() == OS.LINUX) { try { ProcessUtils.getuid(); ProcessUtils.getgid(); } catch (UnsatisfiedLinkError e) { if (verbose) { cmdEnv .getReporter() .handle( Event.error( "Docker sandboxing is disabled, because ProcessUtils.getuid/getgid threw an " + "UnsatisfiedLinkError. This means that you're running a Bazel version " + "that doesn't have JNI libraries - did you build it correctly?\n" + Throwables.getStackTraceAsString(e))); } return false; } } Command cmd = new Command( new String[] {dockerClient.getPathString(), "info"}, cmdEnv.getClientEnv(), cmdEnv.getExecRoot().getPathFile()); try { cmd.execute(ByteStreams.nullOutputStream(), ByteStreams.nullOutputStream()); } catch (CommandException e) { if (verbose) { cmdEnv .getReporter() .handle( Event.error( "Docker sandboxing is disabled, because running 'docker info' failed: " + Throwables.getStackTraceAsString(e))); } return false; } if (verbose) { cmdEnv.getReporter().handle(Event.info("Docker sandboxing is supported")); } return true; } private static final ConcurrentHashMap<String, String> imageMap = new ConcurrentHashMap<>(); private final SandboxHelpers helpers; private final Path execRoot; private final boolean allowNetwork; private final Path dockerClient; private final ProcessWrapper processWrapper; private final Path sandboxBase; private final String defaultImage; private final LocalEnvProvider localEnvProvider; private final String commandId; private final Reporter reporter; private final boolean useCustomizedImages; private final TreeDeleter treeDeleter; private final int uid; private final int gid; private final Set<UUID> containersToCleanup; private final CommandEnvironment cmdEnv; /** * Creates a sandboxed spawn runner that uses the {@code linux-sandbox} tool. * * @param helpers common tools and state across all spawns during sandboxed execution * @param cmdEnv the command environment to use * @param dockerClient path to the `docker` executable * @param sandboxBase path to the sandbox base directory * @param defaultImage the Docker image to use if the platform doesn't specify one * @param useCustomizedImages whether to use customized images for execution * @param treeDeleter scheduler for tree deletions */ DockerSandboxedSpawnRunner( SandboxHelpers helpers, CommandEnvironment cmdEnv, Path dockerClient, Path sandboxBase, String defaultImage, boolean useCustomizedImages, TreeDeleter treeDeleter) { super(cmdEnv); this.helpers = helpers; this.execRoot = cmdEnv.getExecRoot(); this.allowNetwork = helpers.shouldAllowNetwork(cmdEnv.getOptions()); this.dockerClient = dockerClient; this.processWrapper = ProcessWrapper.fromCommandEnvironment(cmdEnv); this.sandboxBase = sandboxBase; this.defaultImage = defaultImage; this.localEnvProvider = LocalEnvProvider.forCurrentOs(cmdEnv.getClientEnv()); this.commandId = cmdEnv.getCommandId().toString(); this.reporter = cmdEnv.getReporter(); this.useCustomizedImages = useCustomizedImages; this.treeDeleter = treeDeleter; this.cmdEnv = cmdEnv; if (OS.getCurrent() == OS.LINUX) { this.uid = ProcessUtils.getuid(); this.gid = ProcessUtils.getgid(); } else { this.uid = -1; this.gid = -1; } this.containersToCleanup = Collections.synchronizedSet(new HashSet<>()); cmdEnv.getEventBus().register(this); } @Override protected SandboxedSpawn prepareSpawn(Spawn spawn, SpawnExecutionContext context) throws IOException, ExecException, InterruptedException { // Each invocation of "exec" gets its own sandbox base, execroot and temporary directory. Path sandboxPath = sandboxBase.getRelative(getName()).getRelative(Integer.toString(context.getId())); sandboxPath.getParentDirectory().createDirectory(); sandboxPath.createDirectory(); // b/64689608: The execroot of the sandboxed process must end with the workspace name, just like // the normal execroot does. Path sandboxExecRoot = sandboxPath.getRelative("execroot").getRelative(execRoot.getBaseName()); sandboxExecRoot.getParentDirectory().createDirectory(); sandboxExecRoot.createDirectory(); ImmutableMap<String, String> environment = localEnvProvider.rewriteLocalEnv(spawn.getEnvironment(), binTools, "/tmp"); SandboxInputs inputs = helpers.processInputFiles( context.getInputMapping(PathFragment.EMPTY_FRAGMENT), spawn, context.getArtifactExpander(), execRoot); SandboxOutputs outputs = helpers.getOutputs(spawn); Duration timeout = context.getTimeout(); UUID uuid = UUID.randomUUID(); String baseImageName = dockerContainerFromSpawn(spawn).orElse(this.defaultImage); if (baseImageName.isEmpty()) { throw new UserExecException( createFailureDetail( String.format( "Cannot execute %s mnemonic with Docker, because no image could be found in the" + " remote_execution_properties of the platform and no default image was set" + " via --experimental_docker_image", spawn.getMnemonic()), Code.NO_DOCKER_IMAGE)); } String customizedImageName = getOrCreateCustomizedImage(baseImageName); DockerCommandLineBuilder cmdLine = new DockerCommandLineBuilder(); cmdLine .setProcessWrapper(processWrapper) .setDockerClient(dockerClient) .setImageName(customizedImageName) .setCommandArguments(spawn.getArguments()) .setSandboxExecRoot(sandboxExecRoot) .setAdditionalMounts(getSandboxOptions().sandboxAdditionalMounts) .setPrivileged(getSandboxOptions().dockerPrivileged) .setEnvironmentVariables(environment) .setCreateNetworkNamespace( !(allowNetwork || Spawns.requiresNetwork(spawn, getSandboxOptions().defaultSandboxAllowNetwork))) .setCommandId(commandId) .setUuid(uuid); // If uid / gid are -1, we are on an operating system that doesn't require us to set them on the // Docker invocation. If they're 0, it means we are running as root and don't need to set them. if (uid > 0) { cmdLine.setUid(uid); } if (gid > 0) { cmdLine.setGid(gid); } if (!timeout.isZero()) { cmdLine.setTimeout(timeout); } // If we were interrupted, it is possible that "docker run" gets killed in exactly the moment // between the create and the start call, leaving behind a container that is created but never // ran. This means that Docker won't automatically clean it up (as --rm only affects the start // phase and has no effect on the create phase of "docker run"). // We register the container UUID for cleanup, but remove the UUID if the process ran // successfully. containersToCleanup.add(uuid); return new CopyingSandboxedSpawn( sandboxPath, sandboxExecRoot, cmdLine.build(), cmdEnv.getClientEnv(), inputs, outputs, ImmutableSet.of(), treeDeleter, /*statisticsPath=*/ null, () -> containersToCleanup.remove(uuid)); } private String getOrCreateCustomizedImage(String baseImage) throws UserExecException, InterruptedException { // TODO(philwo) docker run implicitly does a docker pull if the image does not exist locally. // Pulling an image can take a long time and a user might not be aware of that. We could check // if the image exists locally (docker images -q name:tag) and if not, do a docker pull and // notify the user in a similar way as when we download a http_archive. // // This is mostly relevant for the case where we don't build a customized image, as that prints // a message when it runs. if (!useCustomizedImages) { return baseImage; } // If we're running as root, we can skip this step, as it's safe to assume that every image // already has a built-in root user and group. if (uid == 0 && gid == 0) { return baseImage; } // We only need to create a customized image, if we're running on Linux, as Docker on macOS // and Windows doesn't map users from the host into the container anyway. if (OS.getCurrent() != OS.LINUX) { return baseImage; } AtomicReference<UserExecException> thrownUserExecException = new AtomicReference<>(); AtomicReference<InterruptedException> thrownInterruptedException = new AtomicReference<>(); String result = imageMap.computeIfAbsent( baseImage, (image) -> { reporter.handle(Event.info("Preparing Docker image " + image + " for use...")); String workDir = PathFragment.create("/execroot") .getRelative(execRoot.getBaseName()) .getPathString(); StringBuilder dockerfile = new StringBuilder(); dockerfile.append(String.format("FROM %s\n", image)); dockerfile.append(String.format("RUN [\"mkdir\", \"-p\", \"%s\"]\n", workDir)); // TODO(philwo) this will fail if a user / group with the given uid / gid already // exists // in the container. For now this seems reasonably unlikely, but we'll have to come up // with a better way. if (gid > 0) { dockerfile.append( String.format("RUN [\"groupadd\", \"-g\", \"%d\", \"bazelbuild\"]\n", gid)); } if (uid > 0) { dockerfile.append( String.format( "RUN [\"useradd\", \"-m\", \"-g\", \"%d\", \"-d\", \"%s\", \"-N\", \"-u\", " + "\"%d\", \"bazelbuild\"]\n", gid, workDir, uid)); } dockerfile.append( String.format("RUN [\"chown\", \"-R\", \"%d:%d\", \"%s\"]\n", uid, gid, workDir)); dockerfile.append(String.format("USER %d:%d\n", uid, gid)); dockerfile.append(String.format("ENV HOME %s\n", workDir)); if (uid > 0) { dockerfile.append(String.format("ENV USER bazelbuild\n")); } dockerfile.append(String.format("WORKDIR %s\n", workDir)); try { return executeCommand( ImmutableList.of(dockerClient.getPathString(), "build", "-q", "-"), new ByteArrayInputStream( dockerfile.toString().getBytes(Charset.defaultCharset()))); } catch (UserExecException e) { thrownUserExecException.set(e); return null; } catch (InterruptedException e) { thrownInterruptedException.set(e); return null; } }); if (thrownUserExecException.get() != null) { throw thrownUserExecException.get(); } if (thrownInterruptedException.get() != null) { throw thrownInterruptedException.get(); } return result; } private String executeCommand(List<String> cmdLine, InputStream stdIn) throws UserExecException, InterruptedException { ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); ByteArrayOutputStream stdErr = new ByteArrayOutputStream(); // Docker might need the $HOME and $PATH variables in order to be able to use advanced // authentication mechanisms (e.g. for Google Cloud), thus we pass in the client env. Command cmd = new Command(cmdLine.toArray(new String[0]), cmdEnv.getClientEnv(), execRoot.getPathFile()); try { cmd.executeAsync(stdIn, stdOut, stdErr, Command.KILL_SUBPROCESS_ON_INTERRUPT).get(); } catch (CommandException e) { String message = String.format("Running command %s failed: %s", cmd.toDebugString(), stdErr); throw new UserExecException(e, createFailureDetail(message, Code.DOCKER_COMMAND_FAILURE)); } return stdOut.toString().trim(); } private Optional<String> dockerContainerFromSpawn(Spawn spawn) throws ExecException { Platform platform = PlatformUtils.getPlatformProto(spawn, cmdEnv.getOptions().getOptions(RemoteOptions.class)); if (platform != null) { try { return platform .getPropertiesList() .stream() .filter(p -> p.getName().equals(CONTAINER_IMAGE_ENTRY_NAME)) .map(p -> p.getValue()) .filter(r -> r.startsWith(DOCKER_IMAGE_PREFIX)) .map(r -> r.substring(DOCKER_IMAGE_PREFIX.length())) .collect(MoreCollectors.toOptional()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format( "Platform %s contained multiple container-image entries, but only one is allowed.", spawn.getExecutionPlatform().label()), e); } } else { return Optional.empty(); } } // Remove all Docker containers that might be stuck in "Created" state and weren't automatically // cleaned up by Docker itself. public void cleanup() throws InterruptedException { if (containersToCleanup == null || containersToCleanup.isEmpty()) { return; } ArrayList<String> cmdLine = new ArrayList<>(); cmdLine.add(dockerClient.getPathString()); cmdLine.add("rm"); cmdLine.add("-fv"); for (UUID uuid : containersToCleanup) { cmdLine.add(uuid.toString()); } Command cmd = new Command(cmdLine.toArray(new String[0]), cmdEnv.getClientEnv(), execRoot.getPathFile()); try { cmd.execute(); } catch (CommandException e) { // This is to be expected, as not all UUIDs that we pass to "docker rm" will still be alive // when this method is called. However, it will successfully remove all the containers that // *are* still there, even when the command exits with an error. } containersToCleanup.clear(); } @Subscribe public void commandComplete(@SuppressWarnings("unused") CommandCompleteEvent event) { try { cleanup(); } catch (InterruptedException e) { cmdEnv.getReporter().handle(Event.error("Interrupted while cleaning up docker sandbox")); Thread.currentThread().interrupt(); } } @Override public String getName() { return "docker"; } }
/** * Copyright 2015 LinkedIn Corp. 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. */ package utils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import play.Logger; import play.libs.Json; public class Search { public final static String DATASET_CATEGORY = "datasets"; public final static String METRIC_CATEGORY = "metrics"; public final static String COMMENT_CATEGORY = "comments"; public final static String FLOW_CATEGORY = "flows"; public final static String JOB_CATEGORY = "jobs"; private final static String datasetShouldQueryUnit = "{\"bool\": " + "{\"should\": [" + "{\"wildcard\": {\"name\": {\"value\": \"*$VALUE*\", \"boost\": 16}}}, " + "{\"prefix\": {\"name\": {\"value\": \"$VALUE\", \"boost\": 32}}}, " + "{\"match\": {\"name\": {\"query\": \"$VALUE\", \"boost\": 48}}}, " + "{\"match\": {\"name\": {\"query\": \"$VALUE\", \"type\": \"phrase\", \"boost\": 64}}}, " + "{\"wildcard\": {\"urn\": {\"value\": \"*$VALUE*\", \"boost\": 16}}}, " + "{\"prefix\": {\"urn\": {\"value\": \"$VALUE\", \"boost\": 32}}}, " + "{\"match\": {\"urn\": {\"query\": \"$VALUE\", \"boost\": 48}}}, " + "{\"match\": {\"urn\": {\"query\": \"$VALUE\", \"type\": \"phrase\", \"boost\": 64}}}, " + "{\"wildcard\": {\"field\": {\"value\": \"*$VALUE*\", \"boost\": 4}}}, " + "{\"wildcard\": {\"properties\": {\"value\": \"*$VALUE*\", \"boost\": 2}}}, " + "{\"wildcard\": {\"schema\": {\"value\": \"*$VALUE*\", \"boost\": 1}}}" + "]}" + "}"; private final static String metricShouldQueryUnit = "{\"bool\": " + "{\"should\": [" + "{\"wildcard\": {\"metric_name\": {\"value\": \"*$VALUE*\", \"boost\": 32}}}, " + "{\"prefix\": {\"metric_name\": {\"value\": \"$VALUE\", \"boost\": 36}}}, " + "{\"match\": {\"metric_name\": {\"query\": \"$VALUE\", \"boost\": 48}}}, " + "{\"match\": {\"metric_name\": {\"query\": \"$VALUE\", \"type\": \"phrase\", \"boost\": 64}}}, " + "{\"wildcard\": {\"dashboard_name\": {\"value\": \"*$VALUE*\", \"boost\": 20}}}," + "{\"prefix\": {\"dashboard_name\": {\"value\": \"$VALUE\", \"boost\": 24}}}, " + "{\"match\": {\"dashboard_name\": {\"query\": \"$VALUE\", \"boost\": 26}}}, " + "{\"match\": {\"dashboard_name\": {\"query\": \"$VALUE\", \"type\": \"phrase\", \"boost\": 28}}}, " + "{\"wildcard\": {\"metric_group\": {\"value\": \"*$VALUE*\", \"boost\": 8}}}, " + "{\"prefix\": {\"metric_group\": {\"value\": \"$VALUE\", \"boost\": 12}}}, " + "{\"match\": {\"metric_group\": {\"query\": \"$VALUE\", \"boost\": 14}}}, " + "{\"match\": {\"metric_group\": {\"query\": \"$VALUE\", \"type\": \"phrase\", \"boost\": 16}}}, " + "{\"wildcard\": {\"metric_category\": {\"value\": \"*$VALUE*\", \"boost\": 1}}}, " + "{\"prefix\": {\"metric_category\": {\"value\": \"$VALUE\", \"boost\": 2}}}, " + "{\"match\": {\"metric_category\": {\"query\": \"$VALUE\", \"boost\": 3}}}, " + "{\"match\": {\"metric_category\": {\"query\": \"$VALUE\", \"type\": \"phrase\", \"boost\": 4}}}" + "]" + "}" + "}"; private final static String commentsQuery = "{\"bool\":" + "{ \"should\": [" + "{\"has_child\": {\"type\": \"comment\", \"query\": {\"match\" : {\"text\" : \"$VALUE\"}}}}, " + "{\"has_child\": {\"type\": \"field\", \"query\": {\"match\": {\"comments\" : \"$VALUE\" }}}}" + "]" + "}" + "}"; private final static String flowShouldQueryUnit = "{\"bool\": " + "{\"should\": " + "[{\"wildcard\": {\"app_code\": {\"value\": \"*$VALUE*\", \"boost\": 1}}}, " + "{\"prefix\": {\"app_code\": {\"value\": \"$VALUE\", \"boost\": 2}}}, " + "{\"match\": {\"app_code\": {\"query\": \"$VALUE\", \"boost\": 3}}}, " + "{\"match\": {\"app_code\": {\"query\": \"$VALUE\", \"type\": \"phrase\", \"boost\": 4}}}, " + "{\"wildcard\": {\"flow_name\": {\"value\": \"*$VALUE*\", \"boost\": 8}}}, " + "{\"prefix\": {\"flow_name\": {\"value\": \"$VALUE\", \"boost\": 16}}}, " + "{\"match\": {\"flow_name\": {\"query\": \"$VALUE\", \"boost\": 24}}}, " + "{\"match\": {\"flow_name\": {\"query\": \"$VALUE\", \"type\": \"phrase\", \"boost\": 32}}}, " + "{\"wildcard\": {\"jobs.job_name\": {\"value\": \"*$VALUE*\", \"boost\": 8}}}, " + "{\"prefix\": {\"jobs.job_name\": {\"value\": \"$VALUE\", \"boost\": 16}}}, " + "{\"match\": {\"jobs.job_name\": {\"query\": \"$VALUE\", \"boost\": 24}}}, " + "{\"match\": {\"jobs.job_name\": {\"query\": \"$VALUE\", \"type\": \"phrase\", \"boost\": 32}}}" + "]" + "}" + "}"; private final static String suggesterQueryTemplateSub = "{" + "\"text\": \"$SEARCHKEYWORD\", " + "\"simple_phrase\": { " + "\"phrase\": { " + "\"field\": \"$FIELD\", " + "\"size\": 1, " + "\"direct_generator\": [ " + "{ " + "\"field\": \"$FIELD\", " + "\"suggest_mode\": \"always\", " + "\"min_word_length\": 1 " + "}" + "]" + "}" + "}" + "}"; private final static String completionSuggesterQuery = "{" + "\"wh-suggest\": { " + "\"text\": \"$SEARCHKEYWORD\", " + "\"completion\": { " + "\"field\": \"$FIELD\", " + "\"size\": $LIMIT " + "} " + "} " + "}"; private final static String datasetFilterQueryUnit = "{" + "\"match\": { " + "\"source\": \"$SOURCE\" " + "} " + "}"; public static ObjectNode generateElasticSearchCompletionSuggesterQuery(String field, String searchKeyword, int limit) { if (StringUtils.isBlank(searchKeyword)) { return null; } String queryTemplate = completionSuggesterQuery; String query = queryTemplate.replace("$SEARCHKEYWORD", searchKeyword.toLowerCase()); if (StringUtils.isNotBlank(field)) { query = query.replace("$FIELD", field.toLowerCase()); } query = query.replace("$LIMIT", Integer.toString(limit)); ObjectNode suggestNode = Json.newObject(); ObjectNode textNode = Json.newObject(); try { textNode = (ObjectNode) new ObjectMapper().readTree(query); suggestNode.put("suggest", textNode); } catch (Exception e) { Logger.error("suggest Exception = " + e.getMessage()); } return suggestNode; } public static ObjectNode generateElasticSearchPhraseSuggesterQuery(String category, String field, String searchKeyword) { if (StringUtils.isBlank(searchKeyword)) { return null; } String queryTemplate = suggesterQueryTemplateSub; String query = queryTemplate.replace("$SEARCHKEYWORD", searchKeyword.toLowerCase()); if (StringUtils.isNotBlank(field)) { query = query.replace("$FIELD", field.toLowerCase()); } ObjectNode suggestNode = Json.newObject(); ObjectNode textNode = Json.newObject(); try { textNode = (ObjectNode) new ObjectMapper().readTree(query); suggestNode.put("suggest", textNode); } catch (Exception e) { Logger.error("suggest Exception = " + e.getMessage()); } Logger.info("suggestNode is " + suggestNode.toString()); return suggestNode; } public static ObjectNode generateElasticSearchQueryString(String category, String source, String keywords) { if (StringUtils.isBlank(keywords)) { return null; } List<JsonNode> shouldValueList = new ArrayList<JsonNode>(); String queryTemplate = datasetShouldQueryUnit; String[] values = keywords.trim().split(","); if (StringUtils.isNotBlank(category)) { if (category.equalsIgnoreCase(METRIC_CATEGORY)) { queryTemplate = metricShouldQueryUnit; } else if (category.equalsIgnoreCase(COMMENT_CATEGORY)) { queryTemplate = commentsQuery; } else if (category.equalsIgnoreCase(FLOW_CATEGORY) || category.equalsIgnoreCase(JOB_CATEGORY)) { queryTemplate = flowShouldQueryUnit; } } for (String value : values) { if (StringUtils.isNotBlank(value)) { String query = queryTemplate.replace("$VALUE", value.replace("\"", "").toLowerCase().trim()); shouldValueList.add(Json.parse(query)); } } ObjectNode shouldNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); ObjectNode queryNode = Json.newObject(); queryNode.put("bool", shouldNode); return queryNode; } public static ObjectNode generateDatasetAdvSearchQueryString(JsonNode searchOpt) { List<String> scopeInList = new ArrayList<String>(); List<String> scopeNotInList = new ArrayList<String>(); List<String> tableInList = new ArrayList<String>(); List<String> tableNotInList = new ArrayList<String>(); List<String> fieldAnyList = new ArrayList<String>(); List<String> fieldAllList = new ArrayList<String>(); List<String> fieldNotInList = new ArrayList<String>(); String comments = null; String datasetSources = null; if (searchOpt != null && (searchOpt.isContainerNode())) { if (searchOpt.has("scope")) { JsonNode scopeNode = searchOpt.get("scope"); if (scopeNode != null && scopeNode.isContainerNode()) { if (scopeNode.has("in")) { JsonNode scopeInNode = scopeNode.get("in"); if (scopeInNode != null) { String scopeInStr = scopeInNode.asText(); if (StringUtils.isNotBlank(scopeInStr)) { String[] scopeInArray = scopeInStr.split(","); if (scopeInArray != null) { for (String value : scopeInArray) { if (StringUtils.isNotBlank(value)) { scopeInList.add(value.trim()); } } } } } } if (scopeNode.has("not")) { JsonNode scopeNotInNode = scopeNode.get("not"); if (scopeNotInNode != null) { String scopeNotInStr = scopeNotInNode.asText(); if (StringUtils.isNotBlank(scopeNotInStr)) { String[] scopeNotInArray = scopeNotInStr.split(","); if (scopeNotInArray != null) { for (String value : scopeNotInArray) { if (StringUtils.isNotBlank(value)) { scopeNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("table")) { JsonNode tableNode = searchOpt.get("table"); if (tableNode != null && tableNode.isContainerNode()) { if (tableNode.has("in")) { JsonNode tableInNode = tableNode.get("in"); if (tableInNode != null) { String tableInStr = tableInNode.asText(); if (StringUtils.isNotBlank(tableInStr)) { String[] tableInArray = tableInStr.split(","); if (tableInArray != null) { for (String value : tableInArray) { if (StringUtils.isNotBlank(value)) { tableInList.add(value.trim()); } } } } } } if (tableNode.has("not")) { JsonNode tableNotInNode = tableNode.get("not"); if (tableNotInNode != null) { String tableNotInStr = tableNotInNode.asText(); if (StringUtils.isNotBlank(tableNotInStr)) { String[] tableNotInArray = tableNotInStr.split(","); if (tableNotInArray != null) { for (String value : tableNotInArray) { if (StringUtils.isNotBlank(value)) { tableNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("fields")) { JsonNode fieldNode = searchOpt.get("fields"); if (fieldNode != null && fieldNode.isContainerNode()) { if (fieldNode.has("any")) { JsonNode fieldAnyNode = fieldNode.get("any"); if (fieldAnyNode != null) { String fieldAnyStr = fieldAnyNode.asText(); if (StringUtils.isNotBlank(fieldAnyStr)) { String[] fieldAnyArray = fieldAnyStr.split(","); if (fieldAnyArray != null) { for (String value : fieldAnyArray) { if (StringUtils.isNotBlank(value)) { fieldAnyList.add(value.trim()); } } } } } } if (fieldNode.has("all")) { JsonNode fieldAllNode = fieldNode.get("all"); if (fieldAllNode != null) { String fieldAllStr = fieldAllNode.asText(); if (StringUtils.isNotBlank(fieldAllStr)) { String[] fieldAllArray = fieldAllStr.split(","); if (fieldAllArray != null) { for (String value : fieldAllArray) { if (StringUtils.isNotBlank(value)) { fieldAllList.add(value.trim()); } } } } } } if (fieldNode.has("not")) { JsonNode fieldNotInNode = fieldNode.get("not"); if (fieldNotInNode != null) { String fieldNotInStr = fieldNotInNode.asText(); if (StringUtils.isNotBlank(fieldNotInStr)) { String[] fieldNotInArray = fieldNotInStr.split(","); if (fieldNotInArray != null) { for (String value : fieldNotInArray) { if (StringUtils.isNotBlank(value)) { fieldNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("sources")) { JsonNode sourcesNode = searchOpt.get("sources"); if (sourcesNode != null) { datasetSources = sourcesNode.asText(); } } if (searchOpt.has("comments")) { JsonNode commentsNode = searchOpt.get("comments"); if (commentsNode != null) { comments = commentsNode.asText(); } } } List<JsonNode> mustValueList = new ArrayList<JsonNode>(); List<JsonNode> mustNotValueList = new ArrayList<JsonNode>(); List<JsonNode> shouldValueList = new ArrayList<JsonNode>(); String hasChildValue = "{\"has_child\": " + "{\"type\": \"$TYPE\", \"query\": {\"match\" : {\"$FIELD\" : \"$VALUE\"}}}}"; String matchQueryUnit = "{\"query\": {\"match\" : {\"$FIELD\" : \"$VALUE\"}}}"; String shouldQueryUnit = "{\"bool\": " + "{\"should\": [" + "{\"wildcard\": {\"$FIELD\": {\"value\": \"*$VALUE*\", \"boost\": 1}}}, " + "{\"prefix\": {\"$FIELD\": {\"value\": \"$VALUE\", \"boost\": 4}}}, " + "{\"term\": {\"$FIELD\": {\"value\": \"$VALUE\", \"boost\": 16}}}" + "]}}"; String mustNotQueryUnit = "{\"term\" : {\"$FIELD\" : \"$VALUE\"}}"; if (scopeInList != null && scopeInList.size() > 0) { for (String scope : scopeInList) { if (StringUtils.isNotBlank(scope)) { shouldValueList.add(Json.parse(shouldQueryUnit.replace("$FIELD", "parent_name"). replace("$VALUE", scope.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (scopeNotInList != null && scopeNotInList.size() > 0) { shouldValueList.clear(); for (String scope : scopeNotInList) { if (StringUtils.isNotBlank(scope)) { shouldValueList.add(Json.parse(mustNotQueryUnit.replace("$FIELD", "parent_name"). replace("$VALUE", scope.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustNotValueList.add(boolNode); } if (tableInList != null && tableInList.size() > 0) { shouldValueList.clear(); for (String table : tableInList) { if (StringUtils.isNotBlank(table)) { shouldValueList.add(Json.parse(shouldQueryUnit.replace("$FIELD", "name"). replace("$VALUE", table.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (tableNotInList != null && tableNotInList.size() > 0) { shouldValueList.clear(); for (String table : tableNotInList) { if (StringUtils.isNotBlank(table)) { shouldValueList.add(Json.parse(mustNotQueryUnit.replace("$FIELD", "name"). replace("$VALUE", table.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustNotValueList.add(boolNode); } if (fieldAnyList != null && fieldAnyList.size() > 0) { shouldValueList.clear(); for (String field : fieldAnyList) { if (StringUtils.isNotBlank(field)) { shouldValueList.add(Json.parse(hasChildValue.replace("$TYPE", "field"). replace("$FIELD", "field_name"). replace("$VALUE", field.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (fieldAllList != null && fieldAllList.size() > 0) { for (String field : fieldAllList) { if (StringUtils.isNotBlank(field)) { mustValueList.add(Json.parse(hasChildValue.replace("$TYPE", "field"). replace("$FIELD", "field_name"). replace("$VALUE", field.toLowerCase().trim()))); } } } if (fieldNotInList != null && fieldNotInList.size() > 0) { shouldValueList.clear(); for (String field : fieldNotInList) { if (StringUtils.isNotBlank(field)) { shouldValueList.add(Json.parse(hasChildValue.replace("$TYPE", "field"). replace("$FIELD", "field_name"). replace("$VALUE", field.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustNotValueList.add(boolNode); } if (StringUtils.isNotBlank(comments)) { shouldValueList.clear(); String inputComments[] = comments.trim().split(","); for (String comment : inputComments) { if (StringUtils.isNotBlank(comment)) { shouldValueList.add(Json.parse(hasChildValue.replace("$TYPE", "comment"). replace("$FIELD", "text"). replace("$VALUE", comment.toLowerCase().trim()))); shouldValueList.add(Json.parse(hasChildValue.replace("$TYPE", "field"). replace("$FIELD", "comments"). replace("$VALUE", comment.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (StringUtils.isNotBlank(datasetSources)) { String inputSources[] = datasetSources.trim().split(","); shouldValueList.clear(); for (String source : inputSources) { if (StringUtils.isNotBlank(source)) { shouldValueList.add(Json.parse(matchQueryUnit.replace("$FIELD", "source"). replace("$VALUE", source.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } ObjectNode boolNode = Json.newObject(); ObjectNode queryNode = Json.newObject(); if (mustValueList.size() > 0 && mustNotValueList.size() > 0) { boolNode.set("must", Json.toJson(mustValueList)); boolNode.set("must_not", Json.toJson(mustNotValueList)); queryNode.put("bool", boolNode); } else if (mustValueList.size() > 0) { boolNode.set("must", Json.toJson(mustValueList)); queryNode.put("bool", boolNode); } else if (mustNotValueList.size() > 0) { boolNode.set("must_not", Json.toJson(mustNotValueList)); queryNode.put("bool", boolNode); } return queryNode; } public static ObjectNode generateMetricAdvSearchQueryString(JsonNode searchOpt) { List<String> dashboardInList = new ArrayList<String>(); List<String> dashboardNotInList = new ArrayList<String>(); List<String> groupInList = new ArrayList<String>(); List<String> groupNotInList = new ArrayList<String>(); List<String> categoryInList = new ArrayList<String>(); List<String> categoryNotInList = new ArrayList<String>(); List<String> metricInList = new ArrayList<String>(); List<String> metricNotInList = new ArrayList<String>(); if (searchOpt != null && (searchOpt.isContainerNode())) { if (searchOpt.has("dashboard")) { JsonNode dashboardNode = searchOpt.get("dashboard"); if (dashboardNode != null && dashboardNode.isContainerNode()) { if (dashboardNode.has("in")) { JsonNode dashboardInNode = dashboardNode.get("in"); if (dashboardInNode != null) { String dashboardInStr = dashboardInNode.asText(); if (StringUtils.isNotBlank(dashboardInStr)) { String[] dashboardInArray = dashboardInStr.split(","); if (dashboardInArray != null) { for (String value : dashboardInArray) { if (StringUtils.isNotBlank(value)) { dashboardInList.add(value.trim()); } } } } } } if (dashboardNode.has("not")) { JsonNode dashboardNotInNode = dashboardNode.get("not"); if (dashboardNotInNode != null) { String dashboardNotInStr = dashboardNotInNode.asText(); if (StringUtils.isNotBlank(dashboardNotInStr)) { String[] dashboardNotInArray = dashboardNotInStr.split(","); if (dashboardNotInArray != null) { for (String value : dashboardNotInArray) { if (StringUtils.isNotBlank(value)) { dashboardNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("group")) { JsonNode groupNode = searchOpt.get("group"); if (groupNode != null && groupNode.isContainerNode()) { if (groupNode.has("in")) { JsonNode groupInNode = groupNode.get("in"); if (groupInNode != null) { String groupInStr = groupInNode.asText(); if (StringUtils.isNotBlank(groupInStr)) { String[] groupInArray = groupInStr.split(","); if (groupInArray != null) { for (String value : groupInArray) { if (StringUtils.isNotBlank(value)) { groupInList.add(value.trim()); } } } } } } if (groupNode.has("not")) { JsonNode groupNotInNode = groupNode.get("not"); if (groupNotInNode != null) { String groupNotInStr = groupNotInNode.asText(); if (StringUtils.isNotBlank(groupNotInStr)) { String[] groupNotInArray = groupNotInStr.split(","); if (groupNotInArray != null) { for (String value : groupNotInArray) { if (StringUtils.isNotBlank(value)) { groupNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("cat")) { JsonNode categoryNode = searchOpt.get("cat"); if (categoryNode != null && categoryNode.isContainerNode()) { if (categoryNode.has("in")) { JsonNode categoryInNode = categoryNode.get("in"); if (categoryInNode != null) { String categoryInStr = categoryInNode.asText(); if (StringUtils.isNotBlank(categoryInStr)) { String[] categoryInArray = categoryInStr.split(","); if (categoryInArray != null) { for (String value : categoryInArray) { if (StringUtils.isNotBlank(value)) { categoryInList.add(value.trim()); } } } } } } if (categoryNode.has("not")) { JsonNode categoryNotInNode = categoryNode.get("not"); if (categoryNotInNode != null) { String categoryNotInStr = categoryNotInNode.asText(); if (StringUtils.isNotBlank(categoryNotInStr)) { String[] categoryNotInArray = categoryNotInStr.split(","); if (categoryNotInArray != null) { for (String value : categoryNotInArray) { if (StringUtils.isNotBlank(value)) { categoryNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("metric")) { JsonNode metricNode = searchOpt.get("metric"); if (metricNode != null && metricNode.isContainerNode()) { if (metricNode.has("in")) { JsonNode metricInNode = metricNode.get("in"); if (metricInNode != null) { String metricInStr = metricInNode.asText(); if (StringUtils.isNotBlank(metricInStr)) { String[] metricInArray = metricInStr.split(","); if (metricInArray != null) { for (String value : metricInArray) { if (StringUtils.isNotBlank(value)) { metricInList.add(value.trim()); } } } } } } if (metricNode.has("not")) { JsonNode metricNotInNode = metricNode.get("not"); if (metricNotInNode != null) { String metricNotInStr = metricNotInNode.asText(); if (StringUtils.isNotBlank(metricNotInStr)) { String[] metricNotInArray = metricNotInStr.split(","); if (metricNotInArray != null) { for (String value : metricNotInArray) { if (StringUtils.isNotBlank(value)) { metricNotInList.add(value.trim()); } } } } } } } } } List<JsonNode> mustValueList = new ArrayList<JsonNode>(); List<JsonNode> mustNotValueList = new ArrayList<JsonNode>(); List<JsonNode> shouldValueList = new ArrayList<JsonNode>(); String shouldQueryUnit = "{\"bool\": " + "{\"should\": " + "[{\"wildcard\": {\"$FIELD\": {\"value\": \"*$VALUE*\", \"boost\": 1}}}, " + "{\"prefix\": {\"$FIELD\": {\"value\": \"$VALUE\", \"boost\": 4}}}, " + "{\"term\": {\"$FIELD\": {\"value\": \"$VALUE\", \"boost\": 16}}}" + "]" + "}" + "}"; String shouldMatchQueryUnit = "{\"bool\": " + "{\"should\": " + "[{\"wildcard\": {\"$FIELD\": {\"value\": \"*$VALUE*\", \"boost\": 1}}}, " + "{\"prefix\": {\"$FIELD\": {\"value\": \"$VALUE\", \"boost\": 4}}}, " + "{\"match\": {\"$FIELD\": {\"query\": \"$VALUE\", \"boost\": 16}}}" + "]" + "}" + "}"; String mustNotQueryUnit = "{\"term\" : {\"$FIELD\" : \"$VALUE\"}}"; if (dashboardInList != null && dashboardInList.size() > 0) { for (String dashboard : dashboardInList) { if (StringUtils.isNotBlank(dashboard)) { shouldValueList.add(Json.parse(shouldMatchQueryUnit.replace("$FIELD", "dashboard_name"). replace("$VALUE", dashboard.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (dashboardNotInList != null && dashboardNotInList.size() > 0) { shouldValueList.clear(); for (String dashboard : dashboardNotInList) { if (StringUtils.isNotBlank(dashboard)) { shouldValueList.add(Json.parse(mustNotQueryUnit.replace("$FIELD", "dashboard_name"). replace("$VALUE", dashboard.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustNotValueList.add(boolNode); } if (groupInList != null && groupInList.size() > 0) { shouldValueList.clear(); for (String group : groupInList) { if (StringUtils.isNotBlank(group)) { shouldValueList.add(Json.parse(shouldMatchQueryUnit.replace("$FIELD", "metric_group"). replace("$VALUE", group.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (groupNotInList != null && groupNotInList.size() > 0) { shouldValueList.clear(); for (String group : groupNotInList) { if (StringUtils.isNotBlank(group)) { shouldValueList.add(Json.parse(mustNotQueryUnit.replace("$FIELD", "metric_group"). replace("$VALUE", group.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustNotValueList.add(boolNode); } if (categoryInList != null && categoryInList.size() > 0) { shouldValueList.clear(); for (String category : categoryInList) { if (StringUtils.isNotBlank(category)) { shouldValueList.add(Json.parse(shouldMatchQueryUnit.replace("$FIELD", "metric_category"). replace("$VALUE", category.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (categoryNotInList != null && categoryNotInList.size() > 0) { shouldValueList.clear(); for (String category : categoryNotInList) { if (StringUtils.isNotBlank(category)) { shouldValueList.add(Json.parse(mustNotQueryUnit.replace("$FIELD", "metric_category"). replace("$VALUE", category.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustNotValueList.add(boolNode); } if (metricInList != null && metricInList.size() > 0) { shouldValueList.clear(); for (String name : metricInList) { if (StringUtils.isNotBlank(name)) { shouldValueList.add(Json.parse(shouldMatchQueryUnit.replace("$FIELD", "metric_name"). replace("$VALUE", name.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (metricNotInList != null && metricNotInList.size() > 0) { shouldValueList.clear(); for (String name : metricNotInList) { if (StringUtils.isNotBlank(name)) { shouldValueList.add(Json.parse(mustNotQueryUnit.replace("$FIELD", "metric_name"). replace("$VALUE", name.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustNotValueList.add(boolNode); } ObjectNode boolNode = Json.newObject(); ObjectNode queryNode = Json.newObject(); if (mustValueList.size() > 0 && mustNotValueList.size() > 0) { boolNode.set("must", Json.toJson(mustValueList)); boolNode.set("must_not", Json.toJson(mustNotValueList)); queryNode.put("bool", boolNode); } else if (mustValueList.size() > 0) { boolNode.set("must", Json.toJson(mustValueList)); queryNode.put("bool", boolNode); } else if (mustNotValueList.size() > 0) { boolNode.set("must_not", Json.toJson(mustNotValueList)); queryNode.put("bool", boolNode); } return queryNode; } public static ObjectNode generateFlowJobAdvSearchQueryString(JsonNode searchOpt) { List<String> appcodeInList = new ArrayList<String>(); List<String> appcodeNotInList = new ArrayList<String>(); List<String> flowInList = new ArrayList<String>(); List<String> flowNotInList = new ArrayList<String>(); List<String> jobInList = new ArrayList<String>(); List<String> jobNotInList = new ArrayList<String>(); if (searchOpt != null && (searchOpt.isContainerNode())) { if (searchOpt.has("appcode")) { JsonNode appcodeNode = searchOpt.get("appcode"); if (appcodeNode != null && appcodeNode.isContainerNode()) { if (appcodeNode.has("in")) { JsonNode appcodeInNode = appcodeNode.get("in"); if (appcodeInNode != null) { String appcodeInStr = appcodeInNode.asText(); if (StringUtils.isNotBlank(appcodeInStr)) { String[] appcodeInArray = appcodeInStr.split(","); if (appcodeInArray != null) { for (String value : appcodeInArray) { if (StringUtils.isNotBlank(value)) { appcodeInList.add(value.trim()); } } } } } } if (appcodeNode.has("not")) { JsonNode appcodeNotInNode = appcodeNode.get("not"); if (appcodeNotInNode != null) { String appcodeNotInStr = appcodeNotInNode.asText(); if (StringUtils.isNotBlank(appcodeNotInStr)) { String[] appcodeNotInArray = appcodeNotInStr.split(","); if (appcodeNotInArray != null) { for (String value : appcodeNotInArray) { if (StringUtils.isNotBlank(value)) { appcodeNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("flow")) { JsonNode flowNode = searchOpt.get("flow"); if (flowNode != null && flowNode.isContainerNode()) { if (flowNode.has("in")) { JsonNode flowInNode = flowNode.get("in"); if (flowInNode != null) { String flowInStr = flowInNode.asText(); if (StringUtils.isNotBlank(flowInStr)) { String[] flowInArray = flowInStr.split(","); if (flowInArray != null) { for (String value : flowInArray) { if (StringUtils.isNotBlank(value)) { flowInList.add(value.trim()); } } } } } } if (flowNode.has("not")) { JsonNode flowNotInNode = flowNode.get("not"); if (flowNotInNode != null) { String flowNotInStr = flowNotInNode.asText(); if (StringUtils.isNotBlank(flowNotInStr)) { String[] flowNotInArray = flowNotInStr.split(","); if (flowNotInArray != null) { for (String value : flowNotInArray) { if (StringUtils.isNotBlank(value)) { flowNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("job")) { JsonNode jobNode = searchOpt.get("job"); if (jobNode != null && jobNode.isContainerNode()) { if (jobNode.has("in")) { JsonNode jobInNode = jobNode.get("in"); if (jobInNode != null) { String jobInStr = jobInNode.asText(); if (StringUtils.isNotBlank(jobInStr)) { String[] jobInArray = jobInStr.split(","); if (jobInArray != null) { for (String value : jobInArray) { if (StringUtils.isNotBlank(value)) { jobInList.add(value.trim()); } } } } } } if (jobNode.has("not")) { JsonNode jobNotInNode = jobNode.get("not"); if (jobNotInNode != null) { String jobNotInStr = jobNotInNode.asText(); if (StringUtils.isNotBlank(jobNotInStr)) { String[] jobNotInArray = jobNotInStr.split(","); if (jobNotInArray != null) { for (String value : jobNotInArray) { if (StringUtils.isNotBlank(value)) { jobNotInList.add(value.trim()); } } } } } } } } } List<JsonNode> mustValueList = new ArrayList<JsonNode>(); List<JsonNode> mustNotValueList = new ArrayList<JsonNode>(); List<JsonNode> shouldValueList = new ArrayList<JsonNode>(); String shouldMatchQueryUnit = "{\"bool\": " + "{\"should\": " + "[{\"wildcard\": {\"$FIELD\": {\"value\": \"*$VALUE*\", \"boost\": 1}}}, " + "{\"prefix\": {\"$FIELD\": {\"value\": \"$VALUE\", \"boost\": 4}}}, " + "{\"match\": {\"$FIELD\": {\"query\": \"$VALUE\", \"boost\": 16}}}" + "]" + "}" + "}"; String mustNotQueryUnit = "{\"term\" : {\"$FIELD\" : \"$VALUE\"}}"; if (appcodeInList != null && appcodeInList.size() > 0) { for (String appCode : appcodeInList) { if (StringUtils.isNotBlank(appCode)) { shouldValueList.add(Json.parse(shouldMatchQueryUnit.replace("$FIELD", "app_code"). replace("$VALUE", appCode.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (appcodeNotInList != null && appcodeNotInList.size() > 0) { shouldValueList.clear(); for (String appCode : appcodeNotInList) { if (StringUtils.isNotBlank(appCode)) { shouldValueList.add(Json.parse(mustNotQueryUnit.replace("$FIELD", "app_code"). replace("$VALUE", appCode.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustNotValueList.add(boolNode); } if (flowInList != null && flowInList.size() > 0) { shouldValueList.clear(); for (String flow : flowInList) { if (StringUtils.isNotBlank(flow)) { shouldValueList.add(Json.parse(shouldMatchQueryUnit.replace("$FIELD", "flow_name"). replace("$VALUE", flow.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustValueList.add(boolNode); } if (flowNotInList != null && flowNotInList.size() > 0) { shouldValueList.clear(); for (String flow : flowNotInList) { if (StringUtils.isNotBlank(flow)) { shouldValueList.add(Json.parse(mustNotQueryUnit.replace("$FIELD", "flow_name"). replace("$VALUE", flow.toLowerCase().trim()))); } } ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); mustNotValueList.add(boolNode); } if (jobInList != null && jobInList.size() > 0) { shouldValueList.clear(); for (String job : jobInList) { if (StringUtils.isNotBlank(job)) { shouldValueList.add(Json.parse(shouldMatchQueryUnit.replace("$FIELD", "jobs.job_name"). replace("$VALUE", job.toLowerCase().trim()))); } } ObjectNode nestedNode = Json.newObject(); ObjectNode queryNode = Json.newObject(); ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); queryNode.put("query", boolNode); queryNode.put("path", "jobs"); nestedNode.put("nested", queryNode); mustValueList.add(nestedNode); } if (jobNotInList != null && jobNotInList.size() > 0) { shouldValueList.clear(); for (String job : jobNotInList) { if (StringUtils.isNotBlank(job)) { shouldValueList.add(Json.parse(mustNotQueryUnit.replace("$FIELD", "jobs.job_name"). replace("$VALUE", job.toLowerCase().trim()))); } } ObjectNode nestedNode = Json.newObject(); ObjectNode queryNode = Json.newObject(); ObjectNode shouldNode = Json.newObject(); ObjectNode boolNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); boolNode.put("bool", shouldNode); queryNode.put("query", boolNode); queryNode.put("path", "jobs"); nestedNode.put("nested", queryNode); mustNotValueList.add(nestedNode); } ObjectNode boolNode = Json.newObject(); ObjectNode queryNode = Json.newObject(); if (mustValueList.size() > 0 && mustNotValueList.size() > 0) { boolNode.set("must", Json.toJson(mustValueList)); boolNode.set("must_not", Json.toJson(mustNotValueList)); queryNode.put("bool", boolNode); } else if (mustValueList.size() > 0) { boolNode.set("must", Json.toJson(mustValueList)); queryNode.put("bool", boolNode); } else if (mustNotValueList.size() > 0) { boolNode.set("must_not", Json.toJson(mustNotValueList)); queryNode.put("bool", boolNode); } return queryNode; } public static ObjectNode generateElasticSearchFilterString(String sources) { if (StringUtils.isBlank(sources)) { return null; } List<JsonNode> shouldValueList = new ArrayList<JsonNode>(); String queryTemplate = datasetFilterQueryUnit; String[] values = sources.trim().split(","); for (String value : values) { if (StringUtils.isNotBlank(value)) { String query = queryTemplate.replace("$SOURCE", value.replace("\"", "").toLowerCase().trim()); shouldValueList.add(Json.parse(query)); } } ObjectNode shouldNode = Json.newObject(); shouldNode.set("should", Json.toJson(shouldValueList)); ObjectNode queryNode = Json.newObject(); queryNode.put("bool", shouldNode); return queryNode; } }
package net.scapeemulator.game.model.player; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import net.scapeemulator.game.model.mob.Animation; import net.scapeemulator.game.model.mob.combat.AttackStyle; import net.scapeemulator.game.model.mob.combat.AttackType; import net.scapeemulator.game.model.player.requirement.Requirements; import net.scapeemulator.game.model.player.requirement.SkillRequirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class EquipmentDefinition { public enum WeaponClass { AXE(75, "ACCURATE_SLASH", "AGGRESSIVE_SLASH", "AGGRESSIVE_CRUSH", "DEFENSIVE_SLASH"), HAMMER(76, "ACCURATE_CRUSH", "AGGRESSIVE_CRUSH", "DEFENSIVE_CRUSH"), BOW(77, "ACCURATE_RANGE", "RAPID_RANGE", "DEFENSIVE_RANGE"), CLAWS(78, "ACCURATE_SLASH", "AGGRESSIVE_SLASH", "SHARED_STAB", "DEFENSIVE_SLASH"), LONGBOW(79, "ACCURATE_RANGE", "RAPID_RANGE", "DEFENSIVE_RANGE"), FIXED_DEVICE(80), SWORD(81, "ACCURATE_SLASH", "AGGRESSIVE_SLASH", "SHARED_STAB", "DEFENSIVE_SLASH"), TWO_H_SWORD(82, "ACCURATE_SLASH", "AGGRESSIVE_SLASH", "AGGRESSIVE_CRUSH", "DEFENSIVE_SLASH"), PICKAXE(83, "ACCURATE_STAB", "AGGRESSIVE_STAB", "AGGRESSIVE_CRUSH", "DEFENSIVE_STAB"), HALBERD(84, "SHARED_STAB", "AGGRESSIVE_SLASH", "DEFENSIVE_STAB"), STAFF(85, "ACCURATE_CRUSH", "AGGRESSIVE_CRUSH", "DEFENSIVE_CRUSH"), SCYTHE(86, "ACCURATE_SLASH", "AGGRESSIVE_STAB", "AGGRESSIVE_CRUSH", "DEFENSIVE_SLASH"), SPEAR(87, "SHARED_STAB", "SHARED_SLASH", "SHARED_CRUSH", "DEFENSIVE_STAB"), MACE(88, "ACCURATE_CRUSH", "AGGRESSIVE_CRUSH", "SHARED_STAB", "DEFENSIVE_CRUSH"), DAGGER(89, "ACCURATE_STAB", "AGGRESSIVE_STAB", "AGGRESSIVE_SLASH", "DEFENSIVE_STAB"), MAGIC_STAFF(90, "ACCURATE_CRUSH", "AGGRESSIVE_CRUSH", "DEFENSIVE_CRUSH"), THROWN(91, "ACCURATE_RANGE", "RAPID_RANGE", "DEFENSIVE_RANGE"), UNARMED(92, "ACCURATE_CRUSH", "AGGRESSIVE_CRUSH", "DEFENSIVE_CRUSH"), WHIP(93, "ACCURATE_SLASH", "SHARED_SLASH", "DEFENSIVE_SLASH"); //473, 474 chin/lizard private int tabId; private AttackStyle[] styles; private AttackType[] types; private WeaponClass(int tabId, String ... attackInfo) { this.tabId = tabId; styles = new AttackStyle[attackInfo.length]; types = new AttackType[attackInfo.length]; for(int i = 0; i < attackInfo.length; i++) { String[] info = attackInfo[i].split("_"); styles[i] = AttackStyle.valueOf(info[0]); types[i] = AttackType.valueOf(info[1]); } } public int getTabId() { return tabId; } public AttackStyle getAttackStyle(int index) { if(index < 0 || index >= styles.length) { return null; } return styles[index]; } public AttackType getAttackType(int index) { if(index < 0 || index >= types.length) { return null; } return types[index]; } } public static final int FLAG_TWO_HANDED = 0x1; public static final int FLAG_FULL_HELM = 0x2; public static final int FLAG_FULL_MASK = 0x4; public static final int FLAG_FULL_BODY = 0x8; private static final Logger logger = LoggerFactory.getLogger(EquipmentDefinition.class); private static final Map<Integer, EquipmentDefinition> definitions = new HashMap<>(); public static void init() throws IOException { try (DataInputStream reader = new DataInputStream(new FileInputStream("data/game/equipment.dat"))) { int id; while ((id = reader.readShort()) != -1) { int flags = reader.read() & 0xFF; int slot = reader.read() & 0xFF; int equipId = reader.readShort() & 0xFFFF; int[] bonusValues = new int[13]; for(int i = 0; i < 13; i++) { bonusValues[i] = reader.readShort(); } int stance = 0, weaponClass = 0, speed = 0, range = 0; int[] animations = new int[5]; if (slot == Equipment.WEAPON) { stance = reader.readShort() & 0xFFFF; weaponClass = reader.read() & 0xFF; speed = reader.read() & 0xFF; range = reader.read() & 0xFF; for(int i = 0; i < animations.length; i++) { animations[i] = reader.readShort() & 0xFFFF; } } EquipmentDefinition equipment = new EquipmentDefinition(); equipment.equipmentId = equipId; equipment.slot = slot; equipment.twoHanded = (flags & FLAG_TWO_HANDED) != 0; equipment.fullHelm = (flags & FLAG_FULL_HELM) != 0; equipment.fullMask = (flags & FLAG_FULL_MASK) != 0; equipment.fullBody = (flags & FLAG_FULL_BODY) != 0; EquipmentBonuses bonuses = new EquipmentBonuses(); bonuses.setAttackBonus(AttackType.STAB, bonusValues[0]); bonuses.setAttackBonus(AttackType.SLASH, bonusValues[1]); bonuses.setAttackBonus(AttackType.CRUSH, bonusValues[2]); bonuses.setAttackBonus(AttackType.ALL_MAGIC, bonusValues[3]); bonuses.setAttackBonus(AttackType.RANGE, bonusValues[4]); bonuses.setDefenceBonus(AttackType.STAB, bonusValues[5]); bonuses.setDefenceBonus(AttackType.SLASH, bonusValues[6]); bonuses.setDefenceBonus(AttackType.CRUSH, bonusValues[7]); bonuses.setDefenceBonus(AttackType.ALL_MAGIC, bonusValues[8]); bonuses.setDefenceBonus(AttackType.RANGE, bonusValues[9]); bonuses.setStrengthBonus(bonusValues[10]); bonuses.setPrayerBonus(bonusValues[11]); bonuses.setRangeStrengthBonus(bonusValues[12]); equipment.bonuses = bonuses; if (slot == Equipment.WEAPON) { equipment.stance = stance; equipment.weaponClass = WeaponClass.values()[weaponClass]; equipment.speed = speed; equipment.range = range; equipment.animations = animations; } int skill = 0; while ((skill = reader.read()) != 255) { equipment.requirements.addRequirement(new SkillRequirement(skill, reader.read() & 0xFF, false, slot == Equipment.WEAPON ? "wield that" : "wear that")); } definitions.put(id, equipment); } logger.info("Loaded " + definitions.size() + " equipment definitions."); } } public static EquipmentDefinition forId(int id) { return definitions.get(id); } public static EquipmentDefinition UNARMED = new EquipmentDefinition(); static { UNARMED.slot = Equipment.WEAPON; UNARMED.weaponClass = WeaponClass.UNARMED; UNARMED.speed = 6; UNARMED.range = 1; UNARMED.animations = new int[]{422, 423, 422, -1, 424}; } private int id, equipmentId, slot, stance, speed, range; private int[] animations; private boolean fullBody, fullMask, fullHelm, twoHanded; private EquipmentBonuses bonuses; private WeaponClass weaponClass; private Requirements requirements = new Requirements(); public int getId() { return id; } public int getEquipmentId() { return equipmentId; } public int getSlot() { return slot; } public Requirements getRequirements() { return requirements; } public boolean isFullBody() { if (slot != Equipment.BODY) throw new IllegalStateException("Invalid body item: " + id); return fullBody; } public boolean isFullMask() { if (slot != Equipment.HEAD) throw new IllegalStateException("Invalid head item: " + id); return fullMask; } public boolean isFullHelm() { if (slot != Equipment.HEAD) throw new IllegalStateException("Invalid head item: " + id); return fullHelm; } public boolean isTwoHanded() { if (slot != Equipment.WEAPON) throw new IllegalStateException("Invalid weapon: " + id); return twoHanded; } public int getStance() { if (slot != Equipment.WEAPON) throw new IllegalStateException("Invalid weapon: " + id); return stance; } public int getSpeed() { if (slot != Equipment.WEAPON) throw new IllegalStateException("Invalid weapon: " + id); return speed; } public int getRange() { if (slot != Equipment.WEAPON) throw new IllegalStateException("Invalid weapon: " + id); return range; } public EquipmentBonuses getBonuses() { return bonuses; } public WeaponClass getWeaponClass() { if (slot != Equipment.WEAPON) throw new IllegalStateException("Invalid weapon: " + id); return weaponClass; } public Animation getAnimation(AttackStyle style, AttackType type) { if (slot != Equipment.WEAPON) throw new IllegalStateException("Invalid weapon: " + id); for(int i = 0; i < weaponClass.styles.length; i++) { if(weaponClass.styles[i] == style && weaponClass.types[i] == type) { return new Animation(animations[i]); } } return null; } }
package com.rackspacecloud.blueflood.service; import com.rackspacecloud.blueflood.rollup.Granularity; import com.rackspacecloud.blueflood.rollup.SlotKey; import com.rackspacecloud.blueflood.types.Locator; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import static org.mockito.Mockito.*; public class LocatorFetchRunnableDrainExecutionContextTest { ScheduleContext scheduleCtx; SlotKey destSlotKey; ExecutorService rollupReadExecutor; ThreadPoolExecutor rollupWriteExecutor; ExecutorService enumValidatorExecutor; LocatorFetchRunnable lfr; RollupExecutionContext executionContext; RollupBatchWriter rollupBatchWriter; List<Locator> locators; @Before public void setUp() throws IOException { Configuration.getInstance().init(); this.scheduleCtx = mock(ScheduleContext.class); this.destSlotKey = SlotKey.of(Granularity.FULL, 0, 0); this.rollupReadExecutor = mock(ExecutorService.class); this.rollupWriteExecutor = mock(ThreadPoolExecutor.class); this.enumValidatorExecutor = mock(ExecutorService.class); this.lfr = mock(LocatorFetchRunnable.class); this.lfr.initialize(scheduleCtx, destSlotKey, rollupReadExecutor, rollupWriteExecutor, enumValidatorExecutor); doCallRealMethod().when(lfr).drainExecutionContext( anyLong(), anyInt(), Matchers.<RollupExecutionContext>any(), Matchers.<RollupBatchWriter>any()); executionContext = mock(RollupExecutionContext.class); rollupBatchWriter = mock(RollupBatchWriter.class); locators = getTypicalLocators(); } @After public void tearDown() throws IOException { Configuration.getInstance().init(); } List<Locator> getTypicalLocators() { final Locator locator1 = Locator.createLocatorFromPathComponents("tenant1", "a", "b", "c"); final Locator locator2 = Locator.createLocatorFromPathComponents("tenant2", "a", "b", "x"); final Locator locator3 = Locator.createLocatorFromPathComponents("tenant3", "d", "e", "f"); final List<Locator> locators = new ArrayList<Locator>() {{ add(locator1); add(locator2); add(locator3); }}; return locators; } @Test public void drainExecutionContextAlreadyDoneReadingAndWriting() { // given when(executionContext.doneReading()).thenReturn(true); when(executionContext.doneWriting()).thenReturn(true); // when lfr.drainExecutionContext(0, 0, executionContext, rollupBatchWriter); // then verify(executionContext, times(1)).doneReading(); verify(executionContext, times(1)).doneWriting(); verifyNoMoreInteractions(executionContext); verifyZeroInteractions(rollupBatchWriter); verifyZeroInteractions(scheduleCtx); verifyZeroInteractions(rollupReadExecutor); verifyZeroInteractions(rollupWriteExecutor); verifyZeroInteractions(enumValidatorExecutor); verify(lfr).initialize( Matchers.<ScheduleContext>any(), Matchers.<SlotKey>any(), Matchers.<ExecutorService>any(), Matchers.<ThreadPoolExecutor>any(), Matchers.<ExecutorService>any() ); verify(lfr).drainExecutionContext(anyLong(), anyInt(), Matchers.<RollupExecutionContext>any(), Matchers.<RollupBatchWriter>any()); verify(lfr).finishExecution(anyLong(), Matchers.<RollupExecutionContext>any()); verifyNoMoreInteractions(lfr); } @Test public void drainExecutionContextWaitsForRollups() throws InterruptedException { // given when(executionContext.doneReading()) .thenReturn(false) .thenReturn(false) .thenReturn(false) .thenReturn(true); when(executionContext.doneWriting()).thenReturn(true); // when lfr.drainExecutionContext(0, 0, executionContext, rollupBatchWriter); // then verify(executionContext, times(4)).doneReading(); verify(executionContext, times(1)).doneWriting(); verifyNoMoreInteractions(executionContext); verifyZeroInteractions(rollupBatchWriter); verifyZeroInteractions(scheduleCtx); verifyZeroInteractions(rollupReadExecutor); verifyZeroInteractions(rollupWriteExecutor); verifyZeroInteractions(enumValidatorExecutor); verify(lfr).initialize( Matchers.<ScheduleContext>any(), Matchers.<SlotKey>any(), Matchers.<ExecutorService>any(), Matchers.<ThreadPoolExecutor>any(), Matchers.<ExecutorService>any() ); verify(lfr).drainExecutionContext(anyLong(), anyInt(), Matchers.<RollupExecutionContext>any(), Matchers.<RollupBatchWriter>any()); verify(lfr).finishExecution(anyLong(), Matchers.<RollupExecutionContext>any()); verify(lfr).waitForRollups(); verifyNoMoreInteractions(lfr); } @Test public void drainExecutionContextDoneReadingInFinallyBlock() throws InterruptedException { // given when(executionContext.doneReading()) .thenReturn(false) .thenReturn(false) .thenReturn(true) .thenReturn(true); when(executionContext.doneWriting()).thenReturn(true); // when lfr.drainExecutionContext(0, 0, executionContext, rollupBatchWriter); // then verify(executionContext, times(4)).doneReading(); verify(executionContext, times(1)).doneWriting(); verifyNoMoreInteractions(executionContext); verifyZeroInteractions(rollupBatchWriter); verifyZeroInteractions(scheduleCtx); verifyZeroInteractions(rollupReadExecutor); verifyZeroInteractions(rollupWriteExecutor); verifyZeroInteractions(enumValidatorExecutor); verify(lfr).initialize( Matchers.<ScheduleContext>any(), Matchers.<SlotKey>any(), Matchers.<ExecutorService>any(), Matchers.<ThreadPoolExecutor>any(), Matchers.<ExecutorService>any() ); verify(lfr).drainExecutionContext(anyLong(), anyInt(), Matchers.<RollupExecutionContext>any(), Matchers.<RollupBatchWriter>any()); verify(lfr).finishExecution(anyLong(), Matchers.<RollupExecutionContext>any()); verify(lfr).waitForRollups(); verifyNoMoreInteractions(lfr); } @Test public void drainExecutionContextExceptionWhileWaitingHitsExceptionHandler() throws InterruptedException { // given Throwable cause = new InterruptedException("exception for testing purposes"); doThrow(cause).when(lfr).waitForRollups(); when(executionContext.doneReading()) .thenReturn(false) .thenReturn(false) .thenReturn(true) .thenReturn(true); when(executionContext.doneWriting()).thenReturn(true); // when lfr.drainExecutionContext(0, 0, executionContext, rollupBatchWriter); // then verify(executionContext, times(4)).doneReading(); verify(executionContext, times(1)).doneWriting(); verifyNoMoreInteractions(executionContext); verifyZeroInteractions(rollupBatchWriter); verifyZeroInteractions(scheduleCtx); verifyZeroInteractions(rollupReadExecutor); verifyZeroInteractions(rollupWriteExecutor); verifyZeroInteractions(enumValidatorExecutor); verify(lfr).initialize( Matchers.<ScheduleContext>any(), Matchers.<SlotKey>any(), Matchers.<ExecutorService>any(), Matchers.<ThreadPoolExecutor>any(), Matchers.<ExecutorService>any() ); verify(lfr).drainExecutionContext(anyLong(), anyInt(), Matchers.<RollupExecutionContext>any(), Matchers.<RollupBatchWriter>any()); verify(lfr).finishExecution(anyLong(), Matchers.<RollupExecutionContext>any()); verify(lfr).waitForRollups(); verifyNoMoreInteractions(lfr); } @Test public void drainExecutionContextWhenDoneReadingDrainsBatch() throws InterruptedException { // given when(executionContext.doneReading()).thenReturn(true); when(executionContext.doneWriting()) .thenReturn(false) .thenReturn(true); // when lfr.drainExecutionContext(0, 0, executionContext, rollupBatchWriter); // then verify(executionContext, times(4)).doneReading(); verify(executionContext, times(2)).doneWriting(); verifyNoMoreInteractions(executionContext); verify(rollupBatchWriter).drainBatch(); verifyNoMoreInteractions(rollupBatchWriter); verifyZeroInteractions(scheduleCtx); verifyZeroInteractions(rollupReadExecutor); verifyZeroInteractions(rollupWriteExecutor); verifyZeroInteractions(enumValidatorExecutor); verify(lfr).initialize( Matchers.<ScheduleContext>any(), Matchers.<SlotKey>any(), Matchers.<ExecutorService>any(), Matchers.<ThreadPoolExecutor>any(), Matchers.<ExecutorService>any() ); verify(lfr).drainExecutionContext(anyLong(), anyInt(), Matchers.<RollupExecutionContext>any(), Matchers.<RollupBatchWriter>any()); verify(lfr).finishExecution(anyLong(), Matchers.<RollupExecutionContext>any()); verify(lfr).waitForRollups(); verifyNoMoreInteractions(lfr); } }
/* * Copyright 2000-2010 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.ui.docking.impl; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.UISettingsListener; import com.intellij.openapi.Disposable; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.extensions.ExtensionPointListener; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.FrameWrapper; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.BusyObject; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.MutualMap; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.IdeRootPaneNorthExtension; import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.openapi.wm.impl.IdeFocusManagerImpl; import com.intellij.ui.ScreenUtil; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.components.panels.VerticalBox; import com.intellij.ui.docking.*; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.UiNotifyConnector; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.util.*; import java.util.List; @State( name = "DockManager", storages = {@Storage( id = "other", file = "$WORKSPACE_FILE$")}) public class DockManagerImpl extends DockManager implements PersistentStateComponent<Element>{ private Project myProject; private Map<String, DockContainerFactory> myFactories = new HashMap<String, DockContainerFactory>(); private Set<DockContainer> myContainers = new HashSet<DockContainer>(); private MutualMap<DockContainer, DockWindow> myWindows = new MutualMap<DockContainer, DockWindow>(); private MyDragSession myCurrentDragSession; private BusyObject.Impl myBusyObject = new BusyObject.Impl() { @Override protected boolean isReady() { return myCurrentDragSession == null; } }; private int myWindowIdCounter = 1; private Element myLoadedState; public DockManagerImpl(Project project) { myProject = project; } public void register(final DockContainer container) { myContainers.add(container); Disposer.register(container, new Disposable() { @Override public void dispose() { myContainers.remove(container); } }); } @Override public void register(final String id, DockContainerFactory factory) { myFactories.put(id, factory); Disposer.register(factory, new Disposable() { @Override public void dispose() { myFactories.remove(id); } }); readStateFor(id); } @Override public Set<DockContainer> getContainers() { return Collections.unmodifiableSet(myContainers); } @Override public IdeFrame getIdeFrame(DockContainer container) { Component parent = UIUtil.findUltimateParent(container.getComponent()); if (parent instanceof IdeFrame) { return (IdeFrame)parent; } return null; } @Override public String getDimensionKeyForFocus(@NotNull String key) { Component owner = IdeFocusManagerImpl.getInstance(myProject).getFocusOwner(); if (owner == null) return key; DockWindow wnd = myWindows.getValue(getContainerFor(owner)); return wnd != null ? key + "#" + wnd.myId : key; } public DockContainer getContainerFor(Component c) { if (c == null) return null; for (DockContainer eachContainer : myContainers) { if (SwingUtilities.isDescendingFrom(c, eachContainer.getComponent())) { return eachContainer; } } Component parent = UIUtil.findUltimateParent(c); if (parent == null) return null; for (DockContainer eachContainer : myContainers) { if (parent == UIUtil.findUltimateParent(eachContainer.getComponent())) { return eachContainer; } } return null; } @Override public DragSession createDragSession(MouseEvent mouseEvent, DockableContent content) { stopCurrentDragSession(); for (DockContainer each : myContainers) { if (each.isEmpty() && each.isDisposeWhenEmpty()) { DockWindow window = myWindows.getValue(each); if (window != null) { window.setTransparrent(true); } } } myCurrentDragSession = new MyDragSession(mouseEvent, content); return myCurrentDragSession; } private void stopCurrentDragSession() { if (myCurrentDragSession != null) { myCurrentDragSession.cancel(); myCurrentDragSession = null; myBusyObject.onReady(); for (DockContainer each : myContainers) { if (!each.isEmpty()) { DockWindow window = myWindows.getValue(each); if (window != null) { window.setTransparrent(false); } } } } } private ActionCallback getReady() { return myBusyObject.getReady(this); } @Override public void projectOpened() { } @Override public void projectClosed() { } @NotNull @Override public String getComponentName() { return "DockManager"; } @Override public void initComponent() { } @Override public void disposeComponent() { } private class MyDragSession implements DragSession { private JWindow myWindow; private Image myDragImage; private Image myDefaultDragImage; private DockableContent myContent; private DockContainer myCurrentOverContainer; private JLabel myImageContainer; private MyDragSession(MouseEvent me, DockableContent content) { myWindow = new JWindow(); myContent = content; Image previewImage = content.getPreviewImage(); double requiredSize = 220; double width = previewImage.getWidth(null); double height = previewImage.getHeight(null); double ratio; if (width > height) { ratio = requiredSize / width; } else { ratio = requiredSize / height; } BufferedImage buffer = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_ARGB); buffer.createGraphics().drawImage(previewImage, 0, 0, (int)width, (int)height, null); myDefaultDragImage = buffer.getScaledInstance((int)(width * ratio), (int)(height * ratio), Image.SCALE_SMOOTH); myDragImage = myDefaultDragImage; myWindow.getContentPane().setLayout(new BorderLayout()); myImageContainer = new JLabel(new ImageIcon(myDragImage)); myImageContainer.setBorder(new LineBorder(Color.lightGray)); myWindow.getContentPane().add(myImageContainer, BorderLayout.CENTER); setLocationFrom(me); myWindow.setVisible(true); WindowManagerEx.getInstanceEx().setAlphaModeEnabled(myWindow, true); WindowManagerEx.getInstanceEx().setAlphaModeRatio(myWindow, 0.1f); myWindow.getRootPane().putClientProperty("Window.shadow", Boolean.FALSE); } private void setLocationFrom(MouseEvent me) { Point showPoint = me.getPoint(); SwingUtilities.convertPointToScreen(showPoint, me.getComponent()); showPoint.x -= myDragImage.getWidth(null) / 2; showPoint.y += 10; myWindow.setBounds(new Rectangle(showPoint, new Dimension(myDragImage.getWidth(null), myDragImage.getHeight(null)))); } @Override public void process(MouseEvent e) { RelativePoint point = new RelativePoint(e); Image img = null; if (e.getID() == MouseEvent.MOUSE_DRAGGED) { DockContainer over = findContainerFor(point, myContent); if (myCurrentOverContainer != null && myCurrentOverContainer != over) { myCurrentOverContainer.resetDropOver(myContent); myCurrentOverContainer = null; } if (myCurrentOverContainer == null && over != null) { myCurrentOverContainer = over; img = myCurrentOverContainer.startDropOver(myContent, point); } if (myCurrentOverContainer != null) { img = myCurrentOverContainer.processDropOver(myContent, point); } if (img == null) { img = myDefaultDragImage; } if (img != myDragImage) { myDragImage = img; myImageContainer.setIcon(new ImageIcon(myDragImage)); myWindow.pack(); } setLocationFrom(e); } else if (e.getID() == MouseEvent.MOUSE_RELEASED) { if (myCurrentOverContainer == null) { createNewDockContainerFor(myContent, point); stopCurrentDragSession(); } else { myCurrentOverContainer.add(myContent, point); stopCurrentDragSession(); } } } public void cancel() { myWindow.dispose(); if (myCurrentOverContainer != null) { myCurrentOverContainer.resetDropOver(myContent); myCurrentOverContainer = null; } } } @Nullable private DockContainer findContainerFor(RelativePoint point, DockableContent content) { for (DockContainer each : myContainers) { RelativeRectangle rec = each.getAcceptArea(); if (rec.contains(point) && each.canAccept(content, point)) { return each; } } return null; } private DockContainerFactory getFactory(String type) { assert myFactories.containsKey(type) : "No factory for content type=" + type; return myFactories.get(type); } private void createNewDockContainerFor(DockableContent content, RelativePoint point) { DockContainer container = getFactory(content.getDockContainerType()).createContainer(); register(container); final DockWindow window = createWindowFor(null, container); Dimension size = content.getPreferredSize(); Point showPoint = point.getScreenPoint(); showPoint.x -= size.width / 2; showPoint.y -= size.height / 2; Rectangle target = new Rectangle(showPoint, size); ScreenUtil.moveRectangleToFitTheScreen(target); ScreenUtil.cropRectangleToFitTheScreen(target); window.setLocation(target.getLocation()); window.myDockContentUiContainer.setPreferredSize(target.getSize()); window.show(false); window.getFrame().pack(); container.add(content, new RelativePoint(target.getLocation())); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { window.myUiContainer.setPreferredSize(null); } }); } private DockWindow createWindowFor(@Nullable String id, DockContainer container) { String windowId = id != null ? id : String.valueOf(myWindowIdCounter++); DockWindow window = new DockWindow(windowId, myProject, container); window.setDimensionKey("dock-window-" + windowId); myWindows.put(container, window); return window; } private class DockWindow extends FrameWrapper implements IdeEventQueue.EventDispatcher { private String myId; private DockContainer myContainer; private VerticalBox myNorthPanel = new VerticalBox(); private Map<String, IdeRootPaneNorthExtension> myNorthExtensions = new LinkedHashMap<String, IdeRootPaneNorthExtension>(); private NonOpaquePanel myUiContainer; private NonOpaquePanel myDockContentUiContainer; private DockWindow(String id, Project project, DockContainer container) { super(project); myId = id; myContainer = container; setProject(project); setStatusBar(WindowManager.getInstance().getStatusBar(project).createChild()); myUiContainer = new NonOpaquePanel(new BorderLayout()); NonOpaquePanel center = new NonOpaquePanel(new BorderLayout(0, 2)); center.add(myNorthPanel, BorderLayout.NORTH); myDockContentUiContainer = new NonOpaquePanel(new BorderLayout()); myDockContentUiContainer.add(myContainer.getComponent(), BorderLayout.CENTER); center.add(myDockContentUiContainer, BorderLayout.CENTER); myUiContainer.add(center, BorderLayout.CENTER); myUiContainer.add(myStatusBar.getComponent(), BorderLayout.SOUTH); setComponent(myUiContainer); addDisposable(container); IdeEventQueue.getInstance().addPostprocessor(this, this); myContainer.addListener(new DockContainer.Listener.Adapter() { @Override public void contentRemoved(Object key) { getReady().doWhenDone(new Runnable() { @Override public void run() { if (myContainer.isEmpty()) { close(); } } }); } }, this); Extensions.getArea(myProject).getExtensionPoint(IdeRootPaneNorthExtension.EP_NAME).addExtensionPointListener( new ExtensionPointListener<IdeRootPaneNorthExtension>() { @Override public void extensionAdded(@NotNull IdeRootPaneNorthExtension extension, @Nullable PluginDescriptor pluginDescriptor) { updateNorthPanel(); } @Override public void extensionRemoved(@NotNull IdeRootPaneNorthExtension extension, @Nullable PluginDescriptor pluginDescriptor) { updateNorthPanel(); } }); UISettings.getInstance().addUISettingsListener(new UISettingsListener() { @Override public void uiSettingsChanged(UISettings source) { updateNorthPanel(); } }, this); updateNorthPanel(); } @Override protected IdeRootPaneNorthExtension getNorthExtension(String key) { return myNorthExtensions.get(key); } private void updateNorthPanel() { myNorthPanel.setVisible(UISettings.getInstance().SHOW_NAVIGATION_BAR); IdeRootPaneNorthExtension[] extensions = Extensions.getArea(myProject).getExtensionPoint(IdeRootPaneNorthExtension.EP_NAME).getExtensions(); HashSet<String> processedKeys = new HashSet<String>(); for (IdeRootPaneNorthExtension each : extensions) { processedKeys.add(each.getKey()); if (myNorthExtensions.containsKey(each.getKey())) continue; IdeRootPaneNorthExtension toInstall = each.copy(); myNorthExtensions.put(toInstall.getKey(), toInstall); myNorthPanel.add(toInstall.getComponent()); } Iterator<String> existing = myNorthExtensions.keySet().iterator(); while (existing.hasNext()) { String each = existing.next(); if (processedKeys.contains(each)) continue; IdeRootPaneNorthExtension toRemove = myNorthExtensions.get(each); myNorthPanel.remove(toRemove.getComponent()); existing.remove(); Disposer.dispose(toRemove); } myNorthPanel.revalidate(); myNorthPanel.repaint(); } public void setTransparrent(boolean transparrent) { if (transparrent) { WindowManagerEx.getInstanceEx().setAlphaModeEnabled(getFrame(), true); WindowManagerEx.getInstanceEx().setAlphaModeRatio(getFrame(), 0.5f); } else { WindowManagerEx.getInstanceEx().setAlphaModeEnabled(getFrame(), true); WindowManagerEx.getInstanceEx().setAlphaModeRatio(getFrame(), 0f); } } @Override public void dispose() { super.dispose(); myWindows.remove(myContainer); for (IdeRootPaneNorthExtension each : myNorthExtensions.values()) { Disposer.dispose(each); } myNorthExtensions.clear(); } @Override public boolean dispatch(AWTEvent e) { if (e instanceof KeyEvent) { if (myCurrentDragSession != null) { stopCurrentDragSession(); } } return false; } @Override protected JFrame createJFrame(IdeFrame parent) { JFrame frame = super.createJFrame(parent); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { myContainer.closeAll(); } }); new UiNotifyConnector(frame.getContentPane(), myContainer); return frame; } } @Override public Element getState() { Element root = new Element("DockManager"); for (DockContainer each : myContainers) { DockWindow eachWindow = myWindows.getValue(each); if (eachWindow != null) { if (each instanceof DockContainer.Persistent) { DockContainer.Persistent eachContainer = (DockContainer.Persistent)each; Element eachWindowElement = new Element("window"); eachWindowElement.setAttribute("id", eachWindow.myId); Element content = new Element("content"); content.setAttribute("type", eachContainer.getDockContainerType()); content.addContent(eachContainer.getState()); eachWindowElement.addContent(content); root.addContent(eachWindowElement); } } } return root; } @Override public void loadState(Element state) { myLoadedState = state; } private void readStateFor(String type) { if (myLoadedState == null) return; List windows = myLoadedState.getChildren("window"); for (int i = 0; i < windows.size(); i++) { Element eachWindow = (Element)windows.get(i); if (eachWindow == null) continue; String eachId = eachWindow.getAttributeValue("id"); Element eachContent = eachWindow.getChild("content"); if (eachContent == null) continue; String eachType = eachContent.getAttributeValue("type"); if (eachType == null || !type.equals(eachType) || !myFactories.containsKey(eachType)) continue; DockContainerFactory factory = myFactories.get(eachType); if (!(factory instanceof DockContainerFactory.Persistent)) continue; DockContainerFactory.Persistent persistentFactory = (DockContainerFactory.Persistent)factory; DockContainer container = persistentFactory.loadContainerFrom(eachContent); register(container); createWindowFor(eachId, container).show(); } } }
/* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.systemtest.utils.kafkaUtils; import io.strimzi.api.kafka.model.KafkaTopic; import io.strimzi.systemtest.Constants; import io.strimzi.systemtest.cli.KafkaCmdClient; import io.strimzi.systemtest.resources.ResourceManager; import io.strimzi.systemtest.resources.ResourceOperation; import io.strimzi.systemtest.resources.crd.KafkaTopicResource; import io.strimzi.test.TestUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import static io.strimzi.systemtest.enums.CustomResourceStatus.NotReady; import static io.strimzi.systemtest.enums.CustomResourceStatus.Ready; import static io.strimzi.test.k8s.KubeClusterResource.cmdKubeClient; import static io.strimzi.test.k8s.KubeClusterResource.kubeClient; public class KafkaTopicUtils { private static final Logger LOGGER = LogManager.getLogger(KafkaTopicUtils.class); private static final String TOPIC_NAME_PREFIX = "my-topic-"; private static final long READINESS_TIMEOUT = ResourceOperation.getTimeoutForResourceReadiness(KafkaTopic.RESOURCE_KIND); private static final long DELETION_TIMEOUT = ResourceOperation.getTimeoutForResourceDeletion(); private KafkaTopicUtils() {} /** * Generated random name for the KafkaTopic resource * @return random name with additional salt */ public static String generateRandomNameOfTopic() { String salt = new Random().nextInt(Integer.MAX_VALUE) + "-" + new Random().nextInt(Integer.MAX_VALUE); return TOPIC_NAME_PREFIX + salt; } /** * Method which return UID for specific topic * @param topicName topic name * @return topic UID */ public static String topicSnapshot(String topicName) { return KafkaTopicResource.kafkaTopicClient().inNamespace(kubeClient().getNamespace()).withName(topicName).get().getMetadata().getUid(); } /** * Method which wait until topic has rolled form one generation to another. * @param topicName topic name * @param topicUid topic UID * @return topic new UID */ public static String waitTopicHasRolled(String topicName, String topicUid) { TestUtils.waitFor("Topic " + topicName + " has rolled", Constants.GLOBAL_POLL_INTERVAL, Constants.GLOBAL_TIMEOUT, () -> !topicUid.equals(topicSnapshot(topicName))); return topicSnapshot(topicName); } public static void waitForKafkaTopicCreation(String namespaceName, String topicName) { LOGGER.info("Waiting for KafkaTopic {} creation ", topicName); TestUtils.waitFor("KafkaTopic creation " + topicName, Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, READINESS_TIMEOUT, () -> KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName) .withName(topicName).get().getStatus().getConditions().get(0).getType().equals(Ready.toString()), () -> LOGGER.info(KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(topicName).get()) ); } public static void waitForKafkaTopicCreation(String topicName) { waitForKafkaTopicCreation(kubeClient().getNamespace(), topicName); } public static void waitForKafkaTopicCreationByNamePrefix(String namespaceName, String topicNamePrefix) { LOGGER.info("Waiting for KafkaTopic {} creation", topicNamePrefix); TestUtils.waitFor("KafkaTopic creation " + topicNamePrefix, Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, READINESS_TIMEOUT, () -> KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).list().getItems().stream() .filter(topic -> topic.getMetadata().getName().contains(topicNamePrefix)) .findFirst().orElseThrow().getStatus().getConditions().get(0).getType().equals(Ready.toString()) ); } public static void waitForKafkaTopicCreationByNamePrefix(String topicNamePrefix) { waitForKafkaTopicCreationByNamePrefix(kubeClient().getNamespace(), topicNamePrefix); } public static void waitForKafkaTopicDeletion(String namespaceName, String topicName) { LOGGER.info("Waiting for KafkaTopic {} deletion", topicName); TestUtils.waitFor("KafkaTopic deletion " + topicName, Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, DELETION_TIMEOUT, () -> { if (KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(topicName).get() == null) { return true; } else { LOGGER.warn("KafkaTopic {} is not deleted yet! Triggering force delete by cmd client!", topicName); cmdKubeClient(namespaceName).deleteByName(KafkaTopic.RESOURCE_KIND, topicName); return false; } }, () -> LOGGER.info(KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(topicName).get()) ); } public static void waitForKafkaTopicDeletion(String topicName) { waitForKafkaTopicDeletion(kubeClient().getNamespace(), topicName); } public static void waitForKafkaTopicPartitionChange(String namespaceName, String topicName, int partitions) { LOGGER.info("Waiting for KafkaTopic change {}", topicName); TestUtils.waitFor("KafkaTopic change " + topicName, Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, Constants.GLOBAL_TIMEOUT, () -> KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(topicName).get().getSpec().getPartitions() == partitions, () -> LOGGER.error("Kafka Topic {} did not change partition", KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(topicName).get()) ); } public static void waitForKafkaTopicReplicasChange(String namespaceName, String topicName, int replicas) { LOGGER.info("Waiting for KafkaTopic change {}", topicName); TestUtils.waitFor("KafkaTopic change " + topicName, Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, Constants.GLOBAL_TIMEOUT, () -> KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(topicName).get().getSpec().getReplicas() == replicas, () -> LOGGER.error("Kafka Topic {} did not change replicas", KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(topicName).get()) ); } public static void waitForKafkaTopicPartitionChange(String topicName, int partitions) { waitForKafkaTopicPartitionChange(kubeClient().getNamespace(), topicName, partitions); } /** * Wait until KafkaTopic is in desired status * @param namespaceName Namespace name * @param topicName name of KafkaTopic * @param state desired state */ public static boolean waitForKafkaTopicStatus(String namespaceName, String topicName, Enum<?> state) { return ResourceManager.waitForResourceStatus(KafkaTopicResource.kafkaTopicClient(), KafkaTopic.RESOURCE_KIND, namespaceName, topicName, state, ResourceOperation.getTimeoutForResourceReadiness(KafkaTopic.RESOURCE_KIND)); } public static boolean waitForKafkaTopicReady(String namespaceName, String topicName) { return waitForKafkaTopicStatus(namespaceName, topicName, Ready); } public static boolean waitForKafkaTopicReady(String topicName) { return waitForKafkaTopicStatus(kubeClient().getNamespace(), topicName, Ready); } public static boolean waitForKafkaTopicNotReady(String topicName) { return waitForKafkaTopicStatus(kubeClient().getNamespace(), topicName, NotReady); } public static void waitForKafkaTopicsCount(int topicCount, String clusterName) { LOGGER.info("Wait until we create {} KafkaTopics", topicCount); TestUtils.waitFor(topicCount + " KafkaTopics creation", Constants.GLOBAL_POLL_INTERVAL, Constants.GLOBAL_TIMEOUT, () -> KafkaCmdClient.listTopicsUsingPodCli(clusterName, 0).size() == topicCount); LOGGER.info("{} KafkaTopics were created", topicCount); } public static String describeTopicViaKafkaPod(String topicName, String kafkaPodName, String bootstrapServer) { return cmdKubeClient().execInPod(kafkaPodName, "/opt/kafka/bin/kafka-topics.sh", "--topic", topicName, "--describe", "--bootstrap-server", bootstrapServer) .out(); } public static void waitForKafkaTopicSpecStability(String topicName, String podName, String bootstrapServer) { int[] stableCounter = {0}; String oldSpec = describeTopicViaKafkaPod(topicName, podName, bootstrapServer); TestUtils.waitFor("KafkaTopic's spec will be stable", Constants.GLOBAL_POLL_INTERVAL, Constants.GLOBAL_STATUS_TIMEOUT, () -> { if (oldSpec.equals(describeTopicViaKafkaPod(topicName, podName, bootstrapServer))) { stableCounter[0]++; if (stableCounter[0] == Constants.GLOBAL_STABILITY_OFFSET_COUNT) { LOGGER.info("KafkaTopic's spec is stable for {} polls intervals", stableCounter[0]); return true; } } else { LOGGER.info("KafkaTopic's spec is not stable. Going to set the counter to zero."); stableCounter[0] = 0; return false; } LOGGER.info("KafkaTopic's spec gonna be stable in {} polls", Constants.GLOBAL_STABILITY_OFFSET_COUNT - stableCounter[0]); return false; }); } public static List<KafkaTopic> getAllKafkaTopicsWithPrefix(String namespace, String prefix) { return KafkaTopicResource.kafkaTopicClient().inNamespace(namespace).list().getItems() .stream().filter(p -> p.getMetadata().getName().startsWith(prefix)) .collect(Collectors.toList()); } public static void deleteAllKafkaTopicsWithPrefix(String namespace, String prefix) { KafkaTopicUtils.getAllKafkaTopicsWithPrefix(namespace, prefix).forEach(topic -> cmdKubeClient().namespace(namespace).deleteByName(KafkaTopic.RESOURCE_SINGULAR, topic.getMetadata().getName()) ); } }
/* * Copyright (C) 2010 The Guava 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 com.google.common.collect.testing; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; /** * A wrapper around {@code TreeMap} that aggressively checks to see if keys are * mutually comparable. This implementation passes the navigable map test * suites. * * @author Louis Wasserman */ public final class SafeTreeMap<K, V> implements Serializable, NavigableMap<K, V> { @SuppressWarnings("unchecked") private static final Comparator NATURAL_ORDER = new Comparator<Comparable>() { @Override public int compare(Comparable o1, Comparable o2) { return o1.compareTo(o2); } }; private final NavigableMap<K, V> delegate; public SafeTreeMap() { this(new TreeMap<K, V>()); } public SafeTreeMap(Comparator<? super K> comparator) { this(new TreeMap<K, V>(comparator)); } public SafeTreeMap(Map<? extends K, ? extends V> map) { this(new TreeMap<K, V>(map)); } public SafeTreeMap(SortedMap<K, ? extends V> map) { this(new TreeMap<K, V>(map)); } private SafeTreeMap(NavigableMap<K, V> delegate) { this.delegate = delegate; if (delegate == null) { throw new NullPointerException(); } for (K k : keySet()) { checkValid(k); } } @Override public Entry<K, V> ceilingEntry(K key) { return delegate.ceilingEntry(checkValid(key)); } @Override public K ceilingKey(K key) { return delegate.ceilingKey(checkValid(key)); } @Override public void clear() { delegate.clear(); } @SuppressWarnings("unchecked") @Override public Comparator<? super K> comparator() { Comparator<? super K> comparator = delegate.comparator(); if (comparator == null) { comparator = NATURAL_ORDER; } return comparator; } @Override public boolean containsKey(Object key) { try { return delegate.containsKey(checkValid(key)); } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } @Override public boolean containsValue(Object value) { return delegate.containsValue(value); } @Override public NavigableSet<K> descendingKeySet() { return delegate.descendingKeySet(); } @Override public NavigableMap<K, V> descendingMap() { return new SafeTreeMap<K, V>(delegate.descendingMap()); } @Override public Set<Entry<K, V>> entrySet() { return delegate.entrySet(); } @Override public Entry<K, V> firstEntry() { return delegate.firstEntry(); } @Override public K firstKey() { return delegate.firstKey(); } @Override public Entry<K, V> floorEntry(K key) { return delegate.floorEntry(checkValid(key)); } @Override public K floorKey(K key) { return delegate.floorKey(checkValid(key)); } @Override public V get(Object key) { return delegate.get(checkValid(key)); } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return new SafeTreeMap<K, V>( delegate.headMap(checkValid(toKey), inclusive)); } @Override public Entry<K, V> higherEntry(K key) { return delegate.higherEntry(checkValid(key)); } @Override public K higherKey(K key) { return delegate.higherKey(checkValid(key)); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public NavigableSet<K> keySet() { return navigableKeySet(); } @Override public Entry<K, V> lastEntry() { return delegate.lastEntry(); } @Override public K lastKey() { return delegate.lastKey(); } @Override public Entry<K, V> lowerEntry(K key) { return delegate.lowerEntry(checkValid(key)); } @Override public K lowerKey(K key) { return delegate.lowerKey(checkValid(key)); } @Override public NavigableSet<K> navigableKeySet() { return delegate.navigableKeySet(); } @Override public Entry<K, V> pollFirstEntry() { return delegate.pollFirstEntry(); } @Override public Entry<K, V> pollLastEntry() { return delegate.pollLastEntry(); } @Override public V put(K key, V value) { return delegate.put(checkValid(key), value); } @Override public void putAll(Map<? extends K, ? extends V> map) { for (K key : map.keySet()) { checkValid(key); } delegate.putAll(map); } @Override public V remove(Object key) { return delegate.remove(checkValid(key)); } @Override public int size() { return delegate.size(); } @Override public NavigableMap<K, V> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return new SafeTreeMap<K, V>(delegate.subMap( checkValid(fromKey), fromInclusive, checkValid(toKey), toInclusive)); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return new SafeTreeMap<K, V>( delegate.tailMap(checkValid(fromKey), inclusive)); } @Override public Collection<V> values() { return delegate.values(); } private <T> T checkValid(T t) { // a ClassCastException is what's supposed to happen! @SuppressWarnings("unchecked") K k = (K) t; comparator().compare(k, k); return t; } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public int hashCode() { return delegate.hashCode(); } @Override public String toString() { return delegate.toString(); } private static final long serialVersionUID = 0L; }
package com.example.minesweeper; import java.util.Random; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class MinesweeperActivity extends Activity { public static final int ROWS = 8; public static final int COLUMNS = 8; public static final int MINES = 10; public GameTile[][] grid; int column_width, cheat, noOfMines; float displayWidth; private boolean firstClickFlag = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_minesweeper); cheat = 0; noOfMines = MINES; TextView mineCount = (TextView) findViewById(R.id.mineCount); mineCount.setText("" + MINES); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); displayWidth = metrics.widthPixels; column_width = (int) (displayWidth / (ROWS + 1)); showMineField(column_width, column_width); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.minesweeper, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.restartGame: restartGame(); return true; } return super.onOptionsItemSelected(item); } // -------------- Setup MineField and Plant Mines------------------ /* * Displays a 8 x 8 grid of Tiles. Initially has no mines providing the * player a fair first chance. */ public void showMineField(int w, int h) { TableLayout mineField = (TableLayout) findViewById(R.id.mineField); grid = new GameTile[ROWS][COLUMNS]; for (int row = 0; row < ROWS; ++row) { final int drow = row; TableRow mineRow = new TableRow(getApplicationContext()); for (int col = 0; col < COLUMNS; ++col) { final int dcol = col; grid[row][col] = new GameTile(getApplicationContext()); grid[row][col].initGameTile(w, h); // Set normal click... grid[row][col].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!firstClickFlag) setMines(drow, dcol); if (!checkLose(drow, dcol)) { openTilesRecursive(drow, dcol); } else { loseGame(); } } }); // Set long click... grid[row][col] .setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { setQorF(drow, dcol); return true; } }); mineRow.addView(grid[row][col]); } mineField.addView(mineRow); } } /* * Sets the mines in the Mine Field randomly. This happens after the users * first click on any tile. */ public void setMines(final int rw, final int cl) { firstClickFlag = true; Random rand = new Random(); for (int mines = 1; mines <= MINES; ++mines) { int rand_row = rand.nextInt(ROWS); int rand_col = rand.nextInt(COLUMNS); // prevent the current clicked tile to be set as a Mine. if ((rand_row == rw) && (rand_col == cl)) continue; if (rand_row != ROWS && rand_col != COLUMNS) { if (grid[rand_row][rand_col].isMine()) mines--; else { grid[rand_row][rand_col].plantMine(); // go one row and col back int startRow = rand_row - 1; int startCol = rand_col - 1; // check 3 rows across and 3 down int checkRows = 3; int checkCols = 3; if (startRow < 0) // if it is on the first row { startRow = 0; checkRows = 2; } else if (startRow + 3 > ROWS) // if it is on the last row checkRows = 2; if (startCol < 0) { startCol = 0; checkCols = 2; } else if (startCol + 3 > COLUMNS) // if it is on the last checkCols = 2; // 3 rows across & 3 rows down for (int j = startRow; j < startRow + checkRows; j++) { for (int k = startCol; k < startCol + checkCols; k++) { if (!grid[j][k].isMine()) ++grid[j][k].noOfAdjMines; } } } } } } /* * Displays a Popup on LongClick of a Tile. Player can select a Question * Mark or Flag. */ private void setQorF(final int row, final int col) { RelativeLayout pr = (RelativeLayout) findViewById(R.id.popup); final TextView mineCount = (TextView) findViewById(R.id.mineCount); View popupView = LayoutInflater.from(getApplicationContext()).inflate( R.layout.popup, null); // Creating the PopupWindow final PopupWindow popup = new PopupWindow(getApplicationContext()); popup.setContentView(popupView); popup.setWidth(column_width * 3); popup.setHeight(column_width * 2); popup.setFocusable(true); popup.showAsDropDown(grid[row][col]); Button popupF = (Button) popupView.findViewById(R.id.popupF); popupF.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (grid[row][col].isFlagged()) { // Remove flag grid[row][col].setFlagged(false); grid[row][col].setText(""); grid[row][col].setTextColor(Color.BLACK); int mn = ++noOfMines; mineCount.setText("" + mn); grid[row][col] .setBackgroundResource(R.drawable.active_tile); } else { grid[row][col].setFlagged(true); grid[row][col].setText("F"); grid[row][col].setTextColor(Color.BLUE); grid[row][col].setBackgroundColor(Color.GREEN); int mn = --noOfMines; mineCount.setText("" + mn); } popup.dismiss(); } }); Button popupQ = (Button) popupView.findViewById(R.id.popupQ); popupQ.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (grid[row][col].isQuestionMark()) { // Remove question mark grid[row][col].setQuestionMark(false); grid[row][col].setText(""); grid[row][col].setTextColor(Color.BLACK); grid[row][col] .setBackgroundResource(R.drawable.active_tile); } else { grid[row][col].setQuestionMark(true); grid[row][col].setText("?"); grid[row][col].setTextColor(Color.MAGENTA); grid[row][col].setBackgroundColor(Color.YELLOW); } popup.dismiss(); } }); } /* * Start a new game session */ public void restartGame() { TableLayout mineField = (TableLayout) findViewById(R.id.mineField); mineField.removeAllViews(); firstClickFlag = false; noOfMines = MINES; ImageButton ibutton = (ImageButton) findViewById(R.id.smiley); ibutton.setImageResource(R.drawable.smile_start); TextView mineCount = (TextView) findViewById(R.id.mineCount); mineCount.setText("" + MINES); showMineField(column_width, column_width); } // ----------------Gameplay Logic--------------------------------- /* * Opens the 8 connected neighbours of current tile if they have 0 adjacent * tile count. Else, stops. */ public void openTilesRecursive(int row, int col) { if (grid[row][col].isMine() || grid[row][col].isFlagged()) return; grid[row][col].openTile(); if (grid[row][col].noOfAdjMines != 0) return; int startRow = row - 1; int startCol = col - 1; // check 3 rows across and 3 down int checkRows = 3; int checkCols = 3; if (startRow < 0) // if it is on the first row { startRow = 0; checkRows = 2; } else if (startRow + 3 > ROWS) // if it is on the last row checkRows = 2; if (startCol < 0) { startCol = 0; checkCols = 2; } else if (startCol + 3 > COLUMNS) // if it is on the last row checkCols = 2; for (int i = startRow; i < startRow + checkRows; i++) { for (int j = startCol; j < startCol + checkCols; j++) { if (grid[i][j].isCovered()) openTilesRecursive(i, j); } } } /* * called on Smiley click to validate. */ public void onSmileyClick(View v) { if (!firstClickFlag) // prevent validation when user has not started the // game return; if (validate()) winGame(); else loseGame(); } /* * Checks if all the Mines are flagged or covered on Smiley clicked. */ public boolean validate() { for (int r = 0; r < ROWS; ++r) { for (int c = 0; c < COLUMNS; ++c) { if (grid[r][c].isMine()) { if (noOfMines <= 0) { if (!grid[r][c].isFlagged()) return false; } else { if (!grid[r][c].isCovered()) return false; } } } } return true; } /* * Checks if user clicked a Mine. */ public boolean checkLose(int row, int col) { return grid[row][col].isMine(); } /* * Displays a Dialog indicating Game Over. Option to Restart the game. */ public void loseGame() { ImageButton ibutton = (ImageButton) findViewById(R.id.smiley); ibutton.setImageResource(R.drawable.smiley_lose); showMines(false); AlertDialog.Builder builder = new AlertDialog.Builder( MinesweeperActivity.this); builder.setCancelable(true); builder.setTitle("Game Over :("); builder.setIcon(R.drawable.smiley_lose); builder.setNeutralButton("Restart Game", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { restartGame(); dialog.dismiss(); } }); builder.create().show(); } /* * Displays a Dialog indicating Game won. Option to play a New Game. */ public void winGame() { ImageButton ibutton = (ImageButton) findViewById(R.id.smiley); ibutton.setImageResource(R.drawable.smiley_win); showMines(true); AlertDialog.Builder builder = new AlertDialog.Builder( MinesweeperActivity.this); builder.setCancelable(true); builder.setTitle("Congratultions..You WIN !!!"); builder.setIcon(R.drawable.smiley_win); builder.setNeutralButton("New Game", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { restartGame(); dialog.dismiss(); } }); builder.create().show(); } /* * Displays the mines in the minefield on win or lose to the player. */ public void showMines(boolean gameWon) { for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLUMNS; ++j) { if (grid[i][j].isMine()) { if (gameWon || grid[i][j].isFlagged()) { grid[i][j].setBackgroundColor(Color.GREEN); grid[i][j].setText("Y"); } else { grid[i][j].setBackgroundColor(Color.RED); grid[i][j].setText("X"); } } } } } // start a public void setTimer(View v) { } /* * public void cheat(View v) { // can be used to call different types of * game cheats. gameCheat(++cheat); } * * /* Allows the player 3 cheats by automatically flagging mines. If user * wants more cheats, opens a dialog to buy cheats. * * public void gameCheat(int cheatCount) { if (cheatCount > 3) { * AlertDialog.Builder builder = new AlertDialog.Builder( * MinesweeperActivity.this); builder.setCancelable(true); * builder.setTitle("You are out of Cheats"); * builder.setIcon(R.drawable.logo); builder.setNeutralButton("Buy Cheats", * new DialogInterface.OnClickListener() { * * @Override public void onClick(DialogInterface dialog, int which) { // * String url = "http://www.thumbtack.com/"; // Intent in = new * Intent(Intent.ACTION_VIEW); // in.setData(Uri.parse(url)); // * startActivity(in); dialog.dismiss(); } }); builder.create().show(); } * else { for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLUMNS; j++) * { if (grid[i][j].isMine() && !grid[i][j].isFlagged()) { * grid[i][j].setFlagged(true); grid[i][j].setText("F"); * grid[i][j].setTextColor(Color.BLUE); * grid[i][j].setBackgroundColor(Color.GREEN); TextView mineCount = * (TextView) findViewById(R.id.mineCount); mineCount.setText("" + * --noOfMines); return; } } } } } */ // MineSweeperActivity ends.... }
package com.google.ads.googleads.v8.services; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * <pre> * Service to manage customers. * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/ads/googleads/v8/services/customer_service.proto") @io.grpc.stub.annotations.GrpcGenerated public final class CustomerServiceGrpc { private CustomerServiceGrpc() {} public static final String SERVICE_NAME = "google.ads.googleads.v8.services.CustomerService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GetCustomerRequest, com.google.ads.googleads.v8.resources.Customer> getGetCustomerMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetCustomer", requestType = com.google.ads.googleads.v8.services.GetCustomerRequest.class, responseType = com.google.ads.googleads.v8.resources.Customer.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GetCustomerRequest, com.google.ads.googleads.v8.resources.Customer> getGetCustomerMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GetCustomerRequest, com.google.ads.googleads.v8.resources.Customer> getGetCustomerMethod; if ((getGetCustomerMethod = CustomerServiceGrpc.getGetCustomerMethod) == null) { synchronized (CustomerServiceGrpc.class) { if ((getGetCustomerMethod = CustomerServiceGrpc.getGetCustomerMethod) == null) { CustomerServiceGrpc.getGetCustomerMethod = getGetCustomerMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.GetCustomerRequest, com.google.ads.googleads.v8.resources.Customer>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetCustomer")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GetCustomerRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.resources.Customer.getDefaultInstance())) .setSchemaDescriptor(new CustomerServiceMethodDescriptorSupplier("GetCustomer")) .build(); } } } return getGetCustomerMethod; } private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.MutateCustomerRequest, com.google.ads.googleads.v8.services.MutateCustomerResponse> getMutateCustomerMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "MutateCustomer", requestType = com.google.ads.googleads.v8.services.MutateCustomerRequest.class, responseType = com.google.ads.googleads.v8.services.MutateCustomerResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.MutateCustomerRequest, com.google.ads.googleads.v8.services.MutateCustomerResponse> getMutateCustomerMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.MutateCustomerRequest, com.google.ads.googleads.v8.services.MutateCustomerResponse> getMutateCustomerMethod; if ((getMutateCustomerMethod = CustomerServiceGrpc.getMutateCustomerMethod) == null) { synchronized (CustomerServiceGrpc.class) { if ((getMutateCustomerMethod = CustomerServiceGrpc.getMutateCustomerMethod) == null) { CustomerServiceGrpc.getMutateCustomerMethod = getMutateCustomerMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.MutateCustomerRequest, com.google.ads.googleads.v8.services.MutateCustomerResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "MutateCustomer")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.MutateCustomerRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.MutateCustomerResponse.getDefaultInstance())) .setSchemaDescriptor(new CustomerServiceMethodDescriptorSupplier("MutateCustomer")) .build(); } } } return getMutateCustomerMethod; } private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest, com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse> getListAccessibleCustomersMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListAccessibleCustomers", requestType = com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest.class, responseType = com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest, com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse> getListAccessibleCustomersMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest, com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse> getListAccessibleCustomersMethod; if ((getListAccessibleCustomersMethod = CustomerServiceGrpc.getListAccessibleCustomersMethod) == null) { synchronized (CustomerServiceGrpc.class) { if ((getListAccessibleCustomersMethod = CustomerServiceGrpc.getListAccessibleCustomersMethod) == null) { CustomerServiceGrpc.getListAccessibleCustomersMethod = getListAccessibleCustomersMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest, com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListAccessibleCustomers")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse.getDefaultInstance())) .setSchemaDescriptor(new CustomerServiceMethodDescriptorSupplier("ListAccessibleCustomers")) .build(); } } } return getListAccessibleCustomersMethod; } private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.CreateCustomerClientRequest, com.google.ads.googleads.v8.services.CreateCustomerClientResponse> getCreateCustomerClientMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CreateCustomerClient", requestType = com.google.ads.googleads.v8.services.CreateCustomerClientRequest.class, responseType = com.google.ads.googleads.v8.services.CreateCustomerClientResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.CreateCustomerClientRequest, com.google.ads.googleads.v8.services.CreateCustomerClientResponse> getCreateCustomerClientMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.CreateCustomerClientRequest, com.google.ads.googleads.v8.services.CreateCustomerClientResponse> getCreateCustomerClientMethod; if ((getCreateCustomerClientMethod = CustomerServiceGrpc.getCreateCustomerClientMethod) == null) { synchronized (CustomerServiceGrpc.class) { if ((getCreateCustomerClientMethod = CustomerServiceGrpc.getCreateCustomerClientMethod) == null) { CustomerServiceGrpc.getCreateCustomerClientMethod = getCreateCustomerClientMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.CreateCustomerClientRequest, com.google.ads.googleads.v8.services.CreateCustomerClientResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateCustomerClient")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.CreateCustomerClientRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.CreateCustomerClientResponse.getDefaultInstance())) .setSchemaDescriptor(new CustomerServiceMethodDescriptorSupplier("CreateCustomerClient")) .build(); } } } return getCreateCustomerClientMethod; } /** * Creates a new async stub that supports all call types for the service */ public static CustomerServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CustomerServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CustomerServiceStub>() { @java.lang.Override public CustomerServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CustomerServiceStub(channel, callOptions); } }; return CustomerServiceStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static CustomerServiceBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CustomerServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CustomerServiceBlockingStub>() { @java.lang.Override public CustomerServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CustomerServiceBlockingStub(channel, callOptions); } }; return CustomerServiceBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static CustomerServiceFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CustomerServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CustomerServiceFutureStub>() { @java.lang.Override public CustomerServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CustomerServiceFutureStub(channel, callOptions); } }; return CustomerServiceFutureStub.newStub(factory, channel); } /** * <pre> * Service to manage customers. * </pre> */ public static abstract class CustomerServiceImplBase implements io.grpc.BindableService { /** * <pre> * Returns the requested customer in full detail. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public void getCustomer(com.google.ads.googleads.v8.services.GetCustomerRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.resources.Customer> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetCustomerMethod(), responseObserver); } /** * <pre> * Updates a customer. Operation statuses are returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldMaskError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * [UrlFieldError]() * </pre> */ public void mutateCustomer(com.google.ads.googleads.v8.services.MutateCustomerRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.MutateCustomerResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getMutateCustomerMethod(), responseObserver); } /** * <pre> * Returns resource names of customers directly accessible by the * user authenticating the call. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public void listAccessibleCustomers(com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getListAccessibleCustomersMethod(), responseObserver); } /** * <pre> * Creates a new client under manager. The new client customer is returned. * List of thrown errors: * [AccessInvitationError]() * [AuthenticationError]() * [AuthorizationError]() * [CurrencyCodeError]() * [HeaderError]() * [InternalError]() * [ManagerLinkError]() * [QuotaError]() * [RequestError]() * [StringLengthError]() * [TimeZoneError]() * </pre> */ public void createCustomerClient(com.google.ads.googleads.v8.services.CreateCustomerClientRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.CreateCustomerClientResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCreateCustomerClientMethod(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getGetCustomerMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.GetCustomerRequest, com.google.ads.googleads.v8.resources.Customer>( this, METHODID_GET_CUSTOMER))) .addMethod( getMutateCustomerMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.MutateCustomerRequest, com.google.ads.googleads.v8.services.MutateCustomerResponse>( this, METHODID_MUTATE_CUSTOMER))) .addMethod( getListAccessibleCustomersMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest, com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse>( this, METHODID_LIST_ACCESSIBLE_CUSTOMERS))) .addMethod( getCreateCustomerClientMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.CreateCustomerClientRequest, com.google.ads.googleads.v8.services.CreateCustomerClientResponse>( this, METHODID_CREATE_CUSTOMER_CLIENT))) .build(); } } /** * <pre> * Service to manage customers. * </pre> */ public static final class CustomerServiceStub extends io.grpc.stub.AbstractAsyncStub<CustomerServiceStub> { private CustomerServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CustomerServiceStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CustomerServiceStub(channel, callOptions); } /** * <pre> * Returns the requested customer in full detail. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public void getCustomer(com.google.ads.googleads.v8.services.GetCustomerRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.resources.Customer> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetCustomerMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Updates a customer. Operation statuses are returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldMaskError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * [UrlFieldError]() * </pre> */ public void mutateCustomer(com.google.ads.googleads.v8.services.MutateCustomerRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.MutateCustomerResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getMutateCustomerMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Returns resource names of customers directly accessible by the * user authenticating the call. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public void listAccessibleCustomers(com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getListAccessibleCustomersMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Creates a new client under manager. The new client customer is returned. * List of thrown errors: * [AccessInvitationError]() * [AuthenticationError]() * [AuthorizationError]() * [CurrencyCodeError]() * [HeaderError]() * [InternalError]() * [ManagerLinkError]() * [QuotaError]() * [RequestError]() * [StringLengthError]() * [TimeZoneError]() * </pre> */ public void createCustomerClient(com.google.ads.googleads.v8.services.CreateCustomerClientRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.CreateCustomerClientResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCreateCustomerClientMethod(), getCallOptions()), request, responseObserver); } } /** * <pre> * Service to manage customers. * </pre> */ public static final class CustomerServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<CustomerServiceBlockingStub> { private CustomerServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CustomerServiceBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CustomerServiceBlockingStub(channel, callOptions); } /** * <pre> * Returns the requested customer in full detail. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.ads.googleads.v8.resources.Customer getCustomer(com.google.ads.googleads.v8.services.GetCustomerRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetCustomerMethod(), getCallOptions(), request); } /** * <pre> * Updates a customer. Operation statuses are returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldMaskError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * [UrlFieldError]() * </pre> */ public com.google.ads.googleads.v8.services.MutateCustomerResponse mutateCustomer(com.google.ads.googleads.v8.services.MutateCustomerRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getMutateCustomerMethod(), getCallOptions(), request); } /** * <pre> * Returns resource names of customers directly accessible by the * user authenticating the call. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse listAccessibleCustomers(com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListAccessibleCustomersMethod(), getCallOptions(), request); } /** * <pre> * Creates a new client under manager. The new client customer is returned. * List of thrown errors: * [AccessInvitationError]() * [AuthenticationError]() * [AuthorizationError]() * [CurrencyCodeError]() * [HeaderError]() * [InternalError]() * [ManagerLinkError]() * [QuotaError]() * [RequestError]() * [StringLengthError]() * [TimeZoneError]() * </pre> */ public com.google.ads.googleads.v8.services.CreateCustomerClientResponse createCustomerClient(com.google.ads.googleads.v8.services.CreateCustomerClientRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateCustomerClientMethod(), getCallOptions(), request); } } /** * <pre> * Service to manage customers. * </pre> */ public static final class CustomerServiceFutureStub extends io.grpc.stub.AbstractFutureStub<CustomerServiceFutureStub> { private CustomerServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CustomerServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CustomerServiceFutureStub(channel, callOptions); } /** * <pre> * Returns the requested customer in full detail. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.resources.Customer> getCustomer( com.google.ads.googleads.v8.services.GetCustomerRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetCustomerMethod(), getCallOptions()), request); } /** * <pre> * Updates a customer. Operation statuses are returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldMaskError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * [UrlFieldError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.services.MutateCustomerResponse> mutateCustomer( com.google.ads.googleads.v8.services.MutateCustomerRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getMutateCustomerMethod(), getCallOptions()), request); } /** * <pre> * Returns resource names of customers directly accessible by the * user authenticating the call. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse> listAccessibleCustomers( com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getListAccessibleCustomersMethod(), getCallOptions()), request); } /** * <pre> * Creates a new client under manager. The new client customer is returned. * List of thrown errors: * [AccessInvitationError]() * [AuthenticationError]() * [AuthorizationError]() * [CurrencyCodeError]() * [HeaderError]() * [InternalError]() * [ManagerLinkError]() * [QuotaError]() * [RequestError]() * [StringLengthError]() * [TimeZoneError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.services.CreateCustomerClientResponse> createCustomerClient( com.google.ads.googleads.v8.services.CreateCustomerClientRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCreateCustomerClientMethod(), getCallOptions()), request); } } private static final int METHODID_GET_CUSTOMER = 0; private static final int METHODID_MUTATE_CUSTOMER = 1; private static final int METHODID_LIST_ACCESSIBLE_CUSTOMERS = 2; private static final int METHODID_CREATE_CUSTOMER_CLIENT = 3; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final CustomerServiceImplBase serviceImpl; private final int methodId; MethodHandlers(CustomerServiceImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_GET_CUSTOMER: serviceImpl.getCustomer((com.google.ads.googleads.v8.services.GetCustomerRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.resources.Customer>) responseObserver); break; case METHODID_MUTATE_CUSTOMER: serviceImpl.mutateCustomer((com.google.ads.googleads.v8.services.MutateCustomerRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.MutateCustomerResponse>) responseObserver); break; case METHODID_LIST_ACCESSIBLE_CUSTOMERS: serviceImpl.listAccessibleCustomers((com.google.ads.googleads.v8.services.ListAccessibleCustomersRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.ListAccessibleCustomersResponse>) responseObserver); break; case METHODID_CREATE_CUSTOMER_CLIENT: serviceImpl.createCustomerClient((com.google.ads.googleads.v8.services.CreateCustomerClientRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.CreateCustomerClientResponse>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private static abstract class CustomerServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { CustomerServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.ads.googleads.v8.services.CustomerServiceProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("CustomerService"); } } private static final class CustomerServiceFileDescriptorSupplier extends CustomerServiceBaseDescriptorSupplier { CustomerServiceFileDescriptorSupplier() {} } private static final class CustomerServiceMethodDescriptorSupplier extends CustomerServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; CustomerServiceMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (CustomerServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new CustomerServiceFileDescriptorSupplier()) .addMethod(getGetCustomerMethod()) .addMethod(getMutateCustomerMethod()) .addMethod(getListAccessibleCustomersMethod()) .addMethod(getCreateCustomerClientMethod()) .build(); } } } return result; } }
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 6.0 */ /* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ /** ScriptLangParser Class - BEGIN **/ package com.slang.frontend.parser; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public class SimpleCharStream { /** Whether parser is static. */ public static final boolean staticFlag = false; int bufsize; int available; int tokenBegin; /** Position in buffer. */ public int bufpos = -1; protected int bufline[]; protected int bufcolumn[]; protected int column = 0; protected int line = 1; protected boolean prevCharIsCR = false; protected boolean prevCharIsLF = false; protected java.io.Reader inputStream; protected char[] buffer; protected int maxNextCharInd = 0; protected int inBuf = 0; protected int tabSize = 8; protected boolean trackLineColumn = true; public void setTabSize(int i) { tabSize = i; } public int getTabSize() { return tabSize; } protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } /** Start. */ public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; } @Deprecated /** * @deprecated * @see #getEndColumn */ public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ public int getLine() { return bufline[bufpos]; } /** Get token end column number. */ public int getEndColumn() { return bufcolumn[bufpos]; } /** Get token end line number. */ public int getEndLine() { return bufline[bufpos]; } /** Get token beginning column number. */ public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** Get token beginning line number. */ public int getBeginLine() { return bufline[tokenBegin]; } /** Backup a number of characters. */ public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Get token literal value. */ public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** Get the suffix. */ public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Reset buffer when finished. */ public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } boolean getTrackLineColumn() { return trackLineColumn; } void setTrackLineColumn(boolean tlc) { trackLineColumn = tlc; } } /* JavaCC - OriginalChecksum=0a5d3db51a8e56a98ca314c921f161cc (do not edit this line) */
/** */ package isostdisois_13584_32ed_1techxmlschemaontomlSimplified.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import isostdisois_13584_32ed_1techxmlschemaontomlSimplified.HTTPFILE; import isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>HTTPFILE</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.impl.HTTPFILEImpl#getHttpFile <em>Http File</em>}</li> * <li>{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.impl.HTTPFILEImpl#getFileName <em>File Name</em>}</li> * <li>{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.impl.HTTPFILEImpl#getDirName <em>Dir Name</em>}</li> * <li>{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.impl.HTTPFILEImpl#getCountryCode <em>Country Code</em>}</li> * <li>{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.impl.HTTPFILEImpl#getLanguageCode <em>Language Code</em>}</li> * </ul> * * @generated */ public class HTTPFILEImpl extends MinimalEObjectImpl.Container implements HTTPFILE { /** * The default value of the '{@link #getHttpFile() <em>Http File</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHttpFile() * @generated * @ordered */ protected static final String HTTP_FILE_EDEFAULT = null; /** * The cached value of the '{@link #getHttpFile() <em>Http File</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHttpFile() * @generated * @ordered */ protected String httpFile = HTTP_FILE_EDEFAULT; /** * The default value of the '{@link #getFileName() <em>File Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFileName() * @generated * @ordered */ protected static final String FILE_NAME_EDEFAULT = null; /** * The cached value of the '{@link #getFileName() <em>File Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFileName() * @generated * @ordered */ protected String fileName = FILE_NAME_EDEFAULT; /** * The default value of the '{@link #getDirName() <em>Dir Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDirName() * @generated * @ordered */ protected static final String DIR_NAME_EDEFAULT = null; /** * The cached value of the '{@link #getDirName() <em>Dir Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDirName() * @generated * @ordered */ protected String dirName = DIR_NAME_EDEFAULT; /** * The default value of the '{@link #getCountryCode() <em>Country Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCountryCode() * @generated * @ordered */ protected static final String COUNTRY_CODE_EDEFAULT = null; /** * The cached value of the '{@link #getCountryCode() <em>Country Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCountryCode() * @generated * @ordered */ protected String countryCode = COUNTRY_CODE_EDEFAULT; /** * The default value of the '{@link #getLanguageCode() <em>Language Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLanguageCode() * @generated * @ordered */ protected static final String LANGUAGE_CODE_EDEFAULT = null; /** * The cached value of the '{@link #getLanguageCode() <em>Language Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLanguageCode() * @generated * @ordered */ protected String languageCode = LANGUAGE_CODE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected HTTPFILEImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.Literals.HTTPFILE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getHttpFile() { return httpFile; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setHttpFile(String newHttpFile) { String oldHttpFile = httpFile; httpFile = newHttpFile; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__HTTP_FILE, oldHttpFile, httpFile)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getFileName() { return fileName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFileName(String newFileName) { String oldFileName = fileName; fileName = newFileName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__FILE_NAME, oldFileName, fileName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getDirName() { return dirName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDirName(String newDirName) { String oldDirName = dirName; dirName = newDirName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__DIR_NAME, oldDirName, dirName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getCountryCode() { return countryCode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCountryCode(String newCountryCode) { String oldCountryCode = countryCode; countryCode = newCountryCode; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__COUNTRY_CODE, oldCountryCode, countryCode)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLanguageCode() { return languageCode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLanguageCode(String newLanguageCode) { String oldLanguageCode = languageCode; languageCode = newLanguageCode; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__LANGUAGE_CODE, oldLanguageCode, languageCode)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__HTTP_FILE: return getHttpFile(); case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__FILE_NAME: return getFileName(); case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__DIR_NAME: return getDirName(); case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__COUNTRY_CODE: return getCountryCode(); case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__LANGUAGE_CODE: return getLanguageCode(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__HTTP_FILE: setHttpFile((String)newValue); return; case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__FILE_NAME: setFileName((String)newValue); return; case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__DIR_NAME: setDirName((String)newValue); return; case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__COUNTRY_CODE: setCountryCode((String)newValue); return; case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__LANGUAGE_CODE: setLanguageCode((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__HTTP_FILE: setHttpFile(HTTP_FILE_EDEFAULT); return; case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__FILE_NAME: setFileName(FILE_NAME_EDEFAULT); return; case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__DIR_NAME: setDirName(DIR_NAME_EDEFAULT); return; case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__COUNTRY_CODE: setCountryCode(COUNTRY_CODE_EDEFAULT); return; case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__LANGUAGE_CODE: setLanguageCode(LANGUAGE_CODE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__HTTP_FILE: return HTTP_FILE_EDEFAULT == null ? httpFile != null : !HTTP_FILE_EDEFAULT.equals(httpFile); case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__FILE_NAME: return FILE_NAME_EDEFAULT == null ? fileName != null : !FILE_NAME_EDEFAULT.equals(fileName); case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__DIR_NAME: return DIR_NAME_EDEFAULT == null ? dirName != null : !DIR_NAME_EDEFAULT.equals(dirName); case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__COUNTRY_CODE: return COUNTRY_CODE_EDEFAULT == null ? countryCode != null : !COUNTRY_CODE_EDEFAULT.equals(countryCode); case Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage.HTTPFILE__LANGUAGE_CODE: return LANGUAGE_CODE_EDEFAULT == null ? languageCode != null : !LANGUAGE_CODE_EDEFAULT.equals(languageCode); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (httpFile: "); result.append(httpFile); result.append(", fileName: "); result.append(fileName); result.append(", dirName: "); result.append(dirName); result.append(", countryCode: "); result.append(countryCode); result.append(", languageCode: "); result.append(languageCode); result.append(')'); return result.toString(); } } //HTTPFILEImpl
/** Copyright 2017 Andrea "Stock" Stocchero 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.pepstock.charba.client.annotation; import org.pepstock.charba.client.IsChart; import org.pepstock.charba.client.callbacks.NativeCallback; import org.pepstock.charba.client.callbacks.PointStyleCallback; import org.pepstock.charba.client.callbacks.ScriptableFunctions.ProxyObjectCallback; import org.pepstock.charba.client.callbacks.ScriptableUtils; import org.pepstock.charba.client.commons.AbstractNode; import org.pepstock.charba.client.commons.CallbackPropertyHandler; import org.pepstock.charba.client.commons.CallbackProxy; import org.pepstock.charba.client.commons.Checker; import org.pepstock.charba.client.commons.JsHelper; import org.pepstock.charba.client.commons.Key; import org.pepstock.charba.client.commons.NativeObject; import org.pepstock.charba.client.defaults.IsDefaultPointStyleHandler; import org.pepstock.charba.client.dom.elements.Canvas; import org.pepstock.charba.client.dom.elements.Img; import org.pepstock.charba.client.enums.PointStyle; import org.pepstock.charba.client.options.HasPointStyle; import org.pepstock.charba.client.options.PointStyleHandler; import org.pepstock.charba.client.utils.Utilities; /** * Implements a POINT annotation which draws a point in the a chart. * * @author Andrea "Stock" Stocchero * */ public final class PointAnnotation extends AbstractCircleBasedAnnotation implements IsDefaultsPointAnnotation, HasPointStyle, HasExtendedShadowOptions { /** * Default point annotation border width, <b>{@value DEFAULT_BORDER_WIDTH}</b>. */ public static final int DEFAULT_BORDER_WIDTH = 1; /** * Default point annotation radius, <b>{@value DEFAULT_RADIUS}</b>. */ public static final double DEFAULT_RADIUS = 10D; /** * Name of properties of native object. */ private enum Property implements Key { POINT_STYLE("pointStyle"); // name value of property private final String value; /** * Creates with the property value to use in the native object. * * @param value value of property name */ private Property(String value) { this.value = value; } /* * (non-Javadoc) * * @see org.pepstock.charba.client.commons.Key#value() */ @Override public String value() { return value; } } // --------------------------- // -- CALLBACKS PROXIES --- // --------------------------- // callback proxy to invoke the point style function private final CallbackProxy<ProxyObjectCallback> pointStyleCallbackProxy = JsHelper.get().newCallbackProxy(); // callback instance to handle yAdjustg options private static final CallbackPropertyHandler<PointStyleCallback<AnnotationContext>> POINT_STYLE_PROPERTY_HANDLER = new CallbackPropertyHandler<>(Property.POINT_STYLE); // defaults options private final IsDefaultsPointAnnotation defaultValues; // instance of style of points manager private final InternalPointStyleHandler pointStyleHandler; /** * Creates a point annotation to be added to an {@link AnnotationOptions} instance.<br> * The annotation id is calculated automatically. * * @see AnnotationType#createId() */ public PointAnnotation() { this(AnnotationType.POINT.createId(), AnnotationType.POINT.getDefaultsValues()); } /** * Creates a point annotation to be added to an {@link AnnotationOptions} instance, using the ID passed as argument. * * @param id annotation id to apply to the object, as string */ public PointAnnotation(String id) { this(AnnotationId.create(id)); } /** * Creates a point annotation to be added to an {@link AnnotationOptions} instance, using the ID passed as argument. * * @param id annotation id to apply to the object */ public PointAnnotation(AnnotationId id) { this(id, AnnotationHelper.get().getDefaultsAnnotationOptionsByGlobal(AnnotationType.POINT, id)); } /** * Creates a point annotation to be added to an {@link AnnotationOptions} instance, using the ID passed as argument.<br> * The chart instance, passed as argument, must be the chart where the annotations will be applied and is used to get the whole default options in order to get the default for * this object. * * @param id annotation id to apply to the object, as string * @param chart chart instance related to the plugin options */ public PointAnnotation(String id, IsChart chart) { this(AnnotationId.create(id), chart); } /** * Creates a point annotation to be added to an {@link AnnotationOptions} instance, using the ID passed as argument.<br> * The chart instance, passed as argument, must be the chart where the annotations will be applied and is used to get the whole default options in order to get the default for * this object. * * @param id annotation id to apply to the object * @param chart chart instance related to the plugin options */ public PointAnnotation(AnnotationId id, IsChart chart) { this(id, AnnotationHelper.get().getDefaultsAnnotationOptionsByChart(AnnotationType.POINT, id, chart)); } /** * Creates a point annotation to be added to an {@link AnnotationOptions} instance, using the native object and defaults passed as argument. * * @param id annotation id to apply to the object * @param defaultValues default options instance */ private PointAnnotation(AnnotationId id, IsDefaultsAnnotation defaultValues) { // if id is not consistent, new one is created // if defaults is not consistent, the defaults defined for this annotation type is used super(AnnotationType.POINT, id == null ? AnnotationType.POINT.createId() : id, defaultValues == null ? AnnotationType.POINT.getDefaultsValues() : defaultValues); // checks if default are of the right class Checker.assertCheck(getDefaultsValues() instanceof IsDefaultsPointAnnotation, Utilities.applyTemplate(INVALID_DEFAULTS_VALUES_CLASS, AnnotationType.POINT.value())); // casts and stores it this.defaultValues = (IsDefaultsPointAnnotation) getDefaultsValues(); // creates point style handler this.pointStyleHandler = new InternalPointStyleHandler(this, this.defaultValues, getNativeObject()); // init callbacks initPointCallbacks(); } /** * Creates the object wrapping an existing native object. * * @param nativeObject native object to wrap * @param defaultValues default options instance */ PointAnnotation(NativeObject nativeObject, IsDefaultsAnnotation defaultValues) { super(nativeObject, defaultValues); // checks if default are of the right class Checker.assertCheck(getDefaultsValues() instanceof IsDefaultsPointAnnotation, Utilities.applyTemplate(INVALID_DEFAULTS_VALUES_CLASS, AnnotationType.POINT.value())); // casts and stores it this.defaultValues = (IsDefaultsPointAnnotation) getDefaultsValues(); // creates point style handler this.pointStyleHandler = new InternalPointStyleHandler(this, this.defaultValues, getNativeObject()); // init callbacks initPointCallbacks(); } /** * Initializes the callbacks proxies for the options which can be scriptable. */ private void initPointCallbacks() { // ------------------------------- // -- SET CALLBACKS to PROXIES --- // ------------------------------- // sets function to proxy callback in order to invoke the java interface this.pointStyleCallbackProxy.setCallback(context -> onPointStyle(new AnnotationContext(this, context), getPointStyleCallback(), getPointStyle())); } /* * (non-Javadoc) * * @see org.pepstock.charba.client.options.HasPointStyle#getPointStyleHandler() */ @Override public PointStyleHandler getPointStyleHandler() { return pointStyleHandler; } // --------------------- // CALLBACKS // --------------------- /* * (non-Javadoc) * * @see org.pepstock.charba.client.options.HasPointStyle#setPointStyle(org.pepstock.charba.client.enums.PointStyle) */ @Override public void setPointStyle(PointStyle pointStyle) { // reset callback setPointStyle((PointStyleCallback<AnnotationContext>) null); // stores values HasPointStyle.super.setPointStyle(pointStyle); } /* * (non-Javadoc) * * @see org.pepstock.charba.client.options.HasPointStyle#setPointStyle(org.pepstock.charba.client.dom.elements.Img) */ @Override public void setPointStyle(Img pointStyle) { // reset callback setPointStyle((PointStyleCallback<AnnotationContext>) null); // stores values HasPointStyle.super.setPointStyle(pointStyle); } /* * (non-Javadoc) * * @see org.pepstock.charba.client.options.HasPointStyle#setPointStyle(org.pepstock.charba.client.dom.elements.Canvas) */ @Override public void setPointStyle(Canvas pointStyle) { // reset callback setPointStyle((PointStyleCallback<AnnotationContext>) null); // stores values HasPointStyle.super.setPointStyle(pointStyle); } /** * Returns the point style callback, if set, otherwise <code>null</code>. * * @return the point style callback, if set, otherwise <code>null</code>. */ @Override public PointStyleCallback<AnnotationContext> getPointStyleCallback() { return POINT_STYLE_PROPERTY_HANDLER.getCallback(this, defaultValues.getPointStyleCallback()); } /** * Sets the point style callback. * * @param pointStyleCallback the point style callback. */ public void setPointStyle(PointStyleCallback<AnnotationContext> pointStyleCallback) { POINT_STYLE_PROPERTY_HANDLER.setCallback(this, AnnotationPlugin.ID, pointStyleCallback, pointStyleCallbackProxy.getProxy()); } /** * Sets the point style callback. * * @param pointStyleCallback the point style callback. */ public void setPointStyle(NativeCallback pointStyleCallback) { // resets callback setPointStyle((PointStyleCallback<AnnotationContext>) null); // stores values setValue(Property.POINT_STYLE, pointStyleCallback); } // --------------------- // INTERNALS // --------------------- /** * Returns a {@link PointStyle}, {@link Img} or {@link Canvas} when the callback has been activated. * * @param context annotation context instance. * @param callback callback instance to be invoked * @param defaultValue default point style value * @return a object property value, as {@link PointStyle}, {@link Img} or {@link Canvas} */ final Object onPointStyle(AnnotationContext context, PointStyleCallback<AnnotationContext> callback, PointStyle defaultValue) { // gets value Object result = ScriptableUtils.getOptionValue(context, callback); // checks result if (result instanceof PointStyle) { // is point style instance PointStyle style = (PointStyle) result; return style.value(); } else if (result instanceof Img) { // is image element instance return result; } else if (result instanceof Canvas) { // is canvas element instance return result; } // default result return defaultValue.value(); } /** * Internal class to implement a point style handler. * * @author Andrea "Stock" Stocchero * */ private static class InternalPointStyleHandler extends PointStyleHandler { /** * Creates a point style handler with the native object where POINTSTYLE property must be managed and the default value to use when the property does not exist. * * @param parent model which contains the point style handler. * @param defaultValues default value of point style to use when the properties do not exist * @param nativeObject native object where point style handler properties must be managed */ protected InternalPointStyleHandler(AbstractNode parent, IsDefaultPointStyleHandler defaultValues, NativeObject nativeObject) { super(parent, defaultValues, nativeObject); } } }
package ch.codebulb.lambdaomega; import static ch.codebulb.lambdaomega.L.L; import ch.codebulb.lambdaomega.M.E; import ch.codebulb.lambdaomega.abstractions.IndexedI; import ch.codebulb.lambdaomega.abstractions.SequentialIS; import ch.codebulb.lambdaomega.abstractions.IndexedListIS; import ch.codebulb.lambdaomega.abstractions.ReadonlyIndexedI; import ch.codebulb.lambdaomega.abstractions.SequentialI; import java.util.AbstractMap; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collector; import java.util.stream.Collectors; /** * The "M" stands for "map". An implementation of a wrapper API for {@link Map} which provides both indexed access (from <code>K</code> to <code>V</code>) * and sequential access (of type {@link E} with generic parameters <code>K</code> to <code>V</code>).<p/> * * The constructor of this class is not visible; use one of the convenience {@link #m(Object, Object)} methods to create a new instance of this class. * It's best practice to statically import these functions in client code. * * @param <K> the key type * @param <V> the value type */ public class M<K, V> extends C<M.E<K, V>, K, V> implements SequentialIS<M.E<K, V>>, IndexedListIS<K, V> { /** * The {@link Map} wrapped by this API. */ public final Map<K, V> m; private M(Map<K, V> map) { this.m = map; } /** * Creates an empty {@link M}. * * @see {@link #m(Class, Class)}, {@link #m(Object, Object)} */ public static M m() { return m(new LinkedHashMap<>()); } /** * Turns the map provided into an {@link M}. */ public static <K, V> M<K, V> m(Map<K, V> map) { return new M<>(map); } /** * Creates an empty {@link M} of key type <code>keyClass</code> and value type <code>valueClass</code>. * * @see #m() */ public static <K, V> M<K, V> m(Class<K> keyClass, Class<V> valueClass) { return M.<K, V> m(); } /** * Creates an empty {@link M} of key type {@link String} and value type <code>valueClass</code>. * * @see #m() */ public static <V> M<String, V> m(Class<V> valueClass) { return M.<String, V> m(); } /** * Creates a {@link M} consisting of the entries provided. */ public static <K, V> M<K, V> m(E<K, V>... entries) { M<K, V> map = m(); C.toStream(entries).forEach(it -> map.i(it.k, it.v)); return map; } /** * Creates an empty {@link M} ({@link #m()}) with subsequent {@link #WithDefault(Function)} invocation. */ public static <K, V> M<K, V> m(Function<K, V> defaultValue) { return (M<K, V>) M.<K, V>m().WithDefault(defaultValue); } /** * Creates an empty {@link Map} of key type <code>keyClass</code> and value type <code>valueClass</code>. * * @see #m() */ public static <K, V> Map<K, V> map(Class<K> keyClass, Class<V> valueClas) { return new LinkedHashMap<>(); } /** * Creates a {@link Map} consisting of the entries provided. */ public static <K, V> Map<K, V> map(E<K, V>... entries) { return m(entries).m; } public static <K, V, K2 extends K, V2 extends V> M<K, V> m(K2 k, V2 v) { return (M<K, V>) M.<K, V>m().i(k, v); } @Override public Collection<E<K, V>> toCollection() { return m.entrySet().stream().map(it -> e(it)).collect(Collectors.toSet()); } @Override public Map<K, V> toMap() { return m; } /** * Like {@link ReadonlyIndexedI#get(Object)}, but if there is a default value set with {@link #WithDefault(Function)}, * the newly returned value is also put into the map with the <code>key</code> provided. */ @Override public <VN extends V> VN get(K key) { if (containsAnyKey(key)) { return (VN) m.get(key); } else { V ret = defaultFunction.apply(key); put(key, ret); return (VN) ret; } } @Override public Set<E<K, V>> add(E<K, V>... e) { C.toStream(e).forEach(it -> put(it.k, it.v)); return toSet(); } @Override public Set<E<K, V>> clear() { m.clear(); return toSet(); } @Override public Set<E<K, V>> remove(E<K, V>... value) { return removeAll(C.toList(value)); } @Override public Set<E<K, V>> removeAll(Collection<? extends E<K, V>>... c) { C.toStream(c).forEach(col -> { Map<K, V> asMap = C.toStream(col).map(it -> e(it.k, it.v)).collect(Collectors.toMap(it -> it.k, it -> it.v)); asMap.forEach((k, v) -> m.remove(k, v)); }); return toSet(); } @Override public Set<E<K, V>> retainAll(Collection<? extends E<K, V>>... c) { Map<K, V> allMap = new HashMap<>(); C.toStream(c).forEach(col -> { Map<K, V> asMap = C.toStream(col).map(it -> e(it.k, it.v)).collect(Collectors.toMap(it -> it.k, it -> it.v)); allMap.putAll(asMap); }); List<K> found = L.list(); m.forEach((k, v) -> { if (!Objects.equals(allMap.get(k), v)) { found.add(k); } }); found.stream().forEach(k -> m.remove(k)); return toSet(); } @Override public Set<E<K, V>> addAll(Collection<? extends E<K, V>>... c) { C.toStream(c).forEach(col -> { Map<K, V> asMap = C.toStream(col).map(it -> e(it.k, it.v)).collect(Collectors.toMap(it -> it.k, it -> it.v)); putAll(asMap); }); return toSet(); } @Override public Set<E<K, V>> addAll(SequentialI<? extends E<K, V>>... c) { C.toStream(c).forEach(col -> { Map<K, V> asMap = C.toStream(col.toCollection()).map(it -> e(it.k, it.v)).collect(Collectors.toMap(it -> it.k, it -> it.v)); putAll(asMap); }); return toSet(); } @Override // Use Set as the return type for operation on entries because entries are kept in a Set. public <R> Collector<R, ?, Set<R>> createCollector() { return Collectors.toSet(); } @Override @Deprecated public String join(CharSequence delimiter) { throw new UnsupportedOperationException("Because the order of entries of a map is not defined, " + "joining them leads to undefined results; therefore, it is forbidden."); } @Override public <R> Set<R> map(Function<E<K, V>, R> function) { return (Set<R>)SequentialIS.super.map(function); } @Override @Deprecated public <N> List<N> flatten() { throw new UnsupportedOperationException("Flatten is not supported by map."); } @Override @Deprecated public <N> List<N> flattenDeep() { throw new UnsupportedOperationException("Flatten is not supported by map."); } @Override public <R> L<R> Map(Function<E<K, V>, R> function) { return L(map(function)); } @Override @Deprecated public <N> L<N> Flatten() { return L(flatten()); } @Override @Deprecated public <N> L<N> FlattenDeep() { return L(flattenDeep()); } @Override public L<E<K, V>> FindAll(Predicate<E<K, V>> predicate) { return L(findAll(predicate)); } @Override public L<E<K, V>> Filter(Predicate<E<K, V>> predicate) { return L(filter(predicate)); } @Override public L<E<K, V>> Reject(Predicate<E<K, V>> predicate) { return L(reject(predicate)); } @Override public <R> Map<R, Set<E<K, V>>> groupBy(Function<? super E<K, V>, ? extends R> classifier) { return (Map<R, Set<E<K, V>>>)SequentialIS.super.groupBy(classifier); } @Override public Map<Boolean, Set<E<K, V>>> partition(Predicate<? super E<K, V>> predicate) { return (Map<Boolean, Set<E<K, V>>>)SequentialIS.super.partition(predicate); } @Override public Set<E<K, V>> findAll(Predicate<E<K, V>> predicate) { return (Set<E<K, V>>) SequentialIS.super.findAll(predicate); } @Override public Set<E<K, V>> filter(Predicate<E<K, V>> predicate) { return (Set<E<K, V>>) SequentialIS.super.filter(predicate); } @Override public Set<E<K, V>> reject(Predicate<E<K, V>> predicate) { return (Set<E<K, V>>) SequentialIS.super.reject(predicate); } @Override public <R> Set<R> map(BiFunction<K, V, R> function) { return (Set<R>)IndexedListIS.super.map(function); } @Override public M<K, V> A(SequentialI<? extends E<K, V>>... c) { return (M<K, V>) SequentialIS.super.A(c); } @Override public M<K, V> AddAll(SequentialI<? extends E<K, V>>... c) { return (M<K, V>) SequentialIS.super.AddAll(c); } @Override public M<K, V> A(Collection<? extends E<K, V>>... c) { return (M<K, V>) SequentialIS.super.A(c); } @Override public M<K, V> AddAll(Collection<? extends E<K, V>>... c) { return (M<K, V>) SequentialIS.super.AddAll(c); } @Override public M<K, V> a(E<K, V>... e) { return (M<K, V>) SequentialIS.super.a(e); } @Override public M<K, V> Add(E<K, V>... e) { return (M<K, V>) SequentialIS.super.Add(e); } @Override public M<K, V> I(IndexedI<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.I(m); } @Override public M<K, V> InsertAll(IndexedI<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.InsertAll(m); } @Override public M<K, V> I(Map<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.I(m); } @Override public M<K, V> InsertAll(Map<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.InsertAll(m); } @Override public M<K, V> i(K index, V element) { return (M<K, V>) IndexedListIS.super.i(index, element); } @Override public M<K, V> Insert(K index, V element) { return (M<K, V>) IndexedListIS.super.Insert(index, element); } @Override public M<K, V> S(IndexedI<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.S(m); } @Override public M<K, V> SetAll(IndexedI<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.SetAll(m); } @Override public M<K, V> S(Map<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.S(m); } @Override public M<K, V> SetAll(Map<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.SetAll(m); } @Override public M<K, V> s(K index, V element) { return (M<K, V>) IndexedListIS.super.s(index, element); } @Override public M<K, V> Set(K index, V element) { return (M<K, V>) IndexedListIS.super.Set(index, element); } @Override public M<K, V> D(SequentialI<? extends K>... keys) { return (M<K, V>) IndexedListIS.super.D(keys); } @Override public M<K, V> DeleteAllKeys(SequentialI<? extends K>... keys) { return (M<K, V>) IndexedListIS.super.DeleteAllKeys(keys); } @Override public M<K, V> D(Collection<? extends K>... keys) { return (M<K, V>) IndexedListIS.super.D(keys); } @Override public M<K, V> DeleteAllKeys(Collection<? extends K>... keys) { return (M<K, V>) IndexedListIS.super.DeleteAllKeys(keys); } @Override public M<K, V> d(K... key) { return (M<K, V>) IndexedListIS.super.d(key); } @Override public M<K, V> DeleteKey(K... key) { return (M<K, V>) IndexedListIS.super.DeleteKey(key); } @Override public M<K, V> P(IndexedI<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.P(m); } @Override public M<K, V> PutAll(IndexedI<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.PutAll(m); } @Override public M<K, V> P(Map<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.P(m); } @Override public M<K, V> PutAll(Map<? extends K, ? extends V>... m) { return (M<K, V>) IndexedListIS.super.PutAll(m); } @Override public M<K, V> p(K key, V value) { return (M<K, V>) IndexedListIS.super.p(key, value); } @Override public M<K, V> Put(K key, V value) { return (M<K, V>) IndexedListIS.super.Put(key, value); } @Override public Set<E<K, V>> removeAll(SequentialI<? extends E<K, V>>... c) { return (Set<E<K, V>>) SequentialIS.super.removeAll(c); } @Override public M<K, V> R(SequentialI<? extends E<K, V>>... c) { return (M<K, V>) SequentialIS.super.R(c); } @Override public M<K, V> RemoveAll(SequentialI<? extends E<K, V>>... c) { return (M<K, V>) SequentialIS.super.RemoveAll(c); } @Override public M<K, V> R(Collection<? extends E<K, V>>... c) { return (M<K, V>) SequentialIS.super.R(c); } @Override public M<K, V> RemoveAll(Collection<? extends E<K, V>>... c) { return (M<K, V>) SequentialIS.super.RemoveAll(c); } @Override public M<K, V> r(E<K, V>... value) { return (M<K, V>) SequentialIS.super.r(value); } @Override public M<K, V> Remove(E<K, V>... value) { return (M<K, V>) SequentialIS.super.Remove(value); } @Override public M<K, V> DeleteAllValues(SequentialI<? extends V>... values) { return (M<K, V>) IndexedListIS.super.DeleteAllValues(values); } @Override public M<K, V> DeleteAllValues(Collection<? extends V>... values) { return (M<K, V>) IndexedListIS.super.DeleteAllValues(values); } @Override public M<K, V> DeleteValue(V... value) { return (M<K, V>) IndexedListIS.super.DeleteValue(value); } @Override public M<K, V> WithDefault(Function<K, V> defaultValue) { this.defaultFunction = defaultValue; return this; } @Override public M<K, V> Seq() { return (M<K, V>) super.Seq(); } @Override public M<K, V> Sequential() { return (M<K, V>) super.Sequential(); } @Override public M<K, V> Par() { return (M<K, V>) super.Par(); } @Override public M<K, V> Parallel() { return (M<K, V>) super.Parallel(); } @Override public int hashCode() { int hash = 7; hash = 47 * hash + Objects.hashCode(this.m); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final M<?, ?> other = (M<?, ?>) obj; if (!Objects.equals(this.m, other.m)) { return false; } return true; } @Override public String toString() { return "M" + m.toString(); } /** * Creates an {@link E} with the key and value provided. */ public static <K, V> E<K, V> e(K k, V v) { return new E(k, v); } /** * Turns the {@link Entry} into an {@link E}. */ public static <K, V> E<K, V> e(Map.Entry<K, V> entry) { return new E(entry.getKey(), entry.getValue()); } /** * The "E" stands for "entry". Represents a single {@link Map} entry and can be converted to a {@link Entry}. This is an immutable type.<p/> * * The constructor of this class is not visible; use one of the convenience {@link M#e(Object, Object)} methods to create a new instance of this class. * It's best practice to statically import this function in client code. * * @param <K> the key type * @param <V> the value type */ public static class E<K, V> implements Comparable<E<K, V>> { public final K k; public final V v; public E(K k, V v) { this.k = k; this.v = v; } public Map.Entry<K, V> toEntry() { return new AbstractMap.SimpleEntry<>(k, v); } public K getK() { return k; } public V getV() { return v; } @Override public int hashCode() { int hash = 7; hash = 59 * hash + Objects.hashCode(this.k); hash = 59 * hash + Objects.hashCode(this.v); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final E<?, ?> other = (E<?, ?>) obj; if (!Objects.equals(this.k, other.k)) { return false; } if (!Objects.equals(this.v, other.v)) { return false; } return true; } @Override public String toString() { return "e(" + k + ", " + v + ')'; } @Override public int compareTo(E<K, V> obj) { if (obj == null) { return 1; } if (!(k instanceof Comparable)) { throw new ClassCastException(k.getClass().getName() + " cannot be cast to java.lang.Comparable"); } int ret = ((Comparable<K>)k).compareTo(obj.k); if (ret != 0) { return ret; } if (!(v instanceof Comparable)) { throw new ClassCastException(v.getClass().getName() + " cannot be cast to java.lang.Comparable"); } ret = ((Comparable<V>)v).compareTo(obj.v); return ret; } } }
/* * 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.beam.sdk.io.gcp.bigquery; import static com.google.common.base.Preconditions.checkNotNull; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.util.BackOff; import com.google.api.client.util.BackOffUtils; import com.google.api.client.util.ExponentialBackOff; import com.google.api.client.util.Sleeper; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.Dataset; import com.google.api.services.bigquery.model.DatasetReference; import com.google.api.services.bigquery.model.Job; import com.google.api.services.bigquery.model.JobConfiguration; import com.google.api.services.bigquery.model.JobConfigurationExtract; import com.google.api.services.bigquery.model.JobConfigurationLoad; import com.google.api.services.bigquery.model.JobConfigurationQuery; import com.google.api.services.bigquery.model.JobConfigurationTableCopy; import com.google.api.services.bigquery.model.JobReference; import com.google.api.services.bigquery.model.JobStatistics; import com.google.api.services.bigquery.model.JobStatus; import com.google.api.services.bigquery.model.Table; import com.google.api.services.bigquery.model.TableDataInsertAllRequest; import com.google.api.services.bigquery.model.TableDataInsertAllResponse; import com.google.api.services.bigquery.model.TableDataList; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.cloud.hadoop.util.ApiErrorExtractor; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import org.apache.beam.sdk.options.BigQueryOptions; import org.apache.beam.sdk.options.GcsOptions; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.util.FluentBackoff; import org.apache.beam.sdk.util.Transport; import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An implementation of {@link BigQueryServices} that actually communicates with the cloud BigQuery * service. */ class BigQueryServicesImpl implements BigQueryServices { private static final Logger LOG = LoggerFactory.getLogger(BigQueryServicesImpl.class); // The maximum number of retries to execute a BigQuery RPC. private static final int MAX_RPC_RETRIES = 9; // The initial backoff for executing a BigQuery RPC. private static final Duration INITIAL_RPC_BACKOFF = Duration.standardSeconds(1); // The initial backoff for polling the status of a BigQuery job. private static final Duration INITIAL_JOB_STATUS_POLL_BACKOFF = Duration.standardSeconds(1); @Override public JobService getJobService(BigQueryOptions options) { return new JobServiceImpl(options); } @Override public DatasetService getDatasetService(BigQueryOptions options) { return new DatasetServiceImpl(options); } @Override public BigQueryJsonReader getReaderFromTable(BigQueryOptions bqOptions, TableReference tableRef) { return BigQueryJsonReaderImpl.fromTable(bqOptions, tableRef); } @Override public BigQueryJsonReader getReaderFromQuery( BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flatten, @Nullable Boolean useLegacySql) { return BigQueryJsonReaderImpl.fromQuery(bqOptions, query, projectId, flatten, useLegacySql); } @VisibleForTesting static class JobServiceImpl implements BigQueryServices.JobService { private final ApiErrorExtractor errorExtractor; private final Bigquery client; @VisibleForTesting JobServiceImpl(Bigquery client) { this.errorExtractor = new ApiErrorExtractor(); this.client = client; } private JobServiceImpl(BigQueryOptions options) { this.errorExtractor = new ApiErrorExtractor(); this.client = Transport.newBigQueryClient(options).build(); } /** * {@inheritDoc} * * <p>Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void startLoadJob( JobReference jobRef, JobConfigurationLoad loadConfig) throws InterruptedException, IOException { Job job = new Job() .setJobReference(jobRef) .setConfiguration(new JobConfiguration().setLoad(loadConfig)); startJob(job, errorExtractor, client); } /** * {@inheritDoc} * * <p>Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void startExtractJob(JobReference jobRef, JobConfigurationExtract extractConfig) throws InterruptedException, IOException { Job job = new Job() .setJobReference(jobRef) .setConfiguration( new JobConfiguration().setExtract(extractConfig)); startJob(job, errorExtractor, client); } /** * {@inheritDoc} * * <p>Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void startQueryJob(JobReference jobRef, JobConfigurationQuery queryConfig) throws IOException, InterruptedException { Job job = new Job() .setJobReference(jobRef) .setConfiguration( new JobConfiguration().setQuery(queryConfig)); startJob(job, errorExtractor, client); } /** * {@inheritDoc} * * <p>Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void startCopyJob(JobReference jobRef, JobConfigurationTableCopy copyConfig) throws IOException, InterruptedException { Job job = new Job() .setJobReference(jobRef) .setConfiguration( new JobConfiguration().setCopy(copyConfig)); startJob(job, errorExtractor, client); } private static void startJob(Job job, ApiErrorExtractor errorExtractor, Bigquery client) throws IOException, InterruptedException { BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); startJob(job, errorExtractor, client, Sleeper.DEFAULT, backoff); } @VisibleForTesting static void startJob( Job job, ApiErrorExtractor errorExtractor, Bigquery client, Sleeper sleeper, BackOff backoff) throws IOException, InterruptedException { JobReference jobRef = job.getJobReference(); Exception lastException = null; do { try { client.jobs().insert(jobRef.getProjectId(), job).execute(); return; // SUCCEEDED } catch (GoogleJsonResponseException e) { if (errorExtractor.itemAlreadyExists(e)) { return; // SUCCEEDED } // ignore and retry LOG.warn("Ignore the error and retry inserting the job.", e); lastException = e; } catch (IOException e) { // ignore and retry LOG.warn("Ignore the error and retry inserting the job.", e); lastException = e; } } while (nextBackOff(sleeper, backoff)); throw new IOException( String.format( "Unable to insert job: %s, aborting after %d .", jobRef.getJobId(), MAX_RPC_RETRIES), lastException); } @Override public Job pollJob(JobReference jobRef, int maxAttempts) throws InterruptedException { BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(maxAttempts) .withInitialBackoff(INITIAL_JOB_STATUS_POLL_BACKOFF) .withMaxBackoff(Duration.standardMinutes(1)) .backoff(); return pollJob(jobRef, Sleeper.DEFAULT, backoff); } @VisibleForTesting Job pollJob( JobReference jobRef, Sleeper sleeper, BackOff backoff) throws InterruptedException { do { try { Job job = client.jobs().get(jobRef.getProjectId(), jobRef.getJobId()).execute(); JobStatus status = job.getStatus(); if (status != null && status.getState() != null && status.getState().equals("DONE")) { return job; } // The job is not DONE, wait longer and retry. } catch (IOException e) { // ignore and retry LOG.warn("Ignore the error and retry polling job status.", e); } } while (nextBackOff(sleeper, backoff)); LOG.warn("Unable to poll job status: {}, aborting after reached max .", jobRef.getJobId()); return null; } @Override public JobStatistics dryRunQuery(String projectId, JobConfigurationQuery queryConfig) throws InterruptedException, IOException { Job job = new Job() .setConfiguration(new JobConfiguration() .setQuery(queryConfig) .setDryRun(true)); BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); return executeWithRetries( client.jobs().insert(projectId, job), String.format( "Unable to dry run query: %s, aborting after %d retries.", queryConfig, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff, ALWAYS_RETRY).getStatistics(); } /** * {@inheritDoc} * * <p>Retries the RPC for at most {@code MAX_RPC_ATTEMPTS} times until it succeeds. * * @throws IOException if it exceeds max RPC retries. */ @Override public Job getJob(JobReference jobRef) throws IOException, InterruptedException { BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); return getJob(jobRef, Sleeper.DEFAULT, backoff); } @VisibleForTesting public Job getJob(JobReference jobRef, Sleeper sleeper, BackOff backoff) throws IOException, InterruptedException { String jobId = jobRef.getJobId(); Exception lastException; do { try { return client.jobs().get(jobRef.getProjectId(), jobId).execute(); } catch (GoogleJsonResponseException e) { if (errorExtractor.itemNotFound(e)) { LOG.info("No BigQuery job with job id {} found.", jobId); return null; } LOG.warn( "Ignoring the error encountered while trying to query the BigQuery job {}", jobId, e); lastException = e; } catch (IOException e) { LOG.warn( "Ignoring the error encountered while trying to query the BigQuery job {}", jobId, e); lastException = e; } } while (nextBackOff(sleeper, backoff)); throw new IOException( String.format( "Unable to find BigQuery job: %s, aborting after %d retries.", jobRef, MAX_RPC_RETRIES), lastException); } } @VisibleForTesting static class DatasetServiceImpl implements DatasetService { // Approximate amount of table data to upload per InsertAll request. private static final long UPLOAD_BATCH_SIZE_BYTES = 64 * 1024; // The maximum number of rows to upload per InsertAll request. private static final long MAX_ROWS_PER_BATCH = 500; private static final FluentBackoff INSERT_BACKOFF_FACTORY = FluentBackoff.DEFAULT.withInitialBackoff(Duration.millis(200)).withMaxRetries(5); // A backoff for rate limit exceeded errors. Retries forever. private static final FluentBackoff DEFAULT_BACKOFF_FACTORY = FluentBackoff.DEFAULT .withInitialBackoff(Duration.standardSeconds(1)) .withMaxBackoff(Duration.standardMinutes(2)); private final ApiErrorExtractor errorExtractor; private final Bigquery client; private final PipelineOptions options; private final long maxRowsPerBatch; private ExecutorService executor; @VisibleForTesting DatasetServiceImpl(Bigquery client, PipelineOptions options) { this.errorExtractor = new ApiErrorExtractor(); this.client = client; this.options = options; this.maxRowsPerBatch = MAX_ROWS_PER_BATCH; this.executor = null; } @VisibleForTesting DatasetServiceImpl(Bigquery client, PipelineOptions options, long maxRowsPerBatch) { this.errorExtractor = new ApiErrorExtractor(); this.client = client; this.options = options; this.maxRowsPerBatch = maxRowsPerBatch; this.executor = null; } private DatasetServiceImpl(BigQueryOptions bqOptions) { this.errorExtractor = new ApiErrorExtractor(); this.client = Transport.newBigQueryClient(bqOptions).build(); this.options = bqOptions; this.maxRowsPerBatch = MAX_ROWS_PER_BATCH; this.executor = null; } /** * {@inheritDoc} * * <p>Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public Table getTable(String projectId, String datasetId, String tableId) throws IOException, InterruptedException { BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); return executeWithRetries( client.tables().get(projectId, datasetId, tableId), String.format( "Unable to get table: %s, aborting after %d retries.", tableId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff, DONT_RETRY_NOT_FOUND); } /** * Retry table creation up to 5 minutes (with exponential backoff) when this user is near the * quota for table creation. This relatively innocuous behavior can happen when BigQueryIO is * configured with a table spec function to use different tables for each window. */ private static final int RETRY_CREATE_TABLE_DURATION_MILLIS = (int) TimeUnit.MINUTES.toMillis(5); /** * {@inheritDoc} * * <p>If a table with the same name already exists in the dataset, the function simply * returns. In such a case, * the existing table doesn't necessarily have the same schema as specified * by the parameter. * * @throws IOException if other error than already existing table occurs. */ @Override public void createTable(Table table) throws InterruptedException, IOException { LOG.info("Trying to create BigQuery table: {}", BigQueryIO.toTableSpec(table.getTableReference())); BackOff backoff = new ExponentialBackOff.Builder() .setMaxElapsedTimeMillis(RETRY_CREATE_TABLE_DURATION_MILLIS) .build(); tryCreateTable(table, backoff, Sleeper.DEFAULT); } @VisibleForTesting @Nullable Table tryCreateTable(Table table, BackOff backoff, Sleeper sleeper) throws IOException { boolean retry = false; while (true) { try { return client.tables().insert( table.getTableReference().getProjectId(), table.getTableReference().getDatasetId(), table).execute(); } catch (IOException e) { ApiErrorExtractor extractor = new ApiErrorExtractor(); if (extractor.itemAlreadyExists(e)) { // The table already exists, nothing to return. return null; } else if (extractor.rateLimited(e)) { // The request failed because we hit a temporary quota. Back off and try again. try { if (BackOffUtils.next(sleeper, backoff)) { if (!retry) { LOG.info( "Quota limit reached when creating table {}:{}.{}, retrying up to {} minutes", table.getTableReference().getProjectId(), table.getTableReference().getDatasetId(), table.getTableReference().getTableId(), TimeUnit.MILLISECONDS.toSeconds(RETRY_CREATE_TABLE_DURATION_MILLIS) / 60.0); retry = true; } continue; } } catch (InterruptedException e1) { // Restore interrupted state and throw the last failure. Thread.currentThread().interrupt(); throw e; } } throw e; } } } /** * {@inheritDoc} * * <p>Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void deleteTable(String projectId, String datasetId, String tableId) throws IOException, InterruptedException { BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); executeWithRetries( client.tables().delete(projectId, datasetId, tableId), String.format( "Unable to delete table: %s, aborting after %d retries.", tableId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff, ALWAYS_RETRY); } @Override public boolean isTableEmpty(String projectId, String datasetId, String tableId) throws IOException, InterruptedException { BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); TableDataList dataList = executeWithRetries( client.tabledata().list(projectId, datasetId, tableId), String.format( "Unable to list table data: %s, aborting after %d retries.", tableId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff, ALWAYS_RETRY); return dataList.getRows() == null || dataList.getRows().isEmpty(); } /** * {@inheritDoc} * * <p>Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public Dataset getDataset(String projectId, String datasetId) throws IOException, InterruptedException { BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); return executeWithRetries( client.datasets().get(projectId, datasetId), String.format( "Unable to get dataset: %s, aborting after %d retries.", datasetId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff, DONT_RETRY_NOT_FOUND); } /** * {@inheritDoc} * * <p>Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void createDataset( String projectId, String datasetId, @Nullable String location, @Nullable String description) throws IOException, InterruptedException { BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); createDataset(projectId, datasetId, location, description, Sleeper.DEFAULT, backoff); } private void createDataset( String projectId, String datasetId, @Nullable String location, @Nullable String description, Sleeper sleeper, BackOff backoff) throws IOException, InterruptedException { DatasetReference datasetRef = new DatasetReference() .setProjectId(projectId) .setDatasetId(datasetId); Dataset dataset = new Dataset().setDatasetReference(datasetRef); if (location != null) { dataset.setLocation(location); } if (description != null) { dataset.setFriendlyName(description); dataset.setDescription(description); } Exception lastException; do { try { client.datasets().insert(projectId, dataset).execute(); return; // SUCCEEDED } catch (GoogleJsonResponseException e) { if (errorExtractor.itemAlreadyExists(e)) { return; // SUCCEEDED } // ignore and retry LOG.warn("Ignore the error and retry creating the dataset.", e); lastException = e; } catch (IOException e) { LOG.warn("Ignore the error and retry creating the dataset.", e); lastException = e; } } while (nextBackOff(sleeper, backoff)); throw new IOException( String.format( "Unable to create dataset: %s, aborting after %d .", datasetId, MAX_RPC_RETRIES), lastException); } /** * {@inheritDoc} * * <p>Tries executing the RPC for at most {@code MAX_RPC_RETRIES} times until it succeeds. * * @throws IOException if it exceeds {@code MAX_RPC_RETRIES} attempts. */ @Override public void deleteDataset(String projectId, String datasetId) throws IOException, InterruptedException { BackOff backoff = FluentBackoff.DEFAULT .withMaxRetries(MAX_RPC_RETRIES).withInitialBackoff(INITIAL_RPC_BACKOFF).backoff(); executeWithRetries( client.datasets().delete(projectId, datasetId), String.format( "Unable to delete table: %s, aborting after %d retries.", datasetId, MAX_RPC_RETRIES), Sleeper.DEFAULT, backoff, ALWAYS_RETRY); } @VisibleForTesting long insertAll(TableReference ref, List<TableRow> rowList, @Nullable List<String> insertIdList, BackOff backoff, final Sleeper sleeper) throws IOException, InterruptedException { checkNotNull(ref, "ref"); if (executor == null) { this.executor = options.as(GcsOptions.class).getExecutorService(); } if (insertIdList != null && rowList.size() != insertIdList.size()) { throw new AssertionError("If insertIdList is not null it needs to have at least " + "as many elements as rowList"); } long retTotalDataSize = 0; List<TableDataInsertAllResponse.InsertErrors> allErrors = new ArrayList<>(); // These lists contain the rows to publish. Initially the contain the entire list. // If there are failures, they will contain only the failed rows to be retried. List<TableRow> rowsToPublish = rowList; List<String> idsToPublish = insertIdList; while (true) { List<TableRow> retryRows = new ArrayList<>(); List<String> retryIds = (idsToPublish != null) ? new ArrayList<String>() : null; int strideIndex = 0; // Upload in batches. List<TableDataInsertAllRequest.Rows> rows = new LinkedList<>(); int dataSize = 0; List<Future<List<TableDataInsertAllResponse.InsertErrors>>> futures = new ArrayList<>(); List<Integer> strideIndices = new ArrayList<>(); for (int i = 0; i < rowsToPublish.size(); ++i) { TableRow row = rowsToPublish.get(i); TableDataInsertAllRequest.Rows out = new TableDataInsertAllRequest.Rows(); if (idsToPublish != null) { out.setInsertId(idsToPublish.get(i)); } out.setJson(row.getUnknownKeys()); rows.add(out); dataSize += row.toString().length(); if (dataSize >= UPLOAD_BATCH_SIZE_BYTES || rows.size() >= maxRowsPerBatch || i == rowsToPublish.size() - 1) { TableDataInsertAllRequest content = new TableDataInsertAllRequest(); content.setRows(rows); final Bigquery.Tabledata.InsertAll insert = client.tabledata() .insertAll(ref.getProjectId(), ref.getDatasetId(), ref.getTableId(), content); futures.add( executor.submit(new Callable<List<TableDataInsertAllResponse.InsertErrors>>() { @Override public List<TableDataInsertAllResponse.InsertErrors> call() throws IOException { BackOff backoff = DEFAULT_BACKOFF_FACTORY.backoff(); while (true) { try { return insert.execute().getInsertErrors(); } catch (IOException e) { if (new ApiErrorExtractor().rateLimited(e)) { LOG.info("BigQuery insertAll exceeded rate limit, retrying"); try { sleeper.sleep(backoff.nextBackOffMillis()); } catch (InterruptedException interrupted) { throw new IOException( "Interrupted while waiting before retrying insertAll"); } } else { throw e; } } } } })); strideIndices.add(strideIndex); retTotalDataSize += dataSize; dataSize = 0; strideIndex = i + 1; rows = new LinkedList<>(); } } try { for (int i = 0; i < futures.size(); i++) { List<TableDataInsertAllResponse.InsertErrors> errors = futures.get(i).get(); if (errors != null) { for (TableDataInsertAllResponse.InsertErrors error : errors) { allErrors.add(error); if (error.getIndex() == null) { throw new IOException("Insert failed: " + allErrors); } int errorIndex = error.getIndex().intValue() + strideIndices.get(i); retryRows.add(rowsToPublish.get(errorIndex)); if (retryIds != null) { retryIds.add(idsToPublish.get(errorIndex)); } } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while inserting " + rowsToPublish); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } if (allErrors.isEmpty()) { break; } long nextBackoffMillis = backoff.nextBackOffMillis(); if (nextBackoffMillis == BackOff.STOP) { break; } try { sleeper.sleep(nextBackoffMillis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException( "Interrupted while waiting before retrying insert of " + retryRows); } rowsToPublish = retryRows; idsToPublish = retryIds; allErrors.clear(); LOG.info("Retrying {} failed inserts to BigQuery", rowsToPublish.size()); } if (!allErrors.isEmpty()) { throw new IOException("Insert failed: " + allErrors); } else { return retTotalDataSize; } } @Override public long insertAll( TableReference ref, List<TableRow> rowList, @Nullable List<String> insertIdList) throws IOException, InterruptedException { return insertAll( ref, rowList, insertIdList, INSERT_BACKOFF_FACTORY.backoff(), Sleeper.DEFAULT); } } private static class BigQueryJsonReaderImpl implements BigQueryJsonReader { private BigQueryTableRowIterator iterator; private BigQueryJsonReaderImpl(BigQueryTableRowIterator iterator) { this.iterator = iterator; } private static BigQueryJsonReader fromQuery( BigQueryOptions bqOptions, String query, String projectId, @Nullable Boolean flattenResults, @Nullable Boolean useLegacySql) { return new BigQueryJsonReaderImpl( BigQueryTableRowIterator.fromQuery( query, projectId, Transport.newBigQueryClient(bqOptions).build(), flattenResults, useLegacySql)); } private static BigQueryJsonReader fromTable( BigQueryOptions bqOptions, TableReference tableRef) { return new BigQueryJsonReaderImpl(BigQueryTableRowIterator.fromTable( tableRef, Transport.newBigQueryClient(bqOptions).build())); } @Override public boolean start() throws IOException { try { iterator.open(); return iterator.advance(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted during start() operation", e); } } @Override public boolean advance() throws IOException { try { return iterator.advance(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted during advance() operation", e); } } @Override public TableRow getCurrent() throws NoSuchElementException { return iterator.getCurrent(); } @Override public void close() throws IOException { iterator.close(); } } static final SerializableFunction<IOException, Boolean> DONT_RETRY_NOT_FOUND = new SerializableFunction<IOException, Boolean>() { @Override public Boolean apply(IOException input) { ApiErrorExtractor errorExtractor = new ApiErrorExtractor(); return !errorExtractor.itemNotFound(input); } }; static final SerializableFunction<IOException, Boolean> ALWAYS_RETRY = new SerializableFunction<IOException, Boolean>() { @Override public Boolean apply(IOException input) { return true; } }; @VisibleForTesting static <T> T executeWithRetries( AbstractGoogleClientRequest<T> request, String errorMessage, Sleeper sleeper, BackOff backoff, SerializableFunction<IOException, Boolean> shouldRetry) throws IOException, InterruptedException { Exception lastException = null; do { try { return request.execute(); } catch (IOException e) { LOG.warn("Ignore the error and retry the request.", e); lastException = e; if (!shouldRetry.apply(e)) { break; } } } while (nextBackOff(sleeper, backoff)); throw new IOException( errorMessage, lastException); } /** * Identical to {@link BackOffUtils#next} but without checked IOException. */ private static boolean nextBackOff(Sleeper sleeper, BackOff backoff) throws InterruptedException { try { return BackOffUtils.next(sleeper, backoff); } catch (IOException e) { throw new RuntimeException(e); } } }
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.openvr; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * <h3>Layout</h3> * * <pre><code> * struct VROverlayIntersectionResults_t { * {@link HmdVector3 HmdVector3_t} vPoint; * {@link HmdVector3 HmdVector3_t} vNormal; * {@link HmdVector2 HmdVector2_t} vUVs; * float fDistance; * }</code></pre> */ @NativeType("struct VROverlayIntersectionResults_t") public class VROverlayIntersectionResults extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; /** The struct alignment in bytes. */ public static final int ALIGNOF; /** The struct member offsets. */ public static final int VPOINT, VNORMAL, VUVS, FDISTANCE; static { Layout layout = __struct( __member(HmdVector3.SIZEOF, HmdVector3.ALIGNOF), __member(HmdVector3.SIZEOF, HmdVector3.ALIGNOF), __member(HmdVector2.SIZEOF, HmdVector2.ALIGNOF), __member(4) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); VPOINT = layout.offsetof(0); VNORMAL = layout.offsetof(1); VUVS = layout.offsetof(2); FDISTANCE = layout.offsetof(3); } /** * Creates a {@code VROverlayIntersectionResults} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public VROverlayIntersectionResults(ByteBuffer container) { super(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** @return a {@link HmdVector3} view of the {@code vPoint} field. */ @NativeType("HmdVector3_t") public HmdVector3 vPoint() { return nvPoint(address()); } /** @return a {@link HmdVector3} view of the {@code vNormal} field. */ @NativeType("HmdVector3_t") public HmdVector3 vNormal() { return nvNormal(address()); } /** @return a {@link HmdVector2} view of the {@code vUVs} field. */ @NativeType("HmdVector2_t") public HmdVector2 vUVs() { return nvUVs(address()); } /** @return the value of the {@code fDistance} field. */ public float fDistance() { return nfDistance(address()); } // ----------------------------------- /** Returns a new {@code VROverlayIntersectionResults} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static VROverlayIntersectionResults malloc() { return wrap(VROverlayIntersectionResults.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code VROverlayIntersectionResults} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static VROverlayIntersectionResults calloc() { return wrap(VROverlayIntersectionResults.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code VROverlayIntersectionResults} instance allocated with {@link BufferUtils}. */ public static VROverlayIntersectionResults create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(VROverlayIntersectionResults.class, memAddress(container), container); } /** Returns a new {@code VROverlayIntersectionResults} instance for the specified memory address. */ public static VROverlayIntersectionResults create(long address) { return wrap(VROverlayIntersectionResults.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VROverlayIntersectionResults createSafe(long address) { return address == NULL ? null : wrap(VROverlayIntersectionResults.class, address); } /** * Returns a new {@link VROverlayIntersectionResults.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VROverlayIntersectionResults.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link VROverlayIntersectionResults.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VROverlayIntersectionResults.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link VROverlayIntersectionResults.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static VROverlayIntersectionResults.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link VROverlayIntersectionResults.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static VROverlayIntersectionResults.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VROverlayIntersectionResults.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } // ----------------------------------- /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VROverlayIntersectionResults mallocStack() { return malloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VROverlayIntersectionResults callocStack() { return calloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VROverlayIntersectionResults mallocStack(MemoryStack stack) { return malloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VROverlayIntersectionResults callocStack(MemoryStack stack) { return calloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VROverlayIntersectionResults.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VROverlayIntersectionResults.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VROverlayIntersectionResults.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VROverlayIntersectionResults.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); } /** * Returns a new {@code VROverlayIntersectionResults} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static VROverlayIntersectionResults malloc(MemoryStack stack) { return wrap(VROverlayIntersectionResults.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code VROverlayIntersectionResults} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static VROverlayIntersectionResults calloc(MemoryStack stack) { return wrap(VROverlayIntersectionResults.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link VROverlayIntersectionResults.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VROverlayIntersectionResults.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link VROverlayIntersectionResults.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VROverlayIntersectionResults.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #vPoint}. */ public static HmdVector3 nvPoint(long struct) { return HmdVector3.create(struct + VROverlayIntersectionResults.VPOINT); } /** Unsafe version of {@link #vNormal}. */ public static HmdVector3 nvNormal(long struct) { return HmdVector3.create(struct + VROverlayIntersectionResults.VNORMAL); } /** Unsafe version of {@link #vUVs}. */ public static HmdVector2 nvUVs(long struct) { return HmdVector2.create(struct + VROverlayIntersectionResults.VUVS); } /** Unsafe version of {@link #fDistance}. */ public static float nfDistance(long struct) { return UNSAFE.getFloat(null, struct + VROverlayIntersectionResults.FDISTANCE); } // ----------------------------------- /** An array of {@link VROverlayIntersectionResults} structs. */ public static class Buffer extends StructBuffer<VROverlayIntersectionResults, Buffer> implements NativeResource { private static final VROverlayIntersectionResults ELEMENT_FACTORY = VROverlayIntersectionResults.create(-1L); /** * Creates a new {@code VROverlayIntersectionResults.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link VROverlayIntersectionResults#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected VROverlayIntersectionResults getElementFactory() { return ELEMENT_FACTORY; } /** @return a {@link HmdVector3} view of the {@code vPoint} field. */ @NativeType("HmdVector3_t") public HmdVector3 vPoint() { return VROverlayIntersectionResults.nvPoint(address()); } /** @return a {@link HmdVector3} view of the {@code vNormal} field. */ @NativeType("HmdVector3_t") public HmdVector3 vNormal() { return VROverlayIntersectionResults.nvNormal(address()); } /** @return a {@link HmdVector2} view of the {@code vUVs} field. */ @NativeType("HmdVector2_t") public HmdVector2 vUVs() { return VROverlayIntersectionResults.nvUVs(address()); } /** @return the value of the {@code fDistance} field. */ public float fDistance() { return VROverlayIntersectionResults.nfDistance(address()); } } }
/* * #%L * ACS AEM Commons Bundle * %% * Copyright (C) 2016 Adobe * %% * 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. * #L% */ package com.adobe.acs.commons.exporters.impl.users; import com.day.cq.commons.jcr.JcrConstants; import com.day.text.csv.Csv; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.sling.SlingServlet; import org.apache.jackrabbit.api.JackrabbitSession; import org.apache.jackrabbit.api.security.user.Authorizable; import org.apache.jackrabbit.api.security.user.Group; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ValueMap; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.query.Query; import javax.servlet.ServletException; import java.io.IOException; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.adobe.acs.commons.exporters.impl.users.Constants.*; @SlingServlet( label = "ACS AEM Commons - Users to CSV - Export Servlet", methods = {"GET"}, resourceTypes = {"acs-commons/components/utilities/exporters/users-to-csv"}, selectors = {"export"}, extensions = {"csv"} ) public class UsersExportServlet extends SlingSafeMethodsServlet { private static final Logger log = LoggerFactory.getLogger(UsersExportServlet.class); private static final String QUERY = "SELECT * FROM [rep:User] ORDER BY [rep:principalName]"; private static final String GROUP_DELIMITER = "|"; /** * Generates a CSV file representing the User Data. * * @param request the Sling HTTP Request object * @param response the Sling HTTP Response object * @throws IOException * @throws ServletException */ public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, ServletException { response.setContentType("text/csv"); response.setCharacterEncoding("UTF-8"); final Parameters parameters = new Parameters(request); log.debug("Users to CSV Export Parameters: {}", parameters); final Csv csv = new Csv(); final Writer writer = response.getWriter(); csv.writeInit(writer); final Iterator<Resource> resources = request.getResourceResolver().findResources(QUERY, Query.JCR_SQL2); // Using a HashMap to satisfy issue with duplicate results in AEM 6.1 GA HashMap<String, CsvUser> csvUsers = new LinkedHashMap<String, CsvUser>(); while (resources.hasNext()) { try { Resource resource = resources.next(); CsvUser csvUser = new CsvUser(resource); if (!csvUsers.containsKey(csvUser.getPath()) && checkGroups(parameters.getGroups(), parameters.getGroupFilter(), csvUser)) { csvUsers.put(csvUser.getPath(), csvUser); } } catch (RepositoryException e) { log.error("Unable to extract a user from resource.", e); } } List<String> columns = new ArrayList<String>(); columns.add("Path"); columns.add("User ID"); columns.add("First Name"); columns.add("Last Name"); columns.add("E-mail Address"); columns.add("Created Date"); columns.add("Last Modified Date"); for (String customProperty : parameters.getCustomProperties()) { columns.add(customProperty); } columns.add("All Groups"); columns.add("Direct Groups"); columns.add("Indirect Groups"); csv.writeRow(columns.toArray(new String[columns.size()])); for (final CsvUser csvUser : csvUsers.values()) { List<String> values = new ArrayList<String>(); try { values.add(csvUser.getPath()); values.add(csvUser.getID()); values.add(csvUser.getFirstName()); values.add(csvUser.getLastName()); values.add(csvUser.getEmail()); values.add(csvUser.getCreatedDate()); values.add(csvUser.getLastModifiedDate()); for (String customProperty : parameters.getCustomProperties()) { values.add(csvUser.getCustomProperty(customProperty)); } values.add(StringUtils.join(csvUser.getAllGroups(), GROUP_DELIMITER)); values.add(StringUtils.join(csvUser.getDeclaredGroups(), GROUP_DELIMITER)); values.add(StringUtils.join(csvUser.getTransitiveGroups(), GROUP_DELIMITER)); csv.writeRow(values.toArray(new String[values.size()])); } catch (RepositoryException e) { log.error("Unable to export user to CSV report", e); } } csv.close(); } /** * Determines if the user should be included based on the specified group filter type, and requested groups. * * @param groups the groups * @param groupFilter the groupFilter * @param csvUser the user * @return true if the user should be included. */ protected boolean checkGroups(String[] groups, String groupFilter, CsvUser csvUser) throws RepositoryException { log.debug("Group Filter: {}", groupFilter); if (!ArrayUtils.isEmpty(groups)) { if (GROUP_FILTER_DIRECT.equals(groupFilter) && csvUser.isInDirectGroup(groups)) { log.debug("Adding [ {} ] via [ Direct ] membership", csvUser.getID()); return true; } else if (GROUP_FILTER_INDIRECT.equals(groupFilter) && csvUser.isInIndirectGroup(groups)) { log.debug("Adding [ {} ] via [ Indirect ] membership", csvUser.getID()); return true; } else if (GROUP_FILTER_BOTH.equals(groupFilter) && (csvUser.isInDirectGroup(groups) || csvUser.isInIndirectGroup(groups))) { log.debug("Adding [ {} ] via [ Direct OR Indirect ] membership", csvUser.getID()); return true; } return false; } log.debug("Adding [ {} ] as no groups were specified to specify membership filtering.", csvUser.getID()); return true; } /** * Internal class representing a user that will be exported in CSV format. */ protected static class CsvUser { private final ValueMap properties; private Set<String> declaredGroups = new LinkedHashSet<String>(); private Set<String> transitiveGroups = new LinkedHashSet<String>(); private Set<String> allGroups = new LinkedHashSet<String>(); private Authorizable authorizable; private String email; private String firstName; private String lastName; private Calendar createdDate; private Calendar lastModifiedDate; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); public CsvUser(Resource resource) throws RepositoryException { if (resource == null) { throw new IllegalArgumentException("Authorizable object cannot be null"); } final UserManager userManager = resource.adaptTo(UserManager.class); this.properties = resource.getValueMap(); this.authorizable = userManager.getAuthorizableByPath(resource.getPath()); this.declaredGroups = getGroupIds(authorizable.declaredMemberOf()); this.transitiveGroups = getGroupIds(authorizable.memberOf()); this.allGroups.addAll(this.transitiveGroups); this.allGroups.addAll(this.declaredGroups); this.transitiveGroups.removeAll(this.declaredGroups); this.firstName = properties.get("profile/givenName", ""); this.lastName = properties.get("profile/familyName", ""); this.email = properties.get("profile/email", ""); this.createdDate = properties.get(JcrConstants.JCR_CREATED, Calendar.class); this.lastModifiedDate = properties.get("cq:lastModified", Calendar.class); } public List<String> getDeclaredGroups() { return new ArrayList<String>(declaredGroups); } public List<String> getTransitiveGroups() { return new ArrayList<String>(transitiveGroups); } public List<String> getAllGroups() { return new ArrayList<String>(allGroups); } public String getPath() throws RepositoryException { return authorizable.getPath(); } @SuppressWarnings("checkstyle:abbreviationaswordinname") public String getID() throws RepositoryException { return authorizable.getID(); } private Set<String> getGroupIds(Iterator<Group> groups) throws RepositoryException { final List<String> groupIDs = new ArrayList<String>(); while (groups.hasNext()) { groupIDs.add(groups.next().getID()); } Collections.sort(groupIDs); return new LinkedHashSet<String>(groupIDs); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getCreatedDate() { if (createdDate != null) { return sdf.format(createdDate.getTime()); } else { return ""; } } public String getLastModifiedDate() { if (lastModifiedDate != null) { return sdf.format(lastModifiedDate.getTime()); } else { return ""; } } public String getEmail() { return email; } public boolean isInDirectGroup(String... groups) { return CollectionUtils.containsAny(this.getDeclaredGroups(), Arrays.asList(groups)); } public boolean isInIndirectGroup(String... groups) { return CollectionUtils.containsAny(this.getTransitiveGroups(), Arrays.asList(groups)); } public String getCustomProperty(String customProperty) { return properties.get(customProperty, ""); } } }
/* * 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.ov2021.el.unified.resolver; import java.beans.BeanInfo; import java.beans.FeatureDescriptor; import java.beans.PropertyDescriptor; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import javax.el.ELContext; import javax.el.ELResolver; import javax.el.ValueExpression; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.el.CompositeComponentExpressionHolder; import org.apache.myfaces.shared_ext202patch.config.MyfacesConfig; import org.apache.myfaces.ov2021.view.facelets.FaceletViewDeclarationLanguage; import org.apache.myfaces.ov2021.view.facelets.tag.composite.CompositeComponentBeanInfo; /** * Composite component attribute EL resolver. See JSF spec, section 5.6.2.2. */ public final class CompositeComponentELResolver extends ELResolver { private static final String ATTRIBUTES_MAP = "attrs"; private static final String PARENT_COMPOSITE_COMPONENT = "parent"; private static final String COMPOSITE_COMPONENT_ATTRIBUTES_MAPS = "org.apache.myfaces.COMPOSITE_COMPONENT_ATTRIBUTES_MAPS"; @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { // Per the spec, return String.class. return String.class; } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { // Per the spec, do nothing. return null; } @Override public Class<?> getType(ELContext context, Object base, Object property) { if (base != null && property != null && base instanceof CompositeComponentAttributesMapWrapper && property instanceof String) { FacesContext facesContext = facesContext(context); if (facesContext == null) { facesContext = FacesContext.getCurrentInstance(); } if (facesContext == null) { return null; } if (!MyfacesConfig.getCurrentInstance(facesContext.getExternalContext()).isStrictJsf2CCELResolver()) { // handle JSF 2.2 spec revisions: // code resembles that found in Mojarra because it originates from // the same contributor, whose ICLA is on file Class<?> exprType = null; Class<?> metaType = null; CompositeComponentAttributesMapWrapper evalMap = (CompositeComponentAttributesMapWrapper) base; ValueExpression ve = evalMap.getExpression((String) property); if (ve != null) { exprType = ve.getType(context); } if (!"".equals(property)) { if (evalMap._propertyDescriptors != null) { for (PropertyDescriptor pd : evalMap._propertyDescriptors) { if (property.equals(pd.getName())) { metaType = resolveType(context, pd); break; } } } } if (metaType != null) { // override exprType only if metaType is narrower: if (exprType == null || exprType.isAssignableFrom(metaType)) { context.setPropertyResolved(true); return metaType; } } return exprType; } } // Per the spec, return null. return null; } // adapted from CompositeMetadataTargetImpl#getPropertyType(): private static Class<?> resolveType(ELContext context, PropertyDescriptor pd) { if (pd != null) { Object type = pd.getValue("type"); if (type != null) { type = ((ValueExpression)type).getValue(context); if (type instanceof String) { try { type = FaceletViewDeclarationLanguage._javaTypeToClass((String)type); } catch (ClassNotFoundException e) { type = null; } } return (Class<?>) type; } return pd.getPropertyType(); } return null; } @Override public Object getValue(ELContext context, Object base, Object property) { // Per the spec: base must not be null, an instance of UIComponent, and a composite // component. Property must be a String. if ((base != null) && (base instanceof UIComponent) && UIComponent.isCompositeComponent((UIComponent) base) && (property != null)) { String propName = property.toString(); UIComponent baseComponent = (UIComponent) base; if (propName.equals(ATTRIBUTES_MAP)) { // Return a wrapped map that delegates all calls except get() and put(). context.setPropertyResolved(true); return _getCompositeComponentAttributesMapWrapper(baseComponent, context); } else if (propName.equals(PARENT_COMPOSITE_COMPONENT)) { // Return the parent. context.setPropertyResolved(true); return UIComponent.getCompositeComponentParent(baseComponent); } } // Otherwise, spec says to do nothing (return null). return null; } @SuppressWarnings("unchecked") private Map<String, Object> _getCompositeComponentAttributesMapWrapper( UIComponent baseComponent, ELContext elContext) { Map<Object, Object> contextMap = (Map<Object, Object>) facesContext( elContext).getAttributes(); // We use a WeakHashMap<UIComponent, WeakReference<Map<String, Object>>> to // hold attribute map wrappers by two reasons: // // 1. The wrapper is used multiple times for a very short amount of time (in fact on current request). // 2. The original attribute map has an inner reference to UIComponent, so we need to wrap it // with WeakReference. // Map<UIComponent, WeakReference<Map<String, Object>>> compositeComponentAttributesMaps = (Map<UIComponent, WeakReference<Map<String, Object>>>) contextMap .get(COMPOSITE_COMPONENT_ATTRIBUTES_MAPS); Map<String, Object> attributesMap = null; WeakReference<Map<String, Object>> weakReference; if (compositeComponentAttributesMaps != null) { weakReference = compositeComponentAttributesMaps.get(baseComponent); if (weakReference != null) { attributesMap = weakReference.get(); } if (attributesMap == null) { //create a wrapper map attributesMap = new CompositeComponentAttributesMapWrapper( baseComponent); compositeComponentAttributesMaps.put(baseComponent, new WeakReference<Map<String, Object>>(attributesMap)); } } else { //Create both required maps attributesMap = new CompositeComponentAttributesMapWrapper( baseComponent); compositeComponentAttributesMaps = new WeakHashMap<UIComponent, WeakReference<Map<String, Object>>>(); compositeComponentAttributesMaps.put(baseComponent, new WeakReference<Map<String, Object>>(attributesMap)); contextMap.put(COMPOSITE_COMPONENT_ATTRIBUTES_MAPS, compositeComponentAttributesMaps); } return attributesMap; } // get the FacesContext from the ELContext private static FacesContext facesContext(final ELContext context) { return (FacesContext)context.getContext(FacesContext.class); } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { // Per the spec, return true. return true; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { // Per the spec, do nothing. } // Wrapper map for composite component attributes. Follows spec, section 5.6.2.2, table 5-11. private final class CompositeComponentAttributesMapWrapper implements CompositeComponentExpressionHolder, Map<String, Object> { private final UIComponent _component; private final BeanInfo _beanInfo; private final Map<String, Object> _originalMap; private final PropertyDescriptor [] _propertyDescriptors; private final CompositeComponentBeanInfo _ccBeanInfo; private CompositeComponentAttributesMapWrapper(UIComponent component) { this._component = component; this._originalMap = component.getAttributes(); this._beanInfo = (BeanInfo) _originalMap.get(UIComponent.BEANINFO_KEY); this._propertyDescriptors = _beanInfo.getPropertyDescriptors(); this._ccBeanInfo = (this._beanInfo instanceof CompositeComponentBeanInfo) ? (CompositeComponentBeanInfo) this._beanInfo : null; } public ValueExpression getExpression(String name) { ValueExpression valueExpr = _component.getValueExpression(name); return valueExpr; } public void clear() { _originalMap.clear(); } public boolean containsKey(Object key) { return _originalMap.containsKey(key); } public boolean containsValue(Object value) { return _originalMap.containsValue(value); } public Set<java.util.Map.Entry<String, Object>> entrySet() { return _originalMap.entrySet(); } public Object get(Object key) { Object obj = _originalMap.get(key); if (obj != null) { // _originalMap is a _ComponentAttributesMap and thus any // ValueExpressions will be evaluated by the call to // _originalMap.get(). The only case in which we really will // get a ValueExpression here is when a ValueExpression itself // is stored as an attribute. But in this case we really want to // get the ValueExpression. So we don't have to evaluate possible // ValueExpressions here, but can return obj directly. return obj; } else { if (_ccBeanInfo == null) { for (PropertyDescriptor attribute : _propertyDescriptors) { if (attribute.getName().equals(key)) { obj = attribute.getValue("default"); break; } } } else { PropertyDescriptor attribute = _ccBeanInfo.getPropertyDescriptorsMap().get(key); if (attribute != null) { obj = attribute.getValue("default"); } } // We have to check for a ValueExpression and also evaluate it // here, because in the PropertyDescriptor the default values are // always stored as (Tag-)ValueExpressions. if (obj != null && obj instanceof ValueExpression) { return ((ValueExpression) obj).getValue(FacesContext.getCurrentInstance().getELContext()); } else { return obj; } } } public boolean isEmpty() { return _originalMap.isEmpty(); } public Set<String> keySet() { return _originalMap.keySet(); } public Object put(String key, Object value) { ValueExpression valueExpression = _component.getValueExpression(key); // Per the spec, if the result is a ValueExpression, call setValue(). if (valueExpression != null) { valueExpression.setValue(FacesContext.getCurrentInstance().getELContext(), value); return null; } // Really this map is used to resolve ValueExpressions like // #{cc.attrs.somekey}, so the value returned is not expected to be used, // but is better to delegate to keep the semantic of this method. return _originalMap.put(key, value); } public void putAll(Map<? extends String, ? extends Object> m) { for (String key : m.keySet()) { put(key, m.get(key)); } } public Object remove(Object key) { return _originalMap.remove(key); } public int size() { return _originalMap.size(); } public Collection<Object> values() { return _originalMap.values(); } } }
/* * 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.db.compaction; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.After; import org.junit.Test; import org.apache.cassandra.dht.Murmur3Partitioner; import org.apache.cassandra.locator.InetAddressAndPort; import org.apache.cassandra.schema.MockSchema; import org.apache.cassandra.schema.Schema; import org.apache.cassandra.schema.TableMetadata; import org.apache.cassandra.db.*; import org.apache.cassandra.db.lifecycle.LifecycleTransaction; import org.apache.cassandra.db.rows.EncodingStats; import org.apache.cassandra.db.lifecycle.SSTableSet; import org.apache.cassandra.db.rows.UnfilteredRowIterator; import org.apache.cassandra.dht.ByteOrderedPartitioner.BytesToken; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.io.sstable.*; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.service.ActiveRepairService; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.streaming.PreviewKind; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.UUIDGen; import org.apache.cassandra.utils.concurrent.Refs; import org.apache.cassandra.UpdateBuilder; import org.apache.cassandra.utils.concurrent.Transactional; import static org.apache.cassandra.service.ActiveRepairService.NO_PENDING_REPAIR; import static org.apache.cassandra.service.ActiveRepairService.UNREPAIRED_SSTABLE; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class AntiCompactionTest { private static final String KEYSPACE1 = "AntiCompactionTest"; private static final String CF = "AntiCompactionTest"; private static TableMetadata metadata; private static ColumnFamilyStore cfs; @BeforeClass public static void defineSchema() throws ConfigurationException { SchemaLoader.prepareServer(); metadata = SchemaLoader.standardCFMD(KEYSPACE1, CF).build(); SchemaLoader.createKeyspace(KEYSPACE1, KeyspaceParams.simple(1), metadata); cfs = Schema.instance.getColumnFamilyStoreInstance(metadata.id); } @After public void truncateCF() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.truncateBlocking(); } private void registerParentRepairSession(UUID sessionID, Collection<Range<Token>> ranges, long repairedAt, UUID pendingRepair) throws IOException { ActiveRepairService.instance.registerParentRepairSession(sessionID, InetAddressAndPort.getByName("10.0.0.1"), Lists.newArrayList(cfs), ranges, pendingRepair != null || repairedAt != UNREPAIRED_SSTABLE, repairedAt, true, PreviewKind.NONE); } private void antiCompactOne(long repairedAt, UUID pendingRepair) throws Exception { assert repairedAt != UNREPAIRED_SSTABLE || pendingRepair != null; ColumnFamilyStore store = prepareColumnFamilyStore(); Collection<SSTableReader> sstables = getUnrepairedSSTables(store); assertEquals(store.getLiveSSTables().size(), sstables.size()); Range<Token> range = new Range<Token>(new BytesToken("0".getBytes()), new BytesToken("4".getBytes())); List<Range<Token>> ranges = Arrays.asList(range); int repairedKeys = 0; int pendingKeys = 0; int nonRepairedKeys = 0; try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { if (txn == null) throw new IllegalStateException(); UUID parentRepairSession = pendingRepair == null ? UUID.randomUUID() : pendingRepair; registerParentRepairSession(parentRepairSession, ranges, repairedAt, pendingRepair); CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, repairedAt, pendingRepair, parentRepairSession); } assertEquals(2, store.getLiveSSTables().size()); for (SSTableReader sstable : store.getLiveSSTables()) { try (ISSTableScanner scanner = sstable.getScanner()) { while (scanner.hasNext()) { UnfilteredRowIterator row = scanner.next(); if (sstable.isRepaired() || sstable.isPendingRepair()) { assertTrue(range.contains(row.partitionKey().getToken())); repairedKeys += sstable.isRepaired() ? 1 : 0; pendingKeys += sstable.isPendingRepair() ? 1 : 0; } else { assertFalse(range.contains(row.partitionKey().getToken())); nonRepairedKeys++; } } } } for (SSTableReader sstable : store.getLiveSSTables()) { assertFalse(sstable.isMarkedCompacted()); assertEquals(1, sstable.selfRef().globalCount()); } assertEquals(0, store.getTracker().getCompacting().size()); assertEquals(repairedKeys, repairedAt != UNREPAIRED_SSTABLE ? 4 : 0); assertEquals(pendingKeys, pendingRepair != NO_PENDING_REPAIR ? 4 : 0); assertEquals(nonRepairedKeys, 6); } @Test public void antiCompactOneRepairedAt() throws Exception { antiCompactOne(1000, NO_PENDING_REPAIR); } @Test public void antiCompactOnePendingRepair() throws Exception { antiCompactOne(UNREPAIRED_SSTABLE, UUIDGen.getTimeUUID()); } @Test public void antiCompactionSizeTest() throws InterruptedException, IOException { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF); cfs.disableAutoCompaction(); SSTableReader s = writeFile(cfs, 1000); cfs.addSSTable(s); Range<Token> range = new Range<Token>(new BytesToken(ByteBufferUtil.bytes(0)), new BytesToken(ByteBufferUtil.bytes(500))); List<Range<Token>> ranges = Arrays.asList(range); Collection<SSTableReader> sstables = cfs.getLiveSSTables(); UUID parentRepairSession = UUID.randomUUID(); registerParentRepairSession(parentRepairSession, ranges, UNREPAIRED_SSTABLE, UUIDGen.getTimeUUID()); try (LifecycleTransaction txn = cfs.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { CompactionManager.instance.performAnticompaction(cfs, ranges, refs, txn, 12345, NO_PENDING_REPAIR, parentRepairSession); } long sum = 0; long rows = 0; for (SSTableReader x : cfs.getLiveSSTables()) { sum += x.bytesOnDisk(); rows += x.getTotalRows(); } assertEquals(sum, cfs.metric.liveDiskSpaceUsed.getCount()); assertEquals(rows, 1000 * (1000 * 5));//See writeFile for how this number is derived } private SSTableReader writeFile(ColumnFamilyStore cfs, int count) { File dir = cfs.getDirectories().getDirectoryForNewSSTables(); Descriptor desc = cfs.newSSTableDescriptor(dir); try (SSTableTxnWriter writer = SSTableTxnWriter.create(cfs, desc, 0, 0, NO_PENDING_REPAIR, new SerializationHeader(true, cfs.metadata(), cfs.metadata().regularAndStaticColumns(), EncodingStats.NO_STATS))) { for (int i = 0; i < count; i++) { UpdateBuilder builder = UpdateBuilder.create(metadata, ByteBufferUtil.bytes(i)); for (int j = 0; j < count * 5; j++) builder.newRow("c" + j).add("val", "value1"); writer.append(builder.build().unfilteredIterator()); } Collection<SSTableReader> sstables = writer.finish(true); assertNotNull(sstables); assertEquals(1, sstables.size()); return sstables.iterator().next(); } } public void generateSStable(ColumnFamilyStore store, String Suffix) { for (int i = 0; i < 10; i++) { String localSuffix = Integer.toString(i); new RowUpdateBuilder(metadata, System.currentTimeMillis(), localSuffix + "-" + Suffix) .clustering("c") .add("val", "val" + localSuffix) .build() .applyUnsafe(); } store.forceBlockingFlush(); } @Test public void antiCompactTen() throws InterruptedException, IOException { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.disableAutoCompaction(); for (int table = 0; table < 10; table++) { generateSStable(store,Integer.toString(table)); } Collection<SSTableReader> sstables = getUnrepairedSSTables(store); assertEquals(store.getLiveSSTables().size(), sstables.size()); Range<Token> range = new Range<Token>(new BytesToken("0".getBytes()), new BytesToken("4".getBytes())); List<Range<Token>> ranges = Arrays.asList(range); long repairedAt = 1000; UUID parentRepairSession = UUID.randomUUID(); registerParentRepairSession(parentRepairSession, ranges, repairedAt, null); try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, repairedAt, NO_PENDING_REPAIR, parentRepairSession); } /* Anticompaction will be anti-compacting 10 SSTables but will be doing this two at a time so there will be no net change in the number of sstables */ assertEquals(10, store.getLiveSSTables().size()); int repairedKeys = 0; int nonRepairedKeys = 0; for (SSTableReader sstable : store.getLiveSSTables()) { try (ISSTableScanner scanner = sstable.getScanner()) { while (scanner.hasNext()) { try (UnfilteredRowIterator row = scanner.next()) { if (sstable.isRepaired()) { assertTrue(range.contains(row.partitionKey().getToken())); assertEquals(repairedAt, sstable.getSSTableMetadata().repairedAt); repairedKeys++; } else { assertFalse(range.contains(row.partitionKey().getToken())); assertEquals(ActiveRepairService.UNREPAIRED_SSTABLE, sstable.getSSTableMetadata().repairedAt); nonRepairedKeys++; } } } } } assertEquals(repairedKeys, 40); assertEquals(nonRepairedKeys, 60); } private void shouldMutate(long repairedAt, UUID pendingRepair) throws InterruptedException, IOException { ColumnFamilyStore store = prepareColumnFamilyStore(); Collection<SSTableReader> sstables = getUnrepairedSSTables(store); assertEquals(store.getLiveSSTables().size(), sstables.size()); // the sstables start at "0".getBytes() = 48, we need to include that first token, with "/".getBytes() = 47 Range<Token> range = new Range<Token>(new BytesToken("/".getBytes()), new BytesToken("9999".getBytes())); List<Range<Token>> ranges = Arrays.asList(range); UUID parentRepairSession = pendingRepair == null ? UUID.randomUUID() : pendingRepair; registerParentRepairSession(parentRepairSession, ranges, repairedAt, pendingRepair); try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, repairedAt, pendingRepair, parentRepairSession); } assertThat(store.getLiveSSTables().size(), is(1)); assertThat(Iterables.get(store.getLiveSSTables(), 0).isRepaired(), is(repairedAt != UNREPAIRED_SSTABLE)); assertThat(Iterables.get(store.getLiveSSTables(), 0).isPendingRepair(), is(pendingRepair != NO_PENDING_REPAIR)); assertThat(Iterables.get(store.getLiveSSTables(), 0).selfRef().globalCount(), is(1)); assertThat(store.getTracker().getCompacting().size(), is(0)); } @Test public void shouldMutateRepairedAt() throws InterruptedException, IOException { shouldMutate(1, NO_PENDING_REPAIR); } @Test public void shouldMutatePendingRepair() throws InterruptedException, IOException { shouldMutate(UNREPAIRED_SSTABLE, UUIDGen.getTimeUUID()); } @Test public void shouldSkipAntiCompactionForNonIntersectingRange() throws InterruptedException, IOException { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.disableAutoCompaction(); for (int table = 0; table < 10; table++) { generateSStable(store,Integer.toString(table)); } int refCountBefore = Iterables.get(store.getLiveSSTables(), 0).selfRef().globalCount(); Collection<SSTableReader> sstables = getUnrepairedSSTables(store); assertEquals(store.getLiveSSTables().size(), sstables.size()); Range<Token> range = new Range<Token>(new BytesToken("-1".getBytes()), new BytesToken("-10".getBytes())); List<Range<Token>> ranges = Arrays.asList(range); UUID parentRepairSession = UUID.randomUUID(); registerParentRepairSession(parentRepairSession, ranges, UNREPAIRED_SSTABLE, null); boolean gotException = false; try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, 1, NO_PENDING_REPAIR, parentRepairSession); } catch (IllegalStateException e) { gotException = true; } assertTrue(gotException); assertThat(store.getLiveSSTables().size(), is(10)); assertThat(Iterables.get(store.getLiveSSTables(), 0).isRepaired(), is(false)); assertEquals(refCountBefore, Iterables.get(store.getLiveSSTables(), 0).selfRef().globalCount()); } private ColumnFamilyStore prepareColumnFamilyStore() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.disableAutoCompaction(); for (int i = 0; i < 10; i++) { new RowUpdateBuilder(metadata, System.currentTimeMillis(), Integer.toString(i)) .clustering("c") .add("val", "val") .build() .applyUnsafe(); } store.forceBlockingFlush(); return store; } @After public void truncateCfs() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.truncateBlocking(); } private static Set<SSTableReader> getUnrepairedSSTables(ColumnFamilyStore cfs) { return ImmutableSet.copyOf(cfs.getTracker().getView().sstables(SSTableSet.LIVE, (s) -> !s.isRepaired())); } /** * If the parent repair session is missing, we should still clean up */ @Test public void missingParentRepairSession() throws Exception { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF); store.disableAutoCompaction(); for (int table = 0; table < 10; table++) { generateSStable(store,Integer.toString(table)); } Collection<SSTableReader> sstables = getUnrepairedSSTables(store); assertEquals(10, sstables.size()); Range<Token> range = new Range<Token>(new BytesToken("-1".getBytes()), new BytesToken("-10".getBytes())); List<Range<Token>> ranges = Arrays.asList(range); UUID missingRepairSession = UUIDGen.getTimeUUID(); try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION); Refs<SSTableReader> refs = Refs.ref(sstables)) { Assert.assertFalse(refs.isEmpty()); try { CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, 1, missingRepairSession, missingRepairSession); Assert.fail("expected RuntimeException"); } catch (RuntimeException e) { // expected } Assert.assertEquals(Transactional.AbstractTransactional.State.ABORTED, txn.state()); Assert.assertTrue(refs.isEmpty()); } } @Test public void testSSTablesToInclude() { ColumnFamilyStore cfs = MockSchema.newCFS("anticomp"); List<SSTableReader> sstables = new ArrayList<>(); sstables.add(MockSchema.sstable(1, 10, 100, cfs)); sstables.add(MockSchema.sstable(2, 100, 200, cfs)); Range<Token> r = new Range<>(t(10), t(100)); // should include sstable 1 and 2 above, but none is fully contained (Range is (x, y]) Iterator<SSTableReader> sstableIterator = sstables.iterator(); Set<SSTableReader> fullyContainedSSTables = CompactionManager.findSSTablesToAnticompact(sstableIterator, Collections.singletonList(r), UUID.randomUUID()); assertTrue(fullyContainedSSTables.isEmpty()); assertEquals(2, sstables.size()); } @Test public void testSSTablesToInclude2() { ColumnFamilyStore cfs = MockSchema.newCFS("anticomp"); List<SSTableReader> sstables = new ArrayList<>(); SSTableReader sstable1 = MockSchema.sstable(1, 10, 100, cfs); SSTableReader sstable2 = MockSchema.sstable(2, 100, 200, cfs); sstables.add(sstable1); sstables.add(sstable2); Range<Token> r = new Range<>(t(9), t(100)); // sstable 1 is fully contained Iterator<SSTableReader> sstableIterator = sstables.iterator(); Set<SSTableReader> fullyContainedSSTables = CompactionManager.findSSTablesToAnticompact(sstableIterator, Collections.singletonList(r), UUID.randomUUID()); assertEquals(Collections.singleton(sstable1), fullyContainedSSTables); assertEquals(Collections.singletonList(sstable2), sstables); } @Test(expected = IllegalStateException.class) public void testSSTablesToNotInclude() { ColumnFamilyStore cfs = MockSchema.newCFS("anticomp"); List<SSTableReader> sstables = new ArrayList<>(); SSTableReader sstable1 = MockSchema.sstable(1, 0, 5, cfs); sstables.add(sstable1); Range<Token> r = new Range<>(t(9), t(100)); // sstable is not intersecting and should not be included Iterator<SSTableReader> sstableIterator = sstables.iterator(); CompactionManager.findSSTablesToAnticompact(sstableIterator, Collections.singletonList(r), UUID.randomUUID()); } @Test(expected = IllegalStateException.class) public void testSSTablesToNotInclude2() { ColumnFamilyStore cfs = MockSchema.newCFS("anticomp"); List<SSTableReader> sstables = new ArrayList<>(); SSTableReader sstable1 = MockSchema.sstable(1, 10, 10, cfs); SSTableReader sstable2 = MockSchema.sstable(2, 100, 200, cfs); sstables.add(sstable1); sstables.add(sstable2); Range<Token> r = new Range<>(t(10), t(11)); // no sstable included, throw Iterator<SSTableReader> sstableIterator = sstables.iterator(); CompactionManager.findSSTablesToAnticompact(sstableIterator, Collections.singletonList(r), UUID.randomUUID()); } @Test public void testSSTablesToInclude4() { ColumnFamilyStore cfs = MockSchema.newCFS("anticomp"); List<SSTableReader> sstables = new ArrayList<>(); SSTableReader sstable1 = MockSchema.sstable(1, 10, 100, cfs); SSTableReader sstable2 = MockSchema.sstable(2, 100, 200, cfs); sstables.add(sstable1); sstables.add(sstable2); Range<Token> r = new Range<>(t(9), t(200)); // sstable 2 is fully contained - last token is equal Iterator<SSTableReader> sstableIterator = sstables.iterator(); Set<SSTableReader> fullyContainedSSTables = CompactionManager.findSSTablesToAnticompact(sstableIterator, Collections.singletonList(r), UUID.randomUUID()); assertEquals(Sets.newHashSet(sstable1, sstable2), fullyContainedSSTables); assertTrue(sstables.isEmpty()); } private Token t(long t) { return new Murmur3Partitioner.LongToken(t); } }
package org.elasticsearch.mapping; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; import org.elasticsearch.annotation.*; import org.elasticsearch.annotation.query.*; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.mapping.parser.*; import org.elasticsearch.util.MapUtil; import org.springframework.util.ClassUtils; /** * Process fields in a class to fill-in the properties entry in the class definition map. * * @author luc boutier */ public class FieldsMappingBuilder { private static final ESLogger LOGGER = Loggers.getLogger(MappingBuilder.class); /** * Parse fields from the given class to add properties mapping. * * @param clazz The class for which to parse fields. * @param classDefinitionMap The map that contains the class definition (a "properties" entry will be added with field mapping content). * @param facetFields A list that contains all the field facet mapping. * @param filteredFields A list that contains all the field filters mapping. * @param fetchContexts A list that contains all the fetch contexts mapping. * @param pathPrefix A prefix which is a path (null for root object, and matching the field names for nested objects). * @throws IntrospectionException In case we fail to use reflexion on the given class. */ @SuppressWarnings("unchecked") public void parseFieldMappings(Class<?> clazz, Map<String, Object> classDefinitionMap, List<IFacetBuilderHelper> facetFields, List<IFilterBuilderHelper> filteredFields, Map<String, SourceFetchContext> fetchContexts, String pathPrefix) throws IntrospectionException { if (clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class) { parseFieldMappings(clazz.getSuperclass(), classDefinitionMap, facetFields, filteredFields, fetchContexts, pathPrefix); } List<Indexable> indexables = getIndexables(clazz); Map<String, Object> propertiesDefinitionMap = (Map<String, Object>) classDefinitionMap.get("properties"); if (propertiesDefinitionMap == null) { propertiesDefinitionMap = new HashMap<String, Object>(); classDefinitionMap.put("properties", propertiesDefinitionMap); } for (Indexable indexable : indexables) { parseFieldMappings(clazz, classDefinitionMap, facetFields, filteredFields, fetchContexts, propertiesDefinitionMap, pathPrefix, indexable); } } private void parseFieldMappings(Class<?> clazz, Map<String, Object> classDefinitionMap, List<IFacetBuilderHelper> facetFields, List<IFilterBuilderHelper> filteredFields, Map<String, SourceFetchContext> fetchContexts, Map<String, Object> propertiesDefinitionMap, String pathPrefix, Indexable indexable) { String esFieldName = pathPrefix + indexable.getName(); if (pathPrefix == null || pathPrefix.isEmpty()) { // Id, routing and boost are valid only for root object. processIdAnnotation(classDefinitionMap, esFieldName, indexable); processRoutingAnnotation(classDefinitionMap, esFieldName, indexable); processBoostAnnotation(classDefinitionMap, esFieldName, indexable); // Timestamp field annotation processTimeStampAnnotation(classDefinitionMap, esFieldName, indexable); } processFetchContextAnnotation(fetchContexts, esFieldName, indexable); processFilterAnnotation(filteredFields, esFieldName, indexable); processFacetAnnotation(facetFields, filteredFields, esFieldName, indexable); // process the fields if (ClassUtils.isPrimitiveOrWrapper(indexable.getType()) || indexable.getType() == String.class) { processStringOrPrimitive(clazz, propertiesDefinitionMap, pathPrefix, indexable); } else { Class<?> arrayType = indexable.getComponentType(); // mapping of a complex field if (arrayType != null) { // process the array type. if (ClassUtils.isPrimitiveOrWrapper(arrayType) || arrayType == String.class) { processStringOrPrimitive(clazz, propertiesDefinitionMap, pathPrefix, indexable); } else if (arrayType.isEnum()) { // if this is an enum and there is a String StringField annotation = indexable.getAnnotation(StringField.class); if (annotation != null) { processStringOrPrimitive(clazz, propertiesDefinitionMap, pathPrefix, indexable); } } else { processComplexType(clazz, propertiesDefinitionMap, pathPrefix, indexable, filteredFields, facetFields); } } else { // process the type processComplexType(clazz, propertiesDefinitionMap, pathPrefix, indexable, filteredFields, facetFields); } } } @SuppressWarnings("unchecked") private void processIdAnnotation(Map<String, Object> classDefinitionMap, String esFieldName, Indexable indexable) { Id id = indexable.getAnnotation(Id.class); if (id != null) { if (classDefinitionMap.containsKey("_id")) { LOGGER.warn("An Id annotation is defined on field <" + esFieldName + "> of <" + indexable.getDeclaringClassName() + "> but an id has already be defined for <" + ((Map<String, Object>) classDefinitionMap.get("_id")).get("path") + ">"); } else { classDefinitionMap.put("_id", MapUtil.getMap(new String[] { "path", "index", "store" }, new Object[] { esFieldName, id.index(), id.store() })); } } } @SuppressWarnings("unchecked") private void processRoutingAnnotation(Map<String, Object> classDefinitionMap, String esFieldName, Indexable indexable) { Routing routing = indexable.getAnnotation(Routing.class); if (routing != null) { if (classDefinitionMap.containsKey("_routing")) { LOGGER.warn("A Routing annotation is defined on field <" + esFieldName + "> of <" + indexable.getDeclaringClassName() + "> but a routing has already be defined for <" + ((Map<String, Object>) classDefinitionMap.get("_routing")).get("path") + ">"); } else { Map<String, Object> routingDef = new HashMap<String, Object>(); routingDef.put("path", esFieldName); routingDef.put("required", routing.required()); classDefinitionMap.put("_routing", routingDef); } } } @SuppressWarnings("unchecked") private void processBoostAnnotation(Map<String, Object> classDefinitionMap, String esFieldName, Indexable indexable) { Boost boost = indexable.getAnnotation(Boost.class); if (boost != null) { if (classDefinitionMap.containsKey("_boost")) { LOGGER.warn("A Boost annotation is defined on field <" + esFieldName + "> of <" + indexable.getDeclaringClassName() + "> but a boost has already be defined for <" + ((Map<String, Object>) classDefinitionMap.get("_boost")).get("name") + ">"); } else { Map<String, Object> boostDef = new HashMap<String, Object>(); boostDef.put("name", esFieldName); boostDef.put("null_value", boost.nullValue()); classDefinitionMap.put("_boost", boostDef); } } } @SuppressWarnings("unchecked") private void processTimeStampAnnotation(Map<String, Object> classDefinitionMap, String esFieldName, Indexable indexable) { TimeStamp timeStamp = indexable.getAnnotation(TimeStamp.class); if (timeStamp != null) { if (classDefinitionMap.containsKey("_timestamp")) { LOGGER.warn("A TimeStamp annotation is defined on field <" + esFieldName + "> of <" + indexable.getDeclaringClassName() + "> but a boost has already be defined for <" + ((Map<String, Object>) classDefinitionMap.get("_timestamp")).get("name") + ">"); } else { Map<String, Object> timeStampDefinition = new HashMap<String, Object>(); timeStampDefinition.put("enabled", true); timeStampDefinition.put("path", indexable.getName()); if (!timeStamp.format().isEmpty()) { timeStampDefinition.put("format", timeStamp.format()); } classDefinitionMap.put("_timestamp", timeStampDefinition); } } } private void processFetchContextAnnotation(Map<String, SourceFetchContext> fetchContexts, String esFieldName, Indexable indexable) { FetchContext fetchContext = indexable.getAnnotation(FetchContext.class); if (fetchContext == null) { return; } for (int i = 0; i < fetchContext.contexts().length; i++) { String context = fetchContext.contexts()[i]; boolean isInclude = fetchContext.include()[i]; SourceFetchContext sourceFetchContext = fetchContexts.get(context); if (sourceFetchContext == null) { sourceFetchContext = new SourceFetchContext(); fetchContexts.put(context, sourceFetchContext); } if (isInclude) { sourceFetchContext.getIncludes().add(esFieldName); } else { sourceFetchContext.getExcludes().add(esFieldName); } } } private void processFilterAnnotation(List<IFilterBuilderHelper> classFilters, String esFieldName, Indexable indexable) { TermFilter termFilter = indexable.getAnnotation(TermFilter.class); if (termFilter != null) { String[] paths = termFilter.paths(); for (String path : paths) { path = path.trim(); boolean isAnalyzed = isAnalyzed(indexable); String nestedPath = indexable.getAnnotation(NestedObject.class) == null ? null : esFieldName; if (nestedPath == null) { int nestedIndicator = esFieldName.lastIndexOf("."); if (nestedIndicator > 0) { nestedPath = esFieldName.substring(0, nestedIndicator); esFieldName = esFieldName.substring(nestedIndicator + 1, esFieldName.length()); } } String filterPath = getFilterPath(path, esFieldName); classFilters.add(new TermsFilterBuilderHelper(isAnalyzed, nestedPath, filterPath)); } return; } RangeFilter rangeFilter = indexable.getAnnotation(RangeFilter.class); if (rangeFilter != null) { IFilterBuilderHelper facetBuilderHelper = new RangeFilterBuilderHelper(null, esFieldName, rangeFilter); classFilters.add(facetBuilderHelper); } } private void processFacetAnnotation(List<IFacetBuilderHelper> classFacets, List<IFilterBuilderHelper> classFilters, String esFieldName, Indexable indexable) { TermsFacet termsFacet = indexable.getAnnotation(TermsFacet.class); if (termsFacet != null) { String[] paths = termsFacet.paths(); for (String path : paths) { path = path.trim(); boolean isAnalyzed = isAnalyzed(indexable); String nestedPath = indexable.getAnnotation(NestedObject.class) == null ? null : esFieldName; String filterPath = getFilterPath(path, esFieldName); IFacetBuilderHelper facetBuilderHelper = new TermsFacetBuilderHelper(isAnalyzed, nestedPath, filterPath, termsFacet); classFacets.add(facetBuilderHelper); if (classFilters.contains(facetBuilderHelper)) { classFilters.remove(facetBuilderHelper); LOGGER.warn("Field <" + esFieldName + "> already had a filter that will be replaced by the defined facet. Only a single one is allowed."); } classFilters.add(facetBuilderHelper); } return; } RangeFacet rangeFacet = indexable.getAnnotation(RangeFacet.class); if (rangeFacet != null) { IFacetBuilderHelper facetBuilderHelper = new RangeFacetBuilderHelper(null, esFieldName, rangeFacet); classFacets.add(facetBuilderHelper); if (classFilters.contains(facetBuilderHelper)) { classFilters.remove(facetBuilderHelper); LOGGER.warn("Field <" + esFieldName + "> already had a filter that will be replaced by the defined facet. Only a single one is allowed."); } classFilters.add(facetBuilderHelper); } } private String getFilterPath(String path, String esFieldName) { return path.isEmpty() ? esFieldName : esFieldName + "." + path; } private boolean isAnalyzed(Indexable indexable) { boolean isAnalysed = true; StringField stringFieldAnnotation = indexable.getAnnotation(StringField.class); if (stringFieldAnnotation != null && !IndexType.analyzed.equals(stringFieldAnnotation.indexType())) { isAnalysed = false; } return isAnalysed; } private void processStringOrPrimitive(Class<?> clazz, Map<String, Object> propertiesDefinitionMap, String pathPrefix, Indexable indexable) { processFieldAnnotation(IndexName.class, new IndexNameAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); processFieldAnnotation(NullValue.class, new NullValueAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); // String field annotations. processFieldAnnotation(StringField.class, new StringFieldAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); processFieldAnnotation(Analyser.class, new AnalyserAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); processFieldAnnotation(IndexAnalyser.class, new IndexAnalyserAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); processFieldAnnotation(SearchAnalyser.class, new SearchAnalyserAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); // Numeric field annotation processFieldAnnotation(NumberField.class, new NumberFieldAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); // Date field annotation processFieldAnnotation(DateField.class, new DateFieldAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); processFieldAnnotation(DateFormat.class, new DateFormatAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); // Boolean field annotation processFieldAnnotation(BooleanField.class, new BooleanFieldAnnotationParser(), propertiesDefinitionMap, pathPrefix, indexable); // TODO binary type mapping } private void processComplexType(Class<?> clazz, Map<String, Object> propertiesDefinitionMap, String pathPrefix, Indexable indexable, List<IFilterBuilderHelper> filters, List<IFacetBuilderHelper> facets) { NestedObjectFieldAnnotationParser parser = new NestedObjectFieldAnnotationParser(this, filters, facets); processFieldAnnotation(NestedObject.class, parser, propertiesDefinitionMap, pathPrefix, indexable); } @SuppressWarnings("unchecked") private <T extends Annotation> void processFieldAnnotation(Class<T> annotationClass, IPropertyAnnotationParser<T> propertyAnnotationParser, Map<String, Object> propertiesDefinitionMap, String pathPrefix, Indexable indexable) { T annotation = indexable.getAnnotation(annotationClass); if (annotation != null) { Map<String, Object> fieldDefinition = (Map<String, Object>) propertiesDefinitionMap.get(indexable.getName()); if (fieldDefinition == null) { fieldDefinition = new HashMap<String, Object>(); propertiesDefinitionMap.put(indexable.getName(), fieldDefinition); } propertyAnnotationParser.parseAnnotation(annotation, fieldDefinition, pathPrefix, indexable); } } /** * Get all indexable member of a class (field or property) * * @param clazz class to check * @return list of all indexable members * @throws IntrospectionException */ private List<Indexable> getIndexables(Class<?> clazz) throws IntrospectionException { List<Indexable> indexables = new ArrayList<Indexable>(); Map<String, PropertyDescriptor> pdMap = getValidPropertyDescriptorMap(clazz); Map<String, Field> fdMap = new HashMap<String, Field>(); Field[] fdArr = clazz.getDeclaredFields(); for (Field field : fdArr) { // Check not transient field if (Modifier.isTransient(field.getModifiers())) { continue; } String pdName = field.getName(); if (field.getType().equals(Boolean.TYPE) && field.getName().startsWith("is")) { pdName = field.getName().substring(2, 3).toLowerCase() + field.getName().substring(3, field.getName().length()); } PropertyDescriptor propertyDescriptor = pdMap.get(pdName); if (propertyDescriptor == null || propertyDescriptor.getReadMethod() == null || propertyDescriptor.getWriteMethod() == null) { LOGGER.debug("Field <" + field.getName() + "> of class <" + clazz.getName() + "> has no proper setter/getter and won't be persisted."); } else { fdMap.put(pdName, field); } } Set<String> allIndexablesName = new HashSet<String>(); allIndexablesName.addAll(pdMap.keySet()); allIndexablesName.addAll(fdMap.keySet()); for (String name : allIndexablesName) { indexables.add(new Indexable(fdMap.get(name), pdMap.get(name))); } return indexables; } private Map<String, PropertyDescriptor> getValidPropertyDescriptorMap(Class<?> clazz) throws IntrospectionException { Map<String, PropertyDescriptor> pdMap = new HashMap<String, PropertyDescriptor>(); PropertyDescriptor[] pdArr = Introspector.getBeanInfo(clazz, clazz.getSuperclass()).getPropertyDescriptors(); if (pdArr == null) { return pdMap; } for (PropertyDescriptor pd : pdArr) { // Check valid getter setter if (pd.getReadMethod() != null && pd.getWriteMethod() != null) { pdMap.put(pd.getName(), pd); } } return pdMap; } }
/** * Copyright (c) 2014-2015 by Coffeine Inc * * @author Vitaliy Tsutsman <vitaliyacm@gmail.com> * * @date 12/7/15 10:23 PM */ package com.thecoffeine.virtuoso.music.model.entity; import com.thecoffeine.virtuoso.module.model.AbstractModel; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import org.junit.Test; import java.util.ArrayList; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.constraints.NotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Tests for VideoType * @see VideoType * * @version 1.0 */ public class VideoTypeTest extends AbstractModel { /** * Test field validation for entity filled correct */ @Test public void testVideoTypeFieldsSuccess() { Set< ConstraintViolation< VideoType > > constraintViolationSet; //- Success -// //- Create entity -// VideoType videoTypeSuccess = new VideoType( "POLKA", "Polka", "Ukrainian polka" ); //- Validate -// constraintViolationSet = validator.validate( videoTypeSuccess ); assertEquals( 0, constraintViolationSet.size() ); } /** * Test field validation for entity filled incorrect */ @Test public void testVideoTypeFieldsFailure() { Set< ConstraintViolation< VideoType > > constraintViolationSet; //- Failure -// //- Create entity -// VideoType videoTypeFailure = new VideoType( null, null, "Ukrainian polka" ); //- Validate -// constraintViolationSet = validator.validate( videoTypeFailure ); assertEquals( 4, constraintViolationSet.size() ); for ( ConstraintViolation< VideoType > constraintViolation : constraintViolationSet ) { //- Property name -// assertTrue( new ArrayList< String >() {{ add( "code" ); add( "title" ); }}.contains( this.getPropertyName( constraintViolation.getPropertyPath() ) ) ); //- Annotation type -// assertTrue( new ArrayList< Class >() {{ add( NotNull.class ); add( NotEmpty.class ); }}.contains( constraintViolation.getConstraintDescriptor().getAnnotation().annotationType() ) ); //- Message -// assertTrue( new ArrayList< String >() {{ add( "may not be null" ); add( "may not be empty" ); }}.contains( constraintViolation.getMessage() ) ); } } /** * Test of length constraints */ @Test public void testLengthConstraint() { Set< ConstraintViolation< VideoType > > constraintViolationSet; //- Failure: Incorrect length -// //- Create entity -// VideoType videoTypeFailureLength = new VideoType( "12345678901234567", "123456789012345678901234567890123" ); //- Validate -// constraintViolationSet = validator.validate( videoTypeFailureLength ); assertEquals( 2, constraintViolationSet.size() ); for ( ConstraintViolation< VideoType > constraintViolation : constraintViolationSet ) { //- Property name -// assertTrue( new ArrayList< String >() {{ add( "code" ); add( "title" ); }}.contains( this.getPropertyName( constraintViolation.getPropertyPath() ) ) ); //- Annotation type -// assertTrue( new ArrayList< Class >() {{ add( Length.class ); }}.contains( constraintViolation.getConstraintDescriptor().getAnnotation().annotationType() ) ); //- Message -// assertTrue( new ArrayList< String >() {{ add( "length must be between 0 and 16" ); add( "length must be between 0 and 32" ); }}.contains( constraintViolation.getMessage() ) ); } } /* * Test field validation for entity failure( empty ) */ @Test public void testAccessFieldEmpty() { Set< ConstraintViolation< VideoType > > constraintViolationSet; //- Failure: fields is empty-// //- Create entity -// VideoType videoTypeFailureEmpty = new VideoType( "", "" ); //- Validate -// constraintViolationSet = validator.validate( videoTypeFailureEmpty ); assertEquals( 2, constraintViolationSet.size() ); for ( ConstraintViolation< VideoType > constraintViolation : constraintViolationSet ) { //- Property name -// assertTrue( new ArrayList< String >() {{ add( "code" ); add( "title" ); }}.contains( this.getPropertyName( constraintViolation.getPropertyPath() ) ) ); //- Annotation type -// assertTrue( new ArrayList< Class >() {{ add( NotEmpty.class ); }}.contains( constraintViolation.getConstraintDescriptor().getAnnotation().annotationType() ) ); //- Message -// assertTrue( new ArrayList< String >() {{ add( "may not be empty" ); }}.contains( constraintViolation.getMessage() ) ); } } }
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2021 the original authors 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 io.sarl.eclipse.log; import java.net.URL; import java.text.MessageFormat; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.debug.internal.ui.SWTFactory; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.wizard.IWizard; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.jface.wizard.WizardPage; 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.Link; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.xtext.util.Strings; import org.osgi.service.prefs.BackingStoreException; import io.sarl.eclipse.SARLEclipsePlugin; /** * Page for entering information on an issue to submit to the SARL tracker. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 0.5 */ public class IssueInformationPage extends WizardPage { /** Preference key that stores the Github login. */ public static final String PREFERENCE_LOGIN = IssueInformationPage.class.getName() + ".githubLogin"; //$NON-NLS-1$ private static final char ECHO_CHAR = '*'; private final URL link; private Text titleField; private Text descriptionField; private Text trackerLogin; private Text trackerPassword; /** Constructor. * * @param link the link to put in the page. */ protected IssueInformationPage(URL link) { super(Messages.IssueInformationPage_0); this.link = link; setTitle(Messages.SubmitEclipseLogWizard_0); } @Override public void createControl(Composite parent) { // create a composite with standard margins and spacing final Composite composite = new Composite(parent, SWT.NONE); final GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); if (this.link != null) { final Link linkWidget = new Link(composite, SWT.BORDER); linkWidget.setText(MessageFormat.format(Messages.IssueInformationPage_9, this.link.toString())); linkWidget.setFont(composite.getFont()); final GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; linkWidget.setLayoutData(gd); linkWidget.addSelectionListener(new SelectionAdapter() { @SuppressWarnings("synthetic-access") @Override public void widgetSelected(SelectionEvent event) { try { final IWebBrowser browser = PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser(); browser.openURL(IssueInformationPage.this.link); final IWizard wizard = IssueInformationPage.this.getWizard(); if (wizard instanceof SubmitEclipseLogWizard) { final WizardDialog dialog = ((SubmitEclipseLogWizard) wizard).getWizardDialog(); if (dialog != null) { dialog.close(); } } } catch (PartInitException e) { // } } }); } SWTFactory.createLabel(composite, Messages.IssueInformationPage_1, 1); this.titleField = SWTFactory.createSingleText(composite, 1); SWTFactory.createLabel(composite, Messages.IssueInformationPage_2, 1); this.descriptionField = SWTFactory.createText(composite, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL, 1); this.descriptionField.setLayoutData(new GridData(GridData.FILL_BOTH)); SWTFactory.createLabel(composite, Messages.IssueInformationPage_3, 1); this.trackerLogin = SWTFactory.createSingleText(composite, 1); SWTFactory.createLabel(composite, Messages.IssueInformationPage_4, 1); this.trackerPassword = SWTFactory.createSingleText(composite, 1); this.trackerPassword.setEchoChar(ECHO_CHAR); //add the listeners now to prevent them from monkeying with initialized settings this.titleField.addModifyListener(listeningEvent -> { updatePageStatus(); }); this.descriptionField.addModifyListener(listeningEvent -> { updatePageStatus(); }); this.trackerLogin.addModifyListener(listeningEvent -> { updatePageStatus(); }); this.trackerPassword.addModifyListener(listeningEvent -> { updatePageStatus(); }); Dialog.applyDialogFont(composite); setControl(composite); initFields(); updatePageStatus(); } /** Replies the title of the issue. * * @return the title. */ public String getIssueTitle() { return this.titleField.getText(); } /** Replies the description of the issue. * * @return the description. */ public String getIssueDescription() { return this.descriptionField.getText(); } /** Replies the Github login. * * @return the login. */ public String getGithubLogin() { return this.trackerLogin.getText(); } /** Replies the Github password. * * @return the password. */ public String getGithubPassword() { return this.trackerPassword.getText(); } /** Set the initial values to the fields. */ protected void initFields() { final IEclipsePreferences prefs = SARLEclipsePlugin.getDefault().getPreferences(); this.trackerLogin.setText(prefs.get(PREFERENCE_LOGIN, "")); //$NON-NLS-1$ } /** Update the page status and change the "finish" state button. */ protected void updatePageStatus() { final boolean ok; if (Strings.isEmpty(this.titleField.getText())) { ok = false; setMessage(Messages.IssueInformationPage_5, IMessageProvider.ERROR); } else if (Strings.isEmpty(this.trackerLogin.getText())) { ok = false; setMessage(Messages.IssueInformationPage_6, IMessageProvider.ERROR); } else if (Strings.isEmpty(this.trackerPassword.getText())) { ok = false; setMessage(Messages.IssueInformationPage_7, IMessageProvider.ERROR); } else { ok = true; if (Strings.isEmpty(this.descriptionField.getText())) { setMessage(Messages.IssueInformationPage_8, IMessageProvider.WARNING); } else { setMessage(null, IMessageProvider.NONE); } } setPageComplete(ok); } /** Invoked when the wizard is closed with the "Finish" button. * * @return {@code true} for closing the wizard; {@code false} for keeping it open. */ public boolean performFinish() { final IEclipsePreferences prefs = SARLEclipsePlugin.getDefault().getPreferences(); final String login = this.trackerLogin.getText(); if (Strings.isEmpty(login)) { prefs.remove(PREFERENCE_LOGIN); } else { prefs.put(PREFERENCE_LOGIN, login); } try { prefs.sync(); return true; } catch (BackingStoreException e) { ErrorDialog.openError(getShell(), e.getLocalizedMessage(), e.getLocalizedMessage(), SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, e)); return false; } } }
//$Id: CMTTest.java 10421 2006-09-01 20:52:35Z steve.ebersole@jboss.com $ package org.hibernate.test.tm; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Iterator; import javax.transaction.Transaction; import junit.framework.Test; import junit.framework.TestSuite; import org.hibernate.EntityMode; import org.hibernate.Session; import org.hibernate.ScrollableResults; import org.hibernate.ConnectionReleaseMode; import org.hibernate.dialect.SybaseDialect; import org.hibernate.transaction.CMTTransactionFactory; import org.hibernate.util.SerializationHelper; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.criterion.Order; import org.hibernate.test.TestCase; /** * @author Gavin King */ public class CMTTest extends TestCase { public CMTTest(String str) { super(str); } public void testConcurrent() throws Exception { getSessions().getStatistics().clear(); DummyTransactionManager.INSTANCE.begin(); Session s = openSession(); Map foo = new HashMap(); foo.put("name", "Foo"); foo.put("description", "a big foo"); s.persist("Item", foo); Map bar = new HashMap(); bar.put("name", "Bar"); bar.put("description", "a small bar"); s.persist("Item", bar); DummyTransactionManager.INSTANCE.commit(); getSessions().evictEntity("Item"); DummyTransactionManager.INSTANCE.begin(); Session s1 = openSession(); foo = (Map) s1.get("Item", "Foo"); //foo.put("description", "a big red foo"); //s1.flush(); Transaction tx1 = DummyTransactionManager.INSTANCE.suspend(); DummyTransactionManager.INSTANCE.begin(); Session s2 = openSession(); foo = (Map) s2.get("Item", "Foo"); DummyTransactionManager.INSTANCE.commit(); DummyTransactionManager.INSTANCE.resume(tx1); tx1.commit(); getSessions().evictEntity("Item"); DummyTransactionManager.INSTANCE.begin(); s1 = openSession(); s1.createCriteria("Item").list(); //foo.put("description", "a big red foo"); //s1.flush(); tx1 = DummyTransactionManager.INSTANCE.suspend(); DummyTransactionManager.INSTANCE.begin(); s2 = openSession(); s2.createCriteria("Item").list(); DummyTransactionManager.INSTANCE.commit(); DummyTransactionManager.INSTANCE.resume(tx1); tx1.commit(); DummyTransactionManager.INSTANCE.begin(); s2 = openSession(); s2.createCriteria("Item").list(); DummyTransactionManager.INSTANCE.commit(); assertEquals( getSessions().getStatistics().getEntityLoadCount(), 7 ); assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 3 ); assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 0 ); DummyTransactionManager.INSTANCE.begin(); s = openSession(); s.createQuery("delete from Item").executeUpdate(); DummyTransactionManager.INSTANCE.commit(); } public void testConcurrentCachedQueries() throws Exception { DummyTransactionManager.INSTANCE.begin(); Session s = openSession(); Map foo = new HashMap(); foo.put("name", "Foo"); foo.put("description", "a big foo"); s.persist("Item", foo); Map bar = new HashMap(); bar.put("name", "Bar"); bar.put("description", "a small bar"); s.persist("Item", bar); DummyTransactionManager.INSTANCE.commit(); synchronized (this) { wait(1000); } getSessions().getStatistics().clear(); getSessions().evictEntity("Item"); DummyTransactionManager.INSTANCE.begin(); Session s4 = openSession(); Transaction tx4 = DummyTransactionManager.INSTANCE.suspend(); DummyTransactionManager.INSTANCE.begin(); Session s1 = openSession(); List r1 = s1.createCriteria("Item").addOrder( Order.asc("description") ) .setCacheable(true).list(); assertEquals( r1.size(), 2 ); Transaction tx1 = DummyTransactionManager.INSTANCE.suspend(); DummyTransactionManager.INSTANCE.begin(); Session s2 = openSession(); List r2 = s2.createCriteria("Item").addOrder( Order.asc("description") ) .setCacheable(true).list(); assertEquals( r2.size(), 2 ); DummyTransactionManager.INSTANCE.commit(); assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 2 ); assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 ); assertEquals( getSessions().getStatistics().getEntityLoadCount(), 2 ); assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 ); assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 1 ); assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 1 ); assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 1 ); DummyTransactionManager.INSTANCE.resume(tx1); tx1.commit(); DummyTransactionManager.INSTANCE.begin(); Session s3 = openSession(); s3.createCriteria("Item").addOrder( Order.asc("description") ) .setCacheable(true).list(); DummyTransactionManager.INSTANCE.commit(); assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 4 ); assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 ); assertEquals( getSessions().getStatistics().getEntityLoadCount(), 2 ); assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 ); assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 1 ); assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 2 ); assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 1 ); DummyTransactionManager.INSTANCE.resume(tx4); List r4 = s4.createCriteria("Item").addOrder( Order.asc("description") ) .setCacheable(true).list(); assertEquals( r4.size(), 2 ); tx4.commit(); assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 6 ); assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 ); assertEquals( getSessions().getStatistics().getEntityLoadCount(), 2 ); assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 ); assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 1 ); assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 3 ); assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 1 ); DummyTransactionManager.INSTANCE.begin(); s = openSession(); s.createQuery("delete from Item").executeUpdate(); DummyTransactionManager.INSTANCE.commit(); } public void testConcurrentCachedDirtyQueries() throws Exception { if ( getDialect() instanceof SybaseDialect ) { reportSkip( "dead-lock bug", "concurrent queries" ); return; } DummyTransactionManager.INSTANCE.begin(); Session s = openSession(); Map foo = new HashMap(); foo.put("name", "Foo"); foo.put("description", "a big foo"); s.persist("Item", foo); Map bar = new HashMap(); bar.put("name", "Bar"); bar.put("description", "a small bar"); s.persist("Item", bar); DummyTransactionManager.INSTANCE.commit(); synchronized (this) { wait(1000); } getSessions().getStatistics().clear(); getSessions().evictEntity("Item"); DummyTransactionManager.INSTANCE.begin(); Session s4 = openSession(); Transaction tx4 = DummyTransactionManager.INSTANCE.suspend(); DummyTransactionManager.INSTANCE.begin(); Session s1 = openSession(); List r1 = s1.createCriteria("Item").addOrder( Order.asc("description") ) .setCacheable(true).list(); assertEquals( r1.size(), 2 ); foo = (Map) r1.get(0); foo.put("description", "a big red foo"); s1.flush(); Transaction tx1 = DummyTransactionManager.INSTANCE.suspend(); DummyTransactionManager.INSTANCE.begin(); Session s2 = openSession(); List r2 = s2.createCriteria("Item").addOrder( Order.asc("description") ) .setCacheable(true).list(); assertEquals( r2.size(), 2 ); DummyTransactionManager.INSTANCE.commit(); assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 0 ); assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 ); assertEquals( getSessions().getStatistics().getEntityLoadCount(), 4 ); assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 2 ); assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 2 ); assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 2 ); DummyTransactionManager.INSTANCE.resume(tx1); tx1.commit(); DummyTransactionManager.INSTANCE.begin(); Session s3 = openSession(); s3.createCriteria("Item").addOrder( Order.asc("description") ) .setCacheable(true).list(); DummyTransactionManager.INSTANCE.commit(); assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 0 ); assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 ); assertEquals( getSessions().getStatistics().getEntityLoadCount(), 6 ); assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 3 ); assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 3 ); assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 3 ); DummyTransactionManager.INSTANCE.resume(tx4); List r4 = s4.createCriteria("Item").addOrder( Order.asc("description") ) .setCacheable(true).list(); assertEquals( r4.size(), 2 ); tx4.commit(); assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 2 ); assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 ); assertEquals( getSessions().getStatistics().getEntityLoadCount(), 6 ); assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 ); assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 3 ); assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 3 ); assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 1 ); assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 3 ); DummyTransactionManager.INSTANCE.begin(); s = openSession(); s.createQuery("delete from Item").executeUpdate(); DummyTransactionManager.INSTANCE.commit(); } public void testCMT() throws Exception { getSessions().getStatistics().clear(); DummyTransactionManager.INSTANCE.begin(); Session s = openSession(); DummyTransactionManager.INSTANCE.getTransaction().commit(); assertFalse( s.isOpen() ); assertEquals( getSessions().getStatistics().getFlushCount(), 0 ); DummyTransactionManager.INSTANCE.begin(); s = openSession(); DummyTransactionManager.INSTANCE.getTransaction().rollback(); assertFalse( s.isOpen() ); DummyTransactionManager.INSTANCE.begin(); s = openSession(); Map item = new HashMap(); item.put("name", "The Item"); item.put("description", "The only item we have"); s.persist("Item", item); DummyTransactionManager.INSTANCE.getTransaction().commit(); assertFalse( s.isOpen() ); DummyTransactionManager.INSTANCE.begin(); s = openSession(); item = (Map) s.createQuery("from Item").uniqueResult(); assertNotNull(item); s.delete(item); DummyTransactionManager.INSTANCE.getTransaction().commit(); assertFalse( s.isOpen() ); assertEquals( getSessions().getStatistics().getTransactionCount(), 4 ); assertEquals( getSessions().getStatistics().getSuccessfulTransactionCount(), 3 ); assertEquals( getSessions().getStatistics().getEntityDeleteCount(), 1 ); assertEquals( getSessions().getStatistics().getEntityInsertCount(), 1 ); assertEquals( getSessions().getStatistics().getSessionOpenCount(), 4 ); assertEquals( getSessions().getStatistics().getSessionCloseCount(), 4 ); assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 ); assertEquals( getSessions().getStatistics().getFlushCount(), 2 ); DummyTransactionManager.INSTANCE.begin(); s = openSession(); s.createQuery("delete from Item").executeUpdate(); DummyTransactionManager.INSTANCE.commit(); } public void testCurrentSession() throws Exception { DummyTransactionManager.INSTANCE.begin(); Session s = getSessions().getCurrentSession(); Session s2 = getSessions().getCurrentSession(); assertSame( s, s2 ); DummyTransactionManager.INSTANCE.getTransaction().commit(); assertFalse( s.isOpen() ); // TODO : would be nice to automate-test that the SF internal map actually gets cleaned up // i verified that is does currently in my debugger... } public void testCurrentSessionWithIterate() throws Exception { DummyTransactionManager.INSTANCE.begin(); Session s = openSession(); Map item1 = new HashMap(); item1.put( "name", "Item - 1" ); item1.put( "description", "The first item" ); s.persist( "Item", item1 ); Map item2 = new HashMap(); item2.put( "name", "Item - 2" ); item2.put( "description", "The second item" ); s.persist( "Item", item2 ); DummyTransactionManager.INSTANCE.getTransaction().commit(); // First, test iterating the partial iterator; iterate to past // the first, but not the second, item DummyTransactionManager.INSTANCE.begin(); s = getSessions().getCurrentSession(); Iterator itr = s.createQuery( "from Item" ).iterate(); if ( !itr.hasNext() ) { fail( "No results in iterator" ); } itr.next(); if ( !itr.hasNext() ) { fail( "Only one result in iterator" ); } DummyTransactionManager.INSTANCE.getTransaction().commit(); // Next, iterate the entire result DummyTransactionManager.INSTANCE.begin(); s = getSessions().getCurrentSession(); itr = s.createQuery( "from Item" ).iterate(); if ( !itr.hasNext() ) { fail( "No results in iterator" ); } while ( itr.hasNext() ) { itr.next(); } DummyTransactionManager.INSTANCE.getTransaction().commit(); DummyTransactionManager.INSTANCE.begin(); s = openSession(); s.createQuery( "delete from Item" ).executeUpdate(); DummyTransactionManager.INSTANCE.getTransaction().commit(); } public void testCurrentSessionWithScroll() throws Exception { DummyTransactionManager.INSTANCE.begin(); Session s = getSessions().getCurrentSession(); Map item1 = new HashMap(); item1.put( "name", "Item - 1" ); item1.put( "description", "The first item" ); s.persist( "Item", item1 ); Map item2 = new HashMap(); item2.put( "name", "Item - 2" ); item2.put( "description", "The second item" ); s.persist( "Item", item2 ); DummyTransactionManager.INSTANCE.getTransaction().commit(); // First, test partially scrolling the result with out closing DummyTransactionManager.INSTANCE.begin(); s = getSessions().getCurrentSession(); ScrollableResults results = s.createQuery( "from Item" ).scroll(); results.next(); DummyTransactionManager.INSTANCE.getTransaction().commit(); // Next, test partially scrolling the result with closing DummyTransactionManager.INSTANCE.begin(); s = getSessions().getCurrentSession(); results = s.createQuery( "from Item" ).scroll(); results.next(); results.close(); DummyTransactionManager.INSTANCE.getTransaction().commit(); // Next, scroll the entire result (w/o closing) DummyTransactionManager.INSTANCE.begin(); s = getSessions().getCurrentSession(); results = s.createQuery( "from Item" ).scroll(); while( !results.isLast() ) { results.next(); } DummyTransactionManager.INSTANCE.getTransaction().commit(); // Next, scroll the entire result (closing) DummyTransactionManager.INSTANCE.begin(); s = getSessions().getCurrentSession(); results = s.createQuery( "from Item" ).scroll(); while( !results.isLast() ) { results.next(); } results.close(); DummyTransactionManager.INSTANCE.getTransaction().commit(); DummyTransactionManager.INSTANCE.begin(); s = getSessions().getCurrentSession(); s.createQuery( "delete from Item" ).executeUpdate(); DummyTransactionManager.INSTANCE.getTransaction().commit(); } public void testAggressiveReleaseWithExplicitDisconnectReconnect() throws Exception { DummyTransactionManager.INSTANCE.begin(); Session s = getSessions().getCurrentSession(); s.createQuery( "from Item" ).list(); s.disconnect(); byte[] bytes = SerializationHelper.serialize( s ); s = ( Session ) SerializationHelper.deserialize( bytes ); s.reconnect(); s.createQuery( "from Item" ).list(); DummyTransactionManager.INSTANCE.getTransaction().commit(); } public void testAggressiveReleaseWithConnectionRetreival() throws Exception { DummyTransactionManager.INSTANCE.begin(); Session s = openSession(); Map item1 = new HashMap(); item1.put( "name", "Item - 1" ); item1.put( "description", "The first item" ); s.save( "Item", item1 ); Map item2 = new HashMap(); item2.put( "name", "Item - 2" ); item2.put( "description", "The second item" ); s.save( "Item", item2 ); DummyTransactionManager.INSTANCE.getTransaction().commit(); try { DummyTransactionManager.INSTANCE.begin(); s = getSessions().getCurrentSession(); s.createQuery( "from Item" ).scroll().next(); s.connection(); DummyTransactionManager.INSTANCE.getTransaction().commit(); } finally { DummyTransactionManager.INSTANCE.begin(); s = openSession(); s.createQuery( "delete from Item" ).executeUpdate(); DummyTransactionManager.INSTANCE.getTransaction().commit(); } } protected String[] getMappings() { return new String[] { "tm/Item.hbm.xml" }; } public String getCacheConcurrencyStrategy() { return "transactional"; } public static Test suite() { return new TestSuite(CMTTest.class); } protected void configure(Configuration cfg) { cfg.setProperty( Environment.CONNECTION_PROVIDER, DummyConnectionProvider.class.getName() ); cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, DummyTransactionManagerLookup.class.getName() ); cfg.setProperty( Environment.TRANSACTION_STRATEGY, CMTTransactionFactory.class.getName() ); cfg.setProperty( Environment.AUTO_CLOSE_SESSION, "true" ); cfg.setProperty( Environment.FLUSH_BEFORE_COMPLETION, "true" ); cfg.setProperty( Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.AFTER_STATEMENT.toString() ); cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); cfg.setProperty( Environment.USE_QUERY_CACHE, "true" ); cfg.setProperty( Environment.DEFAULT_ENTITY_MODE, EntityMode.MAP.toString() ); } }
/* * Copyright 2015 The Netty Project * * The Netty Project 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 io.netty.handler.codec.http; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.compression.ZlibCodecFactory; import io.netty.handler.codec.compression.ZlibDecoder; import io.netty.handler.codec.compression.ZlibEncoder; import io.netty.handler.codec.compression.ZlibWrapper; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Queue; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class HttpContentDecoderTest { private static final String HELLO_WORLD = "hello, world"; private static final byte[] GZ_HELLO_WORLD = { 31, -117, 8, 8, 12, 3, -74, 84, 0, 3, 50, 0, -53, 72, -51, -55, -55, -41, 81, 40, -49, 47, -54, 73, 1, 0, 58, 114, -85, -1, 12, 0, 0, 0 }; @Test public void testBinaryDecompression() throws Exception { // baseline test: zlib library and test helpers work correctly. byte[] helloWorld = gzDecompress(GZ_HELLO_WORLD); assertEquals(HELLO_WORLD.length(), helloWorld.length); assertEquals(HELLO_WORLD, new String(helloWorld, CharsetUtil.US_ASCII)); String fullCycleTest = "full cycle test"; byte[] compressed = gzCompress(fullCycleTest.getBytes(CharsetUtil.US_ASCII)); byte[] decompressed = gzDecompress(compressed); assertEquals(decompressed.length, fullCycleTest.length()); assertEquals(fullCycleTest, new String(decompressed, CharsetUtil.US_ASCII)); } @Test public void testRequestDecompression() { // baseline test: request decoder, content decompressor && request aggregator work as expected HttpRequestDecoder decoder = new HttpRequestDecoder(); HttpContentDecoder decompressor = new HttpContentDecompressor(); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor, aggregator); String headers = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; ByteBuf buf = Unpooled.copiedBuffer(headers.getBytes(CharsetUtil.US_ASCII), GZ_HELLO_WORLD); assertTrue(channel.writeInbound(buf)); Object o = channel.readInbound(); assertThat(o, is(instanceOf(FullHttpRequest.class))); FullHttpRequest req = (FullHttpRequest) o; assertEquals(HELLO_WORLD.length(), req.headers().getInt(HttpHeaderNames.CONTENT_LENGTH).intValue()); assertEquals(HELLO_WORLD, req.content().toString(CharsetUtil.US_ASCII)); req.release(); assertHasInboundMessages(channel, false); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); // assert that no messages are left in channel } @Test public void testResponseDecompression() { // baseline test: response decoder, content decompressor && request aggregator work as expected HttpResponseDecoder decoder = new HttpResponseDecoder(); HttpContentDecoder decompressor = new HttpContentDecompressor(); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor, aggregator); String headers = "HTTP/1.1 200 OK\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; ByteBuf buf = Unpooled.copiedBuffer(headers.getBytes(CharsetUtil.US_ASCII), GZ_HELLO_WORLD); assertTrue(channel.writeInbound(buf)); Object o = channel.readInbound(); assertThat(o, is(instanceOf(FullHttpResponse.class))); FullHttpResponse resp = (FullHttpResponse) o; assertEquals(HELLO_WORLD.length(), resp.headers().getInt(HttpHeaderNames.CONTENT_LENGTH).intValue()); assertEquals(HELLO_WORLD, resp.content().toString(CharsetUtil.US_ASCII)); resp.release(); assertHasInboundMessages(channel, false); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); // assert that no messages are left in channel } @Test public void testExpectContinueResponse1() { // request with header "Expect: 100-continue" must be replied with one "100 Continue" response // case 1: no ContentDecoder in chain at all (baseline test) HttpRequestDecoder decoder = new HttpRequestDecoder(); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); EmbeddedChannel channel = new EmbeddedChannel(decoder, aggregator); String req = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Expect: 100-continue\r\n" + "\r\n"; // note: the following writeInbound() returns false as there is no message is inbound buffer // until HttpObjectAggregator caches composes a complete message. // however, http response "100 continue" must be sent as soon as headers are received assertFalse(channel.writeInbound(Unpooled.wrappedBuffer(req.getBytes()))); Object o = channel.readOutbound(); assertThat(o, is(instanceOf(FullHttpResponse.class))); FullHttpResponse r = (FullHttpResponse) o; assertEquals(100, r.status().code()); assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(GZ_HELLO_WORLD))); r.release(); assertHasInboundMessages(channel, true); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } @Test public void testExpectContinueResponse2() { // request with header "Expect: 100-continue" must be replied with one "100 Continue" response // case 2: contentDecoder is in chain, but the content is not encoded, should be no-op HttpRequestDecoder decoder = new HttpRequestDecoder(); HttpContentDecoder decompressor = new HttpContentDecompressor(); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor, aggregator); String req = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Expect: 100-continue\r\n" + "\r\n"; assertFalse(channel.writeInbound(Unpooled.wrappedBuffer(req.getBytes()))); Object o = channel.readOutbound(); assertThat(o, is(instanceOf(FullHttpResponse.class))); FullHttpResponse r = (FullHttpResponse) o; assertEquals(100, r.status().code()); r.release(); assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(GZ_HELLO_WORLD))); assertHasInboundMessages(channel, true); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } @Test public void testExpectContinueResponse3() { // request with header "Expect: 100-continue" must be replied with one "100 Continue" response // case 3: ContentDecoder is in chain and content is encoded HttpRequestDecoder decoder = new HttpRequestDecoder(); HttpContentDecoder decompressor = new HttpContentDecompressor(); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor, aggregator); String req = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Expect: 100-continue\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; assertFalse(channel.writeInbound(Unpooled.wrappedBuffer(req.getBytes()))); Object o = channel.readOutbound(); assertThat(o, is(instanceOf(FullHttpResponse.class))); FullHttpResponse r = (FullHttpResponse) o; assertEquals(100, r.status().code()); r.release(); assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(GZ_HELLO_WORLD))); assertHasInboundMessages(channel, true); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } @Test public void testExpectContinueResponse4() { // request with header "Expect: 100-continue" must be replied with one "100 Continue" response // case 4: ObjectAggregator is up in chain HttpRequestDecoder decoder = new HttpRequestDecoder(); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); HttpContentDecoder decompressor = new HttpContentDecompressor(); EmbeddedChannel channel = new EmbeddedChannel(decoder, aggregator, decompressor); String req = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Expect: 100-continue\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; assertFalse(channel.writeInbound(Unpooled.wrappedBuffer(req.getBytes()))); Object o = channel.readOutbound(); assertThat(o, is(instanceOf(FullHttpResponse.class))); FullHttpResponse r = (FullHttpResponse) o; assertEquals(100, r.status().code()); r.release(); assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(GZ_HELLO_WORLD))); assertHasInboundMessages(channel, true); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } @Test public void testRequestContentLength1() { // case 1: test that ContentDecompressor either sets the correct Content-Length header // or removes it completely (handlers down the chain must rely on LastHttpContent object) // force content to be in more than one chunk (5 bytes/chunk) HttpRequestDecoder decoder = new HttpRequestDecoder(4096, 4096, 5); HttpContentDecoder decompressor = new HttpContentDecompressor(); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor); String headers = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; ByteBuf buf = Unpooled.copiedBuffer(headers.getBytes(CharsetUtil.US_ASCII), GZ_HELLO_WORLD); assertTrue(channel.writeInbound(buf)); Queue<Object> req = channel.inboundMessages(); assertTrue(req.size() >= 1); Object o = req.peek(); assertThat(o, is(instanceOf(HttpRequest.class))); HttpRequest r = (HttpRequest) o; Long value = r.headers().getLong(HttpHeaderNames.CONTENT_LENGTH); assertTrue(value == null || value.longValue() == HELLO_WORLD.length()); assertHasInboundMessages(channel, true); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } @Test public void testRequestContentLength2() { // case 2: if HttpObjectAggregator is down the chain, then correct Content-Length header must be set // force content to be in more than one chunk (5 bytes/chunk) HttpRequestDecoder decoder = new HttpRequestDecoder(4096, 4096, 5); HttpContentDecoder decompressor = new HttpContentDecompressor(); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor, aggregator); String headers = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; ByteBuf buf = Unpooled.copiedBuffer(headers.getBytes(CharsetUtil.US_ASCII), GZ_HELLO_WORLD); assertTrue(channel.writeInbound(buf)); Object o = channel.readInbound(); assertThat(o, is(instanceOf(FullHttpRequest.class))); FullHttpRequest r = (FullHttpRequest) o; Long value = r.headers().getLong(HttpHeaderNames.CONTENT_LENGTH); r.release(); assertNotNull(value); assertEquals(HELLO_WORLD.length(), value.longValue()); assertHasInboundMessages(channel, false); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } @Test public void testResponseContentLength1() { // case 1: test that ContentDecompressor either sets the correct Content-Length header // or removes it completely (handlers down the chain must rely on LastHttpContent object) // force content to be in more than one chunk (5 bytes/chunk) HttpResponseDecoder decoder = new HttpResponseDecoder(4096, 4096, 5); HttpContentDecoder decompressor = new HttpContentDecompressor(); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor); String headers = "HTTP/1.1 200 OK\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; ByteBuf buf = Unpooled.copiedBuffer(headers.getBytes(CharsetUtil.US_ASCII), GZ_HELLO_WORLD); assertTrue(channel.writeInbound(buf)); Queue<Object> resp = channel.inboundMessages(); assertTrue(resp.size() >= 1); Object o = resp.peek(); assertThat(o, is(instanceOf(HttpResponse.class))); HttpResponse r = (HttpResponse) o; Long value = r.headers().getLong(HttpHeaderNames.CONTENT_LENGTH); assertTrue(value == null || value.longValue() == HELLO_WORLD.length()); assertHasInboundMessages(channel, true); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } @Test public void testResponseContentLength2() { // case 2: if HttpObjectAggregator is down the chain, then correct Content-Length header must be set // force content to be in more than one chunk (5 bytes/chunk) HttpResponseDecoder decoder = new HttpResponseDecoder(4096, 4096, 5); HttpContentDecoder decompressor = new HttpContentDecompressor(); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor, aggregator); String headers = "HTTP/1.1 200 OK\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; ByteBuf buf = Unpooled.copiedBuffer(headers.getBytes(CharsetUtil.US_ASCII), GZ_HELLO_WORLD); assertTrue(channel.writeInbound(buf)); Object o = channel.readInbound(); assertThat(o, is(instanceOf(FullHttpResponse.class))); FullHttpResponse r = (FullHttpResponse) o; Long value = r.headers().getLong(HttpHeaderNames.CONTENT_LENGTH); assertNotNull(value); assertEquals(HELLO_WORLD.length(), value.longValue()); r.release(); assertHasInboundMessages(channel, false); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } @Test public void testFullHttpRequest() { // test that ContentDecoder can be used after the ObjectAggregator HttpRequestDecoder decoder = new HttpRequestDecoder(4096, 4096, 5); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); HttpContentDecoder decompressor = new HttpContentDecompressor(); EmbeddedChannel channel = new EmbeddedChannel(decoder, aggregator, decompressor); String headers = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; assertTrue(channel.writeInbound(Unpooled.copiedBuffer(headers.getBytes(), GZ_HELLO_WORLD))); Queue<Object> req = channel.inboundMessages(); assertTrue(req.size() > 1); int contentLength = 0; for (Object o : req) { if (o instanceof HttpContent) { assertTrue(((HttpContent) o).refCnt() > 0); ByteBuf b = ((HttpContent) o).content(); contentLength += b.readableBytes(); } } int readCount = 0; byte[] receivedContent = new byte[contentLength]; for (Object o : req) { if (o instanceof HttpContent) { ByteBuf b = ((HttpContent) o).content(); int readableBytes = b.readableBytes(); b.readBytes(receivedContent, readCount, readableBytes); readCount += readableBytes; } } assertEquals(HELLO_WORLD, new String(receivedContent, CharsetUtil.US_ASCII)); assertHasInboundMessages(channel, true); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } @Test public void testFullHttpResponse() { // test that ContentDecoder can be used after the ObjectAggregator HttpResponseDecoder decoder = new HttpResponseDecoder(4096, 4096, 5); HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); HttpContentDecoder decompressor = new HttpContentDecompressor(); EmbeddedChannel channel = new EmbeddedChannel(decoder, aggregator, decompressor); String headers = "HTTP/1.1 200 OK\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Content-Encoding: gzip\r\n" + "\r\n"; assertTrue(channel.writeInbound(Unpooled.copiedBuffer(headers.getBytes(), GZ_HELLO_WORLD))); Queue<Object> resp = channel.inboundMessages(); assertTrue(resp.size() > 1); int contentLength = 0; for (Object o : resp) { if (o instanceof HttpContent) { assertTrue(((HttpContent) o).refCnt() > 0); ByteBuf b = ((HttpContent) o).content(); contentLength += b.readableBytes(); } } int readCount = 0; byte[] receivedContent = new byte[contentLength]; for (Object o : resp) { if (o instanceof HttpContent) { ByteBuf b = ((HttpContent) o).content(); int readableBytes = b.readableBytes(); b.readBytes(receivedContent, readCount, readableBytes); readCount += readableBytes; } } assertEquals(HELLO_WORLD, new String(receivedContent, CharsetUtil.US_ASCII)); assertHasInboundMessages(channel, true); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); } private byte[] gzDecompress(byte[] input) { ZlibDecoder decoder = ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP); EmbeddedChannel channel = new EmbeddedChannel(decoder); assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(input))); assertTrue(channel.finish()); // close the channel to indicate end-of-data int outputSize = 0; ByteBuf o; List<ByteBuf> inbound = new ArrayList<ByteBuf>(); while ((o = channel.readInbound()) != null) { inbound.add(o); outputSize += o.readableBytes(); } byte[] output = new byte[outputSize]; int readCount = 0; for (ByteBuf b : inbound) { int readableBytes = b.readableBytes(); b.readBytes(output, readCount, readableBytes); b.release(); readCount += readableBytes; } assertTrue(channel.inboundMessages().isEmpty() && channel.outboundMessages().isEmpty()); return output; } private byte[] gzCompress(byte[] input) { ZlibEncoder encoder = ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP); EmbeddedChannel channel = new EmbeddedChannel(encoder); assertTrue(channel.writeOutbound(Unpooled.wrappedBuffer(input))); assertTrue(channel.finish()); // close the channel to indicate end-of-data int outputSize = 0; ByteBuf o; List<ByteBuf> outbound = new ArrayList<ByteBuf>(); while ((o = channel.readOutbound()) != null) { outbound.add(o); outputSize += o.readableBytes(); } byte[] output = new byte[outputSize]; int readCount = 0; for (ByteBuf b : outbound) { int readableBytes = b.readableBytes(); b.readBytes(output, readCount, readableBytes); b.release(); readCount += readableBytes; } assertTrue(channel.inboundMessages().isEmpty() && channel.outboundMessages().isEmpty()); return output; } private void assertHasInboundMessages(EmbeddedChannel channel, boolean hasMessages) { Object o; if (hasMessages) { while (true) { o = channel.readInbound(); assertNotNull(o); ReferenceCountUtil.release(o); if (o instanceof LastHttpContent) { break; } } } else { o = channel.readInbound(); assertNull(o); } } private void assertHasOutboundMessages(EmbeddedChannel channel, boolean hasMessages) { Object o; if (hasMessages) { while (true) { o = channel.readOutbound(); assertNotNull(o); ReferenceCountUtil.release(o); if (o instanceof LastHttpContent) { break; } } } else { o = channel.readOutbound(); assertNull(o); } } }
/* * passportapplet - A reference implementation of the MRTD standards. * * Copyright (C) 2006 SoS group, Radboud University * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * $Id: PassportCrypto.java 945 2009-05-12 08:31:57Z woj76 $ */ package sos.passportapplet; import javacard.framework.APDU; import javacard.framework.ISO7816; import javacard.framework.ISOException; import javacard.framework.JCSystem; import javacard.framework.Util; import javacard.security.CryptoException; import javacard.security.DESKey; import javacard.security.KeyAgreement; import javacard.security.KeyBuilder; import javacard.security.MessageDigest; import javacard.security.RSAPublicKey; import javacard.security.Signature; import javacardx.crypto.Cipher; public class PassportCrypto { public static final byte ENC_MODE = 1; public static final byte MAC_MODE = 2; public static final byte CREF_MODE = 3; public static final byte PERFECTWORLD_MODE = 4; public static final byte JCOP41_MODE = 5; public static final byte INPUT_IS_NOT_PADDED = 5; public static final byte INPUT_IS_PADDED = 6; public static final byte PAD_INPUT = 7; public static final byte DONT_PAD_INPUT = 8; MessageDigest shaDigest; Signature sig; Cipher ciph; Cipher rsaCiph; KeyStore keyStore; Signature rsaSig; KeyAgreement keyAgreement; boolean[] eacChangeKeys; // byte[] eacTerminalKeyHash; private static final short EC_X_LENGTH = (short)((short)(KeyBuilder.LENGTH_EC_F2M_163 / 8)+1); public static byte[] PAD_DATA = { (byte) 0x80, 0, 0, 0, 0, 0, 0, 0 }; protected void init() { sig = Signature.getInstance(Signature.ALG_DES_MAC8_ISO9797_1_M2_ALG3, false); ciph = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false); } public PassportCrypto(KeyStore keyStore) { this.keyStore = keyStore; init(); shaDigest = MessageDigest.getInstance(MessageDigest.ALG_SHA, false); rsaSig = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false); rsaCiph = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false); keyAgreement = KeyAgreement.getInstance(KeyAgreement.ALG_EC_SVDP_DH, false); eacChangeKeys = JCSystem.makeTransientBooleanArray((short) 1, JCSystem.CLEAR_ON_DESELECT); } public void createMacFinal(byte[] msg, short msg_offset, short msg_len, byte[] mac, short mac_offset) { sig.sign(msg, msg_offset, msg_len, mac, mac_offset); } public boolean verifyMacFinal(byte[] msg, short msg_offset, short msg_len, byte[] mac, short mac_offset) { return sig.verify(msg, msg_offset, msg_len, mac, mac_offset, (short) 8); } public void decryptInit() { DESKey k = keyStore.getCryptKey(); ciph.init(k, Cipher.MODE_DECRYPT); } public short decrypt(byte[] ctext, short ctext_offset, short ctext_len, byte[] ptext, short ptext_offset) { return ciph.update(ctext, ctext_offset, ctext_len, ptext, ptext_offset); } public short decryptFinal(byte[] ctext, short ctext_offset, short ctext_len, byte[] ptext, short ptext_offset) { return ciph.doFinal(ctext, ctext_offset, ctext_len, ptext, ptext_offset); } public short encryptInit() { return encryptInit(DONT_PAD_INPUT, null, (short)0, (short)0); } public short encryptInit(byte padding, byte[] ptext, short ptext_offset, short ptext_len) { DESKey k = keyStore.getCryptKey(); short newlen=ptext_len; if(padding == PAD_INPUT) { // pad input newlen = PassportUtil.pad(ptext, ptext_offset, ptext_len); } ciph.init(k, Cipher.MODE_ENCRYPT); return newlen; } public short encrypt(byte[] ptext, short ptext_offset, short ptext_len, byte[] ctext, short ctext_offset) { return ciph.update(ptext, ptext_offset, ptext_len, ctext, ctext_offset); } public short encryptFinal(byte[] ptext, short ptext_offset, short ptext_len, byte[] ctext, short ctext_offset) { return ciph.doFinal(ptext, ptext_offset, ptext_len, ctext, ctext_offset); } public void updateMac(byte[] msg, short msg_offset, short msg_len) { sig.update(msg, msg_offset, msg_len); } public void initMac(byte mode) { DESKey k = keyStore.getMacKey(); sig.init(k, mode); } // public short unwrapCommandAPDU_werkt(byte[] ssc, APDU aapdu) { // byte[] apdu = aapdu.getBuffer(); // short apdu_p = (short) (ISO7816.OFFSET_CDATA & 0xff); // // offset // short lc = (short) (apdu[ISO7816.OFFSET_LC] & 0xff); // short le = 0; // short do87DataLen = 0; // short do87Data_p = 0; // short do87LenBytes = 0; // short hdrLen = 4; // short hdrPadLen = (short) (8 - hdrLen); // short apduLength = (short) (hdrLen + 1 + lc); // // aapdu.setIncomingAndReceive(); // // // sanity check // if (apdu.length < (short) (apduLength + hdrPadLen + ssc.length)) { // ISOException.throwIt((short)0x6d66); // } // // // pad the header, make room for ssc, so we don't have to // // modify pointers to locations in the apdu later. // Util.arrayCopy(apdu, (short) (hdrLen + 1), // toss away lc // apdu, (short) (hdrLen + hdrPadLen), lc); // Util.arrayCopy(PassportCrypto.PAD_DATA, // (short) 0, // apdu, // hdrLen, // hdrPadLen); // apduLength--; // apduLength += hdrPadLen; // // // add ssc in front (needed to calculate the mac) so we don't have to // // modify pointers to locations in the apdu later. // incrementSSC(ssc); // Util.arrayCopy(apdu, (short) 0, apdu, (short) ssc.length, apduLength); // Util.arrayCopy(ssc, (short) 0, apdu, (short) 0, (short) ssc.length); // // apdu_p = (short) (hdrLen + hdrPadLen); // apdu_p += (short) ssc.length; // // if (apdu[apdu_p] == (byte) 0x87) { // apdu_p++; // // do87 // if ((apdu[apdu_p] & 0xff) > 0x80) { // do87LenBytes = (short) (apdu[apdu_p] & 0x7f); // apdu_p++; // } else { // do87LenBytes = 1; // } // if (do87LenBytes > 2) { // sanity check // ISOException.throwIt((short) 0x6d66); // } // for (short i = 0; i < do87LenBytes; i++) { // do87DataLen += (short) ((apdu[(short)(apdu_p + i)] & 0xff) << (short) ((do87LenBytes - 1 - i) * 8)); // } // apdu_p += do87LenBytes; // // if (apdu[apdu_p] != 1) { // ISOException.throwIt((short) (0x6d66)); // } // // store pointer to data and defer decrypt to after mac check (do8e) // do87Data_p = (short) (apdu_p + 1); // apdu_p += do87DataLen; // do87DataLen--; // compensate for 0x01 marker // } // // if (apdu[apdu_p] == (byte) 0x97) { // // do97 // if (apdu[++apdu_p] != 1) // ISOException.throwIt((short) (0x6d66)); // le = (short) (apdu[++apdu_p] & 0xff); // apdu_p++; // } // // // do8e // if (apdu[apdu_p] != (byte) 0x8e) { // ISOException.throwIt((short) (0x6d66)); // } // if (apdu[++apdu_p] != 8) { // ISOException.throwIt(ISO7816.SW_DATA_INVALID); // } // // initMac(); // if (!verifyMacFinal(apdu, // (short) 0, // (short) (apdu_p - 1), // apdu, // (short)(apdu_p + 1))) { // ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); // } // // // construct unprotected apdu // // copy back the hdr // Util.arrayCopy(apdu, (short) ssc.length, apdu, (short) 0, hdrLen); // apduLength -= 4; // // short plaintextLength = 0; // short plaintextLc = 0; // if (do87DataLen != 0) { // // decrypt data, and leave room for lc // decryptInit(); // plaintextLength = decryptFinal(apdu, // do87Data_p, // do87DataLen, // apdu, // (short) (hdrLen + 1)); // // plaintextLc = PassportUtil.calcLcFromPaddedData(apdu, // (short) (hdrLen + 1), // do87DataLen); // apdu[hdrLen] = (byte) (plaintextLc & 0xff); // } // // apduLength = (short) (hdrLen + 1 + plaintextLength); // // // empty out the rest // for (short i = apduLength; i < apdu.length; i++) { // apdu[i] = 0; // } // // return le; // } public short unwrapCommandAPDU(byte[] ssc, APDU apdu) { byte[] buf = apdu.getBuffer(); short apdu_p = (short) (ISO7816.OFFSET_CDATA & 0xff); short start_p = apdu_p; short lc = (short) (buf[ISO7816.OFFSET_LC] & 0xff); short le = 0; short do87DataLen = 0; short do87Data_p = 0; short do87LenBytes = 0; short hdrLen = 4; short hdrPadLen = (short) (8 - hdrLen); apdu.setIncomingAndReceive(); incrementSSC(ssc); if (buf[apdu_p] == (byte) 0x87) { apdu_p++; // do87 if ((buf[apdu_p] & 0xff) > 0x80) { do87LenBytes = (short) (buf[apdu_p] & 0x7f); apdu_p++; } else { do87LenBytes = 1; } if (do87LenBytes > 2) { // sanity check ISOException.throwIt(PassportApplet.SW_INTERNAL_ERROR); } for (short i = 0; i < do87LenBytes; i++) { do87DataLen += (short) ((buf[(short)(apdu_p + i)] & 0xff) << (short) ((do87LenBytes - 1 - i) * 8)); } apdu_p += do87LenBytes; if (buf[apdu_p] != 1) { ISOException.throwIt(PassportApplet.SW_INTERNAL_ERROR); } // store pointer to data and defer decrypt to after mac check (do8e) do87Data_p = (short) (apdu_p + 1); apdu_p += do87DataLen; do87DataLen--; // compensate for 0x01 marker } if (buf[apdu_p] == (byte) 0x97) { // do97 if (buf[++apdu_p] != 1) ISOException.throwIt(PassportApplet.SW_INTERNAL_ERROR); le = (short) (buf[++apdu_p] & 0xff); apdu_p++; } // do8e if (buf[apdu_p] != (byte) 0x8e) { ISOException.throwIt(PassportApplet.SW_INTERNAL_ERROR); } if (buf[++apdu_p] != 8) { ISOException.throwIt(ISO7816.SW_DATA_INVALID); } // verify mac initMac(Signature.MODE_VERIFY); updateMac(ssc, (short)0, (short)ssc.length); updateMac(buf, (short)0, hdrLen); updateMac(PAD_DATA, (short)0, hdrPadLen); if (!verifyMacFinal(buf, start_p, (short) (apdu_p - 1 - start_p), buf, (short)(apdu_p + 1))) { ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); } short plaintextLength = 0; short plaintextLc = 0; if (do87DataLen != 0) { // decrypt data, and leave room for lc decryptInit(); plaintextLength = decryptFinal(buf, do87Data_p, do87DataLen, buf, (short) (hdrLen + 1)); plaintextLc = PassportUtil.calcLcFromPaddedData(buf, (short) (hdrLen + 1), do87DataLen); buf[hdrLen] = (byte) (plaintextLc & 0xff); } return le; } /*** * Space to reserve in buffer when using secure messaging. * * @param plaintextLength length of plaintext in which this offset depends. * @return */ public short getApduBufferOffset(short plaintextLength) { short do87Bytes = 2; // 0x87 len data 0x01 // smallest multiple of 8 strictly larger than plaintextLen + 1 // byte is probably the length of the ciphertext (including do87 0x01) short do87DataLen = (short) ((((short) (plaintextLength + 8) / 8) * 8) + 1); if(do87DataLen < 0x80) { do87Bytes++; } else if(do87DataLen <= 0xff) { do87Bytes += 2; } else { do87Bytes += (short)(plaintextLength > 0xff ? 2 : 1); } return do87Bytes; } public short wrapResponseAPDU(byte[] ssc, APDU aapdu, short plaintextOffset, short plaintextLen, short sw1sw2) { byte[] apdu = aapdu.getBuffer(); short apdu_p = 0; // smallest multiple of 8 strictly larger than plaintextLen short do87DataLen = PassportUtil.lengthWithPadding(plaintextLen); // for 0x01 marker (indicating padding is used) do87DataLen++; short do87DataLenBytes = (short)(do87DataLen > 0xff? 2 : 1); short do87HeaderBytes = getApduBufferOffset(plaintextLen); short do87Bytes = (short)(do87HeaderBytes + do87DataLen - 1); // 0x01 is counted twice boolean hasDo87 = plaintextLen > 0; incrementSSC(ssc); short ciphertextLength=0; short possiblyPaddedPlaintextLength=0; if(hasDo87) { // put ciphertext in proper position. possiblyPaddedPlaintextLength = encryptInit(PAD_INPUT, apdu, plaintextOffset, plaintextLen); ciphertextLength = encryptFinal( apdu, plaintextOffset, possiblyPaddedPlaintextLength, apdu, do87HeaderBytes); } //sanity check //note that this check // (possiblyPaddedPlaintextLength != (short)(do87DataLen -1)) //does not always hold because some algs do the padding in the final, some in the init. if (hasDo87 && (((short) (do87DataLen - 1) != ciphertextLength))) ISOException.throwIt((short) 0x6d66); if (hasDo87) { // build do87 apdu[apdu_p++] = (byte) 0x87; if(do87DataLen < 0x80) { apdu[apdu_p++] = (byte)do87DataLen; } else { apdu[apdu_p++] = (byte) (0x80 + do87DataLenBytes); for(short i=(short)(do87DataLenBytes-1); i>=0; i--) { apdu[apdu_p++] = (byte) ((do87DataLen >>> (i * 8)) & 0xff); } } apdu[apdu_p++] = 0x01; } if(hasDo87) { apdu_p = do87Bytes; } // build do99 apdu[apdu_p++] = (byte) 0x99; apdu[apdu_p++] = 0x02; Util.setShort(apdu, apdu_p, sw1sw2); apdu_p += 2; // calculate and write mac initMac(Signature.MODE_SIGN); updateMac(ssc, (short)0, (short)ssc.length); createMacFinal(apdu, (short) 0, apdu_p, apdu, (short)(apdu_p+2)); // write do8e apdu[apdu_p++] = (byte) 0x8e; apdu[apdu_p++] = 0x08; apdu_p += 8; // for mac written earlier if (eacChangeKeys[0]) { eacChangeKeys[0] = false; keyStore.setSecureMessagingKeys(keyStore.tmpKeys, (short) 0, keyStore.tmpKeys, (short) 16); Util.arrayFillNonAtomic(keyStore.tmpKeys, (short) 0, (short) 32, (byte) 0x00); Util.arrayFillNonAtomic(ssc, (short) 0, (short) ssc.length, (byte) 0x00); } return apdu_p; } /** * Derives the ENC or MAC key from the keySeed. * * @param keySeed * the key seed. * @param mode * either <code>ENC_MODE</code> or <code>MAC_MODE</code>. * * @return the key. */ static byte[] c = { 0x00, 0x00, 0x00, 0x00 }; public void deriveKey(byte[] buffer, short keySeed_offset, short keySeed_length, byte mode, short key_offset) throws CryptoException { // only key_offset is a write pointer // sanity checks if ((short)buffer.length < (short)((short)(key_offset + keySeed_length) + c.length)) { ISOException.throwIt((short)0x6d66); } if(keySeed_offset > key_offset) { ISOException.throwIt((short)0x6d66); } c[(short)(c.length-1)] = mode; // copy seed || c to key_offset Util.arrayCopyNonAtomic(buffer, keySeed_offset, buffer, key_offset, keySeed_length); Util.arrayCopyNonAtomic(c, (short) 0, buffer, (short)(key_offset + keySeed_length), (short)c.length); // compute hash on key_offset (+seed len +c len) shaDigest.doFinal(buffer, key_offset, (short)(keySeed_length + c.length), buffer, key_offset); shaDigest.reset(); // parity bits for (short i = key_offset; i < (short)(key_offset + PassportApplet.KEY_LENGTH); i++) { if (PassportUtil.evenBits(buffer[i]) == 0) buffer[i] = (byte) (buffer[i] ^ 1); } } public static void incrementSSC(byte[] ssc) { if (ssc == null || ssc.length <= 0) return; for (short s = (short) (ssc.length - 1); s >= 0; s--) { if ((short) ((ssc[s] & 0xff) + 1) > 0xff) ssc[s] = 0; else { ssc[s]++; break; } } } public static void computeSSC(byte[] rndICC, short rndICC_offset, byte[] rndIFD, short rndIFD_offset, byte[] ssc) { if (rndICC == null || (short) (rndICC.length - rndICC_offset) < 8 || rndIFD == null || (short) (rndIFD.length - rndIFD_offset) < 8) { ISOException.throwIt((short) 0x6d66); } Util.arrayCopyNonAtomic(rndICC, (short) (rndICC_offset + 4), ssc, (short) 0, (short) 4); Util.arrayCopyNonAtomic(rndIFD, (short) (rndIFD_offset + 4), ssc, (short) 4, (short) 4); } public void createHash(byte[] msg, short msg_offset, short length, byte[] dest, short dest_offset) throws CryptoException { if ((dest.length < (short) (dest_offset + length)) || (msg.length < (short) (msg_offset + length))) ISOException.throwIt((short) 0x6d66); try { shaDigest.doFinal(msg, msg_offset, length, dest, dest_offset); } finally { shaDigest.reset(); } } /** * Chip authentication part of EAP. * * @param pubData * the other parties public key data * @param offset * offset to the public key data * @param length * public key data length * * @return true when authentication successful */ public boolean authenticateChip(byte[] pubData, short offset, short length) { try { // Verify public key first. i.e. see if the data is correct and // makes up a valid // EC public key. keyStore.ecPublicKey.setW(pubData, offset, length); if (!keyStore.ecPublicKey.isInitialized()) { CryptoException.throwIt(CryptoException.ILLEGAL_VALUE); } // Do the key agreement and derive new session keys based on the // outcome: keyAgreement.init(keyStore.ecPrivateKey); short secOffset = (short) (offset + length); short secLength = keyAgreement.generateSecret(pubData, offset, length, pubData, secOffset); // use only first 16 bytes? // secLength = 16; short keysOffset = (short) (secOffset + secLength); deriveKey(pubData, secOffset, secLength, MAC_MODE, keysOffset); short macKeyOffset = keysOffset; keysOffset += PassportApplet.KEY_LENGTH; deriveKey(pubData, secOffset, secLength, ENC_MODE, keysOffset); short encKeyOffset = keysOffset; Util.arrayCopyNonAtomic(pubData, macKeyOffset, keyStore.tmpKeys, (short) 0, PassportApplet.KEY_LENGTH); Util.arrayCopyNonAtomic(pubData, encKeyOffset, keyStore.tmpKeys, PassportApplet.KEY_LENGTH, PassportApplet.KEY_LENGTH); // The secure messaging keys should be replaced with the freshly // computed ones // just after the current APDU is completely processed. eacChangeKeys[0] = true; return true; } catch (Exception e) { eacChangeKeys[0] = false; return false; } } boolean eacVerifySignature(RSAPublicKey key, byte[] rnd, byte[] docNr, byte[] buffer, short offset, short length) { short x_offset = (short)(offset+length); keyStore.ecPublicKey.getW(buffer, x_offset++); rsaSig.init(key, Signature.MODE_VERIFY); rsaSig.update(docNr, (short) 0, (short) docNr.length); rsaSig.update(rnd, (short) 0, PassportApplet.RND_LENGTH); return rsaSig.verify(buffer, x_offset, EC_X_LENGTH, buffer, offset, length); } }
/** * 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.component.stream; import java.nio.charset.Charset; import org.apache.camel.Component; import org.apache.camel.Consumer; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @UriEndpoint(scheme = "stream", consumerClass = StreamConsumer.class, label = "file,system") public class StreamEndpoint extends DefaultEndpoint { private static final Logger LOG = LoggerFactory.getLogger(StreamEndpoint.class); @UriPath private String url; @UriParam private String fileName; @UriParam(defaultValue = "false") private boolean scanStream; @UriParam(defaultValue = "false") private boolean retry; @UriParam(defaultValue = "false") private boolean closeOnDone; @UriParam private long scanStreamDelay; @UriParam(defaultValue = "false") private long delay; @UriParam private String encoding; @UriParam private String promptMessage; @UriParam private long promptDelay; @UriParam(defaultValue = "2000") private long initialPromptDelay = 2000; @UriParam private int groupLines; @UriParam private int autoCloseCount; @UriParam private Charset charset; @UriParam private GroupStrategy groupStrategy = new DefaultGroupStrategy(); public StreamEndpoint(String endpointUri, Component component) throws Exception { super(endpointUri, component); } @Deprecated public StreamEndpoint(String endpointUri) { super(endpointUri); } public Consumer createConsumer(Processor processor) throws Exception { StreamConsumer answer = new StreamConsumer(this, processor, getEndpointUri()); configureConsumer(answer); return answer; } public Producer createProducer() throws Exception { return new StreamProducer(this, getEndpointUri()); } public boolean isSingleton() { return true; } protected Exchange createExchange(Object body, long index, boolean last) { Exchange exchange = createExchange(); exchange.getIn().setBody(body); exchange.getIn().setHeader(StreamConstants.STREAM_INDEX, index); exchange.getIn().setHeader(StreamConstants.STREAM_COMPLETE, last); return exchange; } // Properties //------------------------------------------------------------------------- public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public long getDelay() { return delay; } public void setDelay(long delay) { this.delay = delay; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } public String getPromptMessage() { return promptMessage; } public void setPromptMessage(String promptMessage) { this.promptMessage = promptMessage; } public long getPromptDelay() { return promptDelay; } public void setPromptDelay(long promptDelay) { this.promptDelay = promptDelay; } public long getInitialPromptDelay() { return initialPromptDelay; } public void setInitialPromptDelay(long initialPromptDelay) { this.initialPromptDelay = initialPromptDelay; } public boolean isScanStream() { return scanStream; } public void setScanStream(boolean scanStream) { this.scanStream = scanStream; } public GroupStrategy getGroupStrategy() { return groupStrategy; } public void setGroupStrategy(GroupStrategy strategy) { this.groupStrategy = strategy; } public boolean isRetry() { return retry; } public void setRetry(boolean retry) { this.retry = retry; } public boolean isCloseOnDone() { return closeOnDone; } public void setCloseOnDone(boolean closeOnDone) { this.closeOnDone = closeOnDone; } public long getScanStreamDelay() { return scanStreamDelay; } public void setScanStreamDelay(long scanStreamDelay) { this.scanStreamDelay = scanStreamDelay; } public int getGroupLines() { return groupLines; } public void setGroupLines(int groupLines) { this.groupLines = groupLines; } public int getAutoCloseCount() { return autoCloseCount; } public void setAutoCloseCount(int autoCloseCount) { this.autoCloseCount = autoCloseCount; } public Charset getCharset() { return charset; } // Implementations //------------------------------------------------------------------------- protected void doStart() throws Exception { charset = loadCharset(); } Charset loadCharset() { if (encoding == null) { encoding = Charset.defaultCharset().name(); LOG.debug("No encoding parameter using default charset: {}", encoding); } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding); } }
/* * Copyright 2015 Synced Synapse. 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 org.xbmc.kore.utils; import android.content.Context; import android.os.StatFs; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.Enumeration; /** * Various utilities related to networking */ public class NetUtils { private static final String TAG = LogUtils.makeLogTag(NetUtils.class); /** * Convert a IPv4 address from an integer to an InetAddress. * @param hostAddress an int corresponding to the IPv4 address in network byte order */ public static InetAddress intToInetAddress(int hostAddress) { if (hostAddress == 0) return null; byte[] addressBytes = { (byte)(0xff & hostAddress), (byte)(0xff & (hostAddress >> 8)), (byte)(0xff & (hostAddress >> 16)), (byte)(0xff & (hostAddress >> 24)) }; try { return InetAddress.getByAddress(addressBytes); } catch (UnknownHostException e) { throw new AssertionError(); } } /** * Tries to return the MAC address of a host on the same subnet by looking at the ARP cache.. * Note: This is a synchronous call, so it should only be called on a background thread * * @param hostAddress Hostname or IP address * @return MAC address if found or null */ public static String getMacAddress(String hostAddress) { String ipHostAddress; LogUtils.LOGD(TAG, "Starting get Mac Address for: " + hostAddress); try { InetAddress inet = InetAddress.getByName(hostAddress); // Send some traffic, with a timeout boolean reachable = inet.isReachable(1000); ipHostAddress = inet.getHostAddress(); } catch (UnknownHostException e) { LogUtils.LOGD(TAG, "Got an UnknownHostException for host: " + hostAddress, e); return null; } catch (IOException e) { LogUtils.LOGD(TAG, "Couldn't check reachability of host: " + hostAddress, e); return null; } try { // Read the arp cache BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp")); String arpLine; while ((arpLine = br.readLine()) != null) { if (arpLine.startsWith(ipHostAddress)) { // Ok, this is the line, get the MAC Address br.close(); return arpLine.split("\\s+")[3].toUpperCase(); // 4th element } } br.close(); } catch (IOException e) { LogUtils.LOGD(TAG, "Couldn check ARP cache.", e); } return null; } /** * Sends a Wake On Lan magic packet to a host * Note: This is a synchronous call, so it should only be called on a background thread * * @param macAddress MAC address * @param hostAddress Hostname or IP address * @param port Port for Wake On Lan * @return Whether the packet was successfully sent */ public static boolean sendWolMagicPacket(String macAddress, String hostAddress, int port) { if (macAddress == null) { return false; } // Get MAC adress bytes byte[] macAddressBytes = new byte[6]; String[] hex = macAddress.split("(\\:|\\-)"); if (hex.length != 6) { LogUtils.LOGD(TAG, "Send magic packet: got an invalid MAC address: " + macAddress); return false; } try { for (int i = 0; i < 6; i++) { macAddressBytes[i] = (byte)Integer.parseInt(hex[i], 16); } } catch (NumberFormatException e) { LogUtils.LOGD(TAG, "Send magic packet: got an invalid MAC address: " + macAddress); return false; } byte[] bytes = new byte[6 + 16 * macAddressBytes.length]; for (int i = 0; i < 6; i++) { bytes[i] = (byte)0xff; } for (int i = 6; i < bytes.length; i += macAddressBytes.length) { System.arraycopy(macAddressBytes, 0, bytes, i, macAddressBytes.length); } try { InetAddress address = InetAddress.getByName(hostAddress); DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port); DatagramSocket socket = new DatagramSocket(); LogUtils.LOGD(TAG, "Sending WoL to " + address.getHostAddress() + ":" + port); socket.send(packet); // Piece of code apprehended from here: http://stackoverflow.com/a/29017289 // Check all the existing interfaces that can be broadcasted to Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback()) continue; // Don't want to broadcast to the loopback interface for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); // Android seems smart enough to set to null broadcast to // the external mobile network. It makes sense since Android // silently drop UDP broadcasts involving external mobile network. // Automatically skip IPv6 as it has broadcast IP null if (broadcast != null) { LogUtils.LOGD(TAG, "Sending WoL broadcast to " + broadcast.getHostAddress() + ":" + port); // Broadcasts WOL Magic Packet to every possible broadcast address packet = new DatagramPacket(bytes, bytes.length, broadcast, port); socket.send(packet); } } } socket.close(); } catch (IOException e) { LogUtils.LOGD(TAG, "Exception while sending magic packet.", e); return false; } return true; } private static byte[] getMacBytes(String macStr) throws IllegalArgumentException { byte[] bytes = new byte[6]; String[] hex = macStr.split("(\\:|\\-)"); if (hex.length != 6) { throw new IllegalArgumentException("Invalid MAC address."); } try { for (int i = 0; i < 6; i++) { bytes[i] = (byte) Integer.parseInt(hex[i], 16); } } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid hex digit in MAC address."); } return bytes; } /** * Utility functions to create a cache for images, used with the picasso library * Lifted from com.squareup.picasso.Utils */ private static final String APP_CACHE = "app-cache"; private static final int MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024; // 5MB private static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB public static File createDefaultCacheDir(Context context) { File cache = new File(context.getApplicationContext().getCacheDir(), APP_CACHE); if (!cache.exists()) { //noinspection ResultOfMethodCallIgnored cache.mkdirs(); } return cache; } public static long calculateDiskCacheSize(File dir) { long size = MIN_DISK_CACHE_SIZE; try { StatFs statFs = new StatFs(dir.getAbsolutePath()); long available = ((long) statFs.getBlockCount()) * statFs.getBlockSize(); // Target 2% of the total space. size = available / 50; } catch (IllegalArgumentException ignored) { } // Bound inside min/max size for disk cache. return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE); } }
package edu.psu.compbio.seqcode.gse.tools.chipchip; import java.io.*; import java.util.*; import java.sql.*; import java.util.regex.*; import edu.psu.compbio.seqcode.gse.datasets.chipchip.*; import edu.psu.compbio.seqcode.gse.datasets.general.*; import edu.psu.compbio.seqcode.gse.datasets.species.*; import edu.psu.compbio.seqcode.gse.utils.NotFoundException; import edu.psu.compbio.seqcode.gse.utils.database.*; /** * MSP files are the output of the Young Lab's error model (also known * as the Rosetta error model. * * Usage: * java edu.psu.compbio.seqcode.gse.tools.chipchip.AddMSP --species "$SC;SGDv1" --analysis "Sc Gcn4 in YPD;linefitting normalization" -- file1.msp file2.msp * */ public class AddMSP { private Organism species; private Genome genome; private String analysisname, analysisversion; private int analysisid; private java.sql.Connection core, chipchip; private int chromcol, poscol, ratiocol, xcol, pvalcol, pval3col, redcol, greencol, mediancol; private Map<String,Integer> chrommap; private ArrayList<String> fnames; public AddMSP() throws UnknownRoleException, SQLException { core = DatabaseFactory.getConnection("core"); chipchip = DatabaseFactory.getConnection("chipchip"); fnames = new ArrayList<String>(); } public void parseArgs(String[] args) throws NotFoundException { species = null; genome = null; analysisname = null; analysisversion = null; int i; for (i = 0; i < args.length; i++) { if (args[i].equals("--species")) { String s = args[++i]; String pieces[] = s.split(";"); species = new Organism(pieces[0]); if (pieces.length >= 2) { genome = species.getGenome(pieces[1]); } } if (args[i].equals("--analysis") || args[i].equals("--analysisname")) { String s = args[++i]; String pieces[] = s.split(";"); analysisname = pieces[0]; if (pieces.length >= 2) { analysisversion = pieces[1]; } } if (args[i].equals("--analysisversion")) { analysisversion = args[++i]; } if (args[i].equals("--file")) { fnames.add(args[++i]); } if (args[i].equals("--")) { break; } } for (;i < args.length; i++) { fnames.add(args[i]); } for (i = 0; i < args.length; i++) { if (args[i].equals("--genome")) { genome = species.getGenome(args[++i]); } } if (species == null || genome == null) { throw new RuntimeException("Must supply --species 'species;genomeversion'"); } if (analysisname == null || analysisversion == null) { throw new RuntimeException("Must supply --analysis 'analysisname;analysisversion'"); } } /* parseArgs must be called first. Ensures that the analysis specified by analysisname and analysisversion exists and sets analysisid accordingly. */ public void createAnalysis() throws SQLException { Statement stmt = chipchip.createStatement(); ResultSet rs = stmt.executeQuery("select id from rosettaanalysis where name = '" + analysisname + "' and version = '" + analysisversion + "' and species =" + species.getDBID()); if (rs.next()) { analysisid = rs.getInt(1); } else { rs.close(); ArrayList<String> fieldnames = new ArrayList<String>(); ArrayList<String> values = new ArrayList<String>(); fieldnames.add("id"); values.add(Sequence.getInsertSQL(chipchip,"analysis_id")); fieldnames.add("name"); values.add("'" + analysisname + "'"); fieldnames.add("version"); values.add("'" + analysisversion + "'"); fieldnames.add("species"); values.add(Integer.toString(species.getDBID())); fieldnames.add("active"); values.add("1"); Pattern exptname = Pattern.compile("\\s (\\w.*):(.*):(.*) vs (.*):(.*):(.*\\w)"); Matcher matcher = exptname.matcher(analysisname); if (matcher.matches()) { MetadataLoader loader = new MetadataLoader(); fieldnames.add("factorone"); values.add(Integer.toString(loader.getExptTarget(matcher.group(1)).getDBID())); fieldnames.add("cellsone"); values.add(Integer.toString(loader.getCellLine(matcher.group(2)).getDBID())); fieldnames.add("conditionone"); values.add(Integer.toString(loader.getExptCondition(matcher.group(3)).getDBID())); fieldnames.add("factortwo"); values.add(Integer.toString(loader.getExptTarget(matcher.group(4)).getDBID())); fieldnames.add("cellstwo"); values.add(Integer.toString(loader.getCellLine(matcher.group(5)).getDBID())); fieldnames.add("conditiontwo"); values.add(Integer.toString(loader.getExptCondition(matcher.group(6)).getDBID())); } StringBuffer cmd = new StringBuffer("insert into rosettaanalysis("); for (int i = 0; i < fieldnames.size(); i++) { cmd.append(fieldnames.get(i)); if (i < fieldnames.size() -1 ) { cmd.append(", "); } } cmd.append(") values("); for (int i = 0; i < values.size(); i++) { cmd.append(values.get(i)); if (i < values.size() -1 ) { cmd.append(", "); } } cmd.append(")"); stmt.executeUpdate(cmd.toString()); rs = stmt.executeQuery(Sequence.getLastSQLStatement(chipchip,"analysis_id")); rs.next(); analysisid = rs.getInt(1); } rs.close(); rs = stmt.executeQuery("select count(*) from rosettaToGenome where analysis = " + analysisid + " and genome = " + genome.getDBID()); rs.next(); if (rs.getInt(1) == 0) { stmt.executeUpdate("insert into rosettaToGenome(analysis, genome) values (" + analysisid + "," + genome.getDBID() + ")"); } rs.close(); stmt.close(); } public void createChromMap() { chrommap = genome.getChromIDMap(); if (species.getName().equals("Homo sapies")) { chrommap.put("23",chrommap.get("X")); chrommap.put("24",chrommap.get("Y")); chrommap.put("25",chrommap.get("mt")); } if (species.getName().equals("Mus musculus")) { chrommap.put("20",chrommap.get("X")); chrommap.put("21",chrommap.get("Y")); chrommap.put("22",chrommap.get("mt")); } if (species.getName().equals("Danio rerio")) { chrommap.put("26",chrommap.get("Un")); chrommap.put("27",chrommap.get("NA")); } if (species.getName().equals("Drosophila melanogaster")) { chrommap.put("1",chrommap.get("2L")); chrommap.put("2",chrommap.get("2R")); chrommap.put("3",chrommap.get("3L")); chrommap.put("4",chrommap.get("4")); chrommap.put("5",chrommap.get("3R")); chrommap.put("6",chrommap.get("X")); chrommap.put("7",chrommap.get("Y")); } } public void getColumnHeaders(String hline) { String colnames[] = hline.split("\\t"); for (int i = 0; i < colnames.length; i++) { colnames[i] = colnames[i].toLowerCase(); if (colnames[i].equals("chr")) { chromcol = i; } else if (colnames[i].equals("pos")) { poscol = i; } else if (colnames[i].equals("ratio")) { ratiocol = i; } else if (colnames[i].equals("x'")) { xcol = i; } else if (colnames[i].equals("pval1")) { pvalcol = i; } else if (colnames[i].equals("pval3")) { pval3col = i; } else if (colnames[i].equals("red")) { redcol = i; } else if (colnames[i].equals("green")) { greencol = i; } else if (colnames[i].equals("medianofratios")) { mediancol = i; } } } public void readFile(String fname) throws IOException, SQLException { chipchip.setAutoCommit(false); BufferedReader reader = new BufferedReader(new FileReader(fname)); PreparedStatement insert = chipchip.prepareStatement("insert into rosettaresults(analysis, chromosome, position, ratio, " + "x, pval, pval3, red, green, medianofratios) values (" + "?,?,?,?,?,?,?,?,?,?)"); insert.setInt(1,analysisid); String headerline = reader.readLine(); getColumnHeaders(headerline); String line; int added = 0; int duplicate = 0; while ((line = reader.readLine()) != null) { String pieces[] = line.split("\\t"); if (pieces[mediancol].equals("FLAG") || pieces[ratiocol].equals("FLAG") || pieces[xcol].equals("FLAG")) { continue; } insert.setInt(2, chrommap.get(pieces[chromcol])); insert.setInt(3, Integer.parseInt(pieces[poscol])); insert.setDouble(4, Double.parseDouble(pieces[ratiocol])); insert.setDouble(5, Double.parseDouble(pieces[xcol])); insert.setDouble(6, Double.parseDouble(pieces[pvalcol])); insert.setDouble(7, Double.parseDouble(pieces[pval3col])); insert.setDouble(8, Double.parseDouble(pieces[redcol])); insert.setDouble(9, Double.parseDouble(pieces[greencol])); insert.setDouble(10, Double.parseDouble(pieces[mediancol])); try { insert.execute(); } catch (SQLException e) { if (e.toString().matches(".*unique.*")) { duplicate++; continue; } else { throw e; } } added++; } chipchip.commit(); System.err.println("Added " + added + " values from " + fname); System.err.println("Dropped " + duplicate + " apparently duplicate probe positions"); } public static void main(String args[]) throws Exception { AddMSP msp = new AddMSP(); msp.parseArgs(args); msp.createAnalysis(); msp.createChromMap(); for (String fname : msp.fnames) { msp.readFile(fname); } } }
package org.multibit.hd.core.managers; import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.multibit.hd.core.events.ShutdownEvent; import org.multibit.commons.files.SecureFiles; import org.multibit.hd.core.utils.OSUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.URI; import java.security.Permission; import java.security.PermissionCollection; import java.util.Map; /** * <p>Manager to provide the following to other core classes:</p> * <ul> * <li>Location of the installation directory</li> * <li>Access the configuration file</li> * <li>Utility methods eg copying checkpoint files from installation directory</li> * </ul> */ public class InstallationManager { private static final Logger log = LoggerFactory.getLogger(InstallationManager.class); /** * The main MultiBit download site (HTTPS) */ public static final URI MBHD_WEBSITE_URI = URI.create("https://multibit.org"); /** * The main MultiBit help site (HTTPS to allow secure connection without redirect, with fall back to local help on failure) */ public static final String MBHD_WEBSITE_HELP_DOMAIN = "https://multibit.org"; public static final String MBHD_WEBSITE_HELP_BASE = MBHD_WEBSITE_HELP_DOMAIN + "/hd0.4"; public static final String MBHD_APP_NAME = "MultiBitHD"; public static final String MBHD_PREFIX = "mbhd"; public static final String MBHD_CONFIGURATION_FILE = MBHD_PREFIX + ".yaml"; public static final String SPV_BLOCKCHAIN_SUFFIX = ".spvchain"; public static final String CHECKPOINTS_SUFFIX = ".checkpoints"; public static final String CA_CERTS_NAME = MBHD_PREFIX + "-cacerts"; /** * The current application data directory */ private static File currentApplicationDataDirectory = null; /** * A test flag to allow FEST tests to run efficiently */ // This arises from the global nature of the flag - consider deriving it from test classpath presence @SuppressFBWarnings({"MS_SHOULD_BE_FINAL"}) public static boolean unrestricted = false; /** * <p>Handle any shutdown code</p> * * @param shutdownType The shutdown type */ public static void shutdownNow(ShutdownEvent.ShutdownType shutdownType) { log.debug("Received shutdown: {}", shutdownType.name()); switch (shutdownType) { case HARD: case SOFT: // Force a reset of the application directory (useful for persistence tests) currentApplicationDataDirectory = null; break; case SWITCH: // Reset of the current application directory causes problems during // switch and is not required in normal operation break; } // Reset of the unrestricted field causes problems during FEST tests } /** * @return A reference to where the configuration file should be located */ public static File getConfigurationFile() { return new File(getOrCreateApplicationDataDirectory().getAbsolutePath() + File.separator + MBHD_CONFIGURATION_FILE); } /** * <p>Get the directory for the user's application data, creating if not present</p> * <p>Checks a few OS-dependent locations first</p> * <p>For tests (unrestricted mode) this will create a long-lived temporary directory - use reset() to clear in the tearDown() phase</p> * * @return A suitable application directory for the OS and if running unit tests (unrestricted mode) */ public static File getOrCreateApplicationDataDirectory() { if (currentApplicationDataDirectory != null) { return currentApplicationDataDirectory; } if (unrestricted) { try { log.debug("Unrestricted mode requires a temporary application directory"); // In order to preserve the same behaviour between the test and production environments // this must be maintained throughout the lifetime of a unit test // At tearDown() use reset() to clear currentApplicationDataDirectory = SecureFiles.createTemporaryDirectory(); return currentApplicationDataDirectory; } catch (IOException e) { throw new IllegalStateException("Cannot run without access to temporary directory.", e); } } else { // Fail safe check for unit tests to avoid overwriting existing configuration file try { Class.forName("org.multibit.hd.core.managers.InstallationManagerTest"); throw new IllegalStateException("Cannot run without unrestricted when unit tests are present. You could overwrite live configuration."); } catch (ClassNotFoundException e) { // We have passed the fail safe check } } // Check the current working directory for the configuration file File multibitPropertiesFile = new File(MBHD_CONFIGURATION_FILE); if (multibitPropertiesFile.exists()) { return new File("."); } final String applicationDataDirectoryName; // Locations are OS-dependent if (OSUtils.isWindows()) { // Windows applicationDataDirectoryName = System.getenv("APPDATA") + File.separator + MBHD_APP_NAME; } else if (OSUtils.isMac()) { // OSX if ((new File("../../../../" + MBHD_CONFIGURATION_FILE)).exists()) { applicationDataDirectoryName = new File("../../../..").getAbsolutePath(); } else { applicationDataDirectoryName = System.getProperty("user.home") + "/Library/Application Support/" + MBHD_APP_NAME; } } else { // Other (probably a Unix variant) // Keep a clean home directory by prefixing with "." applicationDataDirectoryName = System.getProperty("user.home") + "/." + MBHD_APP_NAME; } log.debug("Application data directory is\n'{}'", applicationDataDirectoryName); // Create the application data directory if it does not exist File applicationDataDirectory = new File(applicationDataDirectoryName); SecureFiles.verifyOrCreateDirectory(applicationDataDirectory); // Must be OK to be here so set this as the current currentApplicationDataDirectory = applicationDataDirectory; return applicationDataDirectory; } /** * Copy the checkpoints file from the MultiBitHD installation to the specified filename * * @param destinationCheckpointsFile The sink to receive the source checkpoints file */ public static void copyCheckpointsTo(File destinationCheckpointsFile) throws IOException { Preconditions.checkNotNull(destinationCheckpointsFile, "'checkpointsFile' must be present"); // TODO overwrite if larger/ newer if (!destinationCheckpointsFile.exists() || destinationCheckpointsFile.length() == 0) { log.debug("Copying checkpoints to '{}'", destinationCheckpointsFile); // Work out the source checkpoints (put into the program installation directory by the installer) File currentWorkingDirectory = new File("."); File sourceBlockCheckpointsFile = new File(currentWorkingDirectory.getAbsolutePath() + File.separator + MBHD_PREFIX + CHECKPOINTS_SUFFIX); // Prepare an input stream to the checkpoints final InputStream sourceCheckpointsStream; if (sourceBlockCheckpointsFile.exists()) { // Use the file system log.debug("Using source checkpoints from working directory."); sourceCheckpointsStream = new FileInputStream(sourceBlockCheckpointsFile); } else { // Use the classpath log.debug("Using source checkpoints from classpath."); sourceCheckpointsStream = InstallationManager.class.getResourceAsStream("/mbhd.checkpoints"); } // Create the output stream long bytes; try (FileOutputStream sinkCheckpointsStream = new FileOutputStream(destinationCheckpointsFile)) { // Copy the checkpoints bytes = ByteStreams.copy(sourceCheckpointsStream, sinkCheckpointsStream); // Clean up sourceCheckpointsStream.close(); sinkCheckpointsStream.flush(); sinkCheckpointsStream.close(); } finally { if (sourceCheckpointsStream != null) { sourceCheckpointsStream.close(); } } log.debug("New checkpoints are {} bytes in length.", bytes); if (bytes < 13_000) { log.warn("Checkpoints are short."); } } else { log.debug("Checkpoints already exist."); } } /** * Use for testing only (several different test packages use this) * * @param currentApplicationDataDirectory the application data directory to use */ public static void setCurrentApplicationDataDirectory(File currentApplicationDataDirectory) { InstallationManager.currentApplicationDataDirectory = currentApplicationDataDirectory; } /** * Do the following, but with reflection to bypass access checks: * * JceSecurity.isRestricted = false; * JceSecurity.defaultPolicy.perms.clear(); * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE); */ public static void removeCryptographyRestrictions() { if (!isRestrictedCryptography()) { log.debug("Cryptography restrictions removal not needed"); return; } try { final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity"); final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions"); final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission"); final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted"); isRestrictedField.setAccessible(true); isRestrictedField.set(null, false); final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy"); defaultPolicyField.setAccessible(true); final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null); final Field perms = cryptoPermissions.getDeclaredField("perms"); perms.setAccessible(true); ((Map<?, ?>) perms.get(defaultPolicy)).clear(); final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE"); instance.setAccessible(true); defaultPolicy.add((Permission) instance.get(null)); log.debug("Successfully removed cryptography restrictions"); } catch (final Exception e) { log.warn("Failed to remove cryptography restrictions", e); } } private static boolean isRestrictedCryptography() { // This simply matches the Oracle JRE, but not OpenJDK return "Java(TM) SE Runtime Environment".equals(System.getProperty("java.runtime.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 ml.dmlc.tvm.android.demo; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.SystemClock; import android.provider.MediaStore; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import ml.dmlc.tvm.Function; import ml.dmlc.tvm.Module; import ml.dmlc.tvm.NDArray; import ml.dmlc.tvm.TVMContext; import ml.dmlc.tvm.TVMValue; import ml.dmlc.tvm.TVMType; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int PERMISSIONS_REQUEST = 100; private static final int PICTURE_FROM_GALLERY = 101; private static final int PICTURE_FROM_CAMERA = 102; private static final int IMAGE_PREVIEW_WIDTH = 960; private static final int IMAGE_PREVIEW_HEIGHT = 720; // TVM constants private static final int OUTPUT_INDEX = 0; private static final int IMG_CHANNEL = 3; private static final String INPUT_NAME = "data"; // Configuration values for extraction model. Note that the graph, lib and params is not // included with TVM and must be manually placed in the assets/ directory by the user. // Graphs and models downloaded from https://github.com/pjreddie/darknet/blob/ may be // converted e.g. via define_and_compile_model.py. private static final boolean EXE_GPU = false; private static final int MODEL_INPUT_SIZE = 224; private static final String MODEL_CL_LIB_FILE = "file:///android_asset/deploy_lib_opencl.so"; private static final String MODEL_CPU_LIB_FILE = "file:///android_asset/deploy_lib_cpu.so"; private static final String MODEL_GRAPH_FILE = "file:///android_asset/deploy_graph.json"; private static final String MODEL_PARAM_FILE = "file:///android_asset/deploy_param.params"; private static final String MODEL_LABEL_FILE = "file:///android_asset/imagenet.shortnames.list"; private Uri mCameraImageUri; private ImageView mImageView; private TextView mResultView; private AssetManager assetManager; private Module graphRuntimeModule; private Vector<String> labels = new Vector<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); assetManager = getAssets(); mImageView = (ImageView) findViewById(R.id.imageView); mResultView = (TextView) findViewById(R.id.resultTextView); findViewById(R.id.btnPickImage).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPictureDialog(); } }); if (hasPermission()) { // instantiate tvm runtime and setup environment on background after application begin new LoadModleAsyncTask().execute(); } else { requestPermission(); } } /* Load precompiled model on TVM graph runtime and init the system. */ private class LoadModleAsyncTask extends AsyncTask<Void, Void, Integer> { ProgressDialog dialog = new ProgressDialog(MainActivity.this); @Override protected Integer doInBackground(Void... args) { // load synset name String lableFilename = MODEL_LABEL_FILE.split("file:///android_asset/")[1]; Log.i(TAG, "Reading synset name from: " + lableFilename); try { String labelsContent = new String(getBytesFromFile(assetManager, lableFilename)); for (String line : labelsContent.split("\\r?\\n")) { labels.add(line); } } catch (IOException e) { Log.e(TAG, "Problem reading synset name file!" + e); return -1;//failure } // load json graph String modelGraph = null; String graphFilename = MODEL_GRAPH_FILE.split("file:///android_asset/")[1]; Log.i(TAG, "Reading json graph from: " + graphFilename); try { modelGraph = new String(getBytesFromFile(assetManager, graphFilename)); } catch (IOException e) { Log.e(TAG, "Problem reading json graph file!" + e); return -1;//failure } // upload tvm compiled function on application cache folder String libCacheFilePath = null; String libFilename = EXE_GPU ? MODEL_CL_LIB_FILE.split("file:///android_asset/")[1] : MODEL_CPU_LIB_FILE.split("file:///android_asset/")[1]; Log.i(TAG, "Uploading compiled function to cache folder"); try { libCacheFilePath = getTempLibFilePath(libFilename); byte[] modelLibByte = getBytesFromFile(assetManager, libFilename); FileOutputStream fos = new FileOutputStream(libCacheFilePath); fos.write(modelLibByte); fos.close(); } catch (IOException e) { Log.e(TAG, "Problem uploading compiled function!" + e); return -1;//failure } // load parameters byte[] modelParams = null; String paramFilename = MODEL_PARAM_FILE.split("file:///android_asset/")[1]; try { modelParams = getBytesFromFile(assetManager, paramFilename); } catch (IOException e) { Log.e(TAG, "Problem reading params file!" + e); return -1;//failure } // create java tvm context TVMContext tvmCtx = EXE_GPU ? TVMContext.opencl() : TVMContext.cpu(); // tvm module for compiled functions Module modelLib = Module.load(libCacheFilePath); // get global function module for graph runtime Function runtimeCreFun = Function.getFunction("tvm.graph_runtime.create"); TVMValue runtimeCreFunRes = runtimeCreFun.pushArg(modelGraph) .pushArg(modelLib) .pushArg(tvmCtx.deviceType) .pushArg(tvmCtx.deviceId) .invoke(); graphRuntimeModule = runtimeCreFunRes.asModule(); // get the function from the module(load parameters) Function loadParamFunc = graphRuntimeModule.getFunction("load_params"); loadParamFunc.pushArg(modelParams).invoke(); // release tvm local variables modelLib.release(); loadParamFunc.release(); runtimeCreFun.release(); return 0;//success } @Override protected void onPreExecute() { dialog.setCancelable(false); dialog.setMessage("Loading Model..."); dialog.show(); super.onPreExecute(); } @Override protected void onPostExecute(Integer status) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } if (status != 0) { showDialog("Error", "Fail to initialized model, check compiled model"); } } } /* Execute prediction for processed decode input bitmap image content on TVM graph runtime. */ private class ModelRunAsyncTask extends AsyncTask<Bitmap, Void, Integer> { ProgressDialog dialog = new ProgressDialog(MainActivity.this); @Override protected Integer doInBackground(Bitmap... bitmaps) { if (null != graphRuntimeModule) { int count = bitmaps.length; for (int i = 0 ; i < count ; i++) { long processingTimeMs = SystemClock.uptimeMillis(); Log.i(TAG, "Decode JPEG image content"); // extract the jpeg content ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmaps[i].compress(Bitmap.CompressFormat.JPEG,100,stream); byte[] byteArray = stream.toByteArray(); Bitmap imageBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); // crop input image at centre to model input size // commecial deploy note:: instead of cropying image do resize // image to model input size so we never lost the image content Bitmap cropImageBitmap = Bitmap.createBitmap(MODEL_INPUT_SIZE, MODEL_INPUT_SIZE, Bitmap.Config.ARGB_8888); Matrix frameToCropTransform = getTransformationMatrix(imageBitmap.getWidth(), imageBitmap.getHeight(), MODEL_INPUT_SIZE, MODEL_INPUT_SIZE, 0, true); Canvas canvas = new Canvas(cropImageBitmap); canvas.drawBitmap(imageBitmap, frameToCropTransform, null); // image pixel int values int[] pixelValues = new int[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE]; // image RGB float values float[] imgRgbValues = new float[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * IMG_CHANNEL]; // image RGB transpose float values float[] imgRgbTranValues = new float[MODEL_INPUT_SIZE * MODEL_INPUT_SIZE * IMG_CHANNEL]; // pre-process the image data from 0-255 int to normalized float based on the // provided parameters. cropImageBitmap.getPixels(pixelValues, 0, MODEL_INPUT_SIZE, 0, 0, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE); for (int j = 0; j < pixelValues.length; ++j) { imgRgbValues[j * 3 + 0] = ((pixelValues[j] >> 16) & 0xFF)/255.0f; imgRgbValues[j * 3 + 1] = ((pixelValues[j] >> 8) & 0xFF)/255.0f; imgRgbValues[j * 3 + 2] = (pixelValues[j] & 0xFF)/255.0f; } // pre-process the image rgb data transpose based on the provided parameters. for (int k = 0; k < IMG_CHANNEL; ++k) { for (int l = 0; l < MODEL_INPUT_SIZE; ++l) { for (int m = 0; m < MODEL_INPUT_SIZE; ++m) { int dst_index = m + MODEL_INPUT_SIZE*l + MODEL_INPUT_SIZE*MODEL_INPUT_SIZE*k; int src_index = k + IMG_CHANNEL*m + IMG_CHANNEL*MODEL_INPUT_SIZE*l; imgRgbTranValues[dst_index] = imgRgbValues[src_index]; } } } // get the function from the module(set input data) Log.i(TAG, "set input data"); NDArray inputNdArray = NDArray.empty(new long[]{1, IMG_CHANNEL, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE}, new TVMType("float32"));; inputNdArray.copyFrom(imgRgbTranValues); Function setInputFunc = graphRuntimeModule.getFunction("set_input"); setInputFunc.pushArg(INPUT_NAME).pushArg(inputNdArray).invoke(); // release tvm local variables inputNdArray.release(); setInputFunc.release(); // get the function from the module(run it) Log.i(TAG, "run function on target"); Function runFunc = graphRuntimeModule.getFunction("run"); runFunc.invoke(); // release tvm local variables runFunc.release(); // get the function from the module(get output data) Log.i(TAG, "get output data"); NDArray outputNdArray = NDArray.empty(new long[]{1000}, new TVMType("float32")); Function getOutputFunc = graphRuntimeModule.getFunction("get_output"); getOutputFunc.pushArg(OUTPUT_INDEX).pushArg(outputNdArray).invoke(); float[] output = outputNdArray.asFloatArray(); // release tvm local variables outputNdArray.release(); getOutputFunc.release(); // display the result from extracted output data if (null != output) { int maxPosition = -1; float maxValue = 0; for (int j = 0; j < output.length; ++j) { if (output[j] > maxValue) { maxValue = output[j]; maxPosition = j; } } processingTimeMs = SystemClock.uptimeMillis() - processingTimeMs; String label = "Prediction Result : "; label += labels.size() > maxPosition ? labels.get(maxPosition) : "unknown"; label += "\nPrediction Time : " + processingTimeMs + "ms"; mResultView.setText(label); } Log.i(TAG, "prediction finished"); } return 0; } return -1; } @Override protected void onPreExecute() { dialog.setCancelable(false); dialog.setMessage("Prediction running on image..."); dialog.show(); super.onPreExecute(); } @Override protected void onPostExecute(Integer status) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } if (status != 0) { showDialog("Error", "Fail to predict image, GraphRuntime exception"); } } } @Override protected void onDestroy() { // release tvm local variables if (null != graphRuntimeModule) graphRuntimeModule.release(); super.onDestroy(); } /** * Read file from assets and return byte array. * * @param assets The asset manager to be used to load assets. * @param fileName The filepath of read file. * @return byte[] file content * @throws IOException */ private byte[] getBytesFromFile(AssetManager assets, String fileName) throws IOException { InputStream is = assets.open(fileName); int length = is.available(); byte[] bytes = new byte[length]; // Read in the bytes int offset = 0; int numRead = 0; try { while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } } finally { is.close(); } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file " + fileName); } return bytes; } /** * Dialog show pick option for select image from Gallery or Camera. */ private void showPictureDialog(){ AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this); pictureDialog.setTitle("Select Action"); String[] pictureDialogItems = { "Select photo from gallery", "Capture photo from camera" }; pictureDialog.setItems(pictureDialogItems, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: choosePhotoFromGallery(); break; case 1: takePhotoFromCamera(); break; } } }); pictureDialog.show(); } /** * Request to pick image from Gallery. */ public void choosePhotoFromGallery() { Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent, PICTURE_FROM_GALLERY); } /** * Request to capture image from Camera. */ private void takePhotoFromCamera() { Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { mCameraImageUri = Uri.fromFile(createImageFile()); } else { File file = new File(createImageFile().getPath()); mCameraImageUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", file); } intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraImageUri); startActivityForResult(intent, PICTURE_FROM_CAMERA); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == this.RESULT_CANCELED) { return; } Uri contentURI = null; if (requestCode == PICTURE_FROM_GALLERY) { if (data != null) { contentURI = data.getData(); } } else if (requestCode == PICTURE_FROM_CAMERA) { contentURI = mCameraImageUri; } if (null != contentURI) { try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI); Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_PREVIEW_HEIGHT, IMAGE_PREVIEW_WIDTH, true); mImageView.setImageBitmap(scaled); new ModelRunAsyncTask().execute(scaled); } catch (IOException e) { e.printStackTrace(); } } } /** * Get application cache path where to place compiled functions. * * @param fileName library file name. * @return String application cache folder path * @throws IOException */ private final String getTempLibFilePath(String fileName) throws IOException { File tempDir = File.createTempFile("tvm4j_demo_", ""); if (!tempDir.delete() || !tempDir.mkdir()) { throw new IOException("Couldn't create directory " + tempDir.getAbsolutePath()); } return (tempDir + File.separator + fileName); } /** * Create image file under storage where camera application save captured image. * * @return File image file under sdcard where camera can save image */ private File createImageFile() { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); try { File image = File.createTempFile( imageFileName, // prefix ".jpg", // suffix storageDir // directory ); return image; } catch (IOException e) { e.printStackTrace(); } return null; } /** * Show dialog to user. * * @param title dialog display title * @param msg dialog display message */ private void showDialog(String title, String msg) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(title); builder.setMessage(msg); builder.setCancelable(true); builder.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); finish(); } }); builder.create().show(); } @Override public void onRequestPermissionsResult (final int requestCode, final String[] permissions, final int[] grantResults){ if (requestCode == PERMISSIONS_REQUEST) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { // instantiate tvm runtime and setup environment on background after application begin new LoadModleAsyncTask().execute(); } else { requestPermission(); } } } /** * Whether application has required mandatory permissions to run. */ private boolean hasPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; } else { return true; } } /** * Request required mandatory permission for application to run. */ private void requestPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) || shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Toast.makeText(this, "Camera AND storage permission are required for this demo", Toast.LENGTH_LONG).show(); } requestPermissions(new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST); } } /** * Returns a transformation matrix from one reference frame into another. * Handles cropping (if maintaining aspect ratio is desired) and rotation. * * @param srcWidth Width of source frame. * @param srcHeight Height of source frame. * @param dstWidth Width of destination frame. * @param dstHeight Height of destination frame. * @param applyRotation Amount of rotation to apply from one frame to another. * Must be a multiple of 90. * @param maintainAspectRatio If true, will ensure that scaling in x and y remains constant, * cropping the image if necessary. * @return The transformation fulfilling the desired requirements. */ public static Matrix getTransformationMatrix( final int srcWidth, final int srcHeight, final int dstWidth, final int dstHeight, final int applyRotation, final boolean maintainAspectRatio) { final Matrix matrix = new Matrix(); if (applyRotation != 0) { if (applyRotation % 90 != 0) { Log.w(TAG, "Rotation of %d % 90 != 0 " + applyRotation); } // Translate so center of image is at origin. matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f); // Rotate around origin. matrix.postRotate(applyRotation); } // Account for the already applied rotation, if any, and then determine how // much scaling is needed for each axis. final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0; final int inWidth = transpose ? srcHeight : srcWidth; final int inHeight = transpose ? srcWidth : srcHeight; // Apply scaling if necessary. if (inWidth != dstWidth || inHeight != dstHeight) { final float scaleFactorX = dstWidth / (float) inWidth; final float scaleFactorY = dstHeight / (float) inHeight; if (maintainAspectRatio) { // Scale by minimum factor so that dst is filled completely while // maintaining the aspect ratio. Some image may fall off the edge. final float scaleFactor = Math.max(scaleFactorX, scaleFactorY); matrix.postScale(scaleFactor, scaleFactor); } else { // Scale exactly to fill dst from src. matrix.postScale(scaleFactorX, scaleFactorY); } } if (applyRotation != 0) { // Translate back from origin centered reference to destination frame. matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f); } return matrix; } }
/* * Copyright 2017 ThoughtWorks, 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.thoughtworks.go.server; import com.thoughtworks.go.util.ReflectionUtil; import com.thoughtworks.go.util.SystemEnvironment; import org.apache.commons.io.FileUtils; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.*; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.webapp.JettyWebXmlConfiguration; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.webapp.WebInfConfiguration; import org.eclipse.jetty.webapp.WebXmlConfiguration; import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import javax.net.ssl.SSLSocketFactory; import javax.servlet.SessionCookieConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class Jetty9ServerTest { private Jetty9Server jetty9Server; private Server server; private SystemEnvironment systemEnvironment; @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private File configDir; @Before public void setUp() throws Exception { server = mock(Server.class); Answer<Void> setHandlerMock = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Handler handler = (Handler) invocation.getArguments()[0]; handler.setServer((Server) invocation.getMock()); return null; } }; Mockito.doAnswer(setHandlerMock).when(server).setHandler(any(Handler.class)); systemEnvironment = mock(SystemEnvironment.class); when(systemEnvironment.getServerPort()).thenReturn(1234); when(systemEnvironment.keystore()).thenReturn(temporaryFolder.newFolder()); when(systemEnvironment.truststore()).thenReturn(temporaryFolder.newFolder()); when(systemEnvironment.getWebappContextPath()).thenReturn("context"); when(systemEnvironment.getCruiseWar()).thenReturn("cruise.war"); when(systemEnvironment.getParentLoaderPriority()).thenReturn(true); when(systemEnvironment.useCompressedJs()).thenReturn(true); when(systemEnvironment.get(SystemEnvironment.RESPONSE_BUFFER_SIZE)).thenReturn(1000); when(systemEnvironment.get(SystemEnvironment.IDLE_TIMEOUT)).thenReturn(2000); when(systemEnvironment.configDir()).thenReturn(configDir = temporaryFolder.newFile()); when(systemEnvironment.get(SystemEnvironment.GO_SSL_CONFIG_ALLOW)).thenReturn(true); when(systemEnvironment.get(SystemEnvironment.GO_SSL_RENEGOTIATION_ALLOWED)).thenReturn(true); when(systemEnvironment.getJettyConfigFile()).thenReturn(new File("foo")); when(systemEnvironment.isSessionCookieSecure()).thenReturn(false); when(systemEnvironment.sessionTimeoutInSeconds()).thenReturn(1234); when(systemEnvironment.sessionCookieMaxAgeInSeconds()).thenReturn(5678); SSLSocketFactory sslSocketFactory = mock(SSLSocketFactory.class); when(sslSocketFactory.getSupportedCipherSuites()).thenReturn(new String[]{}); jetty9Server = new Jetty9Server(systemEnvironment, "pwd", sslSocketFactory, server); ReflectionUtil.setStaticField(Jetty9Server.class, "JETTY_XML_LOCATION_IN_JAR", "config"); } @Test public void shouldAddMBeanContainerAsEventListener() throws Exception { ArgumentCaptor<MBeanContainer> captor = ArgumentCaptor.forClass(MBeanContainer.class); jetty9Server.configure(); verify(server).addEventListener(captor.capture()); MBeanContainer mBeanContainer = captor.getValue(); assertThat(mBeanContainer.getMBeanServer(), is(not(nullValue()))); } @Test public void shouldAddHttpSocketConnector() throws Exception { ArgumentCaptor<Connector> captor = ArgumentCaptor.forClass(Connector.class); jetty9Server.configure(); verify(server, times(2)).addConnector(captor.capture()); List<Connector> connectors = captor.getAllValues(); Connector plainConnector = connectors.get(0); assertThat(plainConnector instanceof ServerConnector, is(true)); ServerConnector connector = (ServerConnector) plainConnector; assertThat(connector.getServer(), is(server)); assertThat(connector.getConnectionFactories().size(), is(1)); ConnectionFactory connectionFactory = connector.getConnectionFactories().iterator().next(); assertThat(connectionFactory instanceof HttpConnectionFactory, is(true)); } @Test public void shouldAddSSLSocketConnector() throws Exception { ArgumentCaptor<Connector> captor = ArgumentCaptor.forClass(Connector.class); jetty9Server.configure(); verify(server, times(2)).addConnector(captor.capture()); List<Connector> connectors = captor.getAllValues(); Connector sslConnector = connectors.get(1); assertThat(sslConnector instanceof ServerConnector, is(true)); ServerConnector connector = (ServerConnector) sslConnector; assertThat(connector.getServer(), is(server)); assertThat(connector.getConnectionFactories().size(), is(2)); Iterator<ConnectionFactory> iterator = connector.getConnectionFactories().iterator(); ConnectionFactory first = iterator.next(); ConnectionFactory second = iterator.next(); assertThat(first instanceof SslConnectionFactory, is(true)); SslConnectionFactory sslConnectionFactory = (SslConnectionFactory) first; assertThat(sslConnectionFactory.getProtocol(), is("SSL-HTTP/1.1")); assertThat(second instanceof HttpConnectionFactory, is(true)); } @Test public void shouldAddWelcomeRequestHandler() throws Exception { ArgumentCaptor<HandlerCollection> captor = ArgumentCaptor.forClass(HandlerCollection.class); jetty9Server.configure(); verify(server, times(1)).setHandler(captor.capture()); HandlerCollection handlerCollection = captor.getValue(); assertThat(handlerCollection.getHandlers().length, is(3)); Handler handler = handlerCollection.getHandlers()[0]; assertThat(handler instanceof Jetty9Server.GoServerWelcomeFileHandler, is(true)); Jetty9Server.GoServerWelcomeFileHandler welcomeFileHandler = (Jetty9Server.GoServerWelcomeFileHandler) handler; assertThat(welcomeFileHandler.getContextPath(), is("/")); } @Test public void shouldAddDefaultHeadersForRootContext() throws Exception { ArgumentCaptor<HandlerCollection> captor = ArgumentCaptor.forClass(HandlerCollection.class); jetty9Server.configure(); verify(server, times(1)).setHandler(captor.capture()); HandlerCollection handlerCollection = captor.getValue(); Jetty9Server.GoServerWelcomeFileHandler handler = (Jetty9Server.GoServerWelcomeFileHandler)handlerCollection.getHandlers()[0]; Handler rootPathHandler = handler.getHandler(); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(mock(PrintWriter.class)); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getPathInfo()).thenReturn("/"); rootPathHandler.handle("/", mock(Request.class), request, response); verify(response).setHeader("X-XSS-Protection", "1; mode=block"); verify(response).setHeader("X-Content-Type-Options", "nosniff"); verify(response).setHeader("X-Frame-Options", "SAMEORIGIN"); verify(response).setHeader("X-UA-Compatible", "chrome=1"); } @Test public void shouldSkipDefaultHeadersIfContextPathIsGoRootPath() throws Exception { ArgumentCaptor<HandlerCollection> captor = ArgumentCaptor.forClass(HandlerCollection.class); jetty9Server.configure(); verify(server, times(1)).setHandler(captor.capture()); HandlerCollection handlerCollection = captor.getValue(); Jetty9Server.GoServerWelcomeFileHandler handler = (Jetty9Server.GoServerWelcomeFileHandler)handlerCollection.getHandlers()[0]; Handler rootPathHandler = handler.getHandler(); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(mock(PrintWriter.class)); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getPathInfo()).thenReturn("/go"); rootPathHandler.handle("/go", mock(Request.class), request, response); verify(response, never()).setHeader("X-XSS-Protection", "1; mode=block"); verify(response, never()).setHeader("X-Content-Type-Options", "nosniff"); verify(response, never()).setHeader("X-Frame-Options", "SAMEORIGIN"); verify(response, never()).setHeader("X-UA-Compatible", "chrome=1"); } @Test public void shouldSkipDefaultHeadersIfContextPathIsAnyOtherUrlWithinGo() throws Exception { ArgumentCaptor<HandlerCollection> captor = ArgumentCaptor.forClass(HandlerCollection.class); jetty9Server.configure(); verify(server, times(1)).setHandler(captor.capture()); HandlerCollection handlerCollection = captor.getValue(); Jetty9Server.GoServerWelcomeFileHandler handler = (Jetty9Server.GoServerWelcomeFileHandler)handlerCollection.getHandlers()[0]; Handler rootPathHandler = handler.getHandler(); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(mock(PrintWriter.class)); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getPathInfo()).thenReturn("/go/pipelines"); rootPathHandler.handle("/go/pipelines", mock(Request.class), request, response); verify(response, never()).setHeader("X-XSS-Protection", "1; mode=block"); verify(response, never()).setHeader("X-Content-Type-Options", "nosniff"); verify(response, never()).setHeader("X-Frame-Options", "SAMEORIGIN"); verify(response, never()).setHeader("X-UA-Compatible", "chrome=1"); } @Test public void shouldAddResourceHandlerForAssets() throws Exception { ArgumentCaptor<HandlerCollection> captor = ArgumentCaptor.forClass(HandlerCollection.class); jetty9Server.configure(); verify(server, times(1)).setHandler(captor.capture()); HandlerCollection handlerCollection = captor.getValue(); assertThat(handlerCollection.getHandlers().length, is(3)); Handler handler = handlerCollection.getHandlers()[1]; assertThat(handler instanceof AssetsContextHandler, is(true)); AssetsContextHandler assetsContextHandler = (AssetsContextHandler) handler; assertThat(assetsContextHandler.getContextPath(), is("context/assets")); } @Test public void shouldAddWebAppContextHandler() throws Exception { ArgumentCaptor<HandlerCollection> captor = ArgumentCaptor.forClass(HandlerCollection.class); jetty9Server.configure(); verify(server, times(1)).setHandler(captor.capture()); HandlerCollection handlerCollection = captor.getValue(); assertThat(handlerCollection.getHandlers().length, is(3)); Handler handler = handlerCollection.getHandlers()[2]; assertThat(handler instanceof WebAppContext, is(true)); WebAppContext webAppContext = (WebAppContext) handler; List<String> configClasses = new ArrayList<>(Arrays.asList(webAppContext.getConfigurationClasses())); assertThat(configClasses.contains(WebInfConfiguration.class.getCanonicalName()), is(true)); assertThat(configClasses.contains(WebXmlConfiguration.class.getCanonicalName()), is(true)); assertThat(configClasses.contains(JettyWebXmlConfiguration.class.getCanonicalName()), is(true)); assertThat(webAppContext.getContextPath(), is("context")); assertThat(webAppContext.getWar(), is("cruise.war")); assertThat(webAppContext.isParentLoaderPriority(), is(true)); assertThat(webAppContext.getDefaultsDescriptor(), is("jar:file:cruise.war!/WEB-INF/webdefault.xml")); } @Test public void shouldSetStopAtShutdown() throws Exception { jetty9Server.configure(); verify(server).setStopAtShutdown(true); } @Test public void shouldSetSessionMaxInactiveInterval() throws Exception { jetty9Server.configure(); jetty9Server.setSessionConfig(); WebAppContext webAppContext = getWebAppContext(jetty9Server); assertThat(webAppContext.getSessionHandler().getSessionManager().getMaxInactiveInterval(), is(1234)); } @Test public void shouldSetSessionCookieConfig() throws Exception { when(systemEnvironment.isSessionCookieSecure()).thenReturn(true); jetty9Server.configure(); jetty9Server.setSessionConfig(); WebAppContext webAppContext = getWebAppContext(jetty9Server); SessionCookieConfig sessionCookieConfig = webAppContext.getSessionHandler().getSessionManager().getSessionCookieConfig(); assertThat(sessionCookieConfig.isHttpOnly(), is(true)); assertThat(sessionCookieConfig.isSecure(), is(true)); assertThat(sessionCookieConfig.getMaxAge(), is(5678)); when(systemEnvironment.isSessionCookieSecure()).thenReturn(false); jetty9Server.setSessionConfig(); assertThat(sessionCookieConfig.isSecure(), is(false)); } @Test public void shouldAddExtraJarsIntoClassPath() throws Exception { jetty9Server.configure(); jetty9Server.addExtraJarsToClasspath("test-addons/some-addon-dir/addon-1.JAR,test-addons/some-addon-dir/addon-2.jar"); assertThat(getWebAppContext(jetty9Server).getExtraClasspath(), is("test-addons/some-addon-dir/addon-1.JAR,test-addons/some-addon-dir/addon-2.jar," + configDir)); } @Test public void shouldSetInitParams() throws Exception { jetty9Server.configure(); jetty9Server.setInitParameter("name", "value"); assertThat(getWebAppContext(jetty9Server).getInitParameter("name"), CoreMatchers.is("value")); } @Test public void shouldReplaceJettyXmlIfItDoesNotContainCorrespondingJettyVersionNumber() throws IOException { File jettyXml = temporaryFolder.newFile("jetty.xml"); when(systemEnvironment.getJettyConfigFile()).thenReturn(jettyXml); String originalContent = "jetty-v6.2.3\nsome other local changes"; FileUtils.writeStringToFile(jettyXml, originalContent, UTF_8); jetty9Server.replaceJettyXmlIfItBelongsToADifferentVersion(systemEnvironment.getJettyConfigFile()); assertThat(FileUtils.readFileToString(systemEnvironment.getJettyConfigFile(), UTF_8), is(FileUtils.readFileToString(new File(getClass().getResource("config/jetty.xml").getPath()), UTF_8))); } @Test public void shouldNotReplaceJettyXmlIfItAlreadyContainsCorrespondingVersionNumber() throws IOException { File jettyXml = temporaryFolder.newFile("jetty.xml"); when(systemEnvironment.getJettyConfigFile()).thenReturn(jettyXml); String originalContent = "jetty-v9.2.3\nsome other local changes"; FileUtils.writeStringToFile(jettyXml, originalContent, UTF_8); jetty9Server.replaceJettyXmlIfItBelongsToADifferentVersion(systemEnvironment.getJettyConfigFile()); assertThat(FileUtils.readFileToString(systemEnvironment.getJettyConfigFile(), UTF_8), is(originalContent)); } @Test public void shouldSetErrorHandlerForServer() throws Exception { jetty9Server.configure(); verify(server).addBean(any(JettyCustomErrorPageHandler.class)); } @Test public void shouldSetErrorHandlerForWebAppContext() throws Exception { ArgumentCaptor<HandlerCollection> captor = ArgumentCaptor.forClass(HandlerCollection.class); jetty9Server.configure(); verify(server, times(1)).setHandler(captor.capture()); HandlerCollection handlerCollection = captor.getValue(); assertThat(handlerCollection.getHandlers().length, is(3)); Handler handler = handlerCollection.getHandlers()[2]; assertThat(handler instanceof WebAppContext, is(true)); WebAppContext webAppContext = (WebAppContext) handler; assertThat(webAppContext.getErrorHandler() instanceof JettyCustomErrorPageHandler, is(true)); } private WebAppContext getWebAppContext(Jetty9Server server) { return (WebAppContext) ReflectionUtil.getField(server, "webAppContext"); } }
package eu.medsea.mimeutil.detector; import java.io.BufferedReader; import java.io.DataInput; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.arondor.common.io.RandomAccessInterface; import eu.medsea.mimeutil.DetectionStrategy; import eu.medsea.mimeutil.MimeUtil; // import eu.medsea.mimeutil.detector.eclipse.MimeTypeDetectorExtensionPointProcessor; /** * This registry manages plug-ins for detecting mime-types. To implement your own mime-type-detector, * you have to do the following: * <ul> * <li>Subclass {@link AbstractMimeTypeDetector}.</li> * <li>Subclass {@link AbstractMimeTypeDetector}.</li> * <li>Register your -implementation. You can do this in 3 ways: * <ul> * <li>When using an Eclipse runtime, specify an extension to the extension-point * "eu.medsea.mimeutil.mimeTypeDetector". * </li> * <li>When you're not in an Eclipse environment (i.e. the bundle <code>org.eclipse.core.runtime</code> isn't there), * you can create a file named <code>MimeTypeDetector.csv</code> and place it in the root of your JAR (no package). * See the file <code>eu/medsea/mimeutil/detector/MimeTypeDetector.csv</code> for an example and for more details * about this file. * Note, that due to separated class-loaders, your CSV files won't usually be found in an OSGi-container! If your OSGi-container * supports buddy-class-loading, you can register a buddy to this bundle (put "Eclipse-RegisterBuddy: eu.medsea.mimeutil" * into your <code>MANIFEST.MF</code>) to get the CSV-based extension working. * </li> * </ul> * </li> * </ul> * * @author marco schulze - marco at nightlabs dot de */ public class MimeTypeDetectorRegistry { private static Log log = LogFactory.getLog(MimeTypeDetectorRegistry.class); private static MimeTypeDetectorRegistry sharedInstance; public static MimeTypeDetectorRegistry sharedInstance() { if (sharedInstance == null) { sharedInstance = new MimeTypeDetectorRegistry(); } return sharedInstance; } protected MimeTypeDetectorRegistry() { loadCSVRegistrations(); loadExtensionsForExtensionPoint(); } private void loadExtensionsForExtensionPoint() { try { // new MimeTypeDetectorExtensionPointProcessor().process(); } catch (NoClassDefFoundError x) { // ignore - obviously org.eclipse.core.runtime isn't there } catch (Throwable x) { log.error("loadExtensionsForExtensionPoint: " + x.getClass().getName() + ": " + x.getMessage(), x); } } private void loadCSVRegistrations() { String fileName = "MimeTypeDetector.csv"; loadCSVRegistration(MimeTypeDetectorRegistry.class.getResource(fileName)); try { // Trying to avoid generating a NPE if (MimeTypeDetectorRegistry.class.getClassLoader() != null) { Enumeration<URL> urlEnumeration = MimeTypeDetectorRegistry.class.getClassLoader().getResources(fileName); if (urlEnumeration != null) { while (urlEnumeration.hasMoreElements()) { URL url = urlEnumeration.nextElement(); loadCSVRegistration(url); } } } else { log.error("Unable to get classLoader from classpath."); } } catch (Throwable x) { log.error("loadCSVRegistrations: " + x.getClass().getName() + ": " + x.getMessage(), x); } } private void loadCSVRegistration(URL url) { if (url == null) return; int lineNo = -1; try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); try { String line; lineNo = 0; while (null != (line = reader.readLine())) { ++lineNo; line = line.trim(); if (line.isEmpty() || line.startsWith("#")) continue; String[] fields = line.split("\t"); if (fields.length < 1) throw new IllegalStateException("No field at all?! Shouldn't have line.isEmpty() returned true?!!!"); try { String className = fields[0].trim(); String detectorID = fields.length > 1 ? fields[1].trim() : className; String orderHintStr = fields.length > 2 ? fields[2].trim() : String.valueOf(7000); Class clazz = Class.forName(className); int orderHint = Integer.parseInt(orderHintStr); MimeTypeDetector mimeTypeDetector = (MimeTypeDetector) clazz.newInstance(); mimeTypeDetector.setDetectorID(detectorID); mimeTypeDetector.setOrderHint(orderHint); addMimeTypeDetector(mimeTypeDetector); } catch (Throwable x) { log.error("loadCSVRegistration(" + url + ", lineNo " + lineNo + "): " + x.getClass().getName() + ": " + x.getMessage(), x); } } } finally { reader.close(); } } catch (Throwable x) { log.error("loadCSVRegistration(" + url + ", lineNo " + lineNo + "): " + x.getClass().getName() + ": " + x.getMessage(), x); } } /** * Keeps instances of {@link String} as key and {@link MimeTypeDetector} as value. * <p> * As soon as this registry is instantiated, this Map is populated. It might be additionally * be populated from the outside via. * </p> */ private Map detectorID2detector = new HashMap(); private volatile List detectorSortedCache = null; private SortedSet detectorSorted = new TreeSet(new Comparator() { public int compare(Object o0, Object o1) { if (o0 == null) return -1; if (o1 == null) return 1; MimeTypeDetector d0 = (MimeTypeDetector) o0; MimeTypeDetector d1 = (MimeTypeDetector) o1; if (d0.getOrderHint() < d1.getOrderHint()) return -1; else if (d0.getOrderHint() > d1.getOrderHint()) return 1; else return d0.getDetectorID().compareTo(d1.getDetectorID()); } }); public synchronized void addMimeTypeDetector(MimeTypeDetector mimeTypeDetector) { if (mimeTypeDetector.getDetectorID() == null || mimeTypeDetector.getDetectorID().isEmpty()) throw new IllegalArgumentException("mimeTypeDetector.getDetectorID() returned null or an empty String!"); removeMimeTypeDetector(mimeTypeDetector); detectorID2detector.put(mimeTypeDetector.getDetectorID(), mimeTypeDetector); detectorSorted.add(mimeTypeDetector); detectorSortedCache = null; } public synchronized void removeMimeTypeDetector(MimeTypeDetector mimeTypeDetector) { String detectorID = mimeTypeDetector.getDetectorID(); MimeTypeDetector removed = (MimeTypeDetector) detectorID2detector.remove(detectorID); detectorSorted.remove(removed); detectorSortedCache = null; } public List getMimeTypeDetectors() { List result = detectorSortedCache; if (result == null) { synchronized (this) { result = detectorSortedCache; if (result == null) { // DCL = double checked locking result = Collections.unmodifiableList(new ArrayList(detectorSorted)); detectorSortedCache = result; } } } return result; } /** * Try to determine the mime type(s) from the file name or the contents read from the {@link InputStream} * (magic numbers). * * @param inputStream <code>null</code> or the stream to read the data from. It must support <code>mark</code> &amp; <code>reset</code> (see {@link InputStream#markSupported()}. * @param fileName <code>null</code> or the simple name of the file (no path!). * @param detectionStrategy how to proceed detection. If the detect strategy is not supported by your implementation or * it does not match the data specified (e.g. <code>randomAccessFile</code> is <code>null</code> but the strategy * is {@link DetectionStrategy#ONLY_CONTENT}) you should silently return and skip your checks. * @return a collection into which you can add the mime types your implementation detected. It is also * possible to remove elements that another <code>MimeTypeDetector</code> implementation added before (if you can be * sure this result was wrong) and it is possible to take the previously detected mime-types into account for your own * check (for example, skip the check if a certain type is not in there). */ public DetectedMimeTypeSet detectMimeTypes(InputStream inputStream, String fileName, DetectionStrategy detectionStrategy) { return detectMimeTypes(null, inputStream, fileName, detectionStrategy); } private DetectedMimeTypeSet detectMimeTypes(RandomAccessInterface randomAccessFile, InputStream inputStream, String fileName, DetectionStrategy detectionStrategy) { if (DetectionStrategy.ONLY_CONTENT == detectionStrategy) fileName = null; if (DetectionStrategy.ONLY_FILE_NAME == detectionStrategy) { randomAccessFile = null; inputStream = null; } DetectionContext detectionContext; if (inputStream != null) detectionContext = new DetectionContext(inputStream, fileName, detectionStrategy); else detectionContext = new DetectionContext(randomAccessFile, fileName, detectionStrategy); Collection detectors = getMimeTypeDetectors(); for (Iterator it = detectors.iterator(); it.hasNext(); ) { MimeTypeDetector detector = (MimeTypeDetector) it.next(); // @Steve: call MimeTypeDetectorInterceptor.preDetectMimeTypes(...) here? Marco. detector.detectMimeTypes(detectionContext); // @Steve: call MimeTypeDetectorInterceptor.postDetectMimeTypes(...) here? Marco. // @Steve: check a property like detectionContext.isDetectionAborted() here and break the loop??? Marco. } DetectedMimeTypeSet detectedMimeTypeSet = detectionContext.getDetectedMimeTypeSet(); // The magic implementation currently returns MimeUtil.UNKNOWN_MIME_TYPE, which we don't really want // (the new policy is simply not to populate the DetectedMimeTypeSet). Hence, we filter it out. // I just checked and it seems this actually never happens (because we use other methods that return // List instances rather than a single String). // Still I think we should leave this code here (it's fast and guarantees we never have the // UNKNOWN_MIME_TYPE in the result - even if future extensions return it). Marco. Collection c = detectedMimeTypeSet.getDetectedMimeTypes(MimeUtil.UNKNOWN_MIME_TYPE); if (!c.isEmpty()) { for (Iterator iterator = new ArrayList(c).iterator(); iterator.hasNext(); ) { DetectedMimeType detectedMimeType = (DetectedMimeType) iterator.next(); detectedMimeTypeSet.removeDetectedMimeType(detectedMimeType); } } return detectedMimeTypeSet; } /** * Try to determine the mime type(s) from the file name or the contents of the file (magic numbers). * * @param file <code>null</code> or the file to read the data from. * @param fileName <code>null</code> or the simple name of the file (no path!). * @param detectionStrategy how to proceed detection. If the detect strategy is not supported by your implementation or * it does not match the data specified (e.g. <code>randomAccessFile</code> is <code>null</code> but the strategy * is {@link DetectionStrategy#ONLY_CONTENT}) you should silently return and skip your checks. * @return a collection into which you can add the mime types your implementation detected. It is also * possible to remove elements that another <code>MimeTypeDetector</code> implementation added before (if you can be * sure this result was wrong) and it is possible to take the previously detected mime-types into account for your own * check (for example, skip the check if a certain type is not in there). */ public DetectedMimeTypeSet detectMimeTypes(File file, String fileName, DetectionStrategy detectionStrategy) { if (DetectionStrategy.ONLY_FILE_NAME == detectionStrategy) return detectMimeTypes((RandomAccessInterface) null, fileName, detectionStrategy); try { RandomAccessInterface randomAccessFile = new com.arondor.common.io.RandomAccessFile(file, "r"); try { return detectMimeTypes(randomAccessFile, fileName, detectionStrategy); } finally { try { randomAccessFile.close(); } catch (Throwable t) { log.warn(t.getClass().getName() + ": " + t.getMessage(), t); } } } catch (Throwable t) { log.error(t.getClass().getName() + ": " + t.getMessage(), t); return new DetectedMimeTypeSet(); // return empty result } } /** * Try to determine the mime type(s) from the file name or the contents of the file (magic numbers). * * @param randomAccessFile <code>null</code> or the file to read the data from. * @param fileName <code>null</code> or the simple name of the file (no path!). * @param detectionStrategy how to proceed detection. If the detect strategy is not supported by your implementation or * it does not match the data specified (e.g. <code>randomAccessFile</code> is <code>null</code> but the strategy * is {@link DetectionStrategy#ONLY_CONTENT}) you should silently return and skip your checks. * @return a collection into which you can add the mime types your implementation detected. It is also * possible to remove elements that another <code>MimeTypeDetector</code> implementation added before (if you can be * sure this result was wrong) and it is possible to take the previously detected mime-types into account for your own * check (for example, skip the check if a certain type is not in there). */ public DetectedMimeTypeSet detectMimeTypes(RandomAccessInterface randomAccessFile, String fileName, DetectionStrategy detectionStrategy) { return detectMimeTypes(randomAccessFile, null, fileName, detectionStrategy); } }
/* * Copyright 2000-2014 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.psi.impl.include; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.Consumer; import com.intellij.util.containers.FactoryMap; import com.intellij.util.containers.MultiMap; import com.intellij.util.indexing.*; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.IOUtil; import com.intellij.util.io.KeyDescriptor; import org.jetbrains.annotations.NotNull; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Dmitry Avdeev */ public class FileIncludeIndex extends FileBasedIndexExtension<FileIncludeIndex.Key, List<FileIncludeInfoImpl>> { public static final ID<Key,List<FileIncludeInfoImpl>> INDEX_ID = ID.create("fileIncludes"); private static final int BASE_VERSION = 5; public static List<FileIncludeInfoImpl> getIncludes(VirtualFile file, GlobalSearchScope scope) { final List<FileIncludeInfoImpl> result = new ArrayList<>(); FileBasedIndex.getInstance().processValues(INDEX_ID, new FileKey(file), file, (file1, value) -> { result.addAll(value); return true; }, scope); return result; } public static MultiMap<VirtualFile, FileIncludeInfoImpl> getIncludingFileCandidates(String fileName, GlobalSearchScope scope) { final MultiMap<VirtualFile, FileIncludeInfoImpl> result = new MultiMap<>(); FileBasedIndex.getInstance().processValues(INDEX_ID, new IncludeKey(fileName), null, (file, value) -> { result.put(file, value); return true; }, scope); return result; } private static class Holder { private static final FileIncludeProvider[] myProviders = Extensions.getExtensions(FileIncludeProvider.EP_NAME); } @NotNull @Override public ID<Key, List<FileIncludeInfoImpl>> getName() { return INDEX_ID; } @NotNull @Override public DataIndexer<Key, List<FileIncludeInfoImpl>, FileContent> getIndexer() { return new DataIndexer<Key, List<FileIncludeInfoImpl>, FileContent>() { @Override @NotNull public Map<Key, List<FileIncludeInfoImpl>> map(@NotNull FileContent inputData) { Map<Key, List<FileIncludeInfoImpl>> map = FactoryMap.createMap(key -> new ArrayList<>()); for (FileIncludeProvider provider : Holder.myProviders) { if (!provider.acceptFile(inputData.getFile())) continue; FileIncludeInfo[] infos = provider.getIncludeInfos(inputData); if (infos.length == 0) continue; List<FileIncludeInfoImpl> infoList = map.get(new FileKey(inputData.getFile())); for (FileIncludeInfo info : infos) { FileIncludeInfoImpl impl = new FileIncludeInfoImpl(info.path, info.offset, info.runtimeOnly, provider.getId()); map.get(new IncludeKey(info.fileName)).add(impl); infoList.add(impl); } } return map; } }; } @NotNull @Override public KeyDescriptor<Key> getKeyDescriptor() { return new KeyDescriptor<Key>() { @Override public int getHashCode(Key value) { return value.hashCode(); } @Override public boolean isEqual(Key val1, Key val2) { return val1.equals(val2); } @Override public void save(@NotNull DataOutput out, Key value) throws IOException { out.writeBoolean(value.isInclude()); value.writeValue(out); } @Override public Key read(@NotNull DataInput in) throws IOException { boolean isInclude = in.readBoolean(); return isInclude ? new IncludeKey(IOUtil.readUTF(in)) : new FileKey(in.readInt()); } }; } @NotNull @Override public DataExternalizer<List<FileIncludeInfoImpl>> getValueExternalizer() { return new DataExternalizer<List<FileIncludeInfoImpl>>() { @Override public void save(@NotNull DataOutput out, List<FileIncludeInfoImpl> value) throws IOException { out.writeInt(value.size()); for (FileIncludeInfoImpl info : value) { IOUtil.writeUTF(out, info.path); out.writeInt(info.offset); out.writeBoolean(info.runtimeOnly); IOUtil.writeUTF(out, info.providerId); } } @Override public List<FileIncludeInfoImpl> read(@NotNull DataInput in) throws IOException { int size = in.readInt(); ArrayList<FileIncludeInfoImpl> infos = new ArrayList<>(size); for (int i = 0; i < size; i++) { infos.add(new FileIncludeInfoImpl(IOUtil.readUTF(in), in.readInt(), in.readBoolean(), IOUtil.readUTF(in))); } return infos; } }; } @NotNull @Override public FileBasedIndex.InputFilter getInputFilter() { return new FileBasedIndex.FileTypeSpecificInputFilter() { @Override public boolean acceptInput(@NotNull VirtualFile file) { if (file.getFileSystem() == JarFileSystem.getInstance()) { return false; } for (FileIncludeProvider provider : Holder.myProviders) { if (provider.acceptFile(file)) { return true; } } return false; } @Override public void registerFileTypesUsedForIndexing(@NotNull Consumer<FileType> fileTypeSink) { for (FileIncludeProvider provider : Holder.myProviders) { provider.registerFileTypesUsedForIndexing(fileTypeSink); } } }; } @Override public boolean dependsOnFileContent() { return true; } @Override public int getVersion() { int version = BASE_VERSION; for (FileIncludeProvider provider : Holder.myProviders) { version = version * 31 + (provider.getVersion() ^ provider.getClass().getName().hashCode()); } return version; } interface Key { boolean isInclude(); void writeValue(DataOutput out) throws IOException; } private static class IncludeKey implements Key { private final String myFileName; public IncludeKey(String fileName) { myFileName = fileName; } @Override public boolean isInclude() { return true; } @Override public void writeValue(DataOutput out) throws IOException { IOUtil.writeUTF(out, myFileName); } @Override public int hashCode() { return myFileName.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof IncludeKey && ((IncludeKey)obj).myFileName.equals(myFileName); } } private static class FileKey implements Key { private final int myFileId; private FileKey(int fileId) { myFileId = fileId; } private FileKey(VirtualFile file) { myFileId = FileBasedIndex.getFileId(file); } @Override public boolean isInclude() { return false; } @Override public void writeValue(DataOutput out) throws IOException { out.writeInt(myFileId); } @Override public int hashCode() { return myFileId; } @Override public boolean equals(Object obj) { return obj instanceof FileKey && ((FileKey)obj).myFileId == myFileId; } } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // 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: 2015.12.12 at 08:52:29 PM GMT // package com.thalesgroup.timetable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * Defines a Passenger Destination Calling point * * <p>Java class for DT complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DT"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attGroup ref="{http://www.thalesgroup.com/rtti/XmlTimetable/v8}SchedLocAttributes"/> * &lt;attGroup ref="{http://www.thalesgroup.com/rtti/XmlTimetable/v8}CallPtAttributes"/> * &lt;attribute name="wta" use="required" type="{http://www.thalesgroup.com/rtti/PushPort/CommonTypes/v1}WTimeType" /> * &lt;attribute name="wtd" type="{http://www.thalesgroup.com/rtti/PushPort/CommonTypes/v1}WTimeType" /> * &lt;attribute name="rdelay" type="{http://www.thalesgroup.com/rtti/PushPort/CommonTypes/v1}DelayValueType" default="0" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DT") public class DT { @XmlAttribute(name = "wta", required = true) protected String wta; @XmlAttribute(name = "wtd") protected String wtd; @XmlAttribute(name = "rdelay") protected Short rdelay; @XmlAttribute(name = "tpl", required = true) protected String tpl; @XmlAttribute(name = "act") protected String act; @XmlAttribute(name = "planAct") protected String planAct; @XmlAttribute(name = "can") protected Boolean can; @XmlAttribute(name = "plat") protected String plat; @XmlAttribute(name = "pta") protected String pta; @XmlAttribute(name = "ptd") protected String ptd; /** * Gets the value of the wta property. * * @return * possible object is * {@link String } * */ public String getWta() { return wta; } /** * Sets the value of the wta property. * * @param value * allowed object is * {@link String } * */ public void setWta(String value) { this.wta = value; } /** * Gets the value of the wtd property. * * @return * possible object is * {@link String } * */ public String getWtd() { return wtd; } /** * Sets the value of the wtd property. * * @param value * allowed object is * {@link String } * */ public void setWtd(String value) { this.wtd = value; } /** * Gets the value of the rdelay property. * * @return * possible object is * {@link Short } * */ public short getRdelay() { if (rdelay == null) { return ((short) 0); } else { return rdelay; } } /** * Sets the value of the rdelay property. * * @param value * allowed object is * {@link Short } * */ public void setRdelay(Short value) { this.rdelay = value; } /** * Gets the value of the tpl property. * * @return * possible object is * {@link String } * */ public String getTpl() { return tpl; } /** * Sets the value of the tpl property. * * @param value * allowed object is * {@link String } * */ public void setTpl(String value) { this.tpl = value; } /** * Gets the value of the act property. * * @return * possible object is * {@link String } * */ public String getAct() { if (act == null) { return " "; } else { return act; } } /** * Sets the value of the act property. * * @param value * allowed object is * {@link String } * */ public void setAct(String value) { this.act = value; } /** * Gets the value of the planAct property. * * @return * possible object is * {@link String } * */ public String getPlanAct() { return planAct; } /** * Sets the value of the planAct property. * * @param value * allowed object is * {@link String } * */ public void setPlanAct(String value) { this.planAct = value; } /** * Gets the value of the can property. * * @return * possible object is * {@link Boolean } * */ public boolean isCan() { if (can == null) { return false; } else { return can; } } /** * Sets the value of the can property. * * @param value * allowed object is * {@link Boolean } * */ public void setCan(Boolean value) { this.can = value; } /** * Gets the value of the plat property. * * @return * possible object is * {@link String } * */ public String getPlat() { return plat; } /** * Sets the value of the plat property. * * @param value * allowed object is * {@link String } * */ public void setPlat(String value) { this.plat = value; } /** * Gets the value of the pta property. * * @return * possible object is * {@link String } * */ public String getPta() { return pta; } /** * Sets the value of the pta property. * * @param value * allowed object is * {@link String } * */ public void setPta(String value) { this.pta = value; } /** * Gets the value of the ptd property. * * @return * possible object is * {@link String } * */ public String getPtd() { return ptd; } /** * Sets the value of the ptd property. * * @param value * allowed object is * {@link String } * */ public void setPtd(String value) { this.ptd = value; } }
/** * 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.http; import java.io.IOException; import java.io.PrintWriter; import java.net.BindException; import java.net.InetSocketAddress; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.log.LogLevel; import org.apache.hadoop.metrics.MetricsServlet; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.conf.ConfServlet; import org.mortbay.io.Buffer; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Handler; import org.mortbay.jetty.MimeTypes; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.handler.ContextHandler; import org.mortbay.jetty.handler.ContextHandlerCollection; import org.mortbay.jetty.nio.SelectChannelConnector; import org.mortbay.jetty.security.SslSocketConnector; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.DefaultServlet; import org.mortbay.jetty.servlet.FilterHolder; import org.mortbay.jetty.servlet.FilterMapping; import org.mortbay.jetty.servlet.ServletHandler; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.thread.QueuedThreadPool; import org.mortbay.util.MultiException; /** * Create a Jetty embedded server to answer http requests. The primary goal * is to serve up status information for the server. * There are three contexts: * "/logs/" -> points to the log directory * "/static/" -> points to common static files (src/webapps/static) * "/" -> the jsp server code from (src/webapps/<name>) */ public class HttpServer implements FilterContainer { public static final Log LOG = LogFactory.getLog(HttpServer.class); static final String FILTER_INITIALIZER_PROPERTY = "hadoop.http.filter.initializers"; // The ServletContext attribute where the daemon Configuration // gets stored. public static final String CONF_CONTEXT_ATTRIBUTE = "hadoop.conf"; protected final Server webServer; protected final Connector listener; protected final WebAppContext webAppContext; protected final boolean findPort; protected final Map<Context, Boolean> defaultContexts = new HashMap<Context, Boolean>(); protected final List<String> filterNames = new ArrayList<String>(); private static final int MAX_RETRIES = 10; static final String HTTP_MAX_THREADS = "hadoop.http.max.threads"; /** Same as this(name, bindAddress, port, findPort, null); */ public HttpServer(String name, String bindAddress, int port, boolean findPort ) throws IOException { this(name, bindAddress, port, findPort, new Configuration()); } /** * Create a status server on the given port. * The jsp scripts are taken from src/webapps/<name>. * @param name The name of the server * @param port The port to use on the server * @param findPort whether the server should start at the given port and * increment by 1 until it finds a free port. * @param conf Configuration */ public HttpServer(String name, String bindAddress, int port, boolean findPort, Configuration conf) throws IOException { webServer = new Server(); this.findPort = findPort; listener = createBaseListener(conf); listener.setHost(bindAddress); listener.setPort(port); webServer.addConnector(listener); int maxThreads = conf.getInt(HTTP_MAX_THREADS, -1); // If HTTP_MAX_THREADS is not configured, QueueThreadPool() will use the // default value (currently 254). QueuedThreadPool threadPool = maxThreads == -1 ? new QueuedThreadPool() : new QueuedThreadPool(maxThreads); webServer.setThreadPool(threadPool); final String appDir = getWebAppsPath(); ContextHandlerCollection contexts = new ContextHandlerCollection(); webServer.setHandler(contexts); webAppContext = new WebAppContext(); webAppContext.setContextPath("/"); webAppContext.setWar(appDir + "/" + name); webAppContext.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, conf); webServer.addHandler(webAppContext); addDefaultApps(contexts, appDir); addGlobalFilter("safety", QuotingInputFilter.class.getName(), null); final FilterInitializer[] initializers = getFilterInitializers(conf); if (initializers != null) { for(FilterInitializer c : initializers) { c.initFilter(this); } } addDefaultServlets(); } /** * Create a required listener for the Jetty instance listening on the port * provided. This wrapper and all subclasses must create at least one * listener. */ protected Connector createBaseListener(Configuration conf) throws IOException { Connector ret; if (conf.getBoolean("hadoop.http.bio", false)) { SocketConnector conn = new SocketConnector(); conn.setAcceptQueueSize(4096); conn.setResolveNames(false); ret = conn; } else { SelectChannelConnector conn = new SelectChannelConnector(); conn.setAcceptQueueSize(128); conn.setResolveNames(false); conn.setUseDirectBuffers(false); ret = conn; } ret.setLowResourceMaxIdleTime(10000); ret.setHeaderBufferSize(conf.getInt("hadoop.http.header.buffer.size", 4096)); ret.setMaxIdleTime(conf.getInt("dfs.http.timeout", 200000)); return ret; } /** Get an array of FilterConfiguration specified in the conf */ private static FilterInitializer[] getFilterInitializers(Configuration conf) { if (conf == null) { return null; } Class<?>[] classes = conf.getClasses(FILTER_INITIALIZER_PROPERTY); if (classes == null) { return null; } FilterInitializer[] initializers = new FilterInitializer[classes.length]; for(int i = 0; i < classes.length; i++) { initializers[i] = (FilterInitializer)ReflectionUtils.newInstance( classes[i], conf); } return initializers; } /** * Add default apps. * @param appDir The application directory * @throws IOException */ protected void addDefaultApps(ContextHandlerCollection parent, final String appDir) throws IOException { // set up the context for "/logs/" if "hadoop.log.dir" property is defined. String logDir = System.getProperty("hadoop.log.dir"); if (logDir != null) { Context logContext = new Context(parent, "/logs"); logContext.setResourceBase(logDir); logContext.addServlet(DefaultServlet.class, "/"); defaultContexts.put(logContext, true); } // set up the context for "/static/*" Context staticContext = new Context(parent, "/static"); staticContext.setResourceBase(appDir + "/static"); staticContext.addServlet(DefaultServlet.class, "/*"); defaultContexts.put(staticContext, true); } /** * Add default servlets. */ protected void addDefaultServlets() { // set up default servlets addServlet("stacks", "/stacks", StackServlet.class); addServlet("logLevel", "/logLevel", LogLevel.Servlet.class); addServlet("metrics", "/metrics", MetricsServlet.class); addServlet("conf", "/conf", ConfServlet.class); } public void addContext(Context ctxt, boolean isFiltered) throws IOException { webServer.addHandler(ctxt); defaultContexts.put(ctxt, isFiltered); } /** * Add a context * @param pathSpec The path spec for the context * @param dir The directory containing the context * @param isFiltered if true, the servlet is added to the filter path mapping * @throws IOException */ protected void addContext(String pathSpec, String dir, boolean isFiltered) throws IOException { if (0 == webServer.getHandlers().length) { throw new RuntimeException("Couldn't find handler"); } WebAppContext webAppCtx = new WebAppContext(); webAppCtx.setContextPath(pathSpec); webAppCtx.setWar(dir); addContext(webAppCtx, true); } /** * Set a value in the webapp context. These values are available to the jsp * pages as "application.getAttribute(name)". * @param name The name of the attribute * @param value The value of the attribute */ public void setAttribute(String name, Object value) { webAppContext.setAttribute(name, value); } /** * Add a servlet in the server. * @param name The name of the servlet (can be passed as null) * @param pathSpec The path spec for the servlet * @param clazz The servlet class */ public void addServlet(String name, String pathSpec, Class<? extends HttpServlet> clazz) { addInternalServlet(name, pathSpec, clazz); addFilterPathMapping(pathSpec, webAppContext); } /** * Add an internal servlet in the server. * @param name The name of the servlet (can be passed as null) * @param pathSpec The path spec for the servlet * @param clazz The servlet class * @deprecated this is a temporary method */ @Deprecated public void addInternalServlet(String name, String pathSpec, Class<? extends HttpServlet> clazz) { ServletHolder holder = new ServletHolder(clazz); if (name != null) { holder.setName(name); } webAppContext.addServlet(holder, pathSpec); } /** {@inheritDoc} */ public void addFilter(String name, String classname, Map<String, String> parameters) { final String[] USER_FACING_URLS = { "*.html", "*.jsp" }; defineFilter(webAppContext, name, classname, parameters, USER_FACING_URLS); final String[] ALL_URLS = { "/*" }; for (Map.Entry<Context, Boolean> e : defaultContexts.entrySet()) { if (e.getValue()) { Context ctx = e.getKey(); defineFilter(ctx, name, classname, parameters, ALL_URLS); LOG.info("Added filter " + name + " (class=" + classname + ") to context " + ctx.getDisplayName()); } } filterNames.add(name); } /** {@inheritDoc} */ public void addGlobalFilter(String name, String classname, Map<String, String> parameters) { final String[] ALL_URLS = { "/*" }; defineFilter(webAppContext, name, classname, parameters, ALL_URLS); for (Context ctx : defaultContexts.keySet()) { defineFilter(ctx, name, classname, parameters, ALL_URLS); } LOG.info("Added global filter" + name + " (class=" + classname + ")"); } /** * Define a filter for a context and set up default url mappings. */ protected void defineFilter(Context ctx, String name, String classname, Map<String,String> parameters, String[] urls) { FilterHolder holder = new FilterHolder(); holder.setName(name); holder.setClassName(classname); holder.setInitParameters(parameters); FilterMapping fmap = new FilterMapping(); fmap.setPathSpecs(urls); fmap.setDispatches(Handler.ALL); fmap.setFilterName(name); ServletHandler handler = ctx.getServletHandler(); handler.addFilter(holder, fmap); } /** * Add the path spec to the filter path mapping. * @param pathSpec The path spec * @param webAppCtx The WebApplicationContext to add to */ protected void addFilterPathMapping(String pathSpec, Context webAppCtx) { ServletHandler handler = webAppCtx.getServletHandler(); for(String name : filterNames) { FilterMapping fmap = new FilterMapping(); fmap.setPathSpec(pathSpec); fmap.setFilterName(name); fmap.setDispatches(Handler.ALL); handler.addFilterMapping(fmap); } } /** * Get the value in the webapp context. * @param name The name of the attribute * @return The value of the attribute */ public Object getAttribute(String name) { return webAppContext.getAttribute(name); } /** * Get the pathname to the webapps files. * @return the pathname as a URL * @throws IOException if 'webapps' directory cannot be found on CLASSPATH. */ protected String getWebAppsPath() throws IOException { URL url = getClass().getClassLoader().getResource("webapps"); if (url == null) throw new IOException("webapps not found in CLASSPATH"); return url.toString(); } /** * Get the port that the server is on * @return the port */ public int getPort() { return webServer.getConnectors()[0].getLocalPort(); } /** * Set the min, max number of worker threads (simultaneous connections). */ public void setThreads(int min, int max) { QueuedThreadPool pool = (QueuedThreadPool) webServer.getThreadPool() ; pool.setMinThreads(min); pool.setMaxThreads(max); } public int getQueueSize() { return ((QueuedThreadPool) webServer.getThreadPool()).getQueueSize(); } public int getThreads() { return ((QueuedThreadPool) webServer.getThreadPool()).getThreads(); } public boolean isLowOnThreads() { return ((QueuedThreadPool) webServer.getThreadPool()).isLowOnThreads(); } /** * Configure an ssl listener on the server. * @param addr address to listen on * @param keystore location of the keystore * @param storPass password for the keystore * @param keyPass password for the key * @deprecated Use {@link #addSslListener(InetSocketAddress, Configuration, boolean)} */ @Deprecated public void addSslListener(InetSocketAddress addr, String keystore, String storPass, String keyPass) throws IOException { if (webServer.isStarted()) { throw new IOException("Failed to add ssl listener"); } SslSocketConnector sslListener = new SslSocketConnector(); sslListener.setHost(addr.getHostName()); sslListener.setPort(addr.getPort()); sslListener.setKeystore(keystore); sslListener.setPassword(storPass); sslListener.setKeyPassword(keyPass); webServer.addConnector(sslListener); } /** * Configure an ssl listener on the server. * @param addr address to listen on * @param sslConf conf to retrieve ssl options * @param needClientAuth whether client authentication is required */ public void addSslListener(InetSocketAddress addr, Configuration sslConf, boolean needClientAuth) throws IOException { if (webServer.isStarted()) { throw new IOException("Failed to add ssl listener"); } if (needClientAuth) { // setting up SSL truststore for authenticating clients System.setProperty("javax.net.ssl.trustStore", sslConf.get( "ssl.server.truststore.location", "")); System.setProperty("javax.net.ssl.trustStorePassword", sslConf.get( "ssl.server.truststore.password", "")); System.setProperty("javax.net.ssl.trustStoreType", sslConf.get( "ssl.server.truststore.type", "jks")); } SslSocketConnector sslListener = new SslSocketConnector(); sslListener.setHost(addr.getHostName()); sslListener.setPort(addr.getPort()); sslListener.setKeystore(sslConf.get("ssl.server.keystore.location")); sslListener.setPassword(sslConf.get("ssl.server.keystore.password", "")); sslListener.setKeyPassword(sslConf.get("ssl.server.keystore.keypassword", "")); sslListener.setKeystoreType(sslConf.get("ssl.server.keystore.type", "jks")); sslListener.setNeedClientAuth(needClientAuth); webServer.addConnector(sslListener); } /** * Start the server. Does not wait for the server to start. */ public void start() throws IOException { try { int port = 0; int oriPort = listener.getPort(); // The original requested port while (true) { try { port = webServer.getConnectors()[0].getLocalPort(); LOG.info("Port returned by webServer.getConnectors()[0]." + "getLocalPort() before open() is "+ port + ". Opening the listener on " + oriPort); listener.open(); port = listener.getLocalPort(); LOG.info("listener.getLocalPort() returned " + listener.getLocalPort() + " webServer.getConnectors()[0].getLocalPort() returned " + webServer.getConnectors()[0].getLocalPort()); //Workaround to handle the problem reported in HADOOP-4744 if (port < 0) { Thread.sleep(100); int numRetries = 1; while (port < 0) { LOG.warn("listener.getLocalPort returned " + port); if (numRetries++ > MAX_RETRIES) { throw new Exception(" listener.getLocalPort is returning " + "less than 0 even after " +numRetries+" resets"); } for (int i = 0; i < 2; i++) { LOG.info("Retrying listener.getLocalPort()"); port = listener.getLocalPort(); if (port > 0) { break; } Thread.sleep(200); } if (port > 0) { break; } LOG.info("Bouncing the listener"); listener.close(); Thread.sleep(1000); listener.setPort(oriPort == 0 ? 0 : (oriPort += 1)); listener.open(); Thread.sleep(100); port = listener.getLocalPort(); } } //Workaround end LOG.info("Jetty bound to port " + port); webServer.start(); // Workaround for HADOOP-6386 port = listener.getLocalPort(); if (port < 0) { LOG.warn("Bounds port is " + port + " after webserver start"); for (int i = 0; i < MAX_RETRIES/2; i++) { try { webServer.stop(); } catch (Exception e) { LOG.warn("Can't stop web-server", e); } Thread.sleep(1000); listener.setPort(oriPort == 0 ? 0 : (oriPort += 1)); listener.open(); Thread.sleep(100); webServer.start(); LOG.info(i + "attempts to restart webserver"); port = listener.getLocalPort(); if (port > 0) break; } if (port < 0) throw new Exception("listener.getLocalPort() is returning " + "less than 0 even after " +MAX_RETRIES+" resets"); } // End of HADOOP-6386 workaround break; } catch (IOException ex) { // if this is a bind exception, // then try the next port number. if (ex instanceof BindException) { if (!findPort) { throw (BindException) ex; } } else { LOG.info("HttpServer.start() threw a non Bind IOException"); throw ex; } } catch (MultiException ex) { LOG.info("HttpServer.start() threw a MultiException"); throw ex; } listener.setPort((oriPort += 1)); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("Problem starting http server", e); } } /** * Set graceful shutdown timeout. */ public void setGracefulShutdown(int timeoutMS) { webServer.setGracefulShutdown(timeoutMS); } /** * stop the server */ public void stop() throws Exception { listener.close(); webAppContext.clearAttributes(); webServer.removeHandler(webAppContext); webServer.stop(); } public void join() throws InterruptedException { webServer.join(); } /** * A very simple servlet to serve up a text representation of the current * stack traces. It both returns the stacks to the caller and logs them. * Currently the stack traces are done sequentially rather than exactly the * same data. */ public static class StackServlet extends HttpServlet { private static final long serialVersionUID = -6284183679759467039L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = new PrintWriter (HtmlQuoting.quoteOutputStream(response.getOutputStream())); ReflectionUtils.printThreadInfo(out, ""); out.close(); ReflectionUtils.logThreadInfo(LOG, "jsp requested", 1); } } /** * A Servlet input filter that quotes all HTML active characters in the * parameter names and values. The goal is to quote the characters to make * all of the servlets resistant to cross-site scripting attacks. */ public static class QuotingInputFilter implements Filter { private FilterConfig config; public static class RequestQuoter extends HttpServletRequestWrapper { private final HttpServletRequest rawRequest; public RequestQuoter(HttpServletRequest rawRequest) { super(rawRequest); this.rawRequest = rawRequest; } /** * Return the set of parameter names, quoting each name. */ @SuppressWarnings("unchecked") @Override public Enumeration<String> getParameterNames() { return new Enumeration<String>() { private Enumeration<String> rawIterator = rawRequest.getParameterNames(); @Override public boolean hasMoreElements() { return rawIterator.hasMoreElements(); } @Override public String nextElement() { return HtmlQuoting.quoteHtmlChars(rawIterator.nextElement()); } }; } /** * Unquote the name and quote the value. */ @Override public String getParameter(String name) { return HtmlQuoting.quoteHtmlChars(rawRequest.getParameter (HtmlQuoting.unquoteHtmlChars(name))); } @Override public String[] getParameterValues(String name) { String unquoteName = HtmlQuoting.unquoteHtmlChars(name); String[] unquoteValue = rawRequest.getParameterValues(unquoteName); String[] result = new String[unquoteValue.length]; for(int i=0; i < result.length; ++i) { result[i] = HtmlQuoting.quoteHtmlChars(unquoteValue[i]); } return result; } @SuppressWarnings("unchecked") @Override public Map<String, String[]> getParameterMap() { Map<String, String[]> result = new HashMap<String,String[]>(); Map<String, String[]> raw = rawRequest.getParameterMap(); for (Map.Entry<String,String[]> item: raw.entrySet()) { String[] rawValue = item.getValue(); String[] cookedValue = new String[rawValue.length]; for(int i=0; i< rawValue.length; ++i) { cookedValue[i] = HtmlQuoting.quoteHtmlChars(rawValue[i]); } result.put(HtmlQuoting.quoteHtmlChars(item.getKey()), cookedValue); } return result; } /** * Quote the url so that users specifying the HOST HTTP header * can't inject attacks. */ @Override public StringBuffer getRequestURL(){ String url = rawRequest.getRequestURL().toString(); return new StringBuffer(HtmlQuoting.quoteHtmlChars(url)); } /** * Quote the server name so that users specifying the HOST HTTP header * can't inject attacks. */ @Override public String getServerName() { return HtmlQuoting.quoteHtmlChars(rawRequest.getServerName()); } } @Override public void init(FilterConfig config) throws ServletException { this.config = config; } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { HttpServletRequestWrapper quoted = new RequestQuoter((HttpServletRequest) request); HttpServletResponse httpResponse = (HttpServletResponse) response; String mime = inferMimeType(request); if (mime == null) { httpResponse.setContentType("text/html; charset=utf-8"); } else if (mime.startsWith("text/html")) { // HTML with unspecified encoding, we want to // force HTML with utf-8 encoding // This is to avoid the following security issue: // http://openmya.hacker.jp/hasegawa/security/utf7cs.html httpResponse.setContentType("text/html; charset=utf-8"); } else if (mime.startsWith("application/xml")) { httpResponse.setContentType("text/xml; charset=utf-8"); } chain.doFilter(quoted, httpResponse); } /** * Infer the mime type for the response based on the extension of the * request URI. Returns null if unknown. */ private String inferMimeType(ServletRequest request) { String path = ((HttpServletRequest)request).getRequestURI(); ContextHandler.SContext sContext = (ContextHandler.SContext)config.getServletContext(); MimeTypes mimes = sContext.getContextHandler().getMimeTypes(); Buffer mimeBuffer = mimes.getMimeByExtension(path); return (mimeBuffer == null) ? null : mimeBuffer.toString(); } } }
/* * #%L * ImageJ2 software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2021 ImageJ2 developers. * %% * 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. * * 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 HOLDERS 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. * #L% */ package net.imagej.legacy.convert.roi.point; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import ij.IJ; import ij.ImagePlus; import ij.gui.PointRoi; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.imglib2.RealLocalizable; import net.imglib2.RealPoint; import net.imglib2.roi.geom.real.DefaultWritableRealPointCollection; import net.imglib2.roi.geom.real.RealPointCollection; import net.imglib2.roi.geom.real.WritableRealPointCollection; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * Tests {@link PointRoiWrapper} * * @author Alison Walter */ public class PointRoiWrapperTest { private PointRoi point; private RealPointCollection<RealLocalizable> rpc; private WritableRealPointCollection<RealLocalizable> wrap; @Rule public final ExpectedException exception = ExpectedException.none(); @Before public void setup() { point = new PointRoi(new float[] { 12.125f, 17, 1 }, new float[] { -4, 6.5f, 30 }); final List<RealLocalizable> c = new ArrayList<>(); c.add(new RealPoint(new double[] { 12.125, -4 })); c.add(new RealPoint(new double[] { 17, 6.5 })); c.add(new RealPoint(new double[] { 1, 30 })); rpc = new DefaultWritableRealPointCollection<>(c); wrap = new PointRoiWrapper(point); } // -- PointRoiWrapper -- @Test public void testPointRoiWrapperGetters() { Iterator<RealLocalizable> iw = wrap.points().iterator(); final Iterator<RealLocalizable> irpc = rpc.points().iterator(); final float[] x = point.getContainedFloatPoints().xpoints; final float[] y = point.getContainedFloatPoints().ypoints; // Test ImageJ 1.x and wrapper equivalent for (int i = 0; i < 3; i++) { final RealLocalizable r = iw.next(); assertEquals(x[i], r.getFloatPosition(0), 0); assertEquals(y[i], r.getFloatPosition(1), 0); } // Test ImgLib2 and wrapper equivalent iw = wrap.points().iterator(); while (irpc.hasNext()) { final RealLocalizable w = iw.next(); final RealLocalizable pc = irpc.next(); assertEquals(pc.getFloatPosition(0), w.getFloatPosition(0), 0); assertEquals(pc.getFloatPosition(1), w.getFloatPosition(1), 0); } } @Test public void testPointRoiWrapperAddPoint() { wrap.addPoint(new RealPoint(new double[] { -2.25, 13 })); final Iterator<RealLocalizable> iw = wrap.points().iterator(); final RealLocalizable one = iw.next(); final RealLocalizable two = iw.next(); final float[] xp = point.getContainedFloatPoints().xpoints; final float[] yp = point.getContainedFloatPoints().ypoints; assertEquals(xp[0], one.getFloatPosition(0), 0); assertEquals(yp[0], one.getFloatPosition(1), 0); assertEquals(xp[1], two.getFloatPosition(0), 0); assertEquals(yp[1], two.getFloatPosition(1), 0); } @Test public void testPointRoiWrapperRemovePointNoImagePlus() { // Throw an exception since wrapped roi has no associated ImagePlus exception.expect(UnsupportedOperationException.class); wrap.removePoint(new RealPoint(new double[] { 1, 1, })); } @Test public void testPointRoiWrapperRemovePointWithImagePlus() { final ImagePlus i = IJ.createImage("Ramp", "8-bit ramp", 128, 128, 1); i.setRoi(point); point.setImage(i); wrap.removePoint(new RealPoint(new double[] { 17, 6.5 })); Iterator<RealLocalizable> iw = wrap.points().iterator(); RealLocalizable one = iw.next(); RealLocalizable two = iw.next(); float[] x = point.getContainedFloatPoints().xpoints; float[] y = point.getContainedFloatPoints().ypoints; // Since the passed point is part of the collection, it should have been // removed assertEquals(x[0], one.getDoublePosition(0), 0); assertEquals(y[0], one.getDoublePosition(1), 0); assertEquals(x[1], two.getDoublePosition(0), 0); assertEquals(y[1], two.getDoublePosition(1), 0); assertEquals(point.getNCoordinates(), 2); assertFalse(iw.hasNext()); wrap.removePoint(new RealPoint(new double[] { 11, 3 })); iw = wrap.points().iterator(); one = iw.next(); two = iw.next(); x = point.getContainedFloatPoints().xpoints; y = point.getContainedFloatPoints().ypoints; // Point was not part of the collection, so no change assertEquals(x[0], one.getDoublePosition(0), 0); assertEquals(y[0], one.getDoublePosition(1), 0); assertEquals(x[1], two.getDoublePosition(0), 0); assertEquals(y[1], two.getDoublePosition(1), 0); assertEquals(point.getNCoordinates(), 2); assertFalse(iw.hasNext()); } @Test public void testPointRoiWrapperTest() { assertTrue(wrap.test(new RealPoint(new double[] { 12.125, -4 }))); assertFalse(wrap.test(new RealPoint(new double[] { 8, 15.5 }))); } @Test public void testPointRoiWrapperBounds() { assertEquals(1, wrap.realMin(0), 0); assertEquals(-4, wrap.realMin(1), 0); assertEquals(17, wrap.realMax(0), 0); assertEquals(30, wrap.realMax(1), 0); } @Test public void testUpdatedAfterPointRoiWrapperModified() { final RealPoint remove = new RealPoint(new double[] { 12.125, -4 }); final RealPoint add = new RealPoint(new double[] { 8, 100.25 }); assertTrue(wrap.test(remove)); assertFalse(wrap.test(add)); // addPoint wrap.addPoint(add); assertTrue(wrap.test(add)); assertEquals(100.25, wrap.realMax(1), 0); // removePoint final ImagePlus i = IJ.createImage("Ramp", "8-bit ramp", 128, 128, 1); i.setRoi(point); point.setImage(i); // wrapper needs associated ImagePlus in order to // removePoint wrap.removePoint(remove); assertFalse(wrap.test(remove)); // check the points final Iterator<RealLocalizable> iw = wrap.points().iterator(); final float[] x = point.getContainedFloatPoints().xpoints; final float[] y = point.getContainedFloatPoints().ypoints; for (int n = 0; n < point.getNCoordinates(); n++) { final RealLocalizable pt = iw.next(); assertEquals(x[n], pt.getDoublePosition(0), 0); assertEquals(y[n], pt.getDoublePosition(1), 0); } assertFalse(iw.hasNext()); } }
/* * Copyright (c) 2017, 1&1 IONOS Cloud GmbH * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the <organization>. * 4. Neither the name of the 1&1 IONOS Cloud 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 1&1 IONOS Cloud GmbH ''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 1&1 IONOS Cloud GmbH 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 com.ionosenterprise.sdk; import com.ionosenterprise.rest.client.RestClient; import com.ionosenterprise.rest.client.RestClientException; import com.ionosenterprise.rest.domain.Nics; import com.ionosenterprise.rest.domain.PBObject; import com.ionosenterprise.util.Constant; import org.apache.http.HttpStatus; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Collections; public class NicApi extends AbstractBaseApi { public NicApi(RestClient client) { super(client); } protected String getPathFormat() { return Constant.NICS_RESOURCE_PATH_TEMPLATE; } /** * This will retrieve a list of NICs associated with the load balancer. * * @param dataCenterId The unique ID of the data center * @param serverId The unique ID of the server * @return Nics object with a list of Nics datacenter. */ public Nics getAllNics(String dataCenterId, String serverId) throws RestClientException, IOException { return client.get(getResourcePathBuilder().withPathParams(dataCenterId, serverId).withDepth().build(), Collections.EMPTY_MAP, Nics.class); } /** * Retrieves the attributes of a given load balanced NIC. * * @param dataCenterId The unique ID of the data center * @param serverId The unique ID of the server * @param nicId The unique ID of the nic * @return Nic object with properties and metadata */ public com.ionosenterprise.rest.domain.Nic getNic(String dataCenterId, String serverId, String nicId) throws RestClientException, IOException { return client.get(getResourcePathBuilder().withPathParams(dataCenterId, serverId).appendPathSegment(nicId) .withDepth().build(), Collections.EMPTY_MAP, com.ionosenterprise.rest.domain.Nic.class); } /** * Adds a NIC to the target server. * * @param dataCenterId The unique ID of the data center * @param serverId The unique ID of the data center * @param nic object has the following properties: * <br> * <br> * name = The name of the NIC. * <br> * <br> * ips = IPs assigned to the NIC. This can be a collection. * <br> * <br> * dhcp = Set to FALSE if you wish to disable DHCP on the NIC. Default: * TRUE. * <br> * <br> * lan = The LAN ID the NIC will sit on. If the LAN ID does not exist it * will be created. exist. * <br> * <br> * nat = Indicates the private IP address has outbound access to the public * internet. * <br> * <br> * firewallActive = Once you add a firewall rule this will reflect a true * value. * <br> * <br> * @return Nic object with properties and metadata. */ public com.ionosenterprise.rest.domain.Nic createNic(String dataCenterId, String serverId, com.ionosenterprise.rest.domain.Nic nic) throws RestClientException, IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { return client.create(getResourcePathBuilder().withPathParams(dataCenterId, serverId).build(), nic, com.ionosenterprise.rest.domain.Nic.class, HttpStatus.SC_ACCEPTED); } /** * You can update -- in full or partially -- various attributes on the NIC. * * @param dataCenterId The unique ID of the data center * @param serverId The unique ID of the data center * @param nic object has the following properties: * <br> * <br> * name = The name of the NIC. * <br> * <br> * ips = IPs assigned to the NIC. This can be a collection. * <br> * <br> * dhcp = Set to FALSE if you wish to disable DHCP on the NIC. Default: * TRUE. * <br> * <br> * lan = The LAN ID the NIC will sit on. If the LAN ID does not exist it * will be created. exist. * <br> * <br> * nat = Indicates the private IP address has outbound access to the public * internet. * <br> * <br> * @return Nic object with properties and metadata. */ public com.ionosenterprise.rest.domain.Nic updateNic(String dataCenterId, String serverId, String nicId, Object nic) throws RestClientException, IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { return client.update(getResourcePathBuilder().withPathParams(dataCenterId, serverId).appendPathSegment(nicId) .build(), nic, com.ionosenterprise.rest.domain.Nic.class, HttpStatus.SC_ACCEPTED); } /** * Deletes the specified NIC. * * @param dataCenterId The unique ID of the data center * @param serverId The unique ID of the server * @param nicId The unique ID of the nic * @return a String representing the requestId */ public String deleteNic(String dataCenterId, String serverId, String nicId) throws RestClientException, IOException { return client.delete(getResourcePathBuilder().withPathParams(dataCenterId, serverId).appendPathSegment(nicId) .build(), HttpStatus.SC_ACCEPTED); } /** * This will associate a NIC to a Load Balancer, enabling the NIC to * participate in load-balancing. * * @param dataCenterId The unique ID of the data center * @param loadBalancerId The unique ID of the load balancer. * @param nicId The unique ID of the nic. */ public com.ionosenterprise.rest.domain.Nic assignNicToLoadBalancer(String dataCenterId, String loadBalancerId, String nicId) throws RestClientException, IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { PBObject payload = new PBObject(); payload.setId(nicId); return client.create(getResourcePathBuilder("datacenters/%s/loadbalancers/%s/balancednics") .withPathParams(dataCenterId, loadBalancerId).build(), payload, com.ionosenterprise.rest.domain.Nic.class, HttpStatus.SC_ACCEPTED); } /** * Removes the association of a NIC with a load balancer. * * @param dataCenterId The unique ID of the data center * @param loadBalancerId The unique ID of the load balancer. * @param nicId The unique ID of the nic. * @return a String representing the requestId */ public String unassignNicFromLoadBalancer(String dataCenterId, String loadBalancerId, String nicId) throws RestClientException, IOException { return client.delete(getResourcePathBuilder("datacenters/%s/loadbalancers/%s/balancednics") .withPathParams(dataCenterId, loadBalancerId).appendPathSegment(nicId).build(), HttpStatus.SC_ACCEPTED); } /** * This will retrieve a list of NICs associated with the load balancer. * * @param dataCenterId The unique ID of the data center * @param loadBalancerId The unique ID of the load balancer. * @return Nics object with list of balanced nics */ public Nics getAllBalancedNics(String dataCenterId, String loadBalancerId) throws RestClientException, IOException { return client.get(getResourcePathBuilder("datacenters/%s/loadbalancers/%s/balancednics") .withPathParams(dataCenterId, loadBalancerId).withDepth().build(), Collections.EMPTY_MAP, Nics.class); } /** * Retrieves the attributes of a given load balanced NIC. * * @param dataCenterId The unique ID of the data center * @param loadBalancerId The unique ID of the load balancer. * @param nicId The unique ID of the nic. * @return Nic object with properties and metadata */ public com.ionosenterprise.rest.domain.Nic getBalancedNic(String dataCenterId, String loadBalancerId, String nicId) throws RestClientException, IOException { return client.get(getResourcePathBuilder("datacenters/%s/loadbalancers/%s/balancednics") .withPathParams(dataCenterId, loadBalancerId).appendPathSegment(nicId).withDepth().build(), Collections.EMPTY_MAP, com.ionosenterprise.rest.domain.Nic.class); } }
/* * Copyright (C) 2012 The Guava 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 com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.compose; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.MoreObjects; import com.google.common.base.Predicate; import com.google.common.collect.Maps.IteratorBasedAbstractMap; import java.util.AbstractMap; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting * all optional operations. * * <p>Like all {@code RangeMap} implementations, this supports neither null * keys nor null values. * * @author Louis Wasserman * @since 14.0 */ @Beta @GwtIncompatible // NavigableMap public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> { private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound; public static <K extends Comparable, V> TreeRangeMap<K, V> create() { return new TreeRangeMap<K, V>(); } private TreeRangeMap() { this.entriesByLowerBound = Maps.newTreeMap(); } private static final class RangeMapEntry<K extends Comparable, V> extends AbstractMapEntry<Range<K>, V> { private final Range<K> range; private final V value; RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) { this(Range.create(lowerBound, upperBound), value); } RangeMapEntry(Range<K> range, V value) { this.range = range; this.value = value; } @Override public Range<K> getKey() { return range; } @Override public V getValue() { return value; } public boolean contains(K value) { return range.contains(value); } Cut<K> getLowerBound() { return range.lowerBound; } Cut<K> getUpperBound() { return range.upperBound; } } @Override @Nullable public V get(K key) { Entry<Range<K>, V> entry = getEntry(key); return (entry == null) ? null : entry.getValue(); } @Override @Nullable public Entry<Range<K>, V> getEntry(K key) { Map.Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry = entriesByLowerBound.floorEntry(Cut.belowValue(key)); if (mapEntry != null && mapEntry.getValue().contains(key)) { return mapEntry.getValue(); } else { return null; } } @Override public void put(Range<K> range, V value) { // don't short-circuit if the range is empty - it may be between two ranges we can coalesce. if (!range.isEmpty()) { checkNotNull(value); remove(range); entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value)); } } @Override public void putCoalescing(Range<K> range, V value) { if (entriesByLowerBound.isEmpty()) { put(range, value); return; } Range<K> coalescedRange = coalescedRange(range, checkNotNull(value)); put(coalescedRange, value); } /** Computes the coalesced range for the given range+value - does not mutate the map. */ private Range<K> coalescedRange(Range<K> range, V value) { Range<K> coalescedRange = range; Map.Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry = entriesByLowerBound.lowerEntry(range.lowerBound); coalescedRange = coalesce(coalescedRange, value, lowerEntry); Map.Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry = entriesByLowerBound.floorEntry(range.upperBound); coalescedRange = coalesce(coalescedRange, value, higherEntry); return coalescedRange; } /** Returns the range that spans the given range and entry, if the entry can be coalesced. */ private static <K extends Comparable, V> Range<K> coalesce( Range<K> range, V value, @Nullable Map.Entry<Cut<K>, RangeMapEntry<K, V>> entry) { if (entry != null && entry.getValue().getKey().isConnected(range) && entry.getValue().getValue().equals(value)) { return range.span(entry.getValue().getKey()); } return range; } @Override public void putAll(RangeMap<K, V> rangeMap) { for (Map.Entry<Range<K>, V> entry : rangeMap.asMapOfRanges().entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { entriesByLowerBound.clear(); } @Override public Range<K> span() { Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry(); Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry(); if (firstEntry == null) { throw new NoSuchElementException(); } return Range.create( firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound); } private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) { entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value)); } @Override public void remove(Range<K> rangeToRemove) { if (rangeToRemove.isEmpty()) { return; } /* * The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to * indicate the bounds of ranges in the range map. */ Map.Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate = entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound); if (mapEntryBelowToTruncate != null) { // we know ( [ RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue(); if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) { // we know ( [ ) if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) { // we know ( [ ] ), so insert the range ] ) back into the map -- // it's being split apart putRangeMapEntry( rangeToRemove.upperBound, rangeMapEntry.getUpperBound(), mapEntryBelowToTruncate.getValue().getValue()); } // overwrite mapEntryToTruncateBelow with a truncated range putRangeMapEntry( rangeMapEntry.getLowerBound(), rangeToRemove.lowerBound, mapEntryBelowToTruncate.getValue().getValue()); } } Map.Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate = entriesByLowerBound.lowerEntry(rangeToRemove.upperBound); if (mapEntryAboveToTruncate != null) { // we know ( ] RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue(); if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) { // we know ( ] ), and since we dealt with truncating below already, // we know [ ( ] ) putRangeMapEntry( rangeToRemove.upperBound, rangeMapEntry.getUpperBound(), mapEntryAboveToTruncate.getValue().getValue()); } } entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear(); } @Override public Map<Range<K>, V> asMapOfRanges() { return new AsMapOfRanges(entriesByLowerBound.values()); } @Override public Map<Range<K>, V> asDescendingMapOfRanges() { return new AsMapOfRanges(entriesByLowerBound.descendingMap().values()); } private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> { final Iterable<Entry<Range<K>, V>> entryIterable; @SuppressWarnings("unchecked") // it's safe to upcast iterables AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) { this.entryIterable = (Iterable) entryIterable; } @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public V get(@Nullable Object key) { if (key instanceof Range) { Range<?> range = (Range<?>) key; RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound); if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) { return rangeMapEntry.getValue(); } } return null; } @Override public int size() { return entriesByLowerBound.size(); } @Override Iterator<Entry<Range<K>, V>> entryIterator() { return entryIterable.iterator(); } } @Override public RangeMap<K, V> subRangeMap(Range<K> subRange) { if (subRange.equals(Range.all())) { return this; } else { return new SubRangeMap(subRange); } } @SuppressWarnings("unchecked") private RangeMap<K, V> emptySubRangeMap() { return EMPTY_SUB_RANGE_MAP; } private static final RangeMap EMPTY_SUB_RANGE_MAP = new RangeMap() { @Override @Nullable public Object get(Comparable key) { return null; } @Override @Nullable public Entry<Range, Object> getEntry(Comparable key) { return null; } @Override public Range span() { throw new NoSuchElementException(); } @Override public void put(Range range, Object value) { checkNotNull(range); throw new IllegalArgumentException( "Cannot insert range " + range + " into an empty subRangeMap"); } @Override public void putCoalescing(Range range, Object value) { checkNotNull(range); throw new IllegalArgumentException( "Cannot insert range " + range + " into an empty subRangeMap"); } @Override public void putAll(RangeMap rangeMap) { if (!rangeMap.asMapOfRanges().isEmpty()) { throw new IllegalArgumentException( "Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap"); } } @Override public void clear() {} @Override public void remove(Range range) { checkNotNull(range); } @Override public Map<Range, Object> asMapOfRanges() { return Collections.emptyMap(); } @Override public Map<Range, Object> asDescendingMapOfRanges() { return Collections.emptyMap(); } @Override public RangeMap subRangeMap(Range range) { checkNotNull(range); return this; } }; private class SubRangeMap implements RangeMap<K, V> { private final Range<K> subRange; SubRangeMap(Range<K> subRange) { this.subRange = subRange; } @Override @Nullable public V get(K key) { return subRange.contains(key) ? TreeRangeMap.this.get(key) : null; } @Override @Nullable public Entry<Range<K>, V> getEntry(K key) { if (subRange.contains(key)) { Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key); if (entry != null) { return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue()); } } return null; } @Override public Range<K> span() { Cut<K> lowerBound; Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry = entriesByLowerBound.floorEntry(subRange.lowerBound); if (lowerEntry != null && lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) { lowerBound = subRange.lowerBound; } else { lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound); if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) { throw new NoSuchElementException(); } } Cut<K> upperBound; Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry = entriesByLowerBound.lowerEntry(subRange.upperBound); if (upperEntry == null) { throw new NoSuchElementException(); } else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) { upperBound = subRange.upperBound; } else { upperBound = upperEntry.getValue().getUpperBound(); } return Range.create(lowerBound, upperBound); } @Override public void put(Range<K> range, V value) { checkArgument( subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange); TreeRangeMap.this.put(range, value); } @Override public void putCoalescing(Range<K> range, V value) { if (entriesByLowerBound.isEmpty() || range.isEmpty() || !subRange.encloses(range)) { put(range, value); return; } Range<K> coalescedRange = coalescedRange(range, checkNotNull(value)); // only coalesce ranges within the subRange put(coalescedRange.intersection(subRange), value); } @Override public void putAll(RangeMap<K, V> rangeMap) { if (rangeMap.asMapOfRanges().isEmpty()) { return; } Range<K> span = rangeMap.span(); checkArgument( subRange.encloses(span), "Cannot putAll rangeMap with span %s into a subRangeMap(%s)", span, subRange); TreeRangeMap.this.putAll(rangeMap); } @Override public void clear() { TreeRangeMap.this.remove(subRange); } @Override public void remove(Range<K> range) { if (range.isConnected(subRange)) { TreeRangeMap.this.remove(range.intersection(subRange)); } } @Override public RangeMap<K, V> subRangeMap(Range<K> range) { if (!range.isConnected(subRange)) { return emptySubRangeMap(); } else { return TreeRangeMap.this.subRangeMap(range.intersection(subRange)); } } @Override public Map<Range<K>, V> asMapOfRanges() { return new SubRangeMapAsMap(); } @Override public Map<Range<K>, V> asDescendingMapOfRanges() { return new SubRangeMapAsMap() { @Override Iterator<Entry<Range<K>, V>> entryIterator() { if (subRange.isEmpty()) { return Iterators.emptyIterator(); } final Iterator<RangeMapEntry<K, V>> backingItr = entriesByLowerBound .headMap(subRange.upperBound, false) .descendingMap() .values() .iterator(); return new AbstractIterator<Entry<Range<K>, V>>() { @Override protected Entry<Range<K>, V> computeNext() { if (backingItr.hasNext()) { RangeMapEntry<K, V> entry = backingItr.next(); if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) { return endOfData(); } return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue()); } return endOfData(); } }; } }; } @Override public boolean equals(@Nullable Object o) { if (o instanceof RangeMap) { RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o; return asMapOfRanges().equals(rangeMap.asMapOfRanges()); } return false; } @Override public int hashCode() { return asMapOfRanges().hashCode(); } @Override public String toString() { return asMapOfRanges().toString(); } class SubRangeMapAsMap extends AbstractMap<Range<K>, V> { @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public V get(Object key) { try { if (key instanceof Range) { @SuppressWarnings("unchecked") // we catch ClassCastExceptions Range<K> r = (Range<K>) key; if (!subRange.encloses(r) || r.isEmpty()) { return null; } RangeMapEntry<K, V> candidate = null; if (r.lowerBound.compareTo(subRange.lowerBound) == 0) { // r could be truncated on the left Entry<Cut<K>, RangeMapEntry<K, V>> entry = entriesByLowerBound.floorEntry(r.lowerBound); if (entry != null) { candidate = entry.getValue(); } } else { candidate = entriesByLowerBound.get(r.lowerBound); } if (candidate != null && candidate.getKey().isConnected(subRange) && candidate.getKey().intersection(subRange).equals(r)) { return candidate.getValue(); } } } catch (ClassCastException e) { return null; } return null; } @Override public V remove(Object key) { V value = get(key); if (value != null) { @SuppressWarnings("unchecked") // it's definitely in the map, so safe Range<K> range = (Range<K>) key; TreeRangeMap.this.remove(range); return value; } return null; } @Override public void clear() { SubRangeMap.this.clear(); } private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) { List<Range<K>> toRemove = Lists.newArrayList(); for (Entry<Range<K>, V> entry : entrySet()) { if (predicate.apply(entry)) { toRemove.add(entry.getKey()); } } for (Range<K> range : toRemove) { TreeRangeMap.this.remove(range); } return !toRemove.isEmpty(); } @Override public Set<Range<K>> keySet() { return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) { @Override public boolean remove(@Nullable Object o) { return SubRangeMapAsMap.this.remove(o) != null; } @Override public boolean retainAll(Collection<?> c) { return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction())); } }; } @Override public Set<Entry<Range<K>, V>> entrySet() { return new Maps.EntrySet<Range<K>, V>() { @Override Map<Range<K>, V> map() { return SubRangeMapAsMap.this; } @Override public Iterator<Entry<Range<K>, V>> iterator() { return entryIterator(); } @Override public boolean retainAll(Collection<?> c) { return removeEntryIf(not(in(c))); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean isEmpty() { return !iterator().hasNext(); } }; } Iterator<Entry<Range<K>, V>> entryIterator() { if (subRange.isEmpty()) { return Iterators.emptyIterator(); } Cut<K> cutToStart = MoreObjects.firstNonNull( entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound); final Iterator<RangeMapEntry<K, V>> backingItr = entriesByLowerBound.tailMap(cutToStart, true).values().iterator(); return new AbstractIterator<Entry<Range<K>, V>>() { @Override protected Entry<Range<K>, V> computeNext() { while (backingItr.hasNext()) { RangeMapEntry<K, V> entry = backingItr.next(); if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) { return endOfData(); } else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) { // this might not be true e.g. at the start of the iteration return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue()); } } return endOfData(); } }; } @Override public Collection<V> values() { return new Maps.Values<Range<K>, V>(this) { @Override public boolean removeAll(Collection<?> c) { return removeEntryIf(compose(in(c), Maps.<V>valueFunction())); } @Override public boolean retainAll(Collection<?> c) { return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction())); } }; } } } @Override public boolean equals(@Nullable Object o) { if (o instanceof RangeMap) { RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o; return asMapOfRanges().equals(rangeMap.asMapOfRanges()); } return false; } @Override public int hashCode() { return asMapOfRanges().hashCode(); } @Override public String toString() { return entriesByLowerBound.values().toString(); } }
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.assistants; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceEndpointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceFaultInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceInSequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AddressEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AddressEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AddressingEndpointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AggregateMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BAMMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BAMMediatorOutputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BeanMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BuilderMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CacheMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CallMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CallTemplateMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CalloutMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ClassMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloneMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloudConnectorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloudConnectorOperationInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CommandMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ConditionalRouterMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DBLookupMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DBReportMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DataMapperMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DefaultEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DefaultEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DropMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EJBMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EnqueueMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EnrichMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EntitlementMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EventMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FailoverEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FailoverEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FastXSLTMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FaultMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FilterMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ForEachMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.HTTPEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.HTTPEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.HeaderMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.InboundEndpointOnErrorSequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.InboundEndpointSequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.IterateMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.JsonTransformMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LoadBalanceEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LoadBalanceEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LogMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LoopBackMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MergeNodeFirstInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MergeNodeSecondInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MessageInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.NamedEndpointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.OAuthMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PayloadFactoryMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PropertyGroupMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PropertyMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ProxyFaultInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ProxyInSequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ProxyInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PublishEventMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RMSequenceMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RecipientListEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RecipientListEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RespondMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RouterMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RuleMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ScriptMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SendMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SequencesInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SmooksMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SpringMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.StoreMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SwitchMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.TemplateEndpointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.TemplateEndpointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ThrottleMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.TransactionMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.URLRewriteMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ValidateMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.WSDLEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.WSDLEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.XQueryMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.XSLTMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbModelingAssistantProvider; /** * @generated */ public class EsbModelingAssistantProviderOfBAMMediatorOutputConnectorEditPart extends EsbModelingAssistantProvider { /** * @generated */ @Override public List<IElementType> getRelTypesOnSource(IAdaptable source) { IGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source.getAdapter(IGraphicalEditPart.class); return doGetRelTypesOnSource((BAMMediatorOutputConnectorEditPart) sourceEditPart); } /** * @generated */ public List<IElementType> doGetRelTypesOnSource(BAMMediatorOutputConnectorEditPart source) { List<IElementType> types = new ArrayList<IElementType>(1); types.add(EsbElementTypes.EsbLink_4001); return types; } /** * @generated */ @Override public List<IElementType> getRelTypesOnSourceAndTarget(IAdaptable source, IAdaptable target) { IGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source.getAdapter(IGraphicalEditPart.class); IGraphicalEditPart targetEditPart = (IGraphicalEditPart) target.getAdapter(IGraphicalEditPart.class); return doGetRelTypesOnSourceAndTarget((BAMMediatorOutputConnectorEditPart) sourceEditPart, targetEditPart); } /** * @generated */ public List<IElementType> doGetRelTypesOnSourceAndTarget(BAMMediatorOutputConnectorEditPart source, IGraphicalEditPart targetEditPart) { List<IElementType> types = new LinkedList<IElementType>(); if (targetEditPart instanceof ProxyInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ProxyFaultInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DropMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof PropertyMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof PropertyGroupMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ThrottleMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FilterMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof LogMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EnrichMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof XSLTMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SwitchMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EventMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EntitlementMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ClassMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SpringMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ScriptMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FaultMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof XQueryMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CommandMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DBLookupMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DBReportMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SmooksMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SendMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof HeaderMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CloneMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CacheMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof IterateMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CalloutMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof TransactionMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RMSequenceMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RuleMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof OAuthMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof AggregateMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof StoreMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof BuilderMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CallTemplateMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof PayloadFactoryMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EnqueueMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof URLRewriteMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ValidateMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RouterMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ConditionalRouterMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof BAMMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof BeanMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EJBMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DefaultEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof AddressEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FailoverEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RecipientListEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof WSDLEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof NamedEndpointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof LoadBalanceEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof APIResourceEndpointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof AddressingEndpointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof HTTPEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof TemplateEndpointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CloudConnectorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CloudConnectorOperationInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof LoopBackMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RespondMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CallMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DataMapperMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FastXSLTMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ForEachMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof PublishEventMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof JsonTransformMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ProxyInSequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof MessageInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof MergeNodeFirstInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof MergeNodeSecondInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SequencesInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DefaultEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof AddressEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FailoverEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RecipientListEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof WSDLEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof LoadBalanceEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof HTTPEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof TemplateEndpointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof APIResourceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof APIResourceFaultInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof APIResourceInSequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof InboundEndpointSequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof InboundEndpointOnErrorSequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } return types; } /** * @generated */ @Override public List<IElementType> getTypesForTarget(IAdaptable source, IElementType relationshipType) { IGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source.getAdapter(IGraphicalEditPart.class); return doGetTypesForTarget((BAMMediatorOutputConnectorEditPart) sourceEditPart, relationshipType); } /** * @generated */ public List<IElementType> doGetTypesForTarget(BAMMediatorOutputConnectorEditPart source, IElementType relationshipType) { List<IElementType> types = new ArrayList<IElementType>(); if (relationshipType == EsbElementTypes.EsbLink_4001) { types.add(EsbElementTypes.ProxyInputConnector_3003); types.add(EsbElementTypes.ProxyFaultInputConnector_3489); types.add(EsbElementTypes.DropMediatorInputConnector_3008); types.add(EsbElementTypes.PropertyMediatorInputConnector_3033); types.add(EsbElementTypes.PropertyGroupMediatorInputConnector_3789); types.add(EsbElementTypes.ThrottleMediatorInputConnector_3121); types.add(EsbElementTypes.FilterMediatorInputConnector_3010); types.add(EsbElementTypes.LogMediatorInputConnector_3018); types.add(EsbElementTypes.EnrichMediatorInputConnector_3036); types.add(EsbElementTypes.XSLTMediatorInputConnector_3039); types.add(EsbElementTypes.SwitchMediatorInputConnector_3042); types.add(EsbElementTypes.SequenceInputConnector_3049); types.add(EsbElementTypes.EventMediatorInputConnector_3052); types.add(EsbElementTypes.EntitlementMediatorInputConnector_3055); types.add(EsbElementTypes.ClassMediatorInputConnector_3058); types.add(EsbElementTypes.SpringMediatorInputConnector_3061); types.add(EsbElementTypes.ScriptMediatorInputConnector_3064); types.add(EsbElementTypes.FaultMediatorInputConnector_3067); types.add(EsbElementTypes.XQueryMediatorInputConnector_3070); types.add(EsbElementTypes.CommandMediatorInputConnector_3073); types.add(EsbElementTypes.DBLookupMediatorInputConnector_3076); types.add(EsbElementTypes.DBReportMediatorInputConnector_3079); types.add(EsbElementTypes.SmooksMediatorInputConnector_3082); types.add(EsbElementTypes.SendMediatorInputConnector_3085); types.add(EsbElementTypes.HeaderMediatorInputConnector_3100); types.add(EsbElementTypes.CloneMediatorInputConnector_3103); types.add(EsbElementTypes.CacheMediatorInputConnector_3106); types.add(EsbElementTypes.IterateMediatorInputConnector_3109); types.add(EsbElementTypes.CalloutMediatorInputConnector_3115); types.add(EsbElementTypes.TransactionMediatorInputConnector_3118); types.add(EsbElementTypes.RMSequenceMediatorInputConnector_3124); types.add(EsbElementTypes.RuleMediatorInputConnector_3127); types.add(EsbElementTypes.OAuthMediatorInputConnector_3130); types.add(EsbElementTypes.AggregateMediatorInputConnector_3112); types.add(EsbElementTypes.StoreMediatorInputConnector_3589); types.add(EsbElementTypes.BuilderMediatorInputConnector_3592); types.add(EsbElementTypes.CallTemplateMediatorInputConnector_3595); types.add(EsbElementTypes.PayloadFactoryMediatorInputConnector_3598); types.add(EsbElementTypes.EnqueueMediatorInputConnector_3601); types.add(EsbElementTypes.URLRewriteMediatorInputConnector_3621); types.add(EsbElementTypes.ValidateMediatorInputConnector_3624); types.add(EsbElementTypes.RouterMediatorInputConnector_3629); types.add(EsbElementTypes.ConditionalRouterMediatorInputConnector_3636); types.add(EsbElementTypes.BAMMediatorInputConnector_3681); types.add(EsbElementTypes.BeanMediatorInputConnector_3684); types.add(EsbElementTypes.EJBMediatorInputConnector_3687); types.add(EsbElementTypes.DefaultEndPointInputConnector_3021); types.add(EsbElementTypes.AddressEndPointInputConnector_3030); types.add(EsbElementTypes.FailoverEndPointInputConnector_3088); types.add(EsbElementTypes.RecipientListEndPointInputConnector_3693); types.add(EsbElementTypes.WSDLEndPointInputConnector_3092); types.add(EsbElementTypes.NamedEndpointInputConnector_3661); types.add(EsbElementTypes.LoadBalanceEndPointInputConnector_3095); types.add(EsbElementTypes.APIResourceEndpointInputConnector_3675); types.add(EsbElementTypes.AddressingEndpointInputConnector_3690); types.add(EsbElementTypes.HTTPEndPointInputConnector_3710); types.add(EsbElementTypes.TemplateEndpointInputConnector_3717); types.add(EsbElementTypes.CloudConnectorInputConnector_3720); types.add(EsbElementTypes.CloudConnectorOperationInputConnector_3723); types.add(EsbElementTypes.LoopBackMediatorInputConnector_3737); types.add(EsbElementTypes.RespondMediatorInputConnector_3740); types.add(EsbElementTypes.CallMediatorInputConnector_3743); types.add(EsbElementTypes.DataMapperMediatorInputConnector_3762); types.add(EsbElementTypes.FastXSLTMediatorInputConnector_3765); types.add(EsbElementTypes.ForEachMediatorInputConnector_3781); types.add(EsbElementTypes.PublishEventMediatorInputConnector_3786); types.add(EsbElementTypes.JsonTransformMediatorInputConnector_3792); types.add(EsbElementTypes.ProxyInSequenceInputConnector_3731); types.add(EsbElementTypes.MessageInputConnector_3046); types.add(EsbElementTypes.MergeNodeFirstInputConnector_3014); types.add(EsbElementTypes.MergeNodeSecondInputConnector_3015); types.add(EsbElementTypes.SequencesInputConnector_3616); types.add(EsbElementTypes.DefaultEndPointInputConnector_3644); types.add(EsbElementTypes.AddressEndPointInputConnector_3647); types.add(EsbElementTypes.FailoverEndPointInputConnector_3650); types.add(EsbElementTypes.RecipientListEndPointInputConnector_3697); types.add(EsbElementTypes.WSDLEndPointInputConnector_3654); types.add(EsbElementTypes.LoadBalanceEndPointInputConnector_3657); types.add(EsbElementTypes.HTTPEndPointInputConnector_3713); types.add(EsbElementTypes.TemplateEndpointInputConnector_3726); types.add(EsbElementTypes.APIResourceInputConnector_3670); types.add(EsbElementTypes.APIResourceFaultInputConnector_3672); types.add(EsbElementTypes.APIResourceInSequenceInputConnector_3747); types.add(EsbElementTypes.InboundEndpointSequenceInputConnector_3768); types.add(EsbElementTypes.InboundEndpointOnErrorSequenceInputConnector_3770); } return types; } }
/* * 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.fontbox.ttf; import java.io.IOException; /** * A table in a true type font. * * @author Ben Litchfield */ public class PostScriptTable extends TTFTable { private float formatType; private float italicAngle; private short underlinePosition; private short underlineThickness; private long isFixedPitch; private long minMemType42; private long maxMemType42; private long minMemType1; private long maxMemType1; private String[] glyphNames = null; /** * A tag that identifies this table type. */ public static final String TAG = "post"; /** * This will read the required data from the stream. * * @param ttf The font that is being read. * @param data The stream to read the data from. * @throws IOException If there is an error reading the data. */ @Override public void read(TrueTypeFont ttf, TTFDataStream data) throws IOException { formatType = data.read32Fixed(); italicAngle = data.read32Fixed(); underlinePosition = data.readSignedShort(); underlineThickness = data.readSignedShort(); isFixedPitch = data.readUnsignedInt(); minMemType42 = data.readUnsignedInt(); maxMemType42 = data.readUnsignedInt(); minMemType1 = data.readUnsignedInt(); maxMemType1 = data.readUnsignedInt(); if (formatType == 1.0f) { /* * This TrueType font file contains exactly the 258 glyphs in the standard Macintosh TrueType. */ glyphNames = new String[WGL4Names.NUMBER_OF_MAC_GLYPHS]; System.arraycopy(WGL4Names.MAC_GLYPH_NAMES, 0, glyphNames, 0, WGL4Names.NUMBER_OF_MAC_GLYPHS); } else if (formatType == 2.0f) { int numGlyphs = data.readUnsignedShort(); int[] glyphNameIndex = new int[numGlyphs]; glyphNames = new String[numGlyphs]; int maxIndex = Integer.MIN_VALUE; for (int i = 0; i < numGlyphs; i++) { int index = data.readUnsignedShort(); glyphNameIndex[i] = index; // PDFBOX-808: Index numbers between 32768 and 65535 are // reserved for future use, so we should just ignore them if (index <= 32767) { maxIndex = Math.max(maxIndex, index); } } String[] nameArray = null; if (maxIndex >= WGL4Names.NUMBER_OF_MAC_GLYPHS) { nameArray = new String[maxIndex - WGL4Names.NUMBER_OF_MAC_GLYPHS + 1]; for (int i = 0; i < maxIndex - WGL4Names.NUMBER_OF_MAC_GLYPHS + 1; i++) { int numberOfChars = data.readUnsignedByte(); nameArray[i] = data.readString(numberOfChars); } } for (int i = 0; i < numGlyphs; i++) { int index = glyphNameIndex[i]; if (index < WGL4Names.NUMBER_OF_MAC_GLYPHS) { glyphNames[i] = WGL4Names.MAC_GLYPH_NAMES[index]; } else if (index >= WGL4Names.NUMBER_OF_MAC_GLYPHS && index <= 32767) { glyphNames[i] = nameArray[index - WGL4Names.NUMBER_OF_MAC_GLYPHS]; } else { // PDFBOX-808: Index numbers between 32768 and 65535 are // reserved for future use, so we should just ignore them glyphNames[i] = ".undefined"; } } } else if (formatType == 2.5f) { int[] glyphNameIndex = new int[ttf.getNumberOfGlyphs()]; for (int i = 0; i < glyphNameIndex.length; i++) { int offset = data.readSignedByte(); glyphNameIndex[i] = i + 1 + offset; } glyphNames = new String[glyphNameIndex.length]; for (int i = 0; i < glyphNames.length; i++) { String name = WGL4Names.MAC_GLYPH_NAMES[glyphNameIndex[i]]; if (name != null) { glyphNames[i] = name; } } } else if (formatType == 3.0f) { // no postscript information is provided. } initialized = true; } /** * @return Returns the formatType. */ public float getFormatType() { return formatType; } /** * @param formatTypeValue The formatType to set. */ public void setFormatType(float formatTypeValue) { this.formatType = formatTypeValue; } /** * @return Returns the isFixedPitch. */ public long getIsFixedPitch() { return isFixedPitch; } /** * @param isFixedPitchValue The isFixedPitch to set. */ public void setIsFixedPitch(long isFixedPitchValue) { this.isFixedPitch = isFixedPitchValue; } /** * @return Returns the italicAngle. */ public float getItalicAngle() { return italicAngle; } /** * @param italicAngleValue The italicAngle to set. */ public void setItalicAngle(float italicAngleValue) { this.italicAngle = italicAngleValue; } /** * @return Returns the maxMemType1. */ public long getMaxMemType1() { return maxMemType1; } /** * @param maxMemType1Value The maxMemType1 to set. */ public void setMaxMemType1(long maxMemType1Value) { this.maxMemType1 = maxMemType1Value; } /** * @return Returns the maxMemType42. */ public long getMaxMemType42() { return maxMemType42; } /** * @param maxMemType42Value The maxMemType42 to set. */ public void setMaxMemType42(long maxMemType42Value) { this.maxMemType42 = maxMemType42Value; } /** * @return Returns the mimMemType1. */ public long getMinMemType1() { return minMemType1; } /** * @param mimMemType1Value The mimMemType1 to set. */ public void setMimMemType1(long mimMemType1Value) { this.minMemType1 = mimMemType1Value; } /** * @return Returns the minMemType42. */ public long getMinMemType42() { return minMemType42; } /** * @param minMemType42Value The minMemType42 to set. */ public void setMinMemType42(long minMemType42Value) { this.minMemType42 = minMemType42Value; } /** * @return Returns the underlinePosition. */ public short getUnderlinePosition() { return underlinePosition; } /** * @param underlinePositionValue The underlinePosition to set. */ public void setUnderlinePosition(short underlinePositionValue) { this.underlinePosition = underlinePositionValue; } /** * @return Returns the underlineThickness. */ public short getUnderlineThickness() { return underlineThickness; } /** * @param underlineThicknessValue The underlineThickness to set. */ public void setUnderlineThickness(short underlineThicknessValue) { this.underlineThickness = underlineThicknessValue; } /** * @return Returns the glyphNames. */ public String[] getGlyphNames() { return glyphNames; } /** * @param glyphNamesValue The glyphNames to set. */ public void setGlyphNames(String[] glyphNamesValue) { this.glyphNames = glyphNamesValue; } /** * @return Returns the glyph name. */ public String getName(int gid) { if (gid < 0 || glyphNames == null || gid > glyphNames.length) { return null; } return glyphNames[gid]; } }
/** * 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.processor; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Future; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.spi.ExchangeFormatter; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriParams; import org.apache.camel.util.MessageHelper; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.StringHelper; /** * Default {@link ExchangeFormatter} that have fine grained options to configure what to include in the output. */ @UriParams public class DefaultExchangeFormatter implements ExchangeFormatter { protected static final String LS = System.getProperty("line.separator"); private static final String SEPARATOR = "###REPLACE_ME###"; public enum OutputStyle { Default, Tab, Fixed } @UriParam(label = "formatting") private boolean showExchangeId; @UriParam(label = "formatting", defaultValue = "true") private boolean showExchangePattern = true; @UriParam(label = "formatting") private boolean showProperties; @UriParam(label = "formatting") private boolean showHeaders; @UriParam(label = "formatting", defaultValue = "true") private boolean skipBodyLineSeparator = true; @UriParam(label = "formatting", defaultValue = "true", description = "Show the message body.") private boolean showBody = true; @UriParam(label = "formatting", defaultValue = "true") private boolean showBodyType = true; @UriParam(label = "formatting") private boolean showOut; @UriParam(label = "formatting") private boolean showException; @UriParam(label = "formatting") private boolean showCaughtException; @UriParam(label = "formatting") private boolean showStackTrace; @UriParam(label = "formatting") private boolean showAll; @UriParam(label = "formatting") private boolean multiline; @UriParam(label = "formatting") private boolean showFuture; @UriParam(label = "formatting") private boolean showStreams; @UriParam(label = "formatting") private boolean showFiles; @UriParam(label = "formatting", defaultValue = "10000") private int maxChars = 10000; @UriParam(label = "formatting", enums = "Default,Tab,Fixed", defaultValue = "Default") private OutputStyle style = OutputStyle.Default; private String style(String label) { if (style == OutputStyle.Default) { return String.format(", %s: ", label); } if (style == OutputStyle.Tab) { return String.format("\t%s: ", label); } else { return String.format("\t%-20s", label); } } public String format(Exchange exchange) { Message in = exchange.getIn(); StringBuilder sb = new StringBuilder(); if (showAll || showExchangeId) { if (multiline) { sb.append(SEPARATOR); } sb.append(style("Id")).append(exchange.getExchangeId()); } if (showAll || showExchangePattern) { if (multiline) { sb.append(SEPARATOR); } sb.append(style("ExchangePattern")).append(exchange.getPattern()); } if (showAll || showProperties) { if (multiline) { sb.append(SEPARATOR); } sb.append(style("Properties")).append(sortMap(exchange.getProperties())); } if (showAll || showHeaders) { if (multiline) { sb.append(SEPARATOR); } sb.append(style("Headers")).append(sortMap(in.getHeaders())); } if (showAll || showBodyType) { if (multiline) { sb.append(SEPARATOR); } sb.append(style("BodyType")).append(getBodyTypeAsString(in)); } if (showAll || showBody) { if (multiline) { sb.append(SEPARATOR); } String body = getBodyAsString(in); if (skipBodyLineSeparator) { body = StringHelper.replaceAll(body, LS, ""); } sb.append(style("Body")).append(body); } if (showAll || showException || showCaughtException) { // try exception on exchange first Exception exception = exchange.getException(); boolean caught = false; if ((showAll || showCaughtException) && exception == null) { // fallback to caught exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); caught = true; } if (exception != null) { if (multiline) { sb.append(SEPARATOR); } if (caught) { sb.append(style("CaughtExceptionType")).append(exception.getClass().getCanonicalName()); sb.append(style("CaughtExceptionMessage")).append(exception.getMessage()); } else { sb.append(style("ExceptionType")).append(exception.getClass().getCanonicalName()); sb.append(style("ExceptionMessage")).append(exception.getMessage()); } if (showAll || showStackTrace) { StringWriter sw = new StringWriter(); exception.printStackTrace(new PrintWriter(sw)); sb.append(style("StackTrace")).append(sw.toString()); } } } if (showAll || showOut) { if (exchange.hasOut()) { Message out = exchange.getOut(); if (showAll || showHeaders) { if (multiline) { sb.append(SEPARATOR); } sb.append(style("OutHeaders")).append(sortMap(out.getHeaders())); } if (showAll || showBodyType) { if (multiline) { sb.append(SEPARATOR); } sb.append(style("OutBodyType")).append(getBodyTypeAsString(out)); } if (showAll || showBody) { if (multiline) { sb.append(SEPARATOR); } String body = getBodyAsString(out); if (skipBodyLineSeparator) { body = StringHelper.replaceAll(body, LS, ""); } sb.append(style("OutBody")).append(body); } } else { if (multiline) { sb.append(SEPARATOR); } sb.append(style("Out: null")); } } if (maxChars > 0) { StringBuilder answer = new StringBuilder(); for (String s : sb.toString().split(SEPARATOR)) { if (s != null) { if (s.length() > maxChars) { s = s.substring(0, maxChars); answer.append(s).append("..."); } else { answer.append(s); } if (multiline) { answer.append(LS); } } } // switch string buffer sb = answer; } if (multiline) { sb.insert(0, "Exchange["); sb.append("]"); return sb.toString(); } else { // get rid of the leading space comma if needed if (sb.length() > 0 && sb.charAt(0) == ',' && sb.charAt(1) == ' ') { sb.replace(0, 2, ""); } sb.insert(0, "Exchange["); sb.append("]"); return sb.toString(); } } public boolean isShowExchangeId() { return showExchangeId; } /** * Show the unique exchange ID. */ public void setShowExchangeId(boolean showExchangeId) { this.showExchangeId = showExchangeId; } public boolean isShowProperties() { return showProperties; } /** * Show the exchange properties. */ public void setShowProperties(boolean showProperties) { this.showProperties = showProperties; } public boolean isShowHeaders() { return showHeaders; } /** * Show the message headers. */ public void setShowHeaders(boolean showHeaders) { this.showHeaders = showHeaders; } public boolean isSkipBodyLineSeparator() { return skipBodyLineSeparator; } /** * Whether to skip line separators when logging the message body. * This allows to log the message body in one line, setting this option to false will preserve any line separators * from the body, which then will log the body as is. */ public void setSkipBodyLineSeparator(boolean skipBodyLineSeparator) { this.skipBodyLineSeparator = skipBodyLineSeparator; } public boolean isShowBodyType() { return showBodyType; } /** * Show the body Java type. */ public void setShowBodyType(boolean showBodyType) { this.showBodyType = showBodyType; } public boolean isShowBody() { return showBody; } /* * Show the message body. */ public void setShowBody(boolean showBody) { this.showBody = showBody; } public boolean isShowOut() { return showOut; } /** * If the exchange has an out message, show the out message. */ public void setShowOut(boolean showOut) { this.showOut = showOut; } public boolean isShowAll() { return showAll; } /** * Quick option for turning all options on. (multiline, maxChars has to be manually set if to be used) */ public void setShowAll(boolean showAll) { this.showAll = showAll; } public boolean isShowException() { return showException; } /** * If the exchange has an exception, show the exception message (no stacktrace) */ public void setShowException(boolean showException) { this.showException = showException; } public boolean isShowStackTrace() { return showStackTrace; } /** * Show the stack trace, if an exchange has an exception. Only effective if one of showAll, showException or showCaughtException are enabled. */ public void setShowStackTrace(boolean showStackTrace) { this.showStackTrace = showStackTrace; } public boolean isShowCaughtException() { return showCaughtException; } /** * f the exchange has a caught exception, show the exception message (no stack trace). * A caught exception is stored as a property on the exchange (using the key {@link org.apache.camel.Exchange#EXCEPTION_CAUGHT} * and for instance a doCatch can catch exceptions. */ public void setShowCaughtException(boolean showCaughtException) { this.showCaughtException = showCaughtException; } public boolean isMultiline() { return multiline; } public int getMaxChars() { return maxChars; } /** * Limits the number of characters logged per line. */ public void setMaxChars(int maxChars) { this.maxChars = maxChars; } /** * If enabled then each information is outputted on a newline. */ public void setMultiline(boolean multiline) { this.multiline = multiline; } public boolean isShowFuture() { return showFuture; } /** * If enabled Camel will on Future objects wait for it to complete to obtain the payload to be logged. */ public void setShowFuture(boolean showFuture) { this.showFuture = showFuture; } public boolean isShowExchangePattern() { return showExchangePattern; } /** * Shows the Message Exchange Pattern (or MEP for short). */ public void setShowExchangePattern(boolean showExchangePattern) { this.showExchangePattern = showExchangePattern; } public boolean isShowStreams() { return showStreams; } /** * Whether Camel should show stream bodies or not (eg such as java.io.InputStream). * Beware if you enable this option then you may not be able later to access the message body * as the stream have already been read by this logger. * To remedy this you will have to use Stream Caching. */ public void setShowStreams(boolean showStreams) { this.showStreams = showStreams; } public boolean isShowFiles() { return showFiles; } /** * If enabled Camel will output files */ public void setShowFiles(boolean showFiles) { this.showFiles = showFiles; } public OutputStyle getStyle() { return style; } /** * Sets the outputs style to use. */ public void setStyle(OutputStyle style) { this.style = style; } // Implementation methods //------------------------------------------------------------------------- protected String getBodyAsString(Message message) { if (message.getBody() instanceof Future) { if (!isShowFuture()) { // just use a to string of the future object return message.getBody().toString(); } } return MessageHelper.extractBodyForLogging(message, "", isShowStreams(), isShowFiles(), getMaxChars(message)); } private int getMaxChars(Message message) { int maxChars = getMaxChars(); if (message.getExchange() != null) { String property = message.getExchange().getContext().getProperty(Exchange.LOG_DEBUG_BODY_MAX_CHARS); if (property != null) { maxChars = message.getExchange().getContext().getTypeConverter().convertTo(Integer.class, property); } } return maxChars; } protected String getBodyTypeAsString(Message message) { String answer = ObjectHelper.classCanonicalName(message.getBody()); if (answer != null && answer.startsWith("java.lang.")) { return answer.substring(10); } return answer; } private static Map<String, Object> sortMap(Map<String, Object> map) { Map<String, Object> answer = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER); answer.putAll(map); return answer; } }
package cgeo.geocaching.maps; import cgeo.geocaching.CachePopup; import cgeo.geocaching.R; import cgeo.geocaching.WaypointPopup; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.activity.Progress; import cgeo.geocaching.connector.gc.GCMap; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.CoordinatesType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.location.IConversion; import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl; import cgeo.geocaching.maps.interfaces.GeoPointImpl; import cgeo.geocaching.maps.interfaces.ItemizedOverlayImpl; import cgeo.geocaching.maps.interfaces.MapItemFactory; import cgeo.geocaching.maps.interfaces.MapProjectionImpl; import cgeo.geocaching.maps.interfaces.MapProvider; import cgeo.geocaching.maps.interfaces.MapViewImpl; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.models.IWaypoint; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.storage.DataStore; import cgeo.geocaching.utils.Log; import android.app.Activity; import android.content.Context; import android.content.res.Resources.NotFoundException; import android.graphics.Canvas; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.PaintFlagsDrawFilter; import android.graphics.Point; import android.location.Location; import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; public class CachesOverlay extends AbstractItemizedOverlay { private List<CachesOverlayItemImpl> items = new ArrayList<>(); private Context context = null; private boolean displayCircles = false; private final Progress progress = new Progress(); private Paint blockedCircle = null; private PaintFlagsDrawFilter setFilter = null; private PaintFlagsDrawFilter removeFilter = null; private MapItemFactory mapItemFactory = null; public CachesOverlay(final ItemizedOverlayImpl ovlImpl, final Context contextIn) { super(ovlImpl); populate(); context = contextIn; final MapProvider mapProvider = Settings.getMapProvider(); mapItemFactory = mapProvider.getMapItemFactory(); } void updateItems(final CachesOverlayItemImpl item) { final List<CachesOverlayItemImpl> itemsPre = new ArrayList<>(); itemsPre.add(item); updateItems(itemsPre); } void updateItems(final List<CachesOverlayItemImpl> itemsPre) { if (itemsPre == null) { return; } for (final CachesOverlayItemImpl item : itemsPre) { item.setMarker(boundCenterBottom(item.getMarker(0))); } // ensure no interference between the draw and content changing routines getOverlayImpl().lock(); try { items = new ArrayList<>(itemsPre); setLastFocusedItemIndex(-1); // to reset tap during data change populate(); } finally { getOverlayImpl().unlock(); } } boolean getCircles() { return displayCircles; } void switchCircles() { displayCircles = !displayCircles; } @Override public void draw(final Canvas canvas, final MapViewImpl mapView, final boolean shadow) { drawInternal(canvas, mapView.getMapProjection()); super.draw(canvas, mapView, false); } @Override public void drawOverlayBitmap(final Canvas canvas, final Point drawPosition, final MapProjectionImpl projection, final byte drawZoomLevel) { drawInternal(canvas, projection); super.drawOverlayBitmap(canvas, drawPosition, projection, drawZoomLevel); } private void drawInternal(final Canvas canvas, final MapProjectionImpl projection) { if (!displayCircles || items.isEmpty()) { return; } // prevent content changes getOverlayImpl().lock(); try { lazyInitializeDrawingObjects(); canvas.setDrawFilter(setFilter); final int height = canvas.getHeight(); final int width = canvas.getWidth(); final int radius = calculateDrawingRadius(projection); final Point center = new Point(); for (final CachesOverlayItemImpl item : items) { if (item.applyDistanceRule()) { final Geopoint itemCoord = item.getCoord().getCoords(); final GeoPointImpl itemGeo = mapItemFactory.getGeoPointBase(itemCoord); projection.toPixels(itemGeo, center); if (center.x > -radius && center.y > -radius && center.x < width + radius && center.y < height + radius) { // dashed circle around the waypoint blockedCircle.setColor(0x66BB0000); blockedCircle.setStyle(Style.STROKE); canvas.drawCircle(center.x, center.y, radius, blockedCircle); // filling the circle area with a transparent color blockedCircle.setColor(0x44BB0000); blockedCircle.setStyle(Style.FILL); canvas.drawCircle(center.x, center.y, radius, blockedCircle); } } } canvas.setDrawFilter(removeFilter); } finally { getOverlayImpl().unlock(); } } /** * Calculate the radius of the circle to be drawn for the first item only. Those circles are only 528 feet * (approximately 161 meters) in reality and therefore the minor changes due to the projection will not make any * visible difference at the zoom levels which are used to see the circles. * */ private int calculateDrawingRadius(final MapProjectionImpl projection) { final float[] distanceArray = new float[1]; final Geopoint itemCoord = items.get(0).getCoord().getCoords(); Location.distanceBetween(itemCoord.getLatitude(), itemCoord.getLongitude(), itemCoord.getLatitude(), itemCoord.getLongitude() + 1, distanceArray); final float longitudeLineDistance = distanceArray[0]; final GeoPointImpl itemGeo = mapItemFactory.getGeoPointBase(itemCoord); final Geopoint leftCoords = new Geopoint(itemCoord.getLatitude(), itemCoord.getLongitude() - 528.0 * IConversion.FEET_TO_KILOMETER * 1000.0 / longitudeLineDistance); final GeoPointImpl leftGeo = mapItemFactory.getGeoPointBase(leftCoords); final Point center = new Point(); projection.toPixels(itemGeo, center); final Point left = new Point(); projection.toPixels(leftGeo, left); return center.x - left.x; } private void lazyInitializeDrawingObjects() { if (blockedCircle == null) { blockedCircle = new Paint(); blockedCircle.setAntiAlias(true); blockedCircle.setStrokeWidth(2.0f); blockedCircle.setARGB(127, 0, 0, 0); blockedCircle.setPathEffect(new DashPathEffect(new float[] { 3, 2 }, 0)); } if (setFilter == null) { setFilter = new PaintFlagsDrawFilter(0, Paint.FILTER_BITMAP_FLAG); } if (removeFilter == null) { removeFilter = new PaintFlagsDrawFilter(Paint.FILTER_BITMAP_FLAG, 0); } } @Override public boolean onTap(final int index) { try { if (items.size() <= index) { return false; } progress.show(context, context.getString(R.string.map_live), context.getString(R.string.cache_dialog_loading_details), true, null); // prevent concurrent changes getOverlayImpl().lock(); CachesOverlayItemImpl item = null; try { if (index < items.size()) { item = items.get(index); } } finally { getOverlayImpl().unlock(); } if (item == null) { return false; } final IWaypoint coordinate = item.getCoord(); final CoordinatesType coordType = coordinate.getCoordType(); if (coordType == CoordinatesType.CACHE && StringUtils.isNotBlank(coordinate.getGeocode())) { final Geocache cache = DataStore.loadCache(coordinate.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); if (cache != null) { final RequestDetailsThread requestDetailsThread = new RequestDetailsThread(cache); if (!requestDetailsThread.requestRequired()) { // don't show popup if we have enough details progress.dismiss(); } requestDetailsThread.start(); return true; } progress.dismiss(); return false; } if (coordType == CoordinatesType.WAYPOINT && coordinate.getId() >= 0) { CGeoMap.markCacheAsDirty(coordinate.getGeocode()); WaypointPopup.startActivity(context, coordinate.getId(), coordinate.getGeocode()); } else { progress.dismiss(); return false; } progress.dismiss(); } catch (final NotFoundException e) { Log.e("CachesOverlay.onTap", e); progress.dismiss(); } return true; } @Override public CachesOverlayItemImpl createItem(final int index) { try { return items.get(index); } catch (final Exception e) { Log.e("CachesOverlay.createItem", e); } return null; } @Override public int size() { return items.size(); } private class RequestDetailsThread extends Thread { @NonNull private final Geocache cache; RequestDetailsThread(@NonNull final Geocache cache) { this.cache = cache; } public boolean requestRequired() { return cache.getType() == CacheType.UNKNOWN || cache.getDifficulty() == 0; } @Override public void run() { if (requestRequired()) { try { /* final SearchResult search = */GCMap.searchByGeocodes(Collections.singleton(cache.getGeocode())); } catch (final Exception ex) { Log.w("Error requesting cache popup info", ex); ActivityMixin.showToast((Activity) context, R.string.err_request_popup_info); } } CGeoMap.markCacheAsDirty(cache.getGeocode()); CachePopup.startActivity(context, cache.getGeocode()); progress.dismiss(); } } }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.uiDesigner.clientProperties; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.AtomicNotNullLazyValue; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.uiDesigner.LoaderFactory; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; @State(name = "ClientPropertiesManager", defaultStateAsResource = true) public class ClientPropertiesManager implements PersistentStateComponent<Element> { private static final Logger LOG = Logger.getInstance(ClientPropertiesManager.class); @NonNls private static final String ELEMENT_PROPERTIES = "properties"; @NonNls private static final String ELEMENT_PROPERTY = "property"; @NonNls private static final String ATTRIBUTE_CLASS = "class"; @NonNls private static final String ATTRIBUTE_NAME = "name"; @NonNls private static final String COMPONENT_NAME = "ClientPropertiesManager"; public static ClientPropertiesManager getInstance(@NotNull Project project) { return ServiceManager.getService(project, ClientPropertiesManager.class); } private static final NotNullLazyValue<ClientPropertiesManager> ourDefaultManager = new AtomicNotNullLazyValue<ClientPropertiesManager>() { @NotNull @Override protected ClientPropertiesManager compute() { ClientPropertiesManager result = new ClientPropertiesManager(); try { result.loadState(JDOMUtil.load(ClientPropertiesManager.class.getResourceAsStream("/" + COMPONENT_NAME + ".xml"))); } catch (Exception e) { LOG.error(e); } return result; } }; private final Map<String, List<ClientProperty>> myPropertyMap = new TreeMap<>(); public ClientPropertiesManager() { } private ClientPropertiesManager(final Map<String, List<ClientProperty>> propertyMap) { this(); myPropertyMap.putAll(propertyMap); } @SuppressWarnings("MethodDoesntCallSuperMethod") @Override public ClientPropertiesManager clone() { return new ClientPropertiesManager(myPropertyMap); } public void saveFrom(final ClientPropertiesManager manager) { myPropertyMap.clear(); myPropertyMap.putAll(manager.myPropertyMap); } public static class ClientProperty implements Comparable { private final String myName; private final String myClass; public ClientProperty(final String name, final String aClass) { myName = name; myClass = aClass; } public String getName() { return myName; } public String getValueClass() { return myClass; } @Override public int compareTo(final Object o) { ClientProperty prop = (ClientProperty) o; return myName.compareTo(prop.getName()); } public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ClientProperty that = (ClientProperty)o; if (!myClass.equals(that.myClass)) return false; if (!myName.equals(that.myName)) return false; return true; } public int hashCode() { int result; result = myName.hashCode(); result = 31 * result + myClass.hashCode(); return result; } } @Override public void loadState(@NotNull Element state) { myPropertyMap.clear(); for (Element propertiesElement : state.getChildren(ELEMENT_PROPERTIES)) { String aClass = propertiesElement.getAttributeValue(ATTRIBUTE_CLASS); List<ClientProperty> classProps = new ArrayList<>(); for (Element propertyElement : propertiesElement.getChildren(ELEMENT_PROPERTY)) { String propName = propertyElement.getAttributeValue(ATTRIBUTE_NAME); String propClass = propertyElement.getAttributeValue(ATTRIBUTE_CLASS); classProps.add(new ClientProperty(propName, propClass)); } myPropertyMap.put(aClass, classProps); } } @Nullable @Override public Element getState() { Element element = new Element("state"); if (equals(ourDefaultManager.getValue())) { return element; } for (Map.Entry<String, List<ClientProperty>> entry : myPropertyMap.entrySet()) { Element propertiesElement = new Element(ELEMENT_PROPERTIES); propertiesElement.setAttribute(ATTRIBUTE_CLASS, entry.getKey()); for (ClientProperty prop : entry.getValue()) { Element propertyElement = new Element(ELEMENT_PROPERTY); propertyElement.setAttribute(ATTRIBUTE_NAME, prop.getName()); propertyElement.setAttribute(ATTRIBUTE_CLASS, prop.getValueClass()); propertiesElement.addContent(propertyElement); } element.addContent(propertiesElement); } return element; } public void addConfiguredProperty(final Class selectedClass, final ClientProperty enteredProperty) { List<ClientProperty> list = myPropertyMap.get(selectedClass.getName()); if (list == null) { list = new ArrayList<>(); myPropertyMap.put(selectedClass.getName(), list); } list.add(enteredProperty); } public void removeConfiguredProperty(final Class selectedClass, final String name) { List<ClientProperty> list = myPropertyMap.get(selectedClass.getName()); if (list != null) { for(ClientProperty prop: list) { if (prop.getName().equals(name)) { list.remove(prop); break; } } } } public List<Class> getConfiguredClasses(@NotNull Project project) { List<Class> result = new ArrayList<>(); for(String className: myPropertyMap.keySet()) { try { result.add(Class.forName(className, true, LoaderFactory.getInstance(project).getProjectClassLoader())); } catch (ClassNotFoundException e) { // TODO: do something better than ignore? } } return result; } public void addClientPropertyClass(final String className) { if (!myPropertyMap.containsKey(className)) { myPropertyMap.put(className, new ArrayList<>()); } } public void removeClientPropertyClass(final Class selectedClass) { myPropertyMap.remove(selectedClass.getName()); } public List<ClientProperty> getConfiguredProperties(Class componentClass) { List<ClientProperty> list = myPropertyMap.get(componentClass.getName()); if (list == null) { return Collections.emptyList(); } return new ArrayList<>(list); } @NotNull public List<ClientProperty> getClientProperties(Class componentClass) { List<ClientProperty> result = new ArrayList<>(); while(!componentClass.getName().equals(Object.class.getName())) { List<ClientProperty> props = myPropertyMap.get(componentClass.getName()); if (props != null) { result.addAll(props); } componentClass = componentClass.getSuperclass(); } result.sort(null); return result; } @Override public boolean equals(Object obj) { if (!(obj instanceof ClientPropertiesManager)) { return false; } ClientPropertiesManager rhs = (ClientPropertiesManager) obj; if (rhs.myPropertyMap.size() != myPropertyMap.size()) { return false; } for(Map.Entry<String, List<ClientProperty>> entry: myPropertyMap.entrySet()) { List<ClientProperty> rhsList = rhs.myPropertyMap.get(entry.getKey()); if (rhsList == null || rhsList.size() != entry.getValue().size()) { return false; } for(ClientProperty prop: entry.getValue()) { if (!rhsList.contains(prop)) { return false; } } } return true; } }