repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
scheib/chromium | content/public/test/android/javatests/src/org/chromium/content_public/browser/test/mock/MockNavigationController.java | 2977 | // Copyright 2019 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.content_public.browser.test.mock;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.NavigationController;
import org.chromium.content_public.browser.NavigationEntry;
import org.chromium.content_public.browser.NavigationHistory;
/**
* Mock NavigationController implementation for Test.
*/
public class MockNavigationController implements NavigationController {
@Override
public boolean canGoBack() {
return false;
}
@Override
public boolean canGoForward() {
return false;
}
@Override
public boolean canGoToOffset(int offset) {
return false;
}
@Override
public void goToOffset(int offset) {}
@Override
public void goBack() {}
@Override
public void goForward() {}
@Override
public boolean isInitialNavigation() {
return false;
}
@Override
public void loadIfNecessary() {}
@Override
public boolean needsReload() {
return false;
}
@Override
public void setNeedsReload() {}
@Override
public void reload(boolean checkForRepost) {}
@Override
public void reloadBypassingCache(boolean checkForRepost) {}
@Override
public void cancelPendingReload() {}
@Override
public void continuePendingReload() {}
@Override
public void loadUrl(LoadUrlParams params) {}
@Override
public void clearHistory() {}
@Override
public NavigationHistory getNavigationHistory() {
return null;
}
@Override
public void clearSslPreferences() {}
@Override
public boolean getUseDesktopUserAgent() {
return false;
}
@Override
public void setUseDesktopUserAgent(boolean override, boolean reloadOnChange) {}
@Override
public NavigationEntry getEntryAtIndex(int index) {
return null;
}
@Override
public NavigationEntry getVisibleEntry() {
return null;
}
@Override
public NavigationEntry getPendingEntry() {
return null;
}
@Override
public NavigationHistory getDirectedNavigationHistory(boolean isForward, int itemLimit) {
return null;
}
@Override
public void goToNavigationIndex(int index) {}
@Override
public int getLastCommittedEntryIndex() {
return -1;
}
@Override
public boolean removeEntryAtIndex(int index) {
return false;
}
@Override
public void pruneForwardEntries() {}
@Override
public String getEntryExtraData(int index, String key) {
return null;
}
@Override
public void setEntryExtraData(int index, String key, String value) {}
@Override
public boolean isEntryMarkedToBeSkipped(int index) {
return false;
}
}
| bsd-3-clause |
arturog8m/ocs | bundle/edu.gemini.pot/src/main/java/edu/gemini/spModel/gemini/seqcomp/SeqRepeatSmartGcalObsCB.java | 10166 | package edu.gemini.spModel.gemini.seqcomp;
import edu.gemini.pot.sp.ISPSeqComponent;
import edu.gemini.pot.sp.SPNodeKey;
import edu.gemini.spModel.config.IConfigBuilder;
import edu.gemini.spModel.config.MetaDataConfig;
import edu.gemini.spModel.config2.Config;
import edu.gemini.spModel.data.config.DefaultSysConfig;
import edu.gemini.spModel.data.config.IConfig;
import edu.gemini.spModel.data.config.ISysConfig;
import edu.gemini.spModel.data.config.StringParameter;
import edu.gemini.spModel.dataflow.GsaSequenceEditor;
import edu.gemini.spModel.gemini.calunit.calibration.*;
import edu.gemini.spModel.gemini.calunit.smartgcal.Calibration;
import edu.gemini.spModel.gemini.calunit.smartgcal.CalibrationKey;
import edu.gemini.spModel.gemini.calunit.smartgcal.CalibrationKeyProvider;
import edu.gemini.spModel.gemini.calunit.smartgcal.CalibrationProvider;
import edu.gemini.spModel.gemini.seqcomp.smartgcal.SmartgcalSysConfig;
import edu.gemini.spModel.obsclass.ObsClass;
import edu.gemini.spModel.obscomp.InstConstants;
import edu.gemini.spModel.seqcomp.SeqConfigNames;
import edu.gemini.spModel.seqcomp.SeqRepeatCbOptions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* A configuration builder for the Gemini CalUnit sequence
* component that include coadds and exposure time.
*/
public abstract class SeqRepeatSmartGcalObsCB implements IConfigBuilder, Cloneable {
private final SPNodeKey nodeId;
private final ISPSeqComponent seqComponent;
// private transient ObsClass _obsClass;
private transient List<Config> _plannedSteps;
private transient int _stepCount;
private transient int _executedSteps;
private transient CalibrationProvider _calibrationProvider;
private transient boolean _firstTime;
public static class BasecalDay extends SeqRepeatSmartGcalObsCB {
public BasecalDay(ISPSeqComponent seqComp) {
super(seqComp);
}
protected List<Calibration> filter(List<Calibration> calibrations) {
List<Calibration> filteredCalibrations = new ArrayList<>();
for (Calibration c : calibrations) {
if (c.isBasecalDay()) {
filteredCalibrations.add(c);
}
}
return filteredCalibrations;
}
}
public static class BasecalNight extends SeqRepeatSmartGcalObsCB {
public BasecalNight(ISPSeqComponent seqComp) {
super(seqComp);
}
protected List<Calibration> filter(List<Calibration> calibrations) {
List<Calibration> filteredCalibrations = new ArrayList<>();
for (Calibration c : calibrations) {
if (c.isBasecalNight()) {
filteredCalibrations.add(c);
}
}
return filteredCalibrations;
}
}
public static class Flat extends SeqRepeatSmartGcalObsCB {
public Flat(ISPSeqComponent seqComp) {
super(seqComp);
}
protected List<Calibration> filter(List<Calibration> calibrations) {
List<Calibration> filteredCalibrations = new ArrayList<>();
for (Calibration c : calibrations) {
if (c.isFlat()) {
filteredCalibrations.add(c);
}
}
return filteredCalibrations;
}
}
public static class Arc extends SeqRepeatSmartGcalObsCB {
public Arc(ISPSeqComponent seqComp) {
super(seqComp);
}
protected List<Calibration> filter(List<Calibration> calibrations) {
List<Calibration> filteredCalibrations = new ArrayList<>();
for (Calibration c : calibrations) {
if (c.isArc()) {
filteredCalibrations.add(c);
}
}
return filteredCalibrations;
}
}
protected abstract List<Calibration> filter(List<Calibration> calibrations);
public SeqRepeatSmartGcalObsCB(ISPSeqComponent seqComp) {
nodeId = seqComp.getNodeKey();
seqComponent = seqComp;
}
public Object clone() {
SeqRepeatSmartGcalObsCB result;
try {
result = (SeqRepeatSmartGcalObsCB) super.clone();
} catch (CloneNotSupportedException ex) {
// Won't happen, since Object implements cloneable ...
throw new InternalError();
}
_plannedSteps = null;
return result;
}
@Override
public void reset(Map<String, Object> options) {
_firstTime = true;
_plannedSteps = new ArrayList<>();
_stepCount = 0;
_executedSteps = 0;
_calibrationProvider = SeqRepeatCbOptions.getCalibrationProvider(options);
}
@Override
public boolean hasNext() {
return (_firstTime) || (_stepCount < _plannedSteps.size()) || (_stepCount < _executedSteps);
}
@Override
public void applyNext(IConfig current, IConfig prevFull) {
_firstTime = false;
// The node id will be used to tie steps with sequence iterator nodes.
MetaDataConfig mdc = MetaDataConfig.extract(current);
mdc.addNodeKey(nodeId);
setSmartValues(current, prevFull);
}
private ISysConfig getSysConfig(IConfig config, String name) {
ISysConfig sys = config.getSysConfig(name);
if (sys == null) {
sys = new DefaultSysConfig(name);
config.appendSysConfig(sys);
}
return sys;
}
private ISysConfig getObserveConfig(IConfig config) {
return getSysConfig(config, SeqConfigNames.OBSERVE_CONFIG_NAME);
}
private List<Config> getPlannedSteps(IConfig current, IConfig prev) {
ISysConfig instrumentConfig = current.getSysConfig(SeqConfigNames.INSTRUMENT_CONFIG_NAME);
if (instrumentConfig == null) instrumentConfig = new DefaultSysConfig(SeqConfigNames.INSTRUMENT_CONFIG_NAME);
ISysConfig prevInstrumentConfig = prev.getSysConfig(SeqConfigNames.INSTRUMENT_CONFIG_NAME);
if (prevInstrumentConfig != null) {
prevInstrumentConfig = (ISysConfig) prevInstrumentConfig.clone();
prevInstrumentConfig.mergeParameters(instrumentConfig);
instrumentConfig = prevInstrumentConfig;
}
if (_plannedSteps.size() == 0) {
// by default no calibrations are available
List<Calibration> calibrations = Collections.emptyList();
// check if there is a calibration provider available (i.e. instrument supports smart calibrations)
CalibrationKeyProvider provider = SmartgcalSysConfig.extract(current).getCalibrationKeyProvider();
if (provider != null) {
// extract the calibration lookup key for this instrument configuration
CalibrationKey key = provider.extractKey(instrumentConfig);
calibrations = filter(_calibrationProvider.getCalibrations(key));
}
int stepCount = 0;
for (Calibration cal : calibrations) {
for (int i=0; i<cal.getObserve(); ++i) {
_plannedSteps.add(CalConfigFactory.complete(cal, stepCount++));
}
}
}
return _plannedSteps;
}
private boolean isComplete(IConfig current) {
return MetaDataConfig.extract(current).isComplete() && (SmartgcalSysConfig.extract(current).getStepNumber() >= 0);
}
private void setSmartValues(IConfig current, IConfig prev) {
List<Config> steps = getPlannedSteps(current, prev);
if (isComplete(current)) {
_executedSteps = SmartgcalSysConfig.extract(current).getExecutedSteps();
// Fundamental items will already be in the sequence. Fill in the
// derived items.
IndexedCalibrationStep ics = new IConfigBackedIndexedCalibrationStep(current, prev);
Config c = CalConfigFactory.complete(ics);
CalConfigBuilderUtil.updateIConfig(c, current, prev);
} else if (steps.size() == 0) {
getObserveConfig(current).putParameter(StringParameter.getInstance(InstConstants.OBSERVE_TYPE_PROP, InstConstants.CAL_OBSERVE_TYPE));
SmartgcalSysConfig ssc = SmartgcalSysConfig.extract(current);
ssc.setMappingError(true);
} else {
Config step = steps.get(_stepCount);
setObsClass(current, step);
CalConfigBuilderUtil.updateIConfig(step, current, prev);
}
++_stepCount;
}
private void setObsClass(IConfig current, Config step) {
SeqRepeatSmartGcalObs c = (SeqRepeatSmartGcalObs) seqComponent.getDataObject();
final ObsClass obsClass;
if (c.getObsClass() == null) {
// auto mode -> calculate observe class for calibration (depends on node type and baseline calibration type (night/day))
obsClass = calculateAutoObsClass(step);
} else {
// manual mode -> we use the value that is set in the GUI component
obsClass = c.getObsClass();
}
getObserveConfig(current).putParameter(StringParameter.getInstance(InstConstants.OBS_CLASS_PROP, obsClass.sequenceValue()));
GsaSequenceEditor.instance.addProprietaryPeriod(current, seqComponent.getProgram(), obsClass);
}
private ObsClass calculateAutoObsClass(Config step) {
Boolean isBaselineNight = (Boolean) step.getItemValue(CalDictionary.BASECAL_NIGHT_ITEM.key);
ObsClass autoObsClass;
if (this instanceof BasecalDay) {
autoObsClass = ObsClass.DAY_CAL;
} else if (this instanceof BasecalNight) {
autoObsClass = ObsClass.PARTNER_CAL;
} else if (this instanceof Flat) {
autoObsClass = isBaselineNight ? ObsClass.PARTNER_CAL : ObsClass.PROG_CAL;
} else if (this instanceof Arc) {
autoObsClass = isBaselineNight ? ObsClass.PARTNER_CAL : ObsClass.PROG_CAL;
} else {
throw new InternalError("unknown node type");
}
return autoObsClass;
}
}
| bsd-3-clause |
BeyondTheBoundary/cspoker | client/common/src/main/java/org/cspoker/client/common/gamestate/modifiers/RaiseState.java | 3680 | /**
* 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 org.cspoker.client.common.gamestate.modifiers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.cspoker.client.common.gamestate.ForwardingGameState;
import org.cspoker.client.common.gamestate.GameState;
import org.cspoker.client.common.gamestate.GameStateVisitor;
import org.cspoker.client.common.playerstate.ForwardingPlayerState;
import org.cspoker.client.common.playerstate.PlayerState;
import org.cspoker.common.api.lobby.holdemtable.event.RaiseEvent;
import org.cspoker.common.elements.player.PlayerId;
public class RaiseState
extends ForwardingGameState {
private final RaiseEvent event;
private final int newBetSize;
private final int newPotSize;
private final PlayerState playerState;
public RaiseState(final GameState gameState, final RaiseEvent event) {
super(gameState);
this.event = event;
final PlayerState oldPlayerState = super.getPlayer(event.getPlayerId());
this.newBetSize = super.getLargestBet() + event.getAmount();
final int newStack = oldPlayerState.getStack() - event.getMovedAmount();
this.newPotSize = super.getRoundPotSize() + event.getMovedAmount();
playerState = new ForwardingPlayerState(oldPlayerState) {
@Override
public int getBet() {
return RaiseState.this.newBetSize;
}
@Override
public int getTotalInvestment() {
return super.getTotalInvestment()+event.getMovedAmount();
}
@Override
public PlayerId getPlayerId() {
return RaiseState.this.event.getPlayerId();
}
@Override
public int getStack() {
return newStack;
}
@Override
public boolean hasFolded() {
return false;
}
@Override
public boolean hasChecked() {
return false;
}
@Override
public boolean hasBeenDealt() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public List<Integer> getBetProgression() {
List<Integer> result = new ArrayList<Integer>();
result.addAll(gameState.getPlayer(gameState.getLastBettor()).getBetProgression());
result.add(event.getAmount());
return Collections.unmodifiableList(result);
}
};
}
@Override
public PlayerState getPlayer(PlayerId playerId) {
if (event.getPlayerId().equals(playerId)) {
return playerState;
}
return super.getPlayer(playerId);
}
@Override
public int getLargestBet() {
return newBetSize;
}
@Override
public int getMinNextRaise() {
return Math.max(super.getMinNextRaise(),event.getAmount());
}
@Override
public int getRoundPotSize() {
return newPotSize;
}
public RaiseEvent getLastEvent() {
return event;
}
@Override
public PlayerId getLastBettor() {
return event.getPlayerId();
}
@Override
public int getNbRaises() {
return super.getNbRaises() + 1;
}
@Override
public void acceptVisitor(GameStateVisitor visitor) {
visitor.visitRaiseState(this);
}
public RaiseEvent getEvent() {
return event;
}
}
| gpl-2.0 |
BeyondTheBoundary/cspoker | external/plcafe/src/main/java/jp/ac/kobe_u/cs/prolog/lang/JavaPredicate.java | 1231 | package jp.ac.kobe_u.cs.prolog.lang;
/**
* The abstract class <code>JavaPredicate</code> contains methods for
* interoperating with Java</em>.<br>
* For example, the following builtin predicates extends this
* <code>JavaPredicate</code>.
* <ul>
* <li><code>java_constructor</code>
* <li><code>java_method</code>.
* </ul>
*
* @author Mutsunori Banbara (banbara@kobe-u.ac.jp)
* @author Naoyuki Tamura (tamura@kobe-u.ac.jp)
* @version 1.0
*/
public abstract class JavaPredicate extends Predicate {
/**
*
*/
private static final long serialVersionUID = 8631120503794625044L;
/**
* Checks whether all terms in <code>args</code> are convertible to the
* corresponding Java types in <code>paraTypes</code>.
*
* @return <code>true</code> if
* <code>args[i].convertible(paraTypes[i])</code> succeeds for all
* <code>i</code>, otherwise <code>false</code>.
* @see Term#convertible(Class)
*/
protected boolean checkParameterTypes(Class[] paraTypes, Term[] args) {
int arity;
arity = paraTypes.length;
if (arity != args.length) {
return false;
}
for (int i = 0; i < arity; i++) {
if (!args[i].convertible(paraTypes[i])) {
return false;
}
}
return true;
}
}
| gpl-2.0 |
aosm/gccfast | libjava/gnu/awt/j2d/AbstractGraphicsState.java | 3554 | /* Copyright (C) 2000, 2001 Free Software Foundation
This file is part of libgcj.
This software is copyrighted work licensed under the terms of the
Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
details. */
package gnu.awt.j2d;
import java.awt.Color;
import java.awt.Image;
import java.awt.Shape;
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.image.ImageObserver;
/**
* Base class for graphics state objects (State pattern, GOF book)
* that represents the current pipeline configuration. The Graphics2D
* object forwards most of the requests to the state object. The
* Graphics2D object itself only administers properties that are not
* specific for a certain state.
*/
public abstract class AbstractGraphicsState implements Cloneable
{
Graphics2DImpl frontend;
public void setFrontend(Graphics2DImpl frontend)
{
this.frontend = frontend;
}
public void dispose()
{
frontend = null;
}
// -------- Graphics methods:
public abstract void setColor(Color color);
public abstract void setPaintMode();
public abstract void setXORMode(Color altColor);
public abstract void setFont(Font font);
public abstract FontMetrics getFontMetrics(Font font);
public abstract void setClip(Shape clip);
public abstract Shape getClip();
public abstract Rectangle getClipBounds();
public abstract void copyArea(int x, int y,
int width, int height,
int dx, int dy);
public abstract void drawLine(int x1, int y1,
int x2, int y2);
public abstract void fillRect(int x, int y,
int width, int height);
public abstract void clearRect(int x, int y,
int width, int height);
public abstract void drawRoundRect(int x, int y,
int width, int height,
int arcWidth, int arcHeight);
public abstract void fillRoundRect(int x, int y,
int width, int height,
int arcWidth, int arcHeight);
public abstract void drawOval(int x, int y,
int width, int height);
public abstract void fillOval(int x, int y,
int width, int height);
public abstract void drawArc(int x, int y,
int width, int height,
int startAngle, int arcAngle);
public abstract void fillArc(int x, int y,
int width, int height,
int startAngle, int arcAngle);
public abstract void drawPolyline(int[] xPoints, int[] yPoints,int nPoints);
public abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints);
public abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints);
public abstract boolean drawImage(Image image, int x, int y,
ImageObserver observer);
// -------- Graphics2D methods:
public abstract void draw(Shape shape);
public abstract void fill(Shape shape);
public abstract boolean hit(Rectangle rect, Shape text, boolean onStroke);
public abstract void drawString(String text, int x, int y);
public abstract void drawString(String text, float x, float y);
public abstract void translate(int x, int y);
public abstract void translate(double tx, double ty);
public abstract void rotate(double theta);
public abstract void rotate(double theta, double x, double y);
public abstract void scale(double scaleX, double scaleY);
public abstract void shear(double shearX, double shearY);
public Object clone ()
{
return super.clone ();
}
}
| gpl-2.0 |
melissalinkert/bioformats | components/formats-bsd/test/loci/formats/utests/BaseModelReaderTest.java | 3248 | /*
* #%L
* BSD implementations of Bio-Formats readers and writers
* %%
* Copyright (C) 2005 - 2017 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* 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 loci.formats.utests;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import loci.formats.ChannelFiller;
import loci.formats.ChannelSeparator;
import loci.formats.IFormatReader;
import loci.formats.ImageReader;
import loci.formats.MinMaxCalculator;
import loci.formats.meta.IMetadata;
import loci.formats.ome.OMEXMLMetadataImpl;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
*
* @author Chris Allan <callan at blackcat dot ca>
*/
public class BaseModelReaderTest {
private BaseModelMock mock;
private File temporaryFile;
private IFormatReader reader;
private IMetadata metadata;
@BeforeClass
public void setUp() throws Exception {
mock = new BaseModelMock();
temporaryFile = File.createTempFile(this.getClass().getName(), ".ome");
SPWModelReaderTest.writeMockToFile(mock, temporaryFile, true);
}
@AfterClass
public void tearDown() throws Exception {
temporaryFile.delete();
}
@Test
public void testSetId() throws Exception {
reader = new MinMaxCalculator(new ChannelSeparator(
new ChannelFiller(new ImageReader())));
metadata = new OMEXMLMetadataImpl();
reader.setMetadataStore(metadata);
reader.setId(temporaryFile.getAbsolutePath());
}
@Test(dependsOnMethods={"testSetId"})
public void testSeriesCount() {
assertEquals(1, reader.getSeriesCount());
}
@Test(dependsOnMethods={"testSetId"})
public void testCanReadEveryPlane() throws Exception {
assertTrue(SPWModelReaderTest.canReadEveryPlane(reader));
}
}
| gpl-2.0 |
apurtell/hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/net/NioInetPeer.java | 3594 | /**
* 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.hdfs.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.ReadableByteChannel;
import org.apache.hadoop.net.SocketInputStream;
import org.apache.hadoop.net.SocketOutputStream;
import org.apache.hadoop.net.unix.DomainSocket;
/**
* Represents a peer that we communicate with by using non-blocking I/O
* on a Socket.
*/
public class NioInetPeer implements Peer {
private final Socket socket;
/**
* An InputStream which simulates blocking I/O with timeouts using NIO.
*/
private final SocketInputStream in;
/**
* An OutputStream which simulates blocking I/O with timeouts using NIO.
*/
private final SocketOutputStream out;
private final boolean isLocal;
public NioInetPeer(Socket socket) throws IOException {
this.socket = socket;
this.in = new SocketInputStream(socket.getChannel(), 0);
this.out = new SocketOutputStream(socket.getChannel(), 0);
this.isLocal = socket.getInetAddress().equals(socket.getLocalAddress());
}
@Override
public ReadableByteChannel getInputStreamChannel() {
return in;
}
@Override
public void setReadTimeout(int timeoutMs) throws IOException {
in.setTimeout(timeoutMs);
}
@Override
public int getReceiveBufferSize() throws IOException {
return socket.getReceiveBufferSize();
}
@Override
public boolean getTcpNoDelay() throws IOException {
return socket.getTcpNoDelay();
}
@Override
public void setWriteTimeout(int timeoutMs) throws IOException {
out.setTimeout(timeoutMs);
}
@Override
public boolean isClosed() {
return socket.isClosed();
}
@Override
public void close() throws IOException {
// We always close the outermost streams-- in this case, 'in' and 'out'
// Closing either one of these will also close the Socket.
try {
in.close();
} finally {
out.close();
}
}
@Override
public String getRemoteAddressString() {
SocketAddress address = socket.getRemoteSocketAddress();
return address == null ? null : address.toString();
}
@Override
public String getLocalAddressString() {
return socket.getLocalSocketAddress().toString();
}
@Override
public InputStream getInputStream() throws IOException {
return in;
}
@Override
public OutputStream getOutputStream() throws IOException {
return out;
}
@Override
public boolean isLocal() {
return isLocal;
}
@Override
public String toString() {
return "NioInetPeer(" + socket.toString() + ")";
}
@Override
public DomainSocket getDomainSocket() {
return null;
}
@Override
public boolean hasSecureChannel() {
return false;
}
}
| apache-2.0 |
szpak/spock | spock-core/src/main/java/org/spockframework/mock/response/IterableResponseGenerator.java | 1557 | /*
* Copyright 2009 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.spockframework.mock.response;
import java.util.Iterator;
import org.spockframework.mock.IChainableResponseGenerator;
import org.spockframework.mock.IMockInvocation;
import org.spockframework.runtime.GroovyRuntimeUtil;
/**
* Generates result values from an iterable object. If the iterator has no more
* values left, the previous value is returned.
*
* @author Peter Niederwieser
*/
public class IterableResponseGenerator implements IChainableResponseGenerator {
private final Iterator<?> iterator;
private Object nextValue;
public IterableResponseGenerator(Object iterable) {
iterator = GroovyRuntimeUtil.asIterator(iterable);
}
public boolean isAtEndOfCycle() {
return !iterator.hasNext();
}
public Object respond(IMockInvocation invocation) {
if (iterator.hasNext()) nextValue = iterator.next();
return GroovyRuntimeUtil.coerce(nextValue, invocation.getMethod().getReturnType());
}
}
| apache-2.0 |
apurtell/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/TestReservationInputValidator.java | 29993 | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.apache.hadoop.yarn.server.resourcemanager.reservation;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.yarn.api.protocolrecords.ReservationDeleteRequest;
import org.apache.hadoop.yarn.api.protocolrecords.ReservationListRequest;
import org.apache.hadoop.yarn.api.protocolrecords.ReservationSubmissionRequest;
import org.apache.hadoop.yarn.api.protocolrecords.ReservationUpdateRequest;
import org.apache.hadoop.yarn.api.protocolrecords.impl.pb.ReservationDeleteRequestPBImpl;
import org.apache.hadoop.yarn.api.protocolrecords.impl.pb.ReservationListRequestPBImpl;
import org.apache.hadoop.yarn.api.protocolrecords.impl.pb.ReservationSubmissionRequestPBImpl;
import org.apache.hadoop.yarn.api.protocolrecords.impl.pb.ReservationUpdateRequestPBImpl;
import org.apache.hadoop.yarn.api.records.ReservationDefinition;
import org.apache.hadoop.yarn.api.records.ReservationId;
import org.apache.hadoop.yarn.api.records.ReservationRequest;
import org.apache.hadoop.yarn.api.records.ReservationRequestInterpreter;
import org.apache.hadoop.yarn.api.records.ReservationRequests;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.impl.pb.ReservationDefinitionPBImpl;
import org.apache.hadoop.yarn.api.records.impl.pb.ReservationRequestsPBImpl;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.util.Clock;
import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestReservationInputValidator {
private static final Logger LOG = LoggerFactory
.getLogger(TestReservationInputValidator.class);
private static final String PLAN_NAME = "test-reservation";
private Clock clock;
private Map<String, Plan> plans = new HashMap<String, Plan>(1);
private ReservationSystem rSystem;
private Plan plan;
private ReservationInputValidator rrValidator;
@Before
public void setUp() {
clock = mock(Clock.class);
plan = mock(Plan.class);
rSystem = mock(ReservationSystem.class);
plans.put(PLAN_NAME, plan);
rrValidator = new ReservationInputValidator(clock);
when(clock.getTime()).thenReturn(1L);
ResourceCalculator rCalc = new DefaultResourceCalculator();
Resource resource = Resource.newInstance(10240, 10);
when(plan.getResourceCalculator()).thenReturn(rCalc);
when(plan.getTotalCapacity()).thenReturn(resource);
when(plan.getMaximumPeriodicity()).thenReturn(
YarnConfiguration.DEFAULT_RM_RESERVATION_SYSTEM_MAX_PERIODICITY);
when(rSystem.getQueueForReservation(any(ReservationId.class))).thenReturn(
PLAN_NAME);
when(rSystem.getPlan(PLAN_NAME)).thenReturn(plan);
}
@After
public void tearDown() {
rrValidator = null;
clock = null;
plan = null;
}
@Test
public void testSubmitReservationNormal() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 3);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
} catch (YarnException e) {
Assert.fail(e.getMessage());
}
Assert.assertNotNull(plan);
}
@Test
public void testSubmitReservationDoesNotExist() {
ReservationSubmissionRequest request =
new ReservationSubmissionRequestPBImpl();
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertEquals("The queue is not specified. Please try again with a "
+ "valid reservable queue.", message);
LOG.info(message);
}
}
@Test
public void testSubmitReservationInvalidPlan() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 3);
when(rSystem.getPlan(PLAN_NAME)).thenReturn(null);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message
.endsWith(" is not managed by reservation system. Please try again with a valid reservable queue."));
LOG.info(message);
}
}
@Test
public void testSubmitReservationNoDefinition() {
ReservationSubmissionRequest request =
new ReservationSubmissionRequestPBImpl();
request.setQueue(PLAN_NAME);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertEquals("Missing reservation definition. Please try again by "
+ "specifying a reservation definition.", message);
LOG.info(message);
}
}
@Test
public void testSubmitReservationInvalidDeadline() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 0, 3);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("The specified deadline: 0 is the past"));
LOG.info(message);
}
}
@Test
public void testSubmitReservationInvalidRR() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(0, 0, 1, 5, 3);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("No resources have been specified to reserve"));
LOG.info(message);
}
}
@Test
public void testSubmitReservationEmptyRR() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 0, 1, 5, 3);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("No resources have been specified to reserve"));
LOG.info(message);
}
}
@Test
public void testSubmitReservationInvalidDuration() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 3, 4);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message.startsWith("The time difference"));
Assert
.assertTrue(message
.contains("must be greater or equal to the minimum resource duration"));
LOG.info(message);
}
}
@Test
public void testSubmitReservationExceedsGangSize() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 4);
Resource resource = Resource.newInstance(512, 1);
when(plan.getTotalCapacity()).thenReturn(resource);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message.startsWith(
"The size of the largest gang in the reservation definition"));
Assert.assertTrue(message.contains(
"exceed the capacity available "));
LOG.info(message);
}
}
@Test
public void testSubmitReservationValidRecurrenceExpression() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 3, "600000");
plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
} catch (YarnException e) {
Assert.fail(e.getMessage());
}
Assert.assertNotNull(plan);
}
@Test
public void testSubmitReservationNegativeRecurrenceExpression() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 3, "-1234");
plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("Negative Period : "));
LOG.info(message);
}
}
@Test
public void testSubmitReservationMaxPeriodIndivisibleByRecurrenceExp() {
long indivisibleRecurrence =
YarnConfiguration.DEFAULT_RM_RESERVATION_SYSTEM_MAX_PERIODICITY / 2 + 1;
String recurrenceExp = Long.toString(indivisibleRecurrence);
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 3, recurrenceExp);
plan = null;
try {
plan = rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message.startsWith("The maximum periodicity:"));
LOG.info(message);
}
}
@Test
public void testSubmitReservationInvalidRecurrenceExpression() {
// first check recurrence expression
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 3, "123abc");
plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("Invalid period "));
LOG.info(message);
}
// now check duration
request =
createSimpleReservationSubmissionRequest(1, 1, 1, 50, 3, "10");
plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUtil.getNewReservationId());
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("Duration of the requested reservation:"));
LOG.info(message);
}
}
@Test
public void testUpdateReservationNormal() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 3);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
} catch (YarnException e) {
Assert.fail(e.getMessage());
}
Assert.assertNotNull(plan);
}
@Test
public void testUpdateReservationNoID() {
ReservationUpdateRequest request = new ReservationUpdateRequestPBImpl();
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message
.startsWith("Missing reservation id. Please try again by specifying a reservation id."));
LOG.info(message);
}
}
@Test
public void testUpdateReservationDoesnotExist() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 4);
ReservationId rId = request.getReservationId();
when(rSystem.getQueueForReservation(rId)).thenReturn(null);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message.equals(MessageFormat
.format(
"The specified reservation with ID: {0} is unknown. Please try again with a valid reservation.",
rId)));
LOG.info(message);
}
}
@Test
public void testUpdateReservationInvalidPlan() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 4);
when(rSystem.getPlan(PLAN_NAME)).thenReturn(null);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message
.endsWith(" is not associated with any valid plan. Please try again with a valid reservation."));
LOG.info(message);
}
}
@Test
public void testUpdateReservationNoDefinition() {
ReservationUpdateRequest request = new ReservationUpdateRequestPBImpl();
request.setReservationId(ReservationSystemTestUtil.getNewReservationId());
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message
.startsWith("Missing reservation definition. Please try again by specifying a reservation definition."));
LOG.info(message);
}
}
@Test
public void testUpdateReservationInvalidDeadline() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 0, 3);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("The specified deadline: 0 is the past"));
LOG.info(message);
}
}
@Test
public void testUpdateReservationInvalidRR() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(0, 0, 1, 5, 3);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("No resources have been specified to reserve"));
LOG.info(message);
}
}
@Test
public void testUpdateReservationEmptyRR() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 0, 1, 5, 3);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("No resources have been specified to reserve"));
LOG.info(message);
}
}
@Test
public void testUpdateReservationInvalidDuration() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 3, 4);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message
.contains("must be greater or equal to the minimum resource duration"));
LOG.info(message);
}
}
@Test
public void testUpdateReservationExceedsGangSize() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 4);
Resource resource = Resource.newInstance(512, 1);
when(plan.getTotalCapacity()).thenReturn(resource);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message.startsWith(
"The size of the largest gang in the reservation definition"));
Assert.assertTrue(message.contains(
"exceed the capacity available "));
LOG.info(message);
}
}
@Test
public void testUpdateReservationValidRecurrenceExpression() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 3, "600000");
plan = null;
try {
plan =
rrValidator.validateReservationUpdateRequest(rSystem, request);
} catch (YarnException e) {
Assert.fail(e.getMessage());
}
Assert.assertNotNull(plan);
}
@Test
public void testUpdateReservationNegativeRecurrenceExpression() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 3, "-1234");
plan = null;
try {
plan =
rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("Negative Period : "));
LOG.info(message);
}
}
@Test
public void testUpdateReservationInvalidRecurrenceExpression() {
// first check recurrence expression
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 3, "123abc");
plan = null;
try {
plan =
rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("Invalid period "));
LOG.info(message);
}
// now check duration
request =
createSimpleReservationUpdateRequest(1, 1, 1, 50, 3, "10");
plan = null;
try {
plan =
rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message
.startsWith("Duration of the requested reservation:"));
LOG.info(message);
}
}
@Test
public void testDeleteReservationNormal() {
ReservationDeleteRequest request = new ReservationDeleteRequestPBImpl();
ReservationId reservationID =
ReservationSystemTestUtil.getNewReservationId();
request.setReservationId(reservationID);
ReservationAllocation reservation = mock(ReservationAllocation.class);
when(plan.getReservationById(reservationID)).thenReturn(reservation);
Plan plan = null;
try {
plan = rrValidator.validateReservationDeleteRequest(rSystem, request);
} catch (YarnException e) {
Assert.fail(e.getMessage());
}
Assert.assertNotNull(plan);
}
@Test
public void testDeleteReservationNoID() {
ReservationDeleteRequest request = new ReservationDeleteRequestPBImpl();
Plan plan = null;
try {
plan = rrValidator.validateReservationDeleteRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message
.startsWith("Missing reservation id. Please try again by specifying a reservation id."));
LOG.info(message);
}
}
@Test
public void testDeleteReservationDoesnotExist() {
ReservationDeleteRequest request = new ReservationDeleteRequestPBImpl();
ReservationId rId = ReservationSystemTestUtil.getNewReservationId();
request.setReservationId(rId);
when(rSystem.getQueueForReservation(rId)).thenReturn(null);
Plan plan = null;
try {
plan = rrValidator.validateReservationDeleteRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message.equals(MessageFormat
.format(
"The specified reservation with ID: {0} is unknown. Please try again with a valid reservation.",
rId)));
LOG.info(message);
}
}
@Test
public void testDeleteReservationInvalidPlan() {
ReservationDeleteRequest request = new ReservationDeleteRequestPBImpl();
ReservationId reservationID =
ReservationSystemTestUtil.getNewReservationId();
request.setReservationId(reservationID);
when(rSystem.getPlan(PLAN_NAME)).thenReturn(null);
Plan plan = null;
try {
plan = rrValidator.validateReservationDeleteRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert
.assertTrue(message
.endsWith(" is not associated with any valid plan. Please try again with a valid reservation."));
LOG.info(message);
}
}
@Test
public void testListReservationsNormal() {
ReservationListRequest request = new ReservationListRequestPBImpl();
request.setQueue(ReservationSystemTestUtil.reservationQ);
request.setEndTime(1000);
request.setStartTime(0);
when(rSystem.getPlan(ReservationSystemTestUtil.reservationQ)).thenReturn
(this.plan);
Plan plan = null;
try {
plan = rrValidator.validateReservationListRequest(rSystem, request);
} catch (YarnException e) {
Assert.fail(e.getMessage());
}
Assert.assertNotNull(plan);
}
@Test
public void testListReservationsInvalidTimeIntervalDefaults() {
ReservationListRequest request = new ReservationListRequestPBImpl();
request.setQueue(ReservationSystemTestUtil.reservationQ);
// Negative time gets converted to default values for Start Time and End
// Time which are 0 and Long.MAX_VALUE respectively.
request.setEndTime(-2);
request.setStartTime(-1);
when(rSystem.getPlan(ReservationSystemTestUtil.reservationQ)).thenReturn
(this.plan);
Plan plan = null;
try {
plan = rrValidator.validateReservationListRequest(rSystem, request);
} catch (YarnException e) {
Assert.fail(e.getMessage());
}
Assert.assertNotNull(plan);
}
@Test
public void testListReservationsInvalidTimeInterval() {
ReservationListRequest request = new ReservationListRequestPBImpl();
request.setQueue(ReservationSystemTestUtil.reservationQ);
request.setEndTime(1000);
request.setStartTime(2000);
when(rSystem.getPlan(ReservationSystemTestUtil.reservationQ)).thenReturn
(this.plan);
Plan plan = null;
try {
plan = rrValidator.validateReservationListRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message.equals("The specified end time must be " +
"greater than the specified start time."));
LOG.info(message);
}
}
@Test
public void testListReservationsEmptyQueue() {
ReservationListRequest request = new ReservationListRequestPBImpl();
request.setQueue("");
Plan plan = null;
try {
plan = rrValidator.validateReservationListRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message.equals(
"The queue is not specified. Please try again with a valid " +
"reservable queue."));
LOG.info(message);
}
}
@Test
public void testListReservationsNullPlan() {
ReservationListRequest request = new ReservationListRequestPBImpl();
request.setQueue(ReservationSystemTestUtil.reservationQ);
when(rSystem.getPlan(ReservationSystemTestUtil.reservationQ)).thenReturn
(null);
Plan plan = null;
try {
plan = rrValidator.validateReservationListRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
Assert.assertNull(plan);
String message = e.getMessage();
Assert.assertTrue(message.equals(
"The specified queue: " + ReservationSystemTestUtil.reservationQ
+ " is not managed by reservation system."
+ " Please try again with a valid reservable queue."
));
LOG.info(message);
}
}
private ReservationSubmissionRequest createSimpleReservationSubmissionRequest(
int numRequests, int numContainers, long arrival, long deadline,
long duration) {
return createSimpleReservationSubmissionRequest(numRequests, numContainers,
arrival, deadline, duration, "0");
}
private ReservationSubmissionRequest createSimpleReservationSubmissionRequest(
int numRequests, int numContainers, long arrival, long deadline,
long duration, String recurrence) {
// create a request with a single atomic ask
ReservationSubmissionRequest request =
new ReservationSubmissionRequestPBImpl();
ReservationDefinition rDef = new ReservationDefinitionPBImpl();
rDef.setArrival(arrival);
rDef.setDeadline(deadline);
rDef.setRecurrenceExpression(recurrence);
if (numRequests > 0) {
ReservationRequests reqs = new ReservationRequestsPBImpl();
rDef.setReservationRequests(reqs);
if (numContainers > 0) {
ReservationRequest r =
ReservationRequest.newInstance(Resource.newInstance(1024, 1),
numContainers, 1, duration);
reqs.setReservationResources(Collections.singletonList(r));
reqs.setInterpreter(ReservationRequestInterpreter.R_ALL);
}
}
request.setQueue(PLAN_NAME);
request.setReservationDefinition(rDef);
return request;
}
private ReservationUpdateRequest createSimpleReservationUpdateRequest(
int numRequests, int numContainers, long arrival, long deadline,
long duration) {
return createSimpleReservationUpdateRequest(numRequests, numContainers,
arrival, deadline, duration, "0");
}
private ReservationUpdateRequest createSimpleReservationUpdateRequest(
int numRequests, int numContainers, long arrival, long deadline,
long duration, String recurrence) {
// create a request with a single atomic ask
ReservationUpdateRequest request = new ReservationUpdateRequestPBImpl();
ReservationDefinition rDef = new ReservationDefinitionPBImpl();
rDef.setArrival(arrival);
rDef.setDeadline(deadline);
rDef.setRecurrenceExpression(recurrence);
if (numRequests > 0) {
ReservationRequests reqs = new ReservationRequestsPBImpl();
rDef.setReservationRequests(reqs);
if (numContainers > 0) {
ReservationRequest r =
ReservationRequest.newInstance(Resource.newInstance(1024, 1),
numContainers, 1, duration);
reqs.setReservationResources(Collections.singletonList(r));
reqs.setInterpreter(ReservationRequestInterpreter.R_ALL);
}
}
request.setReservationDefinition(rDef);
request.setReservationId(ReservationSystemTestUtil.getNewReservationId());
return request;
}
}
| apache-2.0 |
leichunxin/jeesitedemo | src/main/java/com/thinkgem/jeesite/modules/cms/entity/Site.java | 3513 | /**
* Copyright © 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.thinkgem.jeesite.modules.cms.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.validator.constraints.Length;
import com.thinkgem.jeesite.common.persistence.IdEntity;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
/**
* 站点Entity
* @author ThinkGem
* @version 2013-05-15
*/
@Entity
@Table(name = "cms_site")
@DynamicInsert @DynamicUpdate
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Site extends IdEntity<Category> {
private static final long serialVersionUID = 1L;
private String name; // 站点名称
private String title; // 站点标题
private String logo; // 站点logo
private String description;// 描述,填写有助于搜索引擎优化
private String keywords;// 关键字,填写有助于搜索引擎优化
private String theme; // 主题
private String copyright;// 版权信息
private String customIndexView;// 自定义首页视图文件
public Site() {
super();
}
public Site(String id){
this();
this.id = id;
}
@Length(min=1, max=100)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Length(min=1, max=100)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
@Length(min=0, max=255)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Length(min=0, max=255)
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
@Length(min=1, max=255)
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getCustomIndexView() {
return customIndexView;
}
public void setCustomIndexView(String customIndexView) {
this.customIndexView = customIndexView;
}
/**
* 获取默认站点ID
*/
@Transient
public static String defaultSiteId(){
return "1";
}
/**
* 判断是否为默认(主站)站点
*/
@Transient
public static boolean isDefault(String id){
return id != null && id.equals(defaultSiteId());
}
/**
* 获取当前编辑的站点编号
*/
@Transient
public static String getCurrentSiteId(){
String siteId = (String)UserUtils.getCache("siteId");
return StringUtils.isNotBlank(siteId)?siteId:defaultSiteId();
}
/**
* 模板路径
*/
public static final String TPL_BASE = "/WEB-INF/views/modules/cms/front/themes";
/**
* 获得模板方案路径。如:/WEB-INF/views/modules/cms/front/themes/jeesite
*
* @return
*/
@Transient
public String getSolutionPath() {
return TPL_BASE + "/" + getTheme();
}
} | apache-2.0 |
perojonsson/bridgepoint | src/org.xtuml.bp.xtext.masl.parent/org.xtuml.bp.xtext.masl/emf-gen/org/xtuml/bp/xtext/masl/masl/structure/impl/BuiltinLibraryDefinitionImpl.java | 6737 | /**
* generated by Xtext 2.9.2
*/
package org.xtuml.bp.xtext.masl.masl.structure.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.xtuml.bp.xtext.masl.masl.structure.BuiltinLibraryDefinition;
import org.xtuml.bp.xtext.masl.masl.structure.Characteristic;
import org.xtuml.bp.xtext.masl.masl.structure.ExceptionDeclaration;
import org.xtuml.bp.xtext.masl.masl.structure.StructurePackage;
import org.xtuml.bp.xtext.masl.masl.types.TypeDeclaration;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Builtin Library Definition</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.xtuml.bp.xtext.masl.masl.structure.impl.BuiltinLibraryDefinitionImpl#getTypes <em>Types</em>}</li>
* <li>{@link org.xtuml.bp.xtext.masl.masl.structure.impl.BuiltinLibraryDefinitionImpl#getExceptions <em>Exceptions</em>}</li>
* <li>{@link org.xtuml.bp.xtext.masl.masl.structure.impl.BuiltinLibraryDefinitionImpl#getCharacteristics <em>Characteristics</em>}</li>
* </ul>
*
* @generated
*/
public class BuiltinLibraryDefinitionImpl extends MaslModelImpl implements BuiltinLibraryDefinition {
/**
* The cached value of the '{@link #getTypes() <em>Types</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTypes()
* @generated
* @ordered
*/
protected EList<TypeDeclaration> types;
/**
* The cached value of the '{@link #getExceptions() <em>Exceptions</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getExceptions()
* @generated
* @ordered
*/
protected EList<ExceptionDeclaration> exceptions;
/**
* The cached value of the '{@link #getCharacteristics() <em>Characteristics</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCharacteristics()
* @generated
* @ordered
*/
protected EList<Characteristic> characteristics;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BuiltinLibraryDefinitionImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return StructurePackage.Literals.BUILTIN_LIBRARY_DEFINITION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<TypeDeclaration> getTypes() {
if (types == null) {
types = new EObjectContainmentEList<TypeDeclaration>(TypeDeclaration.class, this, StructurePackage.BUILTIN_LIBRARY_DEFINITION__TYPES);
}
return types;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ExceptionDeclaration> getExceptions() {
if (exceptions == null) {
exceptions = new EObjectContainmentEList<ExceptionDeclaration>(ExceptionDeclaration.class, this, StructurePackage.BUILTIN_LIBRARY_DEFINITION__EXCEPTIONS);
}
return exceptions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Characteristic> getCharacteristics() {
if (characteristics == null) {
characteristics = new EObjectContainmentEList<Characteristic>(Characteristic.class, this, StructurePackage.BUILTIN_LIBRARY_DEFINITION__CHARACTERISTICS);
}
return characteristics;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__TYPES:
return ((InternalEList<?>)getTypes()).basicRemove(otherEnd, msgs);
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__EXCEPTIONS:
return ((InternalEList<?>)getExceptions()).basicRemove(otherEnd, msgs);
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__CHARACTERISTICS:
return ((InternalEList<?>)getCharacteristics()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__TYPES:
return getTypes();
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__EXCEPTIONS:
return getExceptions();
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__CHARACTERISTICS:
return getCharacteristics();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__TYPES:
getTypes().clear();
getTypes().addAll((Collection<? extends TypeDeclaration>)newValue);
return;
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__EXCEPTIONS:
getExceptions().clear();
getExceptions().addAll((Collection<? extends ExceptionDeclaration>)newValue);
return;
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__CHARACTERISTICS:
getCharacteristics().clear();
getCharacteristics().addAll((Collection<? extends Characteristic>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__TYPES:
getTypes().clear();
return;
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__EXCEPTIONS:
getExceptions().clear();
return;
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__CHARACTERISTICS:
getCharacteristics().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__TYPES:
return types != null && !types.isEmpty();
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__EXCEPTIONS:
return exceptions != null && !exceptions.isEmpty();
case StructurePackage.BUILTIN_LIBRARY_DEFINITION__CHARACTERISTICS:
return characteristics != null && !characteristics.isEmpty();
}
return super.eIsSet(featureID);
}
} //BuiltinLibraryDefinitionImpl
| apache-2.0 |
nikhilvibhav/camel | components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/AddressEndpointConfigurationConfigurer.java | 5690 | /* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.twilio;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.component.twilio.AddressEndpointConfiguration;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class AddressEndpointConfigurationConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("ApiName", org.apache.camel.component.twilio.internal.TwilioApiName.class);
map.put("City", java.lang.String.class);
map.put("CustomerName", java.lang.String.class);
map.put("IsoCountry", java.lang.String.class);
map.put("MethodName", java.lang.String.class);
map.put("PathAccountSid", java.lang.String.class);
map.put("PathSid", java.lang.String.class);
map.put("PostalCode", java.lang.String.class);
map.put("Region", java.lang.String.class);
map.put("Street", java.lang.String.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.component.twilio.AddressEndpointConfiguration target = (org.apache.camel.component.twilio.AddressEndpointConfiguration) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiname":
case "ApiName": target.setApiName(property(camelContext, org.apache.camel.component.twilio.internal.TwilioApiName.class, value)); return true;
case "city":
case "City": target.setCity(property(camelContext, java.lang.String.class, value)); return true;
case "customername":
case "CustomerName": target.setCustomerName(property(camelContext, java.lang.String.class, value)); return true;
case "isocountry":
case "IsoCountry": target.setIsoCountry(property(camelContext, java.lang.String.class, value)); return true;
case "methodname":
case "MethodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true;
case "pathaccountsid":
case "PathAccountSid": target.setPathAccountSid(property(camelContext, java.lang.String.class, value)); return true;
case "pathsid":
case "PathSid": target.setPathSid(property(camelContext, java.lang.String.class, value)); return true;
case "postalcode":
case "PostalCode": target.setPostalCode(property(camelContext, java.lang.String.class, value)); return true;
case "region":
case "Region": target.setRegion(property(camelContext, java.lang.String.class, value)); return true;
case "street":
case "Street": target.setStreet(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiname":
case "ApiName": return org.apache.camel.component.twilio.internal.TwilioApiName.class;
case "city":
case "City": return java.lang.String.class;
case "customername":
case "CustomerName": return java.lang.String.class;
case "isocountry":
case "IsoCountry": return java.lang.String.class;
case "methodname":
case "MethodName": return java.lang.String.class;
case "pathaccountsid":
case "PathAccountSid": return java.lang.String.class;
case "pathsid":
case "PathSid": return java.lang.String.class;
case "postalcode":
case "PostalCode": return java.lang.String.class;
case "region":
case "Region": return java.lang.String.class;
case "street":
case "Street": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.component.twilio.AddressEndpointConfiguration target = (org.apache.camel.component.twilio.AddressEndpointConfiguration) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "apiname":
case "ApiName": return target.getApiName();
case "city":
case "City": return target.getCity();
case "customername":
case "CustomerName": return target.getCustomerName();
case "isocountry":
case "IsoCountry": return target.getIsoCountry();
case "methodname":
case "MethodName": return target.getMethodName();
case "pathaccountsid":
case "PathAccountSid": return target.getPathAccountSid();
case "pathsid":
case "PathSid": return target.getPathSid();
case "postalcode":
case "PostalCode": return target.getPostalCode();
case "region":
case "Region": return target.getRegion();
case "street":
case "Street": return target.getStreet();
default: return null;
}
}
}
| apache-2.0 |
GlenRSmith/elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/core/security/transport/ProfileConfigurationsTests.java | 4434 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.security.transport;
import org.elasticsearch.common.settings.MockSecureSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.ssl.SslConfiguration;
import org.elasticsearch.common.ssl.SslVerificationMode;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.core.ssl.SSLService;
import org.hamcrest.Matchers;
import java.nio.file.Path;
import java.util.Map;
public class ProfileConfigurationsTests extends ESTestCase {
public void testGetSecureTransportProfileConfigurations() {
assumeFalse("Can't run in a FIPS JVM, uses JKS/PKCS12 keystores", inFipsJvm());
final Settings settings = getBaseSettings().put("path.home", createTempDir())
.put("xpack.security.transport.ssl.verification_mode", SslVerificationMode.CERTIFICATE.name())
.put("xpack.security.transport.ssl.verification_mode", SslVerificationMode.CERTIFICATE.name())
.put("transport.profiles.full.xpack.security.ssl.verification_mode", SslVerificationMode.FULL.name())
.put("transport.profiles.cert.xpack.security.ssl.verification_mode", SslVerificationMode.CERTIFICATE.name())
.build();
final Environment env = TestEnvironment.newEnvironment(settings);
SSLService sslService = new SSLService(env);
final SslConfiguration defaultConfig = sslService.getSSLConfiguration("xpack.security.transport.ssl");
final Map<String, SslConfiguration> profileConfigurations = ProfileConfigurations.get(settings, sslService, defaultConfig);
assertThat(profileConfigurations.size(), Matchers.equalTo(3));
assertThat(profileConfigurations.keySet(), Matchers.containsInAnyOrder("full", "cert", "default"));
assertThat(profileConfigurations.get("full").getVerificationMode(), Matchers.equalTo(SslVerificationMode.FULL));
assertThat(profileConfigurations.get("cert").getVerificationMode(), Matchers.equalTo(SslVerificationMode.CERTIFICATE));
assertThat(profileConfigurations.get("default"), Matchers.sameInstance(defaultConfig));
}
public void testGetInsecureTransportProfileConfigurations() {
assumeFalse("Can't run in a FIPS JVM with verification mode None", inFipsJvm());
final Settings settings = getBaseSettings().put("path.home", createTempDir())
.put("xpack.security.transport.ssl.verification_mode", SslVerificationMode.CERTIFICATE.name())
.put("transport.profiles.none.xpack.security.ssl.verification_mode", SslVerificationMode.NONE.name())
.build();
final Environment env = TestEnvironment.newEnvironment(settings);
SSLService sslService = new SSLService(env);
final SslConfiguration defaultConfig = sslService.getSSLConfiguration("xpack.security.transport.ssl");
final Map<String, SslConfiguration> profileConfigurations = ProfileConfigurations.get(settings, sslService, defaultConfig);
assertThat(profileConfigurations.size(), Matchers.equalTo(2));
assertThat(profileConfigurations.keySet(), Matchers.containsInAnyOrder("none", "default"));
assertThat(profileConfigurations.get("none").getVerificationMode(), Matchers.equalTo(SslVerificationMode.NONE));
assertThat(profileConfigurations.get("default"), Matchers.sameInstance(defaultConfig));
}
private Settings.Builder getBaseSettings() {
final Path keystore = randomBoolean()
? getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks")
: getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.p12");
MockSecureSettings secureSettings = new MockSecureSettings();
secureSettings.setString("xpack.security.transport.ssl.keystore.secure_password", "testnode");
return Settings.builder()
.setSecureSettings(secureSettings)
.put("xpack.security.transport.ssl.enabled", true)
.put("xpack.security.transport.ssl.keystore.path", keystore.toString());
}
}
| apache-2.0 |
kwave/openhab2-addons | addons/binding/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/message/H_Message.java | 4602 | /**
* Copyright (c) 2014-2016 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.max.internal.message;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.openhab.binding.max.internal.Utils;
import org.slf4j.Logger;
import com.google.common.base.Strings;
/**
* The H message contains information about the MAX! Cube.
*
* @author Andreas Heil (info@aheil.de) - Initial version
* @author Marcel Verpaalen - Details parsing, OH2 version
* @since 1.4.0
*/
public final class H_Message extends Message {
private Calendar cal = Calendar.getInstance();
public Map<String, Object> properties = new HashMap<>();
private String rawSerialNumber = null;
private String rawRFAddress = null;
private String rawFirmwareVersion = null;
private String rawConnectionId = null;
private String rawDutyCycle = null;
private String rawFreeMemorySlots = null;
private String rawCubeTimeState = null;
private String rawNTPCounter = null;
// yet unknown fields
private String rawUnknownfield4 = null;
public H_Message(String raw) {
super(raw);
String[] tokens = this.getPayload().split(Message.DELIMETER);
if (tokens.length < 11) {
throw new ArrayIndexOutOfBoundsException("MAX!Cube raw H_Message corrupt");
}
rawSerialNumber = tokens[0];
rawRFAddress = tokens[1];
rawFirmwareVersion = tokens[2].substring(0, 2) + "." + tokens[2].substring(2, 4);
rawUnknownfield4 = tokens[3];
rawConnectionId = tokens[4];
rawDutyCycle = Integer.toString(Utils.fromHex(tokens[5]));
rawFreeMemorySlots = Integer.toString(Utils.fromHex(tokens[6]));
setDateTime(tokens[7], tokens[8]);
rawCubeTimeState = tokens[9];
rawNTPCounter = Integer.toString(Utils.fromHex(tokens[10]));
properties.put("Serial number", rawSerialNumber);
properties.put("RF address (HEX)", rawRFAddress);
properties.put("Firmware version", rawFirmwareVersion);
properties.put("Connection ID", rawConnectionId);
properties.put("Unknown", rawUnknownfield4);
properties.put("Duty Cycle", rawDutyCycle);
properties.put("FreeMemorySlots", rawFreeMemorySlots);
properties.put("CubeTimeState", rawCubeTimeState);
properties.put("NTPCounter", rawNTPCounter);
}
/**
* @return the Serial Number
*/
public String getSerialNumber() {
return rawSerialNumber;
}
/**
* @return the Rf Address
*/
public String getRFAddress() {
return rawRFAddress;
}
/**
* @return the Firmware Version
*/
public String getFirmwareVersion() {
return rawFirmwareVersion;
}
/**
* @return the ConnectionId
*/
public String getConnectionId() {
return rawConnectionId;
}
/**
* @return the DutyCycle
*/
public int getDutyCycle() {
return Integer.parseInt(rawDutyCycle);
}
/**
* @return the FreeMemorySlots
*/
public int getFreeMemorySlots() {
return Integer.parseInt(rawFreeMemorySlots);
}
/**
* @return the CubeTimeState
*/
public String getCubeTimeState() {
return rawCubeTimeState;
}
/**
* @return the NTPCounter
*/
public String getNTPCounter() {
return rawNTPCounter;
}
private final void setDateTime(String hexDate, String hexTime) {
int year = Utils.fromHex(hexDate.substring(0, 2));
int month = Utils.fromHex(hexDate.substring(2, 4));
int date = Utils.fromHex(hexDate.substring(4, 6));
int hours = Utils.fromHex(hexTime.substring(0, 2));
int minutes = Utils.fromHex(hexTime.substring(2, 4));
cal.set(year, month, date, hours, minutes, 0);
}
@Override
public void debug(Logger logger) {
logger.debug("=== H_Message === ");
logger.trace("\tRAW: : {}", this.getPayload());
logger.trace("\tReading Time : {}", cal.getTime());
for (String key : properties.keySet()) {
logger.debug("\t{}:{}{}", key, Strings.repeat(" ", 25 - key.length()), properties.get(key));
}
}
@Override
public MessageType getType() {
return MessageType.H;
}
}
| epl-1.0 |
vgoldman/openhab | bundles/binding/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/messages/RFXComThermostat3Message.java | 8647 | /**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.rfxcom.internal.messages;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.DatatypeConverter;
import org.openhab.binding.rfxcom.RFXComValueSelector;
import org.openhab.binding.rfxcom.internal.RFXComException;
import org.openhab.core.library.items.ContactItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OpenClosedType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.types.State;
import org.openhab.core.types.Type;
import org.openhab.core.types.UnDefType;
/**
* RFXCOM data class for Thermostat3 message.
*
* @author Damien Servant
* @since 1.9.0
*/
public class RFXComThermostat3Message extends RFXComBaseMessage {
/*
* Thermostat3 packet layout (length 10)
* packetlength = 0
* packettype = 1
* subtype = 2
* seqnbr = 3
* unitcode1 = 4
* unitcode2 = 5
* unitcode3 = 6
* cmnd = 7
* filler = 9 'bits 3-0
* rssi = 9 'bits 7-4
*/
public enum SubType {
MERTIK_G6RH4T1(0), //Mertik G6R-H4T1
MERTIK_G6RH4TB(1), //Mertik G6R-H4TB
MERTIK_G6RH4TD(2), //Mertik G6R-H4TD
MERTIK_G6RH4S(3), //Mertik G6R-H4S
UNKNOWN(255);
private final int subType;
SubType(int subType) {
this.subType = subType;
}
SubType(byte subType) {
this.subType = subType;
}
public byte toByte() {
return (byte) subType;
}
}
public enum Commands {
OFF(0),
ON(1),
UP(2),
DOWN(3),
RUNUP_OFF2ND(4),
RUNDOWN_ON2ND(5),
STOP(6),
UNKNOWN(255);
private final int command;
Commands(int command) {
this.command = command;
}
Commands(byte command) {
this.command = command;
}
public byte toByte() {
return (byte) command;
}
}
private final static List<RFXComValueSelector> supportedValueSelectors = Arrays.asList(RFXComValueSelector.RAW_DATA,
RFXComValueSelector.SIGNAL_LEVEL, RFXComValueSelector.TEMPERATURE,
RFXComValueSelector.SET_POINT, RFXComValueSelector.CONTACT);
public SubType subType = SubType.MERTIK_G6RH4T1;
public int unitcode = 0;
public Commands command = Commands.OFF;
public int commandId = 0;
public byte signalLevel = 0;
public RFXComThermostat3Message() {
packetType = PacketType.THERMOSTAT3;
}
public RFXComThermostat3Message(byte[] data) {
encodeMessage(data);
}
@Override
public String toString() {
String str = "";
str += super.toString();
str += "\n - Sub type = " + subType;
str += "\n - Unit code = " + unitcode;
str += "\n - Command = " + command + "(" + commandId + ")";
str += "\n - Signal level = " + signalLevel;
return str;
}
@Override
public void encodeMessage(byte[] data) {
super.encodeMessage(data);
try {
subType = SubType.values()[super.subType];
} catch (Exception e) {
subType = SubType.UNKNOWN;
}
unitcode = (data[4] & 0xFF) << 16 | (data[5] & 0xFF) << 8 | (data[6] & 0xFF) << 0;
commandId = data[7];
command = Commands.UNKNOWN;
for (Commands loCmd : Commands.values()) {
if (loCmd.toByte() == commandId) {
command = loCmd;
break;
}
}
signalLevel = (byte) ((data[8] & 0xF0) >> 4);
}
@Override
public byte[] decodeMessage() {
byte[] data = new byte[9];
data[0] = 0x08;
data[1] = RFXComBaseMessage.PacketType.THERMOSTAT3.toByte();
data[2] = subType.toByte();
data[3] = seqNbr;
data[4] = (byte) ((unitcode >> 16) & 0xFF);
data[5] = (byte) ((unitcode >> 8) & 0xFF);
data[6] = (byte) (unitcode & 0xFF);
data[7] = command.toByte();
data[8] = (byte) (((signalLevel & 0x0F) << 4));
return data;
}
@Override
public String generateDeviceId() {
return String.valueOf(unitcode);
}
@Override
public State convertToState(RFXComValueSelector valueSelector) throws RFXComException {
org.openhab.core.types.State state = UnDefType.UNDEF;
if (valueSelector.getItemClass() == NumberItem.class) {
if (valueSelector == RFXComValueSelector.SIGNAL_LEVEL) {
state = new DecimalType(signalLevel);
} else if (valueSelector == RFXComValueSelector.COMMAND) {
state = new DecimalType(commandId);
} else {
throw new NumberFormatException("Can't convert " + valueSelector + " to NumberItem");
}
} else if (valueSelector.getItemClass() == StringItem.class) {
if (valueSelector == RFXComValueSelector.RAW_DATA) {
state = new StringType(DatatypeConverter.printHexBinary(rawMessage));
} else {
throw new NumberFormatException("Can't convert " + valueSelector + " to StringItem");
}
} else if (valueSelector.getItemClass() == ContactItem.class) {
if (valueSelector == RFXComValueSelector.COMMAND) {
if (subType == SubType.MERTIK_G6RH4T1) {
switch (command) {
case OFF:
case STOP:
state = OpenClosedType.OPEN;
break;
case ON:
state = OpenClosedType.CLOSED;
break;
default:
break;
}
} else {
switch (command) {
case OFF:
case RUNUP_OFF2ND:
case STOP:
state = OpenClosedType.CLOSED;
break;
case ON:
case RUNDOWN_ON2ND:
state = OpenClosedType.OPEN;
break;
default:
break;
}
}
}
} else if (valueSelector.getItemClass() == SwitchItem.class) {
if (valueSelector == RFXComValueSelector.COMMAND) {
if (subType == SubType.MERTIK_G6RH4T1) {
switch (command) {
case OFF:
case STOP:
state = OnOffType.OFF;
break;
case ON:
state = OnOffType.ON;
break;
default:
break;
}
} else {
switch (command) {
case OFF:
case RUNUP_OFF2ND:
case STOP:
state = OnOffType.OFF;
break;
case ON:
case RUNDOWN_ON2ND:
state = OnOffType.ON;
break;
default:
break;
}
}
}
}
else {
throw new NumberFormatException("Can't convert " + valueSelector + " to " + valueSelector.getItemClass());
}
return state;
}
@Override
public void convertFromState(RFXComValueSelector valueSelector, String id, Object subType, Type type,
byte seqNumber) throws RFXComException {
this.subType = ((SubType) subType);
seqNbr = seqNumber;
String[] ids = id.split("\\.");
unitcode = Byte.parseByte(ids[0]);
switch (valueSelector) {
case COMMAND:
if (type instanceof OnOffType) {
command = (type == OnOffType.ON ? Commands.ON : Commands.OFF);
} else if (type instanceof OpenClosedType) {
command = (type == OpenClosedType.CLOSED ? Commands.ON : Commands.OFF);
} else {
throw new RFXComException("Can't convert " + type + " to Command");
}
break;
default:
throw new RFXComException("Can't convert " + type + " to " + valueSelector);
}
}
@Override
public Object convertSubType(String subType) throws RFXComException {
for (SubType s : SubType.values()) {
if (s.toString().equals(subType)) {
return s;
}
}
throw new RFXComException("Unknown sub type " + subType);
}
@Override
public List<RFXComValueSelector> getSupportedValueSelectors() throws RFXComException {
return supportedValueSelectors;
}
}
| epl-1.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/jdi/Method/returnTypeNames/returntypenames001.java | 12339 | /*
* Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package nsk.jdi.Method.returnTypeNames;
import nsk.share.*;
import nsk.share.jpda.*;
import nsk.share.jdi.*;
import com.sun.jdi.*;
import java.util.*;
import java.io.*;
/**
* The test for the implementation of an object of the type <BR>
* Method. <BR>
* <BR>
* The test checks up that results of the method <BR>
* <code>com.sun.jdi.Method.returnTypeNames()</code> <BR>
* complies with its spec when a type is one of PrimitiveTypes. <BR>
* <BR>
* The cases for testing are as follows. <BR>
* <BR>
* When a gebuggee creates an object of <BR>
* the following class type: <BR>
* class returntypenames001aTestClass { <BR>
* public boolean bl () { return false; } <BR>
* public byte bt () { return 0; } <BR>
* public char ch () { return 0; } <BR>
* public double db () { return 0.0d; } <BR>
* public float fl () { return 0.0f; } <BR>
* public int in () { return 0; } <BR>
* public long ln () { return 0; } <BR>
* public short sh () { return 0; } <BR>
* } <BR>
* <BR>
* for all of the above primitive type return methods, <BR>
* the debugger forms text representations of their <BR>
* corresponding types that is boolean, byte, char, and etc. <BR>
* <BR>
*/
public class returntypenames001 {
//----------------------------------------------------- templete section
static final int PASSED = 0;
static final int FAILED = 2;
static final int PASS_BASE = 95;
//----------------------------------------------------- templete parameters
static final String
sHeader1 = "\n==> nsk/jdi/Method/returnTypeNames/returntypenames001",
sHeader2 = "--> returntypenames001: ",
sHeader3 = "##> returntypenames001: ";
//----------------------------------------------------- main method
public static void main (String argv[]) {
int result = run(argv, System.out);
System.exit(result + PASS_BASE);
}
public static int run (String argv[], PrintStream out) {
return new returntypenames001().runThis(argv, out);
}
//-------------------------------------------------- log procedures
//private static boolean verbMode = false;
private static Log logHandler;
private static void log1(String message) {
logHandler.display(sHeader1 + message);
}
private static void log2(String message) {
logHandler.display(sHeader2 + message);
}
private static void log3(String message) {
logHandler.complain(sHeader3 + message);
}
// ************************************************ test parameters
private String debuggeeName =
"nsk.jdi.Method.returnTypeNames.returntypenames001a";
String mName = "nsk.jdi.Method.returnTypeNames";
//====================================================== test program
static ArgumentHandler argsHandler;
static int testExitCode = PASSED;
//------------------------------------------------------ common section
private int runThis (String argv[], PrintStream out) {
Debugee debuggee;
argsHandler = new ArgumentHandler(argv);
logHandler = new Log(out, argsHandler);
Binder binder = new Binder(argsHandler, logHandler);
if (argsHandler.verbose()) {
debuggee = binder.bindToDebugee(debuggeeName + " -vbs"); // *** tp
} else {
debuggee = binder.bindToDebugee(debuggeeName); // *** tp
}
IOPipe pipe = new IOPipe(debuggee);
debuggee.redirectStderr(out);
log2("returntypenames001a debuggee launched");
debuggee.resume();
String line = pipe.readln();
if ((line == null) || !line.equals("ready")) {
log3("signal received is not 'ready' but: " + line);
return FAILED;
} else {
log2("'ready' recieved");
}
VirtualMachine vm = debuggee.VM();
//------------------------------------------------------ testing section
log1(" TESTING BEGINS");
for (int i = 0; ; i++) {
pipe.println("newcheck");
line = pipe.readln();
if (line.equals("checkend")) {
log2(" : returned string is 'checkend'");
break ;
} else if (!line.equals("checkready")) {
log3("ERROR: returned string is not 'checkready'");
testExitCode = FAILED;
break ;
}
log1("new check: #" + i);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ variable part
List listOfDebuggeeClasses = vm.classesByName(mName + ".returntypenames001aTestClass");
if (listOfDebuggeeClasses.size() != 1) {
testExitCode = FAILED;
log3("ERROR: listOfDebuggeeClasses.size() != 1");
break ;
}
List methods = null;
Method m = null;
String name = null;
int i2;
for (i2 = 0; ; i2++) {
int expresult = 0;
log2("new check: #" + i2);
switch (i2) {
case 0: // boolean
methods = ((ReferenceType) listOfDebuggeeClasses.get(0)).
methodsByName("bl");
m = (Method) methods.get(0);
name = m.returnTypeName();
if (!name.equals("boolean")) {
log3("ERROR: !name.equals('boolean')");
expresult = 1;
break;
}
break;
case 1: // byte
methods = ((ReferenceType) listOfDebuggeeClasses.get(0)).
methodsByName("bt");
m = (Method) methods.get(0);
name = m.returnTypeName();
if (!name.equals("byte")) {
log3("ERROR: !name.equals('byte')");
expresult = 1;
break;
}
break;
case 2: // char
methods = ((ReferenceType) listOfDebuggeeClasses.get(0)).
methodsByName("ch");
m = (Method) methods.get(0);
name = m.returnTypeName();
if (!name.equals("char")) {
log3("ERROR: !name.equals(char')");
expresult = 1;
break;
}
break;
case 3: // double
methods = ((ReferenceType) listOfDebuggeeClasses.get(0)).
methodsByName("db");
m = (Method) methods.get(0);
name = m.returnTypeName();
if (!name.equals("double")) {
log3("ERROR: !name.equals('double')");
expresult = 1;
break;
}
break;
case 4: // float
methods = ((ReferenceType) listOfDebuggeeClasses.get(0)).
methodsByName("fl");
m = (Method) methods.get(0);
name = m.returnTypeName();
if (!name.equals("float")) {
log3("ERROR: !name.equals('float')");
expresult = 1;
break;
}
break;
case 5: // int
methods = ((ReferenceType) listOfDebuggeeClasses.get(0)).
methodsByName("in");
m = (Method) methods.get(0);
name = m.returnTypeName();
if (!name.equals("int")) {
log3("ERROR: !name.equals('int')");
expresult = 1;
break;
}
break;
case 6: // long
methods = ((ReferenceType) listOfDebuggeeClasses.get(0)).
methodsByName("ln");
m = (Method) methods.get(0);
name = m.returnTypeName();
if (!name.equals("long")) {
log3("ERROR: !name.equals('long')");
expresult = 1;
break;
}
break;
case 7: // short
methods = ((ReferenceType) listOfDebuggeeClasses.get(0)).
methodsByName("sh");
m = (Method) methods.get(0);
name = m.returnTypeName();
if (!name.equals("short")) {
log3("ERROR: !name.equals('short')");
expresult = 1;
break;
}
break;
default: expresult = 2;
break ;
}
if (expresult == 2) {
log2(" test cases finished");
break ;
} else if (expresult == 1) {
log3("ERROR: expresult != true; check # = " + i);
testExitCode = FAILED;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
log1(" TESTING ENDS");
//-------------------------------------------------- test summary section
//------------------------------------------------- standard end section
pipe.println("quit");
log2("waiting for the debuggee to finish ...");
debuggee.waitFor();
int status = debuggee.getStatus();
if (status != PASSED + PASS_BASE) {
log3("debuggee returned UNEXPECTED exit status: " +
status + " != PASS_BASE");
testExitCode = FAILED;
} else {
log2("debuggee returned expected exit status: " +
status + " == PASS_BASE");
}
if (testExitCode != PASSED) {
logHandler.complain("TEST FAILED");
}
return testExitCode;
}
}
| gpl-2.0 |
md-5/jdk10 | test/langtools/tools/javac/importChecks/ImportCanonicalSameName/p2/A.java | 1094 | /*
* Copyright (c) 2017, Google Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package p2;
public class A {
public static class I {}
}
| gpl-2.0 |
CharlesZ-Chen/checker-framework | checker/jdk/nullness/src/java/lang/ExceptionInInitializerError.java | 832 | package java.lang;
import org.checkerframework.checker.nullness.qual.Nullable;
public class ExceptionInInitializerError extends LinkageError {
private static final long serialVersionUID = 1521711792217232256L;
private Throwable exception;
public ExceptionInInitializerError() {
initCause(null); // Disallow subsequent initCause
}
public ExceptionInInitializerError(@Nullable Throwable thrown) {
initCause(null); // Disallow subsequent initCause
this.exception = thrown;
}
public ExceptionInInitializerError(@Nullable String s) {
super(s);
initCause(null); // Disallow subsequent initCause
}
public @Nullable Throwable getException() {
return exception;
}
public @Nullable Throwable getCause() {
return exception;
}
}
| gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/jvmti/RedefineClasses/redefclass029/newclass/redefclass029.java | 4587 | /*
* Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package nsk.jvmti.RedefineClasses;
import java.io.*;
import java.util.*;
import nsk.share.*;
public class redefclass029 {
static int status = Consts.TEST_PASSED;
static Log log;
// dummy outer fields to be changed by the nested class
private static int prStOuterFl[] = {0,0,0};
static int packStOuterFl[] = {0,0,0};
public static int pubStOuterFl[] = {0,0,0};
/* a dummy outer private field to be accessed or not in
the nested class and thus provoking compiler to add or not
a synthetic access method into the outer class. */
private static char prOuterFieldToBeAccessed = 'a';
/**
* A copy of the outer method accessing an inner private field
* and thus provoking compiler to add a synthetic access method
* into the nested class. The same synthetic method should be
* present in the redefined nested class to avoid the error
* JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED.
*/
private void checkInnerFields(RedefClass redefCls, int expValue) {
if (redefCls.prInnerFl != expValue
|| redefCls.packInnerFl != expValue
|| redefCls.pubInnerFl != expValue) {
status = Consts.TEST_FAILED;
log.complain("TEST FAILED: unexpected values of inner fields:"
+ "\n\tprInnerFl: got: " + redefCls.prInnerFl
+ ", expected: " + expValue
+ "\n\tpackInnerFl: got: " + redefCls.packInnerFl
+ ", expected: " + expValue
+ "\n\tpubInnerFl: got: " + redefCls.pubInnerFl
+ ", expected: " + expValue);
}
}
/**
* Redefining nested class.
*/
static class RedefClass extends Thread {
boolean stopMe = false;
int iter;
// dummy inner fields to be accessed by the outer class
private int prInnerFl = 2;
int packInnerFl = 2;
public int pubInnerFl = 2;
RedefClass(int iter) {}
/**
* This method will have an active stack frame during
* nested class redefinition, so this version should not
* be invoked, and thus outer fields should not have
* values equal 2.
*/
public void run() {
status = Consts.TEST_FAILED;
log.complain("TEST FAILED: new " + this.getName()
+ ": redefined run() having an active stack frame during redefinition was invoked");
prStOuterFl[0] = 2;
packStOuterFl[0] = 2;
pubStOuterFl[0] = 2;
log.display("new " + this.getName()
+ ": exiting");
}
void warmUpMethod() {
log.display("new " + this.getName()
+ ": warmUpMethod()");
prStOuterFl[1] = 2;
packStOuterFl[1] = 2;
pubStOuterFl[1] = 2;
redefclass029HotMethod(0);
}
/**
* Hotspot method to be compiled.
*/
void redefclass029HotMethod(int i) {
log.display("new " + this.getName()
+ ": redefclass029HotMethod()");
prStOuterFl[2] = 2;
packStOuterFl[2] = 2;
pubStOuterFl[2] = 2;
}
/**
* New version of dummy method which is not accessing
* a private field of the outer class.
* So compiler should not add a synthetic access method
* into the outer class.
*/
void methAccessingOuterPrivateField() {}
}
}
| gpl-2.0 |
karlTH/ardublock | src/main/java/com/ardublock/translator/block/Esplora/Image_Width.java | 879 | package com.ardublock.translator.block.Esplora;
import com.ardublock.translator.Translator;
import com.ardublock.translator.block.TranslatorBlock;
import com.ardublock.translator.block.exception.SocketNullException;
import com.ardublock.translator.block.exception.SubroutineNotDeclaredException;
public class Image_Width extends TranslatorBlock {
public Image_Width (Long blockId, Translator translator, String codePrefix, String codeSuffix, String label)
{
super(blockId, translator, codePrefix, codeSuffix, label);
}
//@Override
public String toCode() throws SocketNullException, SubroutineNotDeclaredException
{
String PImage;
TranslatorBlock translatorBlock = this.getRequiredTranslatorBlockAtSocket(0);
PImage = translatorBlock.toCode();
String ret = PImage+".width()";
return codePrefix + ret + codeSuffix;
}
}
| gpl-3.0 |
michaltakac/astrid | astrid/plugin-src/com/todoroo/astrid/actfm/TagViewFragment.java | 35446 | /**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.actfm;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.timsu.astrid.R;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.NotificationManager;
import com.todoroo.andlib.service.NotificationManager.AndroidNotificationManager;
import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.Query;
import com.todoroo.andlib.utility.AndroidUtilities;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.DialogUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.actfm.sync.ActFmPreferenceService;
import com.todoroo.astrid.actfm.sync.ActFmSyncService;
import com.todoroo.astrid.actfm.sync.ActFmSyncThread;
import com.todoroo.astrid.actfm.sync.ActFmSyncThread.SyncMessageCallback;
import com.todoroo.astrid.actfm.sync.messages.BriefMe;
import com.todoroo.astrid.activity.AstridActivity;
import com.todoroo.astrid.activity.FilterListFragment;
import com.todoroo.astrid.activity.TaskListActivity;
import com.todoroo.astrid.activity.TaskListFragment;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.api.Filter;
import com.todoroo.astrid.api.FilterWithCustomIntent;
import com.todoroo.astrid.core.SortHelper;
import com.todoroo.astrid.dao.MetadataDao;
import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria;
import com.todoroo.astrid.dao.TagDataDao;
import com.todoroo.astrid.dao.TagMetadataDao;
import com.todoroo.astrid.dao.TagMetadataDao.TagMetadataCriteria;
import com.todoroo.astrid.dao.TaskDao.TaskCriteria;
import com.todoroo.astrid.dao.TaskListMetadataDao;
import com.todoroo.astrid.dao.UserDao;
import com.todoroo.astrid.data.RemoteModel;
import com.todoroo.astrid.data.SyncFlags;
import com.todoroo.astrid.data.TagData;
import com.todoroo.astrid.data.TagMetadata;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.data.TaskListMetadata;
import com.todoroo.astrid.data.User;
import com.todoroo.astrid.data.UserActivity;
import com.todoroo.astrid.helper.AsyncImageView;
import com.todoroo.astrid.service.SyncV2Service;
import com.todoroo.astrid.service.TagDataService;
import com.todoroo.astrid.service.ThemeService;
import com.todoroo.astrid.subtasks.SubtasksTagListFragment;
import com.todoroo.astrid.tags.TagFilterExposer;
import com.todoroo.astrid.tags.TagMemberMetadata;
import com.todoroo.astrid.tags.TagService;
import com.todoroo.astrid.tags.TagService.Tag;
import com.todoroo.astrid.tags.TaskToTagMetadata;
import com.todoroo.astrid.utility.AstridPreferences;
import com.todoroo.astrid.utility.Flags;
import com.todoroo.astrid.utility.ResourceDrawableCache;
import com.todoroo.astrid.welcome.HelpInfoPopover;
public class TagViewFragment extends TaskListFragment {
public static final String BROADCAST_TAG_ACTIVITY = AstridApiConstants.API_PACKAGE + ".TAG_ACTIVITY"; //$NON-NLS-1$
public static final String EXTRA_TAG_NAME = "tag"; //$NON-NLS-1$
@Deprecated
private static final String EXTRA_TAG_REMOTE_ID = "remoteId"; //$NON-NLS-1$
public static final String EXTRA_TAG_UUID = "uuid"; //$NON-NLS-1$
public static final String EXTRA_TAG_DATA = "tagData"; //$NON-NLS-1$
protected static final int MENU_REFRESH_ID = MENU_SUPPORT_ID + 1;
protected static final int MENU_LIST_SETTINGS_ID = R.string.tag_settings_title;
private static final int REQUEST_CODE_SETTINGS = 0;
public static final String TOKEN_START_ACTIVITY = "startActivity"; //$NON-NLS-1$
protected TagData tagData;
@Autowired TagDataService tagDataService;
@Autowired TagService tagService;
@Autowired TagDataDao tagDataDao;
@Autowired ActFmSyncService actFmSyncService;
@Autowired ActFmPreferenceService actFmPreferenceService;
@Autowired SyncV2Service syncService;
@Autowired UserDao userDao;
@Autowired MetadataDao metadataDao;
@Autowired TagMetadataDao tagMetadataDao;
@Autowired TaskListMetadataDao taskListMetadataDao;
protected View taskListView;
private boolean dataLoaded = false;
private String currentId = Task.USER_ID_IGNORE;
protected AtomicBoolean isBeingFiltered = new AtomicBoolean(false);
private Filter originalFilter;
protected boolean justDeleted = false;
// --- UI initialization
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setOnKeyListener(null);
// allow for text field entry, needed for android bug #2516
OnTouchListener onTouch = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
v.requestFocusFromTouch();
return false;
}
};
((EditText) getView().findViewById(R.id.quickAddText)).setOnTouchListener(onTouch);
View membersEdit = getView().findViewById(R.id.members_edit);
if (membersEdit != null)
membersEdit.setOnClickListener(settingsListener);
originalFilter = filter;
}
private final OnClickListener settingsListener = new OnClickListener() {
@Override
public void onClick(View v) {
Activity activity = getActivity();
Class<?> settingsClass = AstridPreferences.useTabletLayout(activity) ? TagSettingsActivityTablet.class : TagSettingsActivity.class;
Intent intent = new Intent(getActivity(), settingsClass);
intent.putExtra(EXTRA_TAG_DATA, tagData);
startActivityForResult(intent, REQUEST_CODE_SETTINGS);
if (!AstridPreferences.useTabletLayout(activity)) {
AndroidUtilities.callOverridePendingTransition(activity, R.anim.slide_left_in, R.anim.slide_left_out);
}
}
};
/* (non-Javadoc)
* @see com.todoroo.astrid.activity.TaskListActivity#getListBody(android.view.ViewGroup)
*/
@Override
protected View getListBody(ViewGroup root) {
ViewGroup parent = (ViewGroup) getActivity().getLayoutInflater().inflate(getTaskListBodyLayout(), root, false);
taskListView = super.getListBody(parent);
parent.addView(taskListView);
return parent;
}
protected int getTaskListBodyLayout() {
return R.layout.task_list_body_tag;
}
private void showListSettingsPopover() {
if (!AstridPreferences.canShowPopover())
return;
if (!Preferences.getBoolean(R.string.p_showed_list_settings_help, false)) {
Preferences.setBoolean(R.string.p_showed_list_settings_help, true);
View tabView = getView().findViewById(R.id.members_edit);
if (tabView != null)
HelpInfoPopover.showPopover(getActivity(), tabView,
R.string.help_popover_list_settings, null);
}
}
@Override
protected void addSyncRefreshMenuItem(Menu menu, int themeFlags) {
if(actFmPreferenceService.isLoggedIn()) {
addMenuItem(menu, R.string.actfm_TVA_menu_refresh,
ThemeService.getDrawable(R.drawable.icn_menu_refresh, themeFlags), MENU_REFRESH_ID, true);
} else {
super.addSyncRefreshMenuItem(menu, themeFlags);
}
}
@Override
protected void addMenuItems(Menu menu, Activity activity) {
super.addMenuItems(menu, activity);
if (!Preferences.getBoolean(R.string.p_show_list_members, true)) {
MenuItem item = menu.add(Menu.NONE, MENU_LIST_SETTINGS_ID, 0, R.string.tag_settings_title);
item.setIcon(ThemeService.getDrawable(R.drawable.list_settings));
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
}
// --- data loading
@Override
protected void initializeData() {
synchronized(this) {
if(dataLoaded)
return;
dataLoaded = true;
}
TaskListActivity activity = (TaskListActivity) getActivity();
String tag = extras.getString(EXTRA_TAG_NAME);
String uuid = RemoteModel.NO_UUID;
if (extras.containsKey(EXTRA_TAG_UUID))
uuid = extras.getString(EXTRA_TAG_UUID);
else if (extras.containsKey(EXTRA_TAG_REMOTE_ID)) // For legacy support with shortcuts, widgets, etc.
uuid = Long.toString(extras.getLong(EXTRA_TAG_REMOTE_ID));
if(tag == null && RemoteModel.NO_UUID.equals(uuid))
return;
TodorooCursor<TagData> cursor;
if (!RemoteModel.isUuidEmpty(uuid)) {
cursor = tagDataService.query(Query.select(TagData.PROPERTIES).where(TagData.UUID.eq(uuid)));
} else {
cursor = tagDataService.query(Query.select(TagData.PROPERTIES).where(TagData.NAME.eqCaseInsensitive(tag)));
}
try {
tagData = new TagData();
if(cursor.getCount() == 0) {
tagData.setValue(TagData.NAME, tag);
tagData.setValue(TagData.UUID, uuid);
tagDataService.save(tagData);
} else {
cursor.moveToFirst();
tagData.readFromCursor(cursor);
}
} finally {
cursor.close();
}
super.initializeData();
setUpMembersGallery();
if (extras.getBoolean(TOKEN_START_ACTIVITY, false)) {
extras.remove(TOKEN_START_ACTIVITY);
activity.showComments();
}
}
@Override
public TagData getActiveTagData() {
return tagData;
}
@Override
public void loadTaskListContent(boolean requery) {
super.loadTaskListContent(requery);
if(taskAdapter == null || taskAdapter.getCursor() == null)
return;
int count = taskAdapter.getCursor().getCount();
if(tagData != null && sortFlags <= SortHelper.FLAG_REVERSE_SORT &&
count != tagData.getValue(TagData.TASK_COUNT)) {
tagData.setValue(TagData.TASK_COUNT, count);
tagDataService.save(tagData);
}
updateCommentCount();
}
@Override
public void requestCommentCountUpdate() {
updateCommentCount();
}
private void updateCommentCount() {
if (tagData != null) {
long lastViewedComments = Preferences.getLong(CommentsFragment.UPDATES_LAST_VIEWED + tagData.getValue(TagData.UUID), 0);
int unreadCount = 0;
TodorooCursor<UserActivity> commentCursor = tagDataService.getUserActivityWithExtraCriteria(tagData, UserActivity.CREATED_AT.gt(lastViewedComments));
try {
unreadCount = commentCursor.getCount();
} finally {
commentCursor.close();
}
TaskListActivity tla = (TaskListActivity) getActivity();
if (tla != null)
tla.setCommentsCount(unreadCount);
}
}
// --------------------------------------------------------- refresh data
@Override
protected void initiateAutomaticSyncImpl() {
if (!isCurrentTaskListFragment())
return;
if (tagData != null) {
long lastAutosync = tagData.getValue(TagData.LAST_AUTOSYNC);
if(DateUtilities.now() - lastAutosync > AUTOSYNC_INTERVAL) {
tagData.setValue(TagData.LAST_AUTOSYNC, DateUtilities.now());
tagDataDao.saveExisting(tagData);
refreshData();
}
}
}
/** refresh the list with latest data from the web */
private void refreshData() {
if (actFmPreferenceService.isLoggedIn() && tagData != null && !RemoteModel.isUuidEmpty(tagData.getUuid())) {
((TextView)taskListView.findViewById(android.R.id.empty)).setText(R.string.DLG_loading);
SyncMessageCallback callback = new SyncMessageCallback() {
@Override
public void runOnSuccess() {
synchronized(this) {
Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
reloadTagData(false);
refresh();
((TextView)taskListView.findViewById(android.R.id.empty)).setText(R.string.TLA_no_items);
} catch (Exception e) {
// Can happen when swipe between lists is on
}
}
});
}
}
}
@Override
public void runOnErrors(List<JSONArray> errors) {
Activity activity = getActivity();
if (activity != null && activity instanceof TaskListActivity) {
boolean notAuthorized = false;
for (JSONArray error : errors) {
String errorCode = error.optString(1);
if ("not_authorized".equals(errorCode)) { //$NON-NLS-1$
notAuthorized = true;
break;
}
}
final String tagName = tagData.getValue(TagData.NAME);
if (notAuthorized) {
final TaskListActivity tla = (TaskListActivity) activity;
tla.runOnUiThread(new Runnable() {
@Override
public void run() {
DialogUtilities.okCancelCustomDialog(tla,
tla.getString(R.string.actfm_tag_not_authorized_title),
tla.getString(R.string.actfm_tag_not_authorized_body, tagName),
R.string.actfm_tag_not_authorized_new_list,
R.string.actfm_tag_not_authorized_leave_list,
android.R.drawable.ic_dialog_alert,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String oldUuid = tagData.getUuid();
tagData.setValue(TagData.DELETION_DATE, DateUtilities.now());
tagData.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
tagDataDao.saveExisting(tagData);
// TODO: Make this better
tagData.clearValue(TagData.ID);
tagData.clearValue(TagData.UUID);
tagData.clearValue(TagData.USER_ID);
tagData.clearValue(TagData.DELETION_DATE);
tagData.setValue(TagData.CREATION_DATE, DateUtilities.now());
tagDataDao.createNew(tagData);
String newUuid = tagData.getUuid();
TodorooCursor<Task> tasks = taskService.fetchFiltered(filter.getSqlQuery(), null, Task.ID, Task.UUID, Task.USER_ID);
try {
Task t = new Task();
for (tasks.moveToFirst(); !tasks.isAfterLast(); tasks.moveToNext()) {
t.clear();
t.readFromCursor(tasks);
if (Task.USER_ID_SELF.equals(t.getValue(Task.USER_ID))) {
tagService.createLink(t, tagName, newUuid);
}
}
} finally {
tasks.close();
}
tagService.deleteTagMetadata(oldUuid);
Filter newFilter = TagFilterExposer.filterFromTagData(tla, tagData);
tla.onFilterItemClicked(newFilter);
}
},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String uuid = tagData.getUuid();
tagDataDao.delete(tagData.getId());
metadataDao.deleteWhere(Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_UUID.eq(uuid)));
tagMetadataDao.deleteWhere(TagMetadata.TAG_UUID.eq(uuid));
tla.switchToActiveTasks();
}
});
}
});
}
}
}
};
ActFmSyncThread.getInstance().repopulateQueueFromOutstandingTables();
ActFmSyncThread.getInstance().enqueueMessage(new BriefMe<Task>(Task.class, null, tagData.getValue(TagData.TASKS_PUSHED_AT), BriefMe.TAG_ID_KEY, tagData.getUuid()), callback);
ActFmSyncThread.getInstance().enqueueMessage(new BriefMe<TagData>(TagData.class, tagData.getUuid(), tagData.getValue(TagData.PUSHED_AT)), callback);
ActFmSyncThread.getInstance().enqueueMessage(new BriefMe<TaskListMetadata>(TaskListMetadata.class, null, tagData.getValue(TagData.METADATA_PUSHED_AT), BriefMe.TAG_ID_KEY, tagData.getUuid()), callback);
}
}
protected void setUpMembersGallery() {
if (!Preferences.getBoolean(R.string.p_show_list_members, true)) {
getView().findViewById(R.id.members_header).setVisibility(View.GONE);
return;
}
if (tagData == null)
return;
LinearLayout membersView = (LinearLayout)getView().findViewById(R.id.shared_with);
membersView.setOnClickListener(settingsListener);
boolean addedMembers = false;
try {
String membersString = tagData.getValue(TagData.MEMBERS); // OK for legacy compatibility
if (!TextUtils.isEmpty(membersString)) {
JSONArray members = new JSONArray(membersString);
if (members.length() > 0) {
addedMembers = true;
membersView.setOnClickListener(null);
membersView.removeAllViews();
for (int i = 0; i < members.length(); i++) {
JSONObject member = members.getJSONObject(i);
addImageForMember(membersView, member);
}
}
} else {
TodorooCursor<User> users = userDao.query(Query.select(User.PROPERTIES)
.where(User.UUID.in(Query.select(TagMemberMetadata.USER_UUID)
.from(TagMetadata.TABLE)
.where(Criterion.and(TagMetadataCriteria.byTagAndWithKey(tagData.getUuid(), TagMemberMetadata.KEY), TagMetadata.DELETION_DATE.eq(0))))));
try {
addedMembers = users.getCount() > 0;
if (addedMembers) {
membersView.setOnClickListener(null);
membersView.removeAllViews();
}
User user = new User();
for (users.moveToFirst(); !users.isAfterLast(); users.moveToNext()) {
user.clear();
user.readFromCursor(users);
JSONObject member = new JSONObject();
ActFmSyncService.JsonHelper.jsonFromUser(member, user);
addImageForMember(membersView, member);
}
} finally {
users.close();
}
TodorooCursor<TagMetadata> byEmail = tagMetadataDao.query(Query.select(TagMemberMetadata.USER_UUID)
.where(Criterion.and(TagMetadataCriteria.byTagAndWithKey(tagData.getUuid(), TagMemberMetadata.KEY),
TagMemberMetadata.USER_UUID.like("%@%"), TagMetadata.DELETION_DATE.eq(0)))); //$NON-NLS-1$
try {
if (!addedMembers && byEmail.getCount() > 0) {
membersView.setOnClickListener(null);
membersView.removeAllViews();
}
addedMembers = addedMembers || byEmail.getCount() > 0;
TagMetadata tm = new TagMetadata();
for (byEmail.moveToFirst(); !byEmail.isAfterLast(); byEmail.moveToNext()) {
tm.clear();
tm.readFromCursor(byEmail);
String email = tm.getValue(TagMemberMetadata.USER_UUID);
if (!TextUtils.isEmpty(email)) {
JSONObject member = new JSONObject();
member.put("email", email); //$NON-NLS-1$
addImageForMember(membersView, member);
}
}
} finally {
byEmail.close();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if (addedMembers) {
try {
// Handle creator
JSONObject owner;
if(!Task.USER_ID_SELF.equals(tagData.getValue(TagData.USER_ID))) {
String userString = tagData.getValue(TagData.USER);
if (!TextUtils.isEmpty(userString)) {
owner = new JSONObject(tagData.getValue(TagData.USER));
} else {
User user = userDao.fetch(tagData.getValue(TagData.USER_ID), User.PROPERTIES);
if (user != null) {
owner = new JSONObject();
ActFmSyncService.JsonHelper.jsonFromUser(owner, user);
} else {
owner = null;
}
}
} else {
owner = ActFmPreferenceService.thisUser();
}
if (owner != null)
addImageForMember(membersView, owner);
JSONObject unassigned = new JSONObject();
unassigned.put("id", Task.USER_ID_UNASSIGNED); //$NON-NLS-1$
unassigned.put("name", getActivity().getString(R.string.actfm_EPA_unassigned)); //$NON-NLS-1$
addImageForMember(membersView, unassigned);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
membersView.removeAllViews();
membersView.setOnClickListener(settingsListener);
TextView textView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.no_members_text_view, null);
membersView.addView(textView);
}
View filterAssigned = getView().findViewById(R.id.filter_assigned);
if (filterAssigned != null)
filterAssigned.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
resetAssignedFilter();
}
});
}
@SuppressWarnings("nls")
private void addImageForMember(LinearLayout membersView, JSONObject member) {
DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
AsyncImageView image = new AsyncImageView(getActivity());
image.setLayoutParams(new LinearLayout.LayoutParams((int)(43 * displayMetrics.density),
(int)(43 * displayMetrics.density)));
image.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_default_person_image));
if (Task.USER_ID_UNASSIGNED.equals(Long.toString(member.optLong("id", 0))))
image.setDefaultImageDrawable(ResourceDrawableCache.getImageDrawableFromId(resources, R.drawable.icn_anyone));
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
try {
final String id = Long.toString(member.optLong("id", -2));
if (ActFmPreferenceService.userId().equals(id))
member = ActFmPreferenceService.thisUser();
final JSONObject memberToUse = member;
final String memberName = displayName(memberToUse);
if (memberToUse.has("picture") && !TextUtils.isEmpty(memberToUse.getString("picture"))) {
image.setUrl(memberToUse.getString("picture"));
}
image.setOnClickListener(listenerForImage(memberToUse, id, memberName));
} catch (JSONException e) {
e.printStackTrace();
}
int padding = (int) (3 * displayMetrics.density);
image.setPadding(padding, padding, padding, padding);
membersView.addView(image);
}
private OnClickListener listenerForImage(final JSONObject member, final String id, final String displayName) {
return new OnClickListener() {
final String email = member.optString("email"); //$NON-NLS-1$
@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
if (currentId.equals(id)) {
// Back to all
resetAssignedFilter();
} else {
// New filter
currentId = id;
Criterion assignedCriterion;
if (ActFmPreferenceService.userId().equals(currentId))
assignedCriterion = Criterion.or(Task.USER_ID.eq(0), Task.USER_ID.eq(id));
else if (Task.userIdIsEmail(currentId) && !TextUtils.isEmpty(email))
assignedCriterion = Criterion.or(Task.USER_ID.eq(email), Task.USER.like("%" + email + "%")); //$NON-NLS-1$ //$NON-NLS-2$ // Deprecated field OK for backwards compatibility
else
assignedCriterion = Task.USER_ID.eq(id);
Criterion assigned = Criterion.and(TaskCriteria.activeAndVisible(), assignedCriterion);
filter = TagFilterExposer.filterFromTag(getActivity(), new Tag(tagData), assigned);
TextView filterByAssigned = (TextView) getView().findViewById(R.id.filter_assigned);
if (filterByAssigned != null) {
filterByAssigned.setVisibility(View.VISIBLE);
if (id == Task.USER_ID_UNASSIGNED)
filterByAssigned.setText(getString(R.string.actfm_TVA_filter_by_unassigned));
else
filterByAssigned.setText(getString(R.string.actfm_TVA_filtered_by_assign, displayName));
}
isBeingFiltered.set(true);
setUpTaskList();
}
}
};
}
private void resetAssignedFilter() {
currentId = Task.USER_ID_IGNORE;
isBeingFiltered.set(false);
filter = originalFilter;
View filterAssigned = getView().findViewById(R.id.filter_assigned);
if (filterAssigned != null)
filterAssigned.setVisibility(View.GONE);
setUpTaskList();
}
@SuppressWarnings("nls")
private String displayName(JSONObject user) {
String name = user.optString("name");
if (!TextUtils.isEmpty(name) && !"null".equals(name)) {
name = name.trim();
int index = name.indexOf(' ');
if (index > 0) {
return name.substring(0, index);
} else {
return name;
}
} else {
String email = user.optString("email");
email = email.trim();
int index = email.indexOf('@');
if (index > 0) {
return email.substring(0, index);
} else {
return email;
}
}
}
// --- receivers
private final BroadcastReceiver notifyReceiver = new BroadcastReceiver() {
@SuppressWarnings("nls")
@Override
public void onReceive(Context context, Intent intent) {
if(!intent.hasExtra("tag_id"))
return;
if(tagData == null || !tagData.getValue(TagData.UUID).toString().equals(intent.getStringExtra("tag_id")))
return;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//refreshUpdatesList();
}
});
refreshData();
NotificationManager nm = new AndroidNotificationManager(ContextManager.getContext());
try {
nm.cancel(Integer.parseInt(tagData.getValue(TagData.UUID)));
} catch (NumberFormatException e) {
// Eh
}
}
};
@Override
public void onResume() {
if (justDeleted) {
parentOnResume();
// tag was deleted locally in settings
// go back to active tasks
AstridActivity activity = ((AstridActivity) getActivity());
FilterListFragment fl = activity.getFilterListFragment();
if (fl != null) {
fl.clear(); // Should auto refresh
activity.switchToActiveTasks();
}
return;
}
super.onResume();
IntentFilter intentFilter = new IntentFilter(BROADCAST_TAG_ACTIVITY);
getActivity().registerReceiver(notifyReceiver, intentFilter);
showListSettingsPopover();
updateCommentCount();
}
@Override
public void onPause() {
super.onPause();
AndroidUtilities.tryUnregisterReceiver(getActivity(), notifyReceiver);
}
protected void reloadTagData(boolean onActivityResult) {
tagData = tagDataService.fetchById(tagData.getId(), TagData.PROPERTIES); // refetch
if (tagData == null) {
// This can happen if a tag has been deleted as part of a sync
taskListMetadata = null;
return;
} else if (tagData.isDeleted()) {
justDeleted = true;
return;
}
initializeTaskListMetadata();
filter = TagFilterExposer.filterFromTagData(getActivity(), tagData);
getActivity().getIntent().putExtra(TOKEN_FILTER, filter);
extras.putParcelable(TOKEN_FILTER, filter);
Activity activity = getActivity();
if (activity instanceof TaskListActivity) {
((TaskListActivity) activity).setListsTitle(filter.title);
FilterListFragment flf = ((TaskListActivity) activity).getFilterListFragment();
if (flf != null) {
if (!onActivityResult)
flf.refresh();
else
flf.clear();
}
}
taskAdapter = null;
Flags.set(Flags.REFRESH);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_SETTINGS && resultCode == Activity.RESULT_OK) {
reloadTagData(true);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public boolean handleOptionsMenuItemSelected(int id, Intent intent) {
// handle my own menus
switch (id) {
case MENU_REFRESH_ID:
refreshData();
return true;
case MENU_LIST_SETTINGS_ID:
settingsListener.onClick(null);
return true;
}
return super.handleOptionsMenuItemSelected(id, intent);
}
@Override
protected boolean hasDraggableOption() {
return tagData != null && !tagData.getFlag(TagData.FLAGS, TagData.FLAG_FEATURED);
}
@Override
protected void toggleDragDrop(boolean newState) {
Class<?> customComponent;
if(newState)
customComponent = SubtasksTagListFragment.class;
else {
filter.setFilterQueryOverride(null);
customComponent = TagViewFragment.class;
}
((FilterWithCustomIntent) filter).customTaskList = new ComponentName(getActivity(), customComponent);
extras.putParcelable(TOKEN_FILTER, filter);
((AstridActivity)getActivity()).setupTasklistFragmentWithFilterAndCustomTaskList(filter,
extras, customComponent);
}
@Override
protected void refresh() {
setUpMembersGallery();
loadTaskListContent(true);
((TextView)taskListView.findViewById(android.R.id.empty)).setText(R.string.TLA_no_items);
}
}
| gpl-3.0 |
hoangcuongflp/TextSecure | src/org/thoughtcrime/securesms/mms/MediaConstraints.java | 2832 | package org.thoughtcrime.securesms.mms;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.util.BitmapDecodingException;
import org.thoughtcrime.securesms.util.BitmapUtil;
import org.thoughtcrime.securesms.util.MediaUtil;
import java.io.IOException;
import java.io.InputStream;
import ws.com.google.android.mms.pdu.PduPart;
public abstract class MediaConstraints {
private static final String TAG = MediaConstraints.class.getSimpleName();
public static MediaConstraints MMS_CONSTRAINTS = new MmsMediaConstraints();
public static MediaConstraints PUSH_CONSTRAINTS = new PushMediaConstraints();
public abstract int getImageMaxWidth(Context context);
public abstract int getImageMaxHeight(Context context);
public abstract int getImageMaxSize();
public abstract int getVideoMaxSize();
public abstract int getAudioMaxSize();
public boolean isSatisfied(Context context, MasterSecret masterSecret, PduPart part) {
try {
return (MediaUtil.isImage(part) && part.getDataSize() <= getImageMaxSize() && isWithinBounds(context, masterSecret, part.getDataUri())) ||
(MediaUtil.isAudio(part) && part.getDataSize() <= getAudioMaxSize()) ||
(MediaUtil.isVideo(part) && part.getDataSize() <= getVideoMaxSize()) ||
(!MediaUtil.isImage(part) && !MediaUtil.isAudio(part) && !MediaUtil.isVideo(part));
} catch (IOException ioe) {
Log.w(TAG, "Failed to determine if media's constraints are satisfied.", ioe);
return false;
}
}
public boolean isWithinBounds(Context context, MasterSecret masterSecret, Uri uri) throws IOException {
InputStream is = PartAuthority.getPartStream(context, masterSecret, uri);
Pair<Integer, Integer> dimensions = BitmapUtil.getDimensions(is);
return dimensions.first > 0 && dimensions.first <= getImageMaxWidth(context) &&
dimensions.second > 0 && dimensions.second <= getImageMaxHeight(context);
}
public boolean canResize(PduPart part) {
return part != null && MediaUtil.isImage(part);
}
public byte[] getResizedMedia(Context context, MasterSecret masterSecret, PduPart part)
throws IOException
{
if (!canResize(part) || part.getDataUri() == null) {
throw new UnsupportedOperationException("Cannot resize this content type");
}
try {
return BitmapUtil.createScaledBytes(context, masterSecret, part.getDataUri(),
getImageMaxWidth(context),
getImageMaxHeight(context),
getImageMaxSize());
} catch (BitmapDecodingException bde) {
throw new IOException(bde);
}
}
}
| gpl-3.0 |
arthur87/fcc | src/org/mozilla/javascript/JavaAdapter.java | 45158 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Mike McCabe
* Matthias Radestock
* Andi Vajda
* Andrew Wason
* Kemal Bayram
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
import org.mozilla.classfile.*;
import java.lang.reflect.*;
import java.io.*;
import java.security.*;
import java.util.*;
public final class JavaAdapter implements IdFunctionCall
{
/**
* Provides a key with which to distinguish previously generated
* adapter classes stored in a hash table.
*/
static class JavaAdapterSignature
{
Class<?> superClass;
Class<?>[] interfaces;
ObjToIntMap names;
JavaAdapterSignature(Class<?> superClass, Class<?>[] interfaces,
ObjToIntMap names)
{
this.superClass = superClass;
this.interfaces = interfaces;
this.names = names;
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof JavaAdapterSignature))
return false;
JavaAdapterSignature sig = (JavaAdapterSignature) obj;
if (superClass != sig.superClass)
return false;
if (interfaces != sig.interfaces) {
if (interfaces.length != sig.interfaces.length)
return false;
for (int i=0; i < interfaces.length; i++)
if (interfaces[i] != sig.interfaces[i])
return false;
}
if (names.size() != sig.names.size())
return false;
ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(names);
for (iter.start(); !iter.done(); iter.next()) {
String name = (String)iter.getKey();
int arity = iter.getValue();
if (arity != sig.names.get(name, arity + 1))
return false;
}
return true;
}
@Override
public int hashCode()
{
return (superClass.hashCode() + Arrays.hashCode(interfaces)) ^ names.size();
}
}
public static void init(Context cx, Scriptable scope, boolean sealed)
{
JavaAdapter obj = new JavaAdapter();
IdFunctionObject ctor = new IdFunctionObject(obj, FTAG, Id_JavaAdapter,
"JavaAdapter", 1, scope);
ctor.markAsConstructor(null);
if (sealed) {
ctor.sealObject();
}
ctor.exportAsScopeProperty();
}
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (f.hasTag(FTAG)) {
if (f.methodId() == Id_JavaAdapter) {
return js_createAdapter(cx, scope, args);
}
}
throw f.unknown();
}
public static Object convertResult(Object result, Class<?> c)
{
if (result == Undefined.instance &&
(c != ScriptRuntime.ObjectClass &&
c != ScriptRuntime.StringClass))
{
// Avoid an error for an undefined value; return null instead.
return null;
}
return Context.jsToJava(result, c);
}
public static Scriptable createAdapterWrapper(Scriptable obj,
Object adapter)
{
Scriptable scope = ScriptableObject.getTopLevelScope(obj);
NativeJavaObject res = new NativeJavaObject(scope, adapter, null, true);
res.setPrototype(obj);
return res;
}
public static Object getAdapterSelf(Class<?> adapterClass, Object adapter)
throws NoSuchFieldException, IllegalAccessException
{
Field self = adapterClass.getDeclaredField("self");
return self.get(adapter);
}
static Object js_createAdapter(Context cx, Scriptable scope, Object[] args)
{
int N = args.length;
if (N == 0) {
throw ScriptRuntime.typeError0("msg.adapter.zero.args");
}
Class<?> superClass = null;
Class<?>[] intfs = new Class[N - 1];
int interfaceCount = 0;
for (int i = 0; i != N - 1; ++i) {
Object arg = args[i];
if (!(arg instanceof NativeJavaClass)) {
throw ScriptRuntime.typeError2("msg.not.java.class.arg",
String.valueOf(i),
ScriptRuntime.toString(arg));
}
Class<?> c = ((NativeJavaClass) arg).getClassObject();
if (!c.isInterface()) {
if (superClass != null) {
throw ScriptRuntime.typeError2("msg.only.one.super",
superClass.getName(), c.getName());
}
superClass = c;
} else {
intfs[interfaceCount++] = c;
}
}
if (superClass == null)
superClass = ScriptRuntime.ObjectClass;
Class<?>[] interfaces = new Class[interfaceCount];
System.arraycopy(intfs, 0, interfaces, 0, interfaceCount);
Scriptable obj = ScriptRuntime.toObject(cx, scope, args[N - 1]);
Class<?> adapterClass = getAdapterClass(scope, superClass, interfaces,
obj);
Class<?>[] ctorParms = {
ScriptRuntime.ContextFactoryClass,
ScriptRuntime.ScriptableClass
};
Object[] ctorArgs = { cx.getFactory(), obj };
try {
Object adapter = adapterClass.getConstructor(ctorParms).
newInstance(ctorArgs);
Object self = getAdapterSelf(adapterClass, adapter);
// Return unwrapped JavaAdapter if it implements Scriptable
if (self instanceof Wrapper) {
Object unwrapped = ((Wrapper) self).unwrap();
if (unwrapped instanceof Scriptable) {
if (unwrapped instanceof ScriptableObject) {
ScriptRuntime.setObjectProtoAndParent(
(ScriptableObject)unwrapped, scope);
}
return unwrapped;
}
}
return self;
} catch (Exception ex) {
throw Context.throwAsScriptRuntimeEx(ex);
}
}
// Needed by NativeJavaObject serializer
public static void writeAdapterObject(Object javaObject,
ObjectOutputStream out)
throws IOException
{
Class<?> cl = javaObject.getClass();
out.writeObject(cl.getSuperclass().getName());
Class<?>[] interfaces = cl.getInterfaces();
String[] interfaceNames = new String[interfaces.length];
for (int i=0; i < interfaces.length; i++)
interfaceNames[i] = interfaces[i].getName();
out.writeObject(interfaceNames);
try {
Object delegee = cl.getField("delegee").get(javaObject);
out.writeObject(delegee);
return;
} catch (IllegalAccessException e) {
} catch (NoSuchFieldException e) {
}
throw new IOException();
}
// Needed by NativeJavaObject de-serializer
public static Object readAdapterObject(Scriptable self,
ObjectInputStream in)
throws IOException, ClassNotFoundException
{
ContextFactory factory;
Context cx = Context.getCurrentContext();
if (cx != null) {
factory = cx.getFactory();
} else {
factory = null;
}
Class<?> superClass = Class.forName((String)in.readObject());
String[] interfaceNames = (String[])in.readObject();
Class<?>[] interfaces = new Class[interfaceNames.length];
for (int i=0; i < interfaceNames.length; i++)
interfaces[i] = Class.forName(interfaceNames[i]);
Scriptable delegee = (Scriptable)in.readObject();
Class<?> adapterClass = getAdapterClass(self, superClass, interfaces,
delegee);
Class<?>[] ctorParms = {
ScriptRuntime.ContextFactoryClass,
ScriptRuntime.ScriptableClass,
ScriptRuntime.ScriptableClass
};
Object[] ctorArgs = { factory, delegee, self };
try {
return adapterClass.getConstructor(ctorParms).newInstance(ctorArgs);
} catch(InstantiationException e) {
} catch(IllegalAccessException e) {
} catch(InvocationTargetException e) {
} catch(NoSuchMethodException e) {
}
throw new ClassNotFoundException("adapter");
}
private static ObjToIntMap getObjectFunctionNames(Scriptable obj)
{
Object[] ids = ScriptableObject.getPropertyIds(obj);
ObjToIntMap map = new ObjToIntMap(ids.length);
for (int i = 0; i != ids.length; ++i) {
if (!(ids[i] instanceof String))
continue;
String id = (String) ids[i];
Object value = ScriptableObject.getProperty(obj, id);
if (value instanceof Function) {
Function f = (Function)value;
int length = ScriptRuntime.toInt32(
ScriptableObject.getProperty(f, "length"));
if (length < 0) {
length = 0;
}
map.put(id, length);
}
}
return map;
}
private static Class<?> getAdapterClass(Scriptable scope, Class<?> superClass,
Class<?>[] interfaces, Scriptable obj)
{
ClassCache cache = ClassCache.get(scope);
Map<JavaAdapterSignature,Class<?>> generated
= cache.getInterfaceAdapterCacheMap();
ObjToIntMap names = getObjectFunctionNames(obj);
JavaAdapterSignature sig;
sig = new JavaAdapterSignature(superClass, interfaces, names);
Class<?> adapterClass = generated.get(sig);
if (adapterClass == null) {
String adapterName = "adapter"
+ cache.newClassSerialNumber();
byte[] code = createAdapterCode(names, adapterName,
superClass, interfaces, null);
adapterClass = loadAdapterClass(adapterName, code);
if (cache.isCachingEnabled()) {
generated.put(sig, adapterClass);
}
}
return adapterClass;
}
public static byte[] createAdapterCode(ObjToIntMap functionNames,
String adapterName,
Class<?> superClass,
Class<?>[] interfaces,
String scriptClassName)
{
ClassFileWriter cfw = new ClassFileWriter(adapterName,
superClass.getName(),
"<adapter>");
cfw.addField("factory", "Lorg/mozilla/javascript/ContextFactory;",
(short) (ClassFileWriter.ACC_PUBLIC |
ClassFileWriter.ACC_FINAL));
cfw.addField("delegee", "Lorg/mozilla/javascript/Scriptable;",
(short) (ClassFileWriter.ACC_PUBLIC |
ClassFileWriter.ACC_FINAL));
cfw.addField("self", "Lorg/mozilla/javascript/Scriptable;",
(short) (ClassFileWriter.ACC_PUBLIC |
ClassFileWriter.ACC_FINAL));
int interfacesCount = interfaces == null ? 0 : interfaces.length;
for (int i=0; i < interfacesCount; i++) {
if (interfaces[i] != null)
cfw.addInterface(interfaces[i].getName());
}
String superName = superClass.getName().replace('.', '/');
generateCtor(cfw, adapterName, superName);
generateSerialCtor(cfw, adapterName, superName);
if (scriptClassName != null)
generateEmptyCtor(cfw, adapterName, superName, scriptClassName);
ObjToIntMap generatedOverrides = new ObjToIntMap();
ObjToIntMap generatedMethods = new ObjToIntMap();
// generate methods to satisfy all specified interfaces.
for (int i = 0; i < interfacesCount; i++) {
Method[] methods = interfaces[i].getMethods();
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
int mods = method.getModifiers();
if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) {
continue;
}
String methodName = method.getName();
Class<?>[] argTypes = method.getParameterTypes();
if (!functionNames.has(methodName)) {
try {
superClass.getMethod(methodName, argTypes);
// The class we're extending implements this method and
// the JavaScript object doesn't have an override. See
// bug 61226.
continue;
} catch (NoSuchMethodException e) {
// Not implemented by superclass; fall through
}
}
// make sure to generate only one instance of a particular
// method/signature.
String methodSignature = getMethodSignature(method, argTypes);
String methodKey = methodName + methodSignature;
if (! generatedOverrides.has(methodKey)) {
generateMethod(cfw, adapterName, methodName,
argTypes, method.getReturnType());
generatedOverrides.put(methodKey, 0);
generatedMethods.put(methodName, 0);
}
}
}
// Now, go through the superclass's methods, checking for abstract
// methods or additional methods to override.
// generate any additional overrides that the object might contain.
Method[] methods = getOverridableMethods(superClass);
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
int mods = method.getModifiers();
// if a method is marked abstract, must implement it or the
// resulting class won't be instantiable. otherwise, if the object
// has a property of the same name, then an override is intended.
boolean isAbstractMethod = Modifier.isAbstract(mods);
String methodName = method.getName();
if (isAbstractMethod || functionNames.has(methodName)) {
// make sure to generate only one instance of a particular
// method/signature.
Class<?>[] argTypes = method.getParameterTypes();
String methodSignature = getMethodSignature(method, argTypes);
String methodKey = methodName + methodSignature;
if (! generatedOverrides.has(methodKey)) {
generateMethod(cfw, adapterName, methodName,
argTypes, method.getReturnType());
generatedOverrides.put(methodKey, 0);
generatedMethods.put(methodName, 0);
// if a method was overridden, generate a "super$method"
// which lets the delegate call the superclass' version.
if (!isAbstractMethod) {
generateSuper(cfw, adapterName, superName,
methodName, methodSignature,
argTypes, method.getReturnType());
}
}
}
}
// Generate Java methods for remaining properties that are not
// overrides.
ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(functionNames);
for (iter.start(); !iter.done(); iter.next()) {
String functionName = (String)iter.getKey();
if (generatedMethods.has(functionName))
continue;
int length = iter.getValue();
Class<?>[] parms = new Class[length];
for (int k=0; k < length; k++)
parms[k] = ScriptRuntime.ObjectClass;
generateMethod(cfw, adapterName, functionName, parms,
ScriptRuntime.ObjectClass);
}
return cfw.toByteArray();
}
static Method[] getOverridableMethods(Class<?> clazz)
{
ArrayList<Method> list = new ArrayList<Method>();
HashSet<String> skip = new HashSet<String>();
// Check superclasses before interfaces so we always choose
// implemented methods over abstract ones, even if a subclass
// re-implements an interface already implemented in a superclass
// (e.g. java.util.ArrayList)
for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
appendOverridableMethods(c, list, skip);
}
for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
for (Class<?> intf: c.getInterfaces())
appendOverridableMethods(intf, list, skip);
}
return list.toArray(new Method[list.size()]);
}
private static void appendOverridableMethods(Class<?> c,
ArrayList<Method> list, HashSet<String> skip)
{
Method[] methods = c.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
String methodKey = methods[i].getName() +
getMethodSignature(methods[i],
methods[i].getParameterTypes());
if (skip.contains(methodKey))
continue; // skip this method
int mods = methods[i].getModifiers();
if (Modifier.isStatic(mods))
continue;
if (Modifier.isFinal(mods)) {
// Make sure we don't add a final method to the list
// of overridable methods.
skip.add(methodKey);
continue;
}
if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) {
list.add(methods[i]);
skip.add(methodKey);
}
}
}
static Class<?> loadAdapterClass(String className, byte[] classBytes)
{
Object staticDomain;
Class<?> domainClass = SecurityController.getStaticSecurityDomainClass();
if(domainClass == CodeSource.class || domainClass == ProtectionDomain.class) {
// use the calling script's security domain if available
ProtectionDomain protectionDomain = SecurityUtilities.getScriptProtectionDomain();
if (protectionDomain == null) {
protectionDomain = JavaAdapter.class.getProtectionDomain();
}
if(domainClass == CodeSource.class) {
staticDomain = protectionDomain == null ? null : protectionDomain.getCodeSource();
}
else {
staticDomain = protectionDomain;
}
}
else {
staticDomain = null;
}
GeneratedClassLoader loader = SecurityController.createLoader(null,
staticDomain);
Class<?> result = loader.defineClass(className, classBytes);
loader.linkClass(result);
return result;
}
public static Function getFunction(Scriptable obj, String functionName)
{
Object x = ScriptableObject.getProperty(obj, functionName);
if (x == Scriptable.NOT_FOUND) {
// This method used to swallow the exception from calling
// an undefined method. People have come to depend on this
// somewhat dubious behavior. It allows people to avoid
// implementing listener methods that they don't care about,
// for instance.
return null;
}
if (!(x instanceof Function))
throw ScriptRuntime.notFunctionError(x, functionName);
return (Function)x;
}
/**
* Utility method which dynamically binds a Context to the current thread,
* if none already exists.
*/
public static Object callMethod(ContextFactory factory,
final Scriptable thisObj,
final Function f, final Object[] args,
final long argsToWrap)
{
if (f == null) {
// See comments in getFunction
return Undefined.instance;
}
if (factory == null) {
factory = ContextFactory.getGlobal();
}
final Scriptable scope = f.getParentScope();
if (argsToWrap == 0) {
return Context.call(factory, f, scope, thisObj, args);
}
Context cx = Context.getCurrentContext();
if (cx != null) {
return doCall(cx, scope, thisObj, f, args, argsToWrap);
} else {
return factory.call(new ContextAction() {
public Object run(Context cx)
{
return doCall(cx, scope, thisObj, f, args, argsToWrap);
}
});
}
}
private static Object doCall(Context cx, Scriptable scope,
Scriptable thisObj, Function f,
Object[] args, long argsToWrap)
{
// Wrap the rest of objects
for (int i = 0; i != args.length; ++i) {
if (0 != (argsToWrap & (1 << i))) {
Object arg = args[i];
if (!(arg instanceof Scriptable)) {
args[i] = cx.getWrapFactory().wrap(cx, scope, arg,
null);
}
}
}
return f.call(cx, scope, thisObj, args);
}
public static Scriptable runScript(final Script script)
{
return (Scriptable)ContextFactory.getGlobal().call(
new ContextAction() {
public Object run(Context cx)
{
ScriptableObject global = ScriptRuntime.getGlobal(cx);
script.exec(cx, global);
return global;
}
});
}
private static void generateCtor(ClassFileWriter cfw, String adapterName,
String superName)
{
cfw.startMethod("<init>",
"(Lorg/mozilla/javascript/ContextFactory;"
+"Lorg/mozilla/javascript/Scriptable;)V",
ClassFileWriter.ACC_PUBLIC);
// Invoke base class constructor
cfw.add(ByteCode.ALOAD_0); // this
cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", "()V");
// Save parameter in instance variable "factory"
cfw.add(ByteCode.ALOAD_0); // this
cfw.add(ByteCode.ALOAD_1); // first arg: ContextFactory instance
cfw.add(ByteCode.PUTFIELD, adapterName, "factory",
"Lorg/mozilla/javascript/ContextFactory;");
// Save parameter in instance variable "delegee"
cfw.add(ByteCode.ALOAD_0); // this
cfw.add(ByteCode.ALOAD_2); // second arg: Scriptable delegee
cfw.add(ByteCode.PUTFIELD, adapterName, "delegee",
"Lorg/mozilla/javascript/Scriptable;");
cfw.add(ByteCode.ALOAD_0); // this for the following PUTFIELD for self
// create a wrapper object to be used as "this" in method calls
cfw.add(ByteCode.ALOAD_2); // the Scriptable delegee
cfw.add(ByteCode.ALOAD_0); // this
cfw.addInvoke(ByteCode.INVOKESTATIC,
"org/mozilla/javascript/JavaAdapter",
"createAdapterWrapper",
"(Lorg/mozilla/javascript/Scriptable;"
+"Ljava/lang/Object;"
+")Lorg/mozilla/javascript/Scriptable;");
cfw.add(ByteCode.PUTFIELD, adapterName, "self",
"Lorg/mozilla/javascript/Scriptable;");
cfw.add(ByteCode.RETURN);
cfw.stopMethod((short)3); // 3: this + factory + delegee
}
private static void generateSerialCtor(ClassFileWriter cfw,
String adapterName,
String superName)
{
cfw.startMethod("<init>",
"(Lorg/mozilla/javascript/ContextFactory;"
+"Lorg/mozilla/javascript/Scriptable;"
+"Lorg/mozilla/javascript/Scriptable;"
+")V",
ClassFileWriter.ACC_PUBLIC);
// Invoke base class constructor
cfw.add(ByteCode.ALOAD_0); // this
cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", "()V");
// Save parameter in instance variable "factory"
cfw.add(ByteCode.ALOAD_0); // this
cfw.add(ByteCode.ALOAD_1); // first arg: ContextFactory instance
cfw.add(ByteCode.PUTFIELD, adapterName, "factory",
"Lorg/mozilla/javascript/ContextFactory;");
// Save parameter in instance variable "delegee"
cfw.add(ByteCode.ALOAD_0); // this
cfw.add(ByteCode.ALOAD_2); // second arg: Scriptable delegee
cfw.add(ByteCode.PUTFIELD, adapterName, "delegee",
"Lorg/mozilla/javascript/Scriptable;");
// save self
cfw.add(ByteCode.ALOAD_0); // this
cfw.add(ByteCode.ALOAD_3); // second arg: Scriptable self
cfw.add(ByteCode.PUTFIELD, adapterName, "self",
"Lorg/mozilla/javascript/Scriptable;");
cfw.add(ByteCode.RETURN);
cfw.stopMethod((short)4); // 4: this + factory + delegee + self
}
private static void generateEmptyCtor(ClassFileWriter cfw,
String adapterName,
String superName,
String scriptClassName)
{
cfw.startMethod("<init>", "()V", ClassFileWriter.ACC_PUBLIC);
// Invoke base class constructor
cfw.add(ByteCode.ALOAD_0); // this
cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", "()V");
// Set factory to null to use current global when necessary
cfw.add(ByteCode.ALOAD_0);
cfw.add(ByteCode.ACONST_NULL);
cfw.add(ByteCode.PUTFIELD, adapterName, "factory",
"Lorg/mozilla/javascript/ContextFactory;");
// Load script class
cfw.add(ByteCode.NEW, scriptClassName);
cfw.add(ByteCode.DUP);
cfw.addInvoke(ByteCode.INVOKESPECIAL, scriptClassName, "<init>", "()V");
// Run script and save resulting scope
cfw.addInvoke(ByteCode.INVOKESTATIC,
"org/mozilla/javascript/JavaAdapter",
"runScript",
"(Lorg/mozilla/javascript/Script;"
+")Lorg/mozilla/javascript/Scriptable;");
cfw.add(ByteCode.ASTORE_1);
// Save the Scriptable in instance variable "delegee"
cfw.add(ByteCode.ALOAD_0); // this
cfw.add(ByteCode.ALOAD_1); // the Scriptable
cfw.add(ByteCode.PUTFIELD, adapterName, "delegee",
"Lorg/mozilla/javascript/Scriptable;");
cfw.add(ByteCode.ALOAD_0); // this for the following PUTFIELD for self
// create a wrapper object to be used as "this" in method calls
cfw.add(ByteCode.ALOAD_1); // the Scriptable
cfw.add(ByteCode.ALOAD_0); // this
cfw.addInvoke(ByteCode.INVOKESTATIC,
"org/mozilla/javascript/JavaAdapter",
"createAdapterWrapper",
"(Lorg/mozilla/javascript/Scriptable;"
+"Ljava/lang/Object;"
+")Lorg/mozilla/javascript/Scriptable;");
cfw.add(ByteCode.PUTFIELD, adapterName, "self",
"Lorg/mozilla/javascript/Scriptable;");
cfw.add(ByteCode.RETURN);
cfw.stopMethod((short)2); // this + delegee
}
/**
* Generates code to wrap Java arguments into Object[].
* Non-primitive Java types are left as-is pending conversion
* in the helper method. Leaves the array object on the top of the stack.
*/
static void generatePushWrappedArgs(ClassFileWriter cfw,
Class<?>[] argTypes,
int arrayLength)
{
// push arguments
cfw.addPush(arrayLength);
cfw.add(ByteCode.ANEWARRAY, "java/lang/Object");
int paramOffset = 1;
for (int i = 0; i != argTypes.length; ++i) {
cfw.add(ByteCode.DUP); // duplicate array reference
cfw.addPush(i);
paramOffset += generateWrapArg(cfw, paramOffset, argTypes[i]);
cfw.add(ByteCode.AASTORE);
}
}
/**
* Generates code to wrap Java argument into Object.
* Non-primitive Java types are left unconverted pending conversion
* in the helper method. Leaves the wrapper object on the top of the stack.
*/
private static int generateWrapArg(ClassFileWriter cfw, int paramOffset,
Class<?> argType)
{
int size = 1;
if (!argType.isPrimitive()) {
cfw.add(ByteCode.ALOAD, paramOffset);
} else if (argType == Boolean.TYPE) {
// wrap boolean values with java.lang.Boolean.
cfw.add(ByteCode.NEW, "java/lang/Boolean");
cfw.add(ByteCode.DUP);
cfw.add(ByteCode.ILOAD, paramOffset);
cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Boolean",
"<init>", "(Z)V");
} else if (argType == Character.TYPE) {
// Create a string of length 1 using the character parameter.
cfw.add(ByteCode.ILOAD, paramOffset);
cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/String",
"valueOf", "(C)Ljava/lang/String;");
} else {
// convert all numeric values to java.lang.Double.
cfw.add(ByteCode.NEW, "java/lang/Double");
cfw.add(ByteCode.DUP);
String typeName = argType.getName();
switch (typeName.charAt(0)) {
case 'b':
case 's':
case 'i':
// load an int value, convert to double.
cfw.add(ByteCode.ILOAD, paramOffset);
cfw.add(ByteCode.I2D);
break;
case 'l':
// load a long, convert to double.
cfw.add(ByteCode.LLOAD, paramOffset);
cfw.add(ByteCode.L2D);
size = 2;
break;
case 'f':
// load a float, convert to double.
cfw.add(ByteCode.FLOAD, paramOffset);
cfw.add(ByteCode.F2D);
break;
case 'd':
cfw.add(ByteCode.DLOAD, paramOffset);
size = 2;
break;
}
cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Double",
"<init>", "(D)V");
}
return size;
}
/**
* Generates code to convert a wrapped value type to a primitive type.
* Handles unwrapping java.lang.Boolean, and java.lang.Number types.
* Generates the appropriate RETURN bytecode.
*/
static void generateReturnResult(ClassFileWriter cfw, Class<?> retType,
boolean callConvertResult)
{
// wrap boolean values with java.lang.Boolean, convert all other
// primitive values to java.lang.Double.
if (retType == Void.TYPE) {
cfw.add(ByteCode.POP);
cfw.add(ByteCode.RETURN);
} else if (retType == Boolean.TYPE) {
cfw.addInvoke(ByteCode.INVOKESTATIC,
"org/mozilla/javascript/Context",
"toBoolean", "(Ljava/lang/Object;)Z");
cfw.add(ByteCode.IRETURN);
} else if (retType == Character.TYPE) {
// characters are represented as strings in JavaScript.
// return the first character.
// first convert the value to a string if possible.
cfw.addInvoke(ByteCode.INVOKESTATIC,
"org/mozilla/javascript/Context",
"toString",
"(Ljava/lang/Object;)Ljava/lang/String;");
cfw.add(ByteCode.ICONST_0);
cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/String",
"charAt", "(I)C");
cfw.add(ByteCode.IRETURN);
} else if (retType.isPrimitive()) {
cfw.addInvoke(ByteCode.INVOKESTATIC,
"org/mozilla/javascript/Context",
"toNumber", "(Ljava/lang/Object;)D");
String typeName = retType.getName();
switch (typeName.charAt(0)) {
case 'b':
case 's':
case 'i':
cfw.add(ByteCode.D2I);
cfw.add(ByteCode.IRETURN);
break;
case 'l':
cfw.add(ByteCode.D2L);
cfw.add(ByteCode.LRETURN);
break;
case 'f':
cfw.add(ByteCode.D2F);
cfw.add(ByteCode.FRETURN);
break;
case 'd':
cfw.add(ByteCode.DRETURN);
break;
default:
throw new RuntimeException("Unexpected return type " +
retType.toString());
}
} else {
String retTypeStr = retType.getName();
if (callConvertResult) {
cfw.addLoadConstant(retTypeStr);
cfw.addInvoke(ByteCode.INVOKESTATIC,
"java/lang/Class",
"forName",
"(Ljava/lang/String;)Ljava/lang/Class;");
cfw.addInvoke(ByteCode.INVOKESTATIC,
"org/mozilla/javascript/JavaAdapter",
"convertResult",
"(Ljava/lang/Object;"
+"Ljava/lang/Class;"
+")Ljava/lang/Object;");
}
// Now cast to return type
cfw.add(ByteCode.CHECKCAST, retTypeStr);
cfw.add(ByteCode.ARETURN);
}
}
private static void generateMethod(ClassFileWriter cfw, String genName,
String methodName, Class<?>[] parms,
Class<?> returnType)
{
StringBuffer sb = new StringBuffer();
int paramsEnd = appendMethodSignature(parms, returnType, sb);
String methodSignature = sb.toString();
cfw.startMethod(methodName, methodSignature,
ClassFileWriter.ACC_PUBLIC);
// Prepare stack to call method
// push factory
cfw.add(ByteCode.ALOAD_0);
cfw.add(ByteCode.GETFIELD, genName, "factory",
"Lorg/mozilla/javascript/ContextFactory;");
// push self
cfw.add(ByteCode.ALOAD_0);
cfw.add(ByteCode.GETFIELD, genName, "self",
"Lorg/mozilla/javascript/Scriptable;");
// push function
cfw.add(ByteCode.ALOAD_0);
cfw.add(ByteCode.GETFIELD, genName, "delegee",
"Lorg/mozilla/javascript/Scriptable;");
cfw.addPush(methodName);
cfw.addInvoke(ByteCode.INVOKESTATIC,
"org/mozilla/javascript/JavaAdapter",
"getFunction",
"(Lorg/mozilla/javascript/Scriptable;"
+"Ljava/lang/String;"
+")Lorg/mozilla/javascript/Function;");
// push arguments
generatePushWrappedArgs(cfw, parms, parms.length);
// push bits to indicate which parameters should be wrapped
if (parms.length > 64) {
// If it will be an issue, then passing a static boolean array
// can be an option, but for now using simple bitmask
throw Context.reportRuntimeError0(
"JavaAdapter can not subclass methods with more then"
+" 64 arguments.");
}
long convertionMask = 0;
for (int i = 0; i != parms.length; ++i) {
if (!parms[i].isPrimitive()) {
convertionMask |= (1 << i);
}
}
cfw.addPush(convertionMask);
// go through utility method, which creates a Context to run the
// method in.
cfw.addInvoke(ByteCode.INVOKESTATIC,
"org/mozilla/javascript/JavaAdapter",
"callMethod",
"(Lorg/mozilla/javascript/ContextFactory;"
+"Lorg/mozilla/javascript/Scriptable;"
+"Lorg/mozilla/javascript/Function;"
+"[Ljava/lang/Object;"
+"J"
+")Ljava/lang/Object;");
generateReturnResult(cfw, returnType, true);
cfw.stopMethod((short)paramsEnd);
}
/**
* Generates code to push typed parameters onto the operand stack
* prior to a direct Java method call.
*/
private static int generatePushParam(ClassFileWriter cfw, int paramOffset,
Class<?> paramType)
{
if (!paramType.isPrimitive()) {
cfw.addALoad(paramOffset);
return 1;
}
String typeName = paramType.getName();
switch (typeName.charAt(0)) {
case 'z':
case 'b':
case 'c':
case 's':
case 'i':
// load an int value, convert to double.
cfw.addILoad(paramOffset);
return 1;
case 'l':
// load a long, convert to double.
cfw.addLLoad(paramOffset);
return 2;
case 'f':
// load a float, convert to double.
cfw.addFLoad(paramOffset);
return 1;
case 'd':
cfw.addDLoad(paramOffset);
return 2;
}
throw Kit.codeBug();
}
/**
* Generates code to return a Java type, after calling a Java method
* that returns the same type.
* Generates the appropriate RETURN bytecode.
*/
private static void generatePopResult(ClassFileWriter cfw,
Class<?> retType)
{
if (retType.isPrimitive()) {
String typeName = retType.getName();
switch (typeName.charAt(0)) {
case 'b':
case 'c':
case 's':
case 'i':
case 'z':
cfw.add(ByteCode.IRETURN);
break;
case 'l':
cfw.add(ByteCode.LRETURN);
break;
case 'f':
cfw.add(ByteCode.FRETURN);
break;
case 'd':
cfw.add(ByteCode.DRETURN);
break;
}
} else {
cfw.add(ByteCode.ARETURN);
}
}
/**
* Generates a method called "super$methodName()" which can be called
* from JavaScript that is equivalent to calling "super.methodName()"
* from Java. Eventually, this may be supported directly in JavaScript.
*/
private static void generateSuper(ClassFileWriter cfw,
String genName, String superName,
String methodName, String methodSignature,
Class<?>[] parms, Class<?> returnType)
{
cfw.startMethod("super$" + methodName, methodSignature,
ClassFileWriter.ACC_PUBLIC);
// push "this"
cfw.add(ByteCode.ALOAD, 0);
// push the rest of the parameters.
int paramOffset = 1;
for (int i = 0; i < parms.length; i++) {
paramOffset += generatePushParam(cfw, paramOffset, parms[i]);
}
// call the superclass implementation of the method.
cfw.addInvoke(ByteCode.INVOKESPECIAL,
superName,
methodName,
methodSignature);
// now, handle the return type appropriately.
Class<?> retType = returnType;
if (!retType.equals(Void.TYPE)) {
generatePopResult(cfw, retType);
} else {
cfw.add(ByteCode.RETURN);
}
cfw.stopMethod((short)(paramOffset + 1));
}
/**
* Returns a fully qualified method name concatenated with its signature.
*/
private static String getMethodSignature(Method method, Class<?>[] argTypes)
{
StringBuffer sb = new StringBuffer();
appendMethodSignature(argTypes, method.getReturnType(), sb);
return sb.toString();
}
static int appendMethodSignature(Class<?>[] argTypes,
Class<?> returnType,
StringBuffer sb)
{
sb.append('(');
int firstLocal = 1 + argTypes.length; // includes this.
for (int i = 0; i < argTypes.length; i++) {
Class<?> type = argTypes[i];
appendTypeString(sb, type);
if (type == Long.TYPE || type == Double.TYPE) {
// adjust for duble slot
++firstLocal;
}
}
sb.append(')');
appendTypeString(sb, returnType);
return firstLocal;
}
private static StringBuffer appendTypeString(StringBuffer sb, Class<?> type)
{
while (type.isArray()) {
sb.append('[');
type = type.getComponentType();
}
if (type.isPrimitive()) {
char typeLetter;
if (type == Boolean.TYPE) {
typeLetter = 'Z';
} else if (type == Long.TYPE) {
typeLetter = 'J';
} else {
String typeName = type.getName();
typeLetter = Character.toUpperCase(typeName.charAt(0));
}
sb.append(typeLetter);
} else {
sb.append('L');
sb.append(type.getName().replace('.', '/'));
sb.append(';');
}
return sb;
}
static int[] getArgsToConvert(Class<?>[] argTypes)
{
int count = 0;
for (int i = 0; i != argTypes.length; ++i) {
if (!argTypes[i].isPrimitive())
++count;
}
if (count == 0)
return null;
int[] array = new int[count];
count = 0;
for (int i = 0; i != argTypes.length; ++i) {
if (!argTypes[i].isPrimitive())
array[count++] = i;
}
return array;
}
private static final Object FTAG = "JavaAdapter";
private static final int Id_JavaAdapter = 1;
}
| mpl-2.0 |
JNPA/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/accounting/util/PersonRotationPaymentCodeGenerator.java | 5727 | /**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic 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 3 of the License, or
* (at your option) any later version.
*
* FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain.accounting.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.fenixedu.academic.domain.Person;
import org.fenixedu.academic.domain.accounting.PaymentCode;
import org.fenixedu.academic.domain.accounting.PaymentCodeType;
/**
* Code Format: <numericPartOfIstId{6}><typeDigit{1}><controlDigits{2}>
*/
@Deprecated
public class PersonRotationPaymentCodeGenerator extends PaymentCodeGenerator {
public static Comparator<PaymentCode> COMPARATOR_BY_PAYMENT_CODE_CONTROL_DIGITS = new Comparator<PaymentCode>() {
@Override
public int compare(PaymentCode leftPaymentCode, PaymentCode rightPaymentCode) {
final String leftCodeControlDigits =
leftPaymentCode.getCode().substring(leftPaymentCode.getCode().length() - CONTROL_DIGITS_LENGTH);
final String rightCodeControlDigits =
rightPaymentCode.getCode().substring(rightPaymentCode.getCode().length() - CONTROL_DIGITS_LENGTH);
int comparationResult = leftCodeControlDigits.compareTo(rightCodeControlDigits);
return (comparationResult == 0) ? leftPaymentCode.getExternalId().compareTo(rightPaymentCode.getExternalId()) : comparationResult;
}
};
private static final int CONTROL_DIGITS_LENGTH = 2;
private static final String CODE_FILLER = "0";
private static final int PERSON_CODE_LENGTH = 6;
private static final int CODE_LENGTH = 9;
public PersonRotationPaymentCodeGenerator() {
}
@Override
public boolean canGenerateNewCode(final PaymentCodeType paymentCodeType, final Person person) {
final PaymentCode lastPaymentCode = findLastPaymentCode(paymentCodeType, person);
return (lastPaymentCode == null) ? true : (getSignificantNumberForCodeGeneration(lastPaymentCode) + 1 <= 99);
}
@Override
public String generateNewCodeFor(final PaymentCodeType paymentCodeType, final Person person) {
final PaymentCode lastPaymentCode = findLastPaymentCode(paymentCodeType, person);
return lastPaymentCode == null ? generateFirstCodeForType(paymentCodeType, person) : generateNewCodeBasedOnLastPaymentCode(lastPaymentCode);
}
private PaymentCode findLastPaymentCode(final PaymentCodeType paymentCodeType, Person person) {
final List<PaymentCode> paymentCodes = new ArrayList<PaymentCode>();
for (PaymentCode code : person.getPaymentCodesBy(paymentCodeType)) {
if (isCodeMadeByThisFactory(code)) {
paymentCodes.add(code);
}
}
return paymentCodes.isEmpty() ? null : Collections.max(paymentCodes, COMPARATOR_BY_PAYMENT_CODE_CONTROL_DIGITS);
}
private static String generateFirstCodeForType(final PaymentCodeType paymentCodeType, final Person person) {
return generateFinalCode(paymentCodeType, person, 0);
}
private static String generateNewCodeBasedOnLastPaymentCode(PaymentCode paymentCode) {
return generateNewCodeBasedOnSignificantNumber(paymentCode.getType(), paymentCode.getPerson(),
getSignificantNumberForCodeGeneration(paymentCode));
}
private static int getSignificantNumberForCodeGeneration(final PaymentCode lastPaymentCode) {
return Integer.valueOf(lastPaymentCode.getCode().substring(lastPaymentCode.getCode().length() - 2));
}
private static String generateNewCodeBasedOnSignificantNumber(final PaymentCodeType paymentCodeType, final Person person,
int number) {
return generateFinalCode(paymentCodeType, person, number + 1);
}
private static String generateFinalCode(final PaymentCodeType paymentCodeType, final Person person, int digits) {
final String finalCode =
getCodePrefix(paymentCodeType, person)
+ StringUtils.leftPad(String.valueOf(digits), CONTROL_DIGITS_LENGTH, CODE_FILLER);
if (finalCode.length() != CODE_LENGTH) {
throw new RuntimeException("Unexpected code length for generated code");
}
return finalCode;
}
private static String getCodePrefix(final PaymentCodeType paymentCodeType, final Person person) {
return getPersonCodeDigits(person) + paymentCodeType.getTypeDigit();
}
private static String getPersonCodeDigits(Person person) {
if (person.getUsername().length() > 9) {
throw new RuntimeException("SIBS Payment Code: " + person.getUsername() + " exceeded maximun size accepted");
}
return StringUtils.leftPad(person.getUsername().replace("ist", ""), PERSON_CODE_LENGTH, CODE_FILLER);
}
@Override
public boolean isCodeMadeByThisFactory(PaymentCode paymentCode) {
return paymentCode.getCode().startsWith(getPersonCodeDigits(paymentCode.getPerson()));
}
}
| lgpl-3.0 |
ASU-Capstone/uPortal-Forked | uportal-war/src/main/java/org/jasig/portal/events/tincan/converters/GeneralEventConverter.java | 1846 | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.jasig.portal.events.tincan.converters;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import org.jasig.portal.events.PortalEvent;
import org.jasig.portal.events.tincan.om.LocalizedString;
import org.jasig.portal.events.tincan.om.LrsObject;
/**
* General event converter. This is a super generic event handler. It's not
* intended for production use. It's primarily intended to help with debugging.
*
* @author Josh Helmer, jhelmer@unicon.net
*/
public class GeneralEventConverter extends AbstractPortalEventToLrsStatementConverter {
@Override
public boolean supports(PortalEvent event) {
return true;
}
@Override
protected LrsObject getLrsObject(PortalEvent event) {
Builder<String, LocalizedString> definitionBuilder = ImmutableMap.builder();
return new LrsObject(
buildUrn("other", event.getClass().getName()),
getDefaultObjectType(),
definitionBuilder.build());
}
}
| apache-2.0 |
melix/golo-lang | src/main/java/fr/insalyon/citi/golo/cli/package-info.java | 723 | /*
* Copyright 2012-2013 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* (this is an internal API)
*/
package fr.insalyon.citi.golo.cli; | apache-2.0 |
antoaravinth/incubator-groovy | subprojects/groovy-json/src/main/java/groovy/json/StreamingJsonBuilder.java | 14741 | /*
* 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 groovy.json;
import groovy.lang.Closure;
import groovy.lang.GroovyObjectSupport;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
/**
* A builder for creating JSON payloads.
* <p>
* This builder supports the usual builder syntax made of nested method calls and closures,
* but also some specific aspects of JSON data structures, such as list of values, etc.
* Please make sure to have a look at the various methods provided by this builder
* to be able to learn about the various possibilities of usage.
* <p>
* Unlike the JsonBuilder class which creates a data structure in memory,
* which is handy in those situations where you want to alter the structure programatically before output,
* the StreamingJsonBuilder streams to a writer directly without any memory data structure.
* So if you don't need to modify the structure, and want a more memory-efficient approach,
* please use the StreamingJsonBuilder.
* <p>
* Example:
* <pre class="groovyTestCase">
* new StringWriter().with { w ->
* def builder = new groovy.json.StreamingJsonBuilder(w)
* builder.people {
* person {
* firstName 'Tim'
* lastName 'Yates'
* // Named arguments are valid values for objects too
* address(
* city: 'Manchester',
* country: 'UK',
* zip: 'M1 2AB',
* )
* living true
* eyes 'left', 'right'
* }
* }
*
* assert w.toString() == '{"people":{"person":{"firstName":"Tim","lastName":"Yates","address":{"city":"Manchester","country":"UK","zip":"M1 2AB"},"living":true,"eyes":["left","right"]}}}'
* }
* </pre>
*
* @author Tim Yates
* @author Andrey Bloschetsov
* @since 1.8.1
*/
public class StreamingJsonBuilder extends GroovyObjectSupport {
private Writer writer;
/**
* Instantiates a JSON builder.
*
* @param writer A writer to which Json will be written
*/
public StreamingJsonBuilder(Writer writer) {
this.writer = writer;
}
/**
* Instantiates a JSON builder, possibly with some existing data structure.
*
* @param writer A writer to which Json will be written
* @param content a pre-existing data structure, default to null
*/
public StreamingJsonBuilder(Writer writer, Object content) throws IOException {
this(writer);
if (content != null) {
writer.write(JsonOutput.toJson(content));
}
}
/**
* Named arguments can be passed to the JSON builder instance to create a root JSON object
* <p>
* Example:
* <pre class="groovyTestCase">
* new StringWriter().with { w ->
* def json = new groovy.json.StreamingJsonBuilder(w)
* json name: "Tim", age: 31
*
* assert w.toString() == '{"name":"Tim","age":31}'
* }
* </pre>
*
* @param m a map of key / value pairs
* @return a map of key / value pairs
*/
public Object call(Map m) throws IOException {
writer.write(JsonOutput.toJson(m));
return m;
}
/**
* A list of elements as arguments to the JSON builder creates a root JSON array
* <p>
* Example:
* <pre class="groovyTestCase">
* new StringWriter().with { w ->
* def json = new groovy.json.StreamingJsonBuilder(w)
* def result = json([1, 2, 3])
*
* assert result == [ 1, 2, 3 ]
* assert w.toString() == "[1,2,3]"
* }
* </pre>
*
* @param l a list of values
* @return a list of values
*/
public Object call(List l) throws IOException {
writer.write(JsonOutput.toJson(l));
return l;
}
/**
* Varargs elements as arguments to the JSON builder create a root JSON array
* <p>
* Example:
* <pre class="groovyTestCase">
* new StringWriter().with { w ->
* def json = new groovy.json.StreamingJsonBuilder(w)
* def result = json 1, 2, 3
*
* assert result instanceof List
* assert w.toString() == "[1,2,3]"
* }
* </pre>
* @param args an array of values
* @return a list of values
*/
public Object call(Object... args) throws IOException {
return call(Arrays.asList(args));
}
/**
* A collection and closure passed to a JSON builder will create a root JSON array applying
* the closure to each object in the collection
* <p>
* Example:
* <pre class="groovyTestCase">
* class Author {
* String name
* }
* def authors = [new Author (name: "Guillaume"), new Author (name: "Jochen"), new Author (name: "Paul")]
*
* new StringWriter().with { w ->
* def json = new groovy.json.StreamingJsonBuilder(w)
* json authors, { Author author ->
* name author.name
* }
*
* assert w.toString() == '[{"name":"Guillaume"},{"name":"Jochen"},{"name":"Paul"}]'
* }
* </pre>
* @param coll a collection
* @param c a closure used to convert the objects of coll
*/
public Object call(Collection coll, Closure c) throws IOException {
StreamingJsonDelegate.writeCollectionWithClosure(writer, coll, c);
return null;
}
/**
* A closure passed to a JSON builder will create a root JSON object
* <p>
* Example:
* <pre class="groovyTestCase">
* new StringWriter().with { w ->
* def json = new groovy.json.StreamingJsonBuilder(w)
* json {
* name "Tim"
* age 39
* }
*
* assert w.toString() == '{"name":"Tim","age":39}'
* }
* </pre>
*
* @param c a closure whose method call statements represent key / values of a JSON object
*/
public Object call(Closure c) throws IOException {
writer.write("{");
StreamingJsonDelegate.cloneDelegateAndGetContent(writer, c);
writer.write("}");
return null;
}
/**
* A method call on the JSON builder instance will create a root object with only one key
* whose name is the name of the method being called.
* This method takes as arguments:
* <ul>
* <li>a closure</li>
* <li>a map (ie. named arguments)</li>
* <li>a map and a closure</li>
* <li>or no argument at all</li>
* </ul>
* <p>
* Example with a classical builder-style:
* <pre class="groovyTestCase">
* new StringWriter().with { w ->
* def json = new groovy.json.StreamingJsonBuilder(w)
* json.person {
* name "Tim"
* age 28
* }
*
* assert w.toString() == '{"person":{"name":"Tim","age":28}}'
* }
* </pre>
*
* Or alternatively with a method call taking named arguments:
* <pre class="groovyTestCase">
* new StringWriter().with { w ->
* def json = new groovy.json.StreamingJsonBuilder(w)
* json.person name: "Tim", age: 32
*
* assert w.toString() == '{"person":{"name":"Tim","age":32}}'
* }
* </pre>
*
* If you use named arguments and a closure as last argument,
* the key/value pairs of the map (as named arguments)
* and the key/value pairs represented in the closure
* will be merged together —
* the closure properties overriding the map key/values
* in case the same key is used.
* <pre class="groovyTestCase">
* new StringWriter().with { w ->
* def json = new groovy.json.StreamingJsonBuilder(w)
* json.person(name: "Tim", age: 35) { town "Manchester" }
*
* assert w.toString() == '{"person":{"name":"Tim","age":35,"town":"Manchester"}}'
* }
* </pre>
*
* The empty args call will create a key whose value will be an empty JSON object:
* <pre class="groovyTestCase">
* new StringWriter().with { w ->
* def json = new groovy.json.StreamingJsonBuilder(w)
* json.person()
*
* assert w.toString() == '{"person":{}}'
* }
* </pre>
*
* @param name the single key
* @param args the value associated with the key
*/
public Object invokeMethod(String name, Object args) {
boolean notExpectedArgs = false;
if (args != null && Object[].class.isAssignableFrom(args.getClass())) {
Object[] arr = (Object[]) args;
try {
if (arr.length == 0) {
writer.write(JsonOutput.toJson(Collections.singletonMap(name, Collections.emptyMap())));
} else if (arr.length == 1) {
if (arr[0] instanceof Closure) {
writer.write("{");
writer.write(JsonOutput.toJson(name));
writer.write(":");
call((Closure) arr[0]);
writer.write("}");
} else if (arr[0] instanceof Map) {
writer.write(JsonOutput.toJson(Collections.singletonMap(name, (Map) arr[0])));
} else {
notExpectedArgs = true;
}
} else if (arr.length == 2 && arr[0] instanceof Map && arr[1] instanceof Closure) {
writer.write("{");
writer.write(JsonOutput.toJson(name));
writer.write(":{");
boolean first = true;
Map map = (Map) arr[0];
for (Object it : map.entrySet()) {
if (!first) {
writer.write(",");
} else {
first = false;
}
Map.Entry entry = (Map.Entry) it;
writer.write(JsonOutput.toJson(entry.getKey()));
writer.write(":");
writer.write(JsonOutput.toJson(entry.getValue()));
}
StreamingJsonDelegate.cloneDelegateAndGetContent(writer, (Closure) arr[1], map.size() == 0);
writer.write("}}");
} else if (StreamingJsonDelegate.isCollectionWithClosure(arr)) {
writer.write("{");
writer.write(JsonOutput.toJson(name));
writer.write(":");
call((Collection) arr[0], (Closure) arr[1]);
writer.write("}");
} else {
notExpectedArgs = true;
}
} catch (IOException ioe) {
throw new JsonException(ioe);
}
} else {
notExpectedArgs = true;
}
if (!notExpectedArgs) {
return this;
} else {
throw new JsonException("Expected no arguments, a single map, a single closure, or a map and closure as arguments.");
}
}
}
class StreamingJsonDelegate extends GroovyObjectSupport {
private Writer writer;
private boolean first;
public StreamingJsonDelegate(Writer w, boolean first) {
this.writer = w;
this.first = first;
}
public Object invokeMethod(String name, Object args) {
if (args != null && Object[].class.isAssignableFrom(args.getClass())) {
try {
if (!first) {
writer.write(",");
} else {
first = false;
}
writer.write(JsonOutput.toJson(name));
writer.write(":");
Object[] arr = (Object[]) args;
if (arr.length == 1) {
writer.write(JsonOutput.toJson(arr[0]));
} else if (isCollectionWithClosure(arr)) {
writeCollectionWithClosure(writer, (Collection) arr[0], (Closure) arr[1]);
} else {
writer.write(JsonOutput.toJson(Arrays.asList(arr)));
}
} catch (IOException ioe) {
throw new JsonException(ioe);
}
}
return this;
}
public static boolean isCollectionWithClosure(Object[] args) {
return args.length == 2 && args[0] instanceof Collection && args[1] instanceof Closure;
}
public static Object writeCollectionWithClosure(Writer writer, Collection coll, Closure closure) throws IOException {
writer.write("[");
boolean first = true;
for (Object it : coll) {
if (!first) {
writer.write(",");
} else {
first = false;
}
writer.write("{");
curryDelegateAndGetContent(writer, closure, it);
writer.write("}");
}
writer.write("]");
return writer;
}
public static void cloneDelegateAndGetContent(Writer w, Closure c) {
cloneDelegateAndGetContent(w, c, true);
}
public static void cloneDelegateAndGetContent(Writer w, Closure c, boolean first) {
StreamingJsonDelegate delegate = new StreamingJsonDelegate(w, first);
Closure cloned = (Closure) c.clone();
cloned.setDelegate(delegate);
cloned.setResolveStrategy(Closure.DELEGATE_FIRST);
cloned.call();
}
public static void curryDelegateAndGetContent(Writer w, Closure c, Object o) {
curryDelegateAndGetContent(w, c, o, true);
}
public static void curryDelegateAndGetContent(Writer w, Closure c, Object o, boolean first) {
StreamingJsonDelegate delegate = new StreamingJsonDelegate(w, first);
Closure curried = c.curry(o);
curried.setDelegate(delegate);
curried.setResolveStrategy(Closure.DELEGATE_FIRST);
curried.call();
}
}
| apache-2.0 |
sergeymazin/zeppelin | python/src/test/java/org/apache/zeppelin/python/PythonDockerInterpreterTest.java | 3211 | /*
* 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.zeppelin.python;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterGroup;
import org.apache.zeppelin.interpreter.InterpreterOutput;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.File;
import java.util.Arrays;
import java.util.Properties;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class PythonDockerInterpreterTest {
private PythonDockerInterpreter docker;
private PythonInterpreter python;
@Before
public void setUp() throws InterpreterException {
docker = spy(new PythonDockerInterpreter(new Properties()));
python = mock(PythonInterpreter.class);
InterpreterGroup group = new InterpreterGroup();
group.put("note", Arrays.asList(python, docker));
python.setInterpreterGroup(group);
docker.setInterpreterGroup(group);
doReturn(true).when(docker).pull(any(InterpreterOutput.class), anyString());
doReturn(new File("/scriptpath")).when(python).getPythonWorkDir();
doReturn(PythonDockerInterpreter.class.getName()).when(docker).getClassName();
doReturn(PythonInterpreter.class.getName()).when(python).getClassName();
docker.open();
}
@Test
public void testActivateEnv() throws InterpreterException {
InterpreterContext context = getInterpreterContext();
docker.interpret("activate env", context);
verify(python, times(1)).open();
verify(python, times(1)).close();
verify(docker, times(1)).pull(any(InterpreterOutput.class), anyString());
verify(python).setPythonExec(Mockito.matches("docker run -i --rm -v.*"));
}
@Test
public void testDeactivate() throws InterpreterException {
InterpreterContext context = getInterpreterContext();
docker.interpret("deactivate", context);
verify(python, times(1)).open();
verify(python, times(1)).close();
verify(python).setPythonExec(null);
}
private InterpreterContext getInterpreterContext() {
return InterpreterContext.builder()
.setInterpreterOut(new InterpreterOutput(null))
.build();
}
}
| apache-2.0 |
irham0019/product-as | modules/integration/tests-integration/tests/src/test/java/org/wso2/appserver/integration/tests/javaee/jpa/JpaJaxRsTestCase.java | 4658 | /*
* Copyright 2004,2013 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.wso2.appserver.integration.tests.javaee.jpa;
import java.io.File;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.appserver.integration.common.utils.ASIntegrationTest;
import org.wso2.appserver.integration.common.utils.WebAppDeploymentUtil;
import org.wso2.appserver.integration.common.utils.WebAppTypes;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpClientUtil;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class JpaJaxRsTestCase extends ASIntegrationTest {
private static final Log log = LogFactory.getLog(JpaJaxRsTestCase.class);
private static final String webAppFileName = "jpa-student-register-1.0.war";
private static final String webAppName = "jpa-student-register-1.0";
private static final String webAppLocalURL = "/jpa-student-register-1.0";
String hostname;
private TestUserMode userMode;
@Factory(dataProvider = "userModeProvider")
public JpaJaxRsTestCase(TestUserMode userMode) {
this.userMode = userMode;
}
@DataProvider
private static TestUserMode[][] userModeProvider() {
return new TestUserMode[][]{
new TestUserMode[]{TestUserMode.SUPER_TENANT_ADMIN},
new TestUserMode[]{TestUserMode.TENANT_USER},
};
}
@BeforeClass(alwaysRun = true)
public void init() throws Exception {
super.init(userMode);
hostname = asServer.getInstance().getHosts().get("default");
webAppURL = getWebAppURL(WebAppTypes.WEBAPPS) + webAppLocalURL;
String webAppFilePath = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator +
"AS" + File.separator + "javaee" + File.separator + "jpa" + File.separator + webAppFileName;
WebAppDeploymentUtil.deployWebApplication(backendURL, sessionCookie, webAppFilePath);
assertTrue(WebAppDeploymentUtil.isWebApplicationDeployed(backendURL, sessionCookie, webAppName),
"Web Application Deployment failed");
}
/**
* ex. getall response in xml
* <p/>
* <Students><students><index>100</index><name>John</name></students></Students>
*/
//todo enable this test method after the sample is fixed
// todo jira : https://wso2.org/jira/browse/WSAS-1996
@Test(groups = "wso2.as", description = "test jpa and jax-rs", enabled = false)
public void testJpaRsGet() throws Exception {
String getAll = "/student/getall";
String jndiUrl = webAppURL + getAll;
HttpClientUtil client = new HttpClientUtil();
//todo client.get is not working properly
OMElement result = client.get(jndiUrl);
log.info("Response - " + result.toString());
OMElement students = result.getFirstElement();
assertEquals(students.getLocalName(), "students", "response is invalid for " + jndiUrl);
assertEquals(students.getFirstChildWithName(new QName("index")).toString(), "<index>100</index>",
"response is invalid for " + jndiUrl);
assertEquals(students.getFirstChildWithName(new QName("name")).toString(), "<name>John</name>",
"response is invalid for " + jndiUrl);
}
@AfterClass(alwaysRun = true)
public void cleanupWebApps() throws Exception {
WebAppDeploymentUtil.unDeployWebApplication(backendURL, hostname, sessionCookie, webAppFileName);
assertTrue(WebAppDeploymentUtil.isWebApplicationUnDeployed(backendURL, sessionCookie, webAppName),
"Web Application unDeployment failed");
}
}
| apache-2.0 |
bhupeshchawda/incubator-samoa | samoa-api/src/main/java/org/apache/samoa/moa/clusterers/KMeans.java | 6088 | package org.apache.samoa.moa.clusterers;
/*
* #%L
* SAMOA
* %%
* Copyright (C) 2014 - 2015 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.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import org.apache.samoa.moa.cluster.CFCluster;
import org.apache.samoa.moa.cluster.Cluster;
import org.apache.samoa.moa.cluster.Clustering;
import org.apache.samoa.moa.cluster.SphereCluster;
/**
* A kMeans implementation for microclusterings. For now it only uses the real centers of the groundtruthclustering for
* implementation. There should also be an option to use random centers. TODO: random centers TODO: Create a macro
* clustering interface to make different macro clustering algorithms available to micro clustering algorithms like
* clustream, denstream and clustree
*
*/
public class KMeans {
/**
* This kMeans implementation clusters a big number of microclusters into a smaller amount of macro clusters. To make
* it comparable to other algorithms it uses the real centers of the ground truth macro clustering to have the best
* possible initialization. The quality of resulting macro clustering yields an upper bound for kMeans on the
* underlying microclustering.
*
* @param centers
* of the ground truth clustering
* @param data
* list of microclusters
* @return
*/
public static Clustering kMeans(Cluster[] centers, List<? extends Cluster> data) {
int k = centers.length;
int dimensions = centers[0].getCenter().length;
ArrayList<ArrayList<Cluster>> clustering =
new ArrayList<ArrayList<Cluster>>();
for (int i = 0; i < k; i++) {
clustering.add(new ArrayList<Cluster>());
}
int repetitions = 100;
while (repetitions-- >= 0) {
// Assign points to clusters
for (Cluster point : data) {
double minDistance = distance(point.getCenter(), centers[0].getCenter());
int closestCluster = 0;
for (int i = 1; i < k; i++) {
double distance = distance(point.getCenter(), centers[i].getCenter());
if (distance < minDistance) {
closestCluster = i;
minDistance = distance;
}
}
clustering.get(closestCluster).add(point);
}
// Calculate new centers and clear clustering lists
SphereCluster[] newCenters = new SphereCluster[centers.length];
for (int i = 0; i < k; i++) {
newCenters[i] = calculateCenter(clustering.get(i), dimensions);
clustering.get(i).clear();
}
centers = newCenters;
}
return new Clustering(centers);
}
private static double distance(double[] pointA, double[] pointB) {
double distance = 0.0;
for (int i = 0; i < pointA.length; i++) {
double d = pointA[i] - pointB[i];
distance += d * d;
}
return Math.sqrt(distance);
}
private static SphereCluster calculateCenter(ArrayList<Cluster> cluster, int dimensions) {
double[] res = new double[dimensions];
for (int i = 0; i < res.length; i++) {
res[i] = 0.0;
}
if (cluster.size() == 0) {
return new SphereCluster(res, 0.0);
}
for (Cluster point : cluster) {
double[] center = point.getCenter();
for (int i = 0; i < res.length; i++) {
res[i] += center[i];
}
}
// Normalize
for (int i = 0; i < res.length; i++) {
res[i] /= cluster.size();
}
// Calculate radius
double radius = 0.0;
for (Cluster point : cluster) {
double dist = distance(res, point.getCenter());
if (dist > radius) {
radius = dist;
}
}
return new SphereCluster(res, radius);
}
public static Clustering gaussianMeans(Clustering gtClustering, Clustering clustering) {
ArrayList<CFCluster> microclusters = new ArrayList<CFCluster>();
for (int i = 0; i < clustering.size(); i++) {
if (clustering.get(i) instanceof CFCluster) {
microclusters.add((CFCluster) clustering.get(i));
}
else {
System.out.println("Unsupported Cluster Type:" + clustering.get(i).getClass()
+ ". Cluster needs to extend moa.cluster.CFCluster");
}
}
Cluster[] centers = new Cluster[gtClustering.size()];
for (int i = 0; i < centers.length; i++) {
centers[i] = gtClustering.get(i);
}
int k = centers.length;
if (microclusters.size() < k) {
return new Clustering(new Cluster[0]);
}
Clustering kMeansResult = kMeans(centers, microclusters);
k = kMeansResult.size();
CFCluster[] res = new CFCluster[k];
for (CFCluster microcluster : microclusters) {
// Find closest kMeans cluster
double minDistance = Double.MAX_VALUE;
int closestCluster = 0;
for (int i = 0; i < k; i++) {
double distance = distance(kMeansResult.get(i).getCenter(), microcluster.getCenter());
if (distance < minDistance) {
closestCluster = i;
minDistance = distance;
}
}
// Add to cluster
if (res[closestCluster] == null) {
res[closestCluster] = (CFCluster) microcluster.copy();
} else {
res[closestCluster].add(microcluster);
}
}
// Clean up res
int count = 0;
for (int i = 0; i < res.length; i++) {
if (res[i] != null)
++count;
}
CFCluster[] cleaned = new CFCluster[count];
count = 0;
for (int i = 0; i < res.length; i++) {
if (res[i] != null)
cleaned[count++] = res[i];
}
return new Clustering(cleaned);
}
}
| apache-2.0 |
kleopatra999/solutions-mobile-backend-starter-java | src/com/google/cloud/backend/beans/FilterDto.java | 8559 | /*
* Copyright (c) 2013 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.cloud.backend.beans;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.prospectivesearch.FieldType;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
/**
* Represents an AST (abstract syntax tree) made of filters that represents a
* query filter for a {@link QueryDto}. Equivalent to {@link FilterPredicate}
* and {@link CompositeFilter} of Datastore query.
*
* The values property takes different number of elements depending on the Op:
*
* - For EQ, LT, LE, GT, GE, NE: This object works as a filter predicate. Values
* should have two values, where the first value should be a property name and
* the second value should be a value.
*
* - For IN: This object works as a filter predicate with IN op. Values may have
* any number of values.
*
* - For AND, OR: This works as a composite filter. Values may have any number
* of FilterDto instances.
*
* TODO: This kind of behaviors should be implemented by polymorphism, but
* Endpoints doesn't support inheritance.
*/
public class FilterDto {
private static final DatatypeFactory datatypeFactory;
static {
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
throw new RuntimeException(e);
}
}
/**
* Filter operations
*/
public enum Op {
EQ, LT, LE, GT, GE, NE, IN, AND, OR
}
private List<Object> values;
private List<FilterDto> subfilters;
private Op operator;
public Op getOperator() {
return operator;
}
public void setOperator(Op operator) {
this.operator = operator;
}
public List<Object> getValues() {
return values;
}
public void setValues(List<Object> values) {
this.values = values;
}
/**
* Converts the tree of {@link FilterDto}s to a tree of {@link FilterDto}s.
*/
public Filter getDatastoreFilter() {
switch (this.operator) {
case EQ:
return new Query.FilterPredicate(getPropName(), Query.FilterOperator.EQUAL, getOperand());
case LT:
return new Query.FilterPredicate(getPropName(), Query.FilterOperator.LESS_THAN, getOperand());
case LE:
return new Query.FilterPredicate(getPropName(), Query.FilterOperator.LESS_THAN_OR_EQUAL,
getOperand());
case GT:
return new Query.FilterPredicate(getPropName(), Query.FilterOperator.GREATER_THAN,
getOperand());
case GE:
return new Query.FilterPredicate(getPropName(), Query.FilterOperator.GREATER_THAN_OR_EQUAL,
getOperand());
case NE:
return new Query.FilterPredicate(getPropName(), Query.FilterOperator.NOT_EQUAL, getOperand());
case IN:
LinkedList<Object> l = new LinkedList<Object>(values);
l.removeFirst();
return new Query.FilterPredicate(getPropName(), Query.FilterOperator.IN, l);
case AND:
return new Query.CompositeFilter(CompositeFilterOperator.AND, getSubfilters(subfilters));
case OR:
return new Query.CompositeFilter(CompositeFilterOperator.OR, getSubfilters(subfilters));
}
return null;
}
private String getPropName() {
return (String) values.get(0);
}
// returns Date if the operand is JSON date string
private Object getOperand() {
String s = String.valueOf(values.get(1));
long t = convertJSONDateToEpochTime(s);
return t == 0 ? values.get(1) : new Date(t);
}
private List<Filter> getSubfilters(List<FilterDto> values) {
List<Filter> subfilters = new LinkedList<Query.Filter>();
for (FilterDto cb : values) {
subfilters.add(cb.getDatastoreFilter());
}
return subfilters;
}
@Override
public String toString() {
return "FilterDto op: " + operator.toString() + ", values: " + values;
}
public List<FilterDto> getSubfilters() {
return subfilters;
}
public void setSubfilters(List<FilterDto> subfilters) {
this.subfilters = subfilters;
}
/**
* Returns Prospective Search query string that is converted form this filter.
*/
protected String buildProsSearchQuery() {
switch (this.operator) {
case EQ:
return "( " + getPropName() + " : " + getOperandString() + ")";
case LT:
return "( " + getPropName() + " < " + getOperandString() + " )";
case LE:
return "( " + getPropName() + " <= " + getOperandString() + " )";
case GT:
return "( " + getPropName() + " > " + getOperandString() + " )";
case GE:
return "( " + getPropName() + " <= " + getOperandString() + " )";
case NE:
return "(NOT " + getPropName() + " : " + getOperandString() + ")";
case IN:
return buildQueryForOperatorIN();
case AND:
return buildQueryForLogicalOperator("AND");
case OR:
return buildQueryForLogicalOperator("OR");
}
return null;
}
private String getOperandString() {
return getOperandString(1);
}
// returns epoch time if the operand is JSON date string
private String getOperandString(int i) {
FieldType ft = detectFieldType(values.get(i));
String s = String.valueOf(values.get(i));
if (ft == FieldType.STRING || ft == FieldType.TEXT) {
s = "\"" + s + "\"";
}
long t = convertJSONDateToEpochTime(s);
return t == 0 ? s : String.valueOf(t);
}
private String buildQueryForOperatorIN() {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 1; i < this.values.size(); i++) {
sb.append("(" + this.getPropName() + " : " + getOperandString(i) + " )");
if (i != this.values.size() - 1) {
sb.append(" OR ");
}
}
sb.append(")");
return sb.toString();
}
private String buildQueryForLogicalOperator(String op) {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < this.subfilters.size(); i++) {
sb.append(this.subfilters.get(i).buildProsSearchQuery());
if (i != this.subfilters.size() - 1) {
sb.append(" " + op + " ");
}
}
sb.append(")");
return sb.toString();
}
/**
* Builds schema of Prospective Search for this filter.
*/
protected Map<String, FieldType> buildProsSearchSchema() {
Map<String, FieldType> schema = new HashMap<String, FieldType>();
switch (this.operator) {
case EQ:
case LT:
case LE:
case GT:
case GE:
case NE:
schema.put(getPropName(), detectFieldType(values.get(1)));
break;
case IN: // IN supports only String
schema.put(getPropName(), FieldType.STRING);
break;
case AND:
case OR:
for (FilterDto cb : this.subfilters) {
schema.putAll(cb.buildProsSearchSchema());
}
break;
}
return schema;
}
private FieldType detectFieldType(Object value) {
if (value instanceof Boolean) {
return FieldType.BOOLEAN;
} else if (value instanceof Number) {
if (value instanceof Integer) {
return FieldType.INT32;
} else {
return FieldType.DOUBLE;
}
} else {
boolean isNotJSONDate = convertJSONDateToEpochTime(String.valueOf(value)) == 0;
if (isNotJSONDate) {
return FieldType.STRING;
} else {
return FieldType.DOUBLE;
}
}
}
// converts JSON date to epoch time value
// return 0 if it can't be converted
private long convertJSONDateToEpochTime(String date) {
// fast check if date could be a JSON date time
if (date == null || !date.matches("^\\d.+[Z\\d]$")) {
return 0;
}
// try to convert to epoch time
try {
return datatypeFactory.newXMLGregorianCalendar(date).toGregorianCalendar().getTimeInMillis();
} catch (Throwable th) {
return 0;
}
}
}
| apache-2.0 |
siosio/intellij-community | java/java-impl/src/com/intellij/codeInsight/unwrap/JavaSynchronizedUnwrapper.java | 1453 | /*
* 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.unwrap;
import com.intellij.java.JavaBundle;
import com.intellij.psi.PsiCodeBlock;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiSynchronizedStatement;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
public class JavaSynchronizedUnwrapper extends JavaUnwrapper {
public JavaSynchronizedUnwrapper() {
super(JavaBundle.message("unwrap.synchronized"));
}
@Override
public boolean isApplicableTo(@NotNull PsiElement e) {
return e instanceof PsiSynchronizedStatement;
}
@Override
protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException {
PsiCodeBlock body = ((PsiSynchronizedStatement)element).getBody();
context.extractFromCodeBlock(body, element);
context.delete(element);
}
} | apache-2.0 |
ThiagoGarciaAlves/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java | 6427 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.gradle.codeInsight.actions;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.lookup.impl.LookupCellRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorModificationUtil;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.EditorFontType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.components.JBList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.gradle.util.GradleBundle;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import javax.swing.*;
import java.awt.*;
import java.util.List;
/**
* @author Vladislav.Soroka
* @since 10/24/13
*/
class AddGradleDslPluginActionHandler implements CodeInsightActionHandler {
private final List<Pair<String, String>> myPlugins;
public AddGradleDslPluginActionHandler(List<Pair<String, String>> plugins) {
myPlugins = plugins;
}
@Override
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
if (!EditorModificationUtil.checkModificationAllowed(editor)) return;
if (!FileModificationService.getInstance().preparePsiElementsForWrite(file)) return;
final JBList list = new JBList(myPlugins);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setCellRenderer(new MyListCellRenderer());
Runnable runnable = () -> {
final Pair selected = (Pair)list.getSelectedValue();
new WriteCommandAction.Simple(project, GradleBundle.message("gradle.codeInsight.action.apply_plugin.text"), file) {
@Override
protected void run() {
if (selected == null) return;
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
GrStatement grStatement = factory.createStatementFromText(String.format("apply plugin: '%s'", selected.first), null);
PsiElement anchor = file.findElementAt(editor.getCaretModel().getOffset());
PsiElement currentElement = PsiTreeUtil.getParentOfType(anchor, GrClosableBlock.class, GroovyFile.class);
if (currentElement != null) {
currentElement.addAfter(grStatement, anchor);
}
else {
file.addAfter(grStatement, file.findElementAt(editor.getCaretModel().getOffset() - 1));
}
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
Document document = documentManager.getDocument(file);
if (document != null) {
documentManager.commitDocument(document);
}
}
}.execute();
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
Pair<String, String> descriptor = ContainerUtil.find(myPlugins, value -> value.first.equals(AddGradleDslPluginAction.TEST_THREAD_LOCAL.get()));
list.setSelectedValue(descriptor, false);
runnable.run();
}
else {
JBPopupFactory.getInstance().createListPopupBuilder(list)
.setTitle(GradleBundle.message("gradle.codeInsight.action.apply_plugin.popup.title"))
.setItemChoosenCallback(runnable)
.setFilteringEnabled(o -> String.valueOf(((Pair)o).first))
.createPopup()
.showInBestPositionFor(editor);
}
}
@Override
public boolean startInWriteAction() {
return false;
}
private static class MyListCellRenderer implements ListCellRenderer {
private final JPanel myPanel;
private final JLabel myNameLabel;
private final JLabel myDescLabel;
public MyListCellRenderer() {
myPanel = new JPanel(new BorderLayout());
myPanel.setBorder(JBUI.Borders.emptyLeft(2));
myNameLabel = new JLabel();
myPanel.add(myNameLabel, BorderLayout.WEST);
myPanel.add(new JLabel(" "));
myDescLabel = new JLabel();
myPanel.add(myDescLabel, BorderLayout.EAST);
EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
Font font = scheme.getFont(EditorFontType.PLAIN);
myNameLabel.setFont(font);
myDescLabel.setFont(font);
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Pair descriptor = (Pair)value;
Color backgroundColor = isSelected ? list.getSelectionBackground() : list.getBackground();
myNameLabel.setText(String.valueOf(descriptor.first));
myNameLabel.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
myPanel.setBackground(backgroundColor);
String description = String.format("<html><div WIDTH=%d>%s</div><html>", 400, String.valueOf(descriptor.second));
myDescLabel.setText(description);
myDescLabel.setForeground(LookupCellRenderer.getGrayedForeground(isSelected));
myDescLabel.setBackground(backgroundColor);
return myPanel;
}
}
} | apache-2.0 |
krosenvold/selenium-git-release-candidate | java/client/src/org/openqa/selenium/android/library/DefaultViewClient.java | 4496 | /*
Copyright 2011 Software Freedom Conservatory.
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.openqa.selenium.android.library;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Message;
import android.view.KeyEvent;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* This class provides a default implementation for WebViewClient to be used
* by WebDriver.
*
* This class overrides WebView default behavior when loading new URL. It makes sure that the URL
* is always loaded by the WebView.
*/
class DefaultViewClient extends WebViewClient implements DriverProvider {
private final WebViewClient delegate;
private WebDriverViewClient wdViewClient;
/**
* Use this constructor if the WebView used does not have custom
* bahvior defined in the WebViewClient.
*/
public DefaultViewClient() {
this(null);
}
/**
* Use this constructor if the WebView used has custom behavior defined
* in the WebViewClient.
*
* @param client the WebViewClient used by the WebView.
*/
public DefaultViewClient(WebViewClient client) {
if (client == null) {
delegate = new WebViewClient();
} else {
delegate = client;
}
}
public void setDriver(AndroidWebDriver driver) {
this.wdViewClient = new WebDriverViewClient(driver);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description,
String failingUrl) {
wdViewClient.onReceivedError(view, errorCode, description, failingUrl);
delegate.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void onFormResubmission(WebView view, Message dontResend, Message resend) {
delegate.onFormResubmission(view, dontResend, resend);
}
@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
delegate.doUpdateVisitedHistory(view, url, isReload);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
wdViewClient.onReceivedSslError(view, handler, error);
delegate.onReceivedSslError(view, handler, error);
}
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
String realm) {
delegate.onReceivedHttpAuthRequest(view, handler, host, realm);
}
@Override
public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
return delegate.shouldOverrideKeyEvent(view, event);
}
@Override
public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
delegate.onUnhandledKeyEvent(view, event);
}
@Override
public void onScaleChanged(WebView view, float oldScale, float newScale) {
delegate.onScaleChanged(view, oldScale, newScale);
}
@Override
public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
delegate.onReceivedLoginRequest(view, realm, account, args);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return delegate.shouldOverrideUrlLoading(view, url);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
wdViewClient.onPageStarted(view, url);
delegate.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
wdViewClient.onPageFinished(view, url);
delegate.onPageFinished(view, url);
}
@Override
public void onLoadResource(WebView view, String url) {
delegate.onLoadResource(view, url);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return delegate.shouldInterceptRequest(view, url);
}
@Override
public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) {
delegate.onTooManyRedirects(view, cancelMsg, continueMsg);
}
}
| apache-2.0 |
apereo/cas | core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/gen/DefaultRandomNumberGenerator.java | 623 | package org.apereo.cas.util.gen;
import lombok.NoArgsConstructor;
/**
* Implementation of the RandomStringGenerator that allows you to define the
* length of the random part.
*
* @author Scott Battaglia
* @since 3.0.0
*/
@NoArgsConstructor
public class DefaultRandomNumberGenerator extends DefaultRandomStringGenerator {
private static final char[] PRINTABLE_CHARACTERS = "012345679".toCharArray();
public DefaultRandomNumberGenerator(final int defaultLength) {
super(defaultLength);
}
@Override
protected char[] getPrintableCharacters() {
return PRINTABLE_CHARACTERS;
}
}
| apache-2.0 |
vbonamy/esup-uportal | uportal-war/src/main/java/org/jasig/portal/security/PersonFactory.java | 4097 | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.jasig.portal.security;
import org.jasig.portal.IUserIdentityStore;
import org.jasig.portal.properties.PropertiesManager;
import org.jasig.portal.security.provider.PersonImpl;
import org.jasig.portal.security.provider.RestrictedPerson;
import org.jasig.portal.spring.locator.UserIdentityStoreLocator;
import org.jasig.portal.utils.threading.SingletonDoubleCheckedCreator;
/**
* Creates a person.
* <p>
* Can create representations of a <i>system</i> user and a <i>guest</i> user.
* <p>
* <i>system</i> users have an ID of 0
* <p>
* <i>guest</i> users have both of the following characteristics<br>
* <ol>
* <li>User is not successfully authenticated with the portal.</li>
* <li>User name matches the value of the property
* <code>org.jasig.portal.security.PersonFactory.guest_user_name</code>
* in <code>portal.properties</code>.</li>
* </ol>
* @author Ken Weiner, kweiner@unicon.net
* @version $Revision$
*/
public class PersonFactory {
/**
* The guest user name specified in portal.properties.
*/
public static final String GUEST_USERNAME =
PropertiesManager.getProperty("org.jasig.portal.security.PersonFactory.guest_user_name", "guest");
private static final SingletonDoubleCheckedCreator<Integer> GUEST_USER_ID_LOADER = new SingletonDoubleCheckedCreator<Integer>() {
/* (non-Javadoc)
* @see org.jasig.portal.utils.threading.SingletonDoubleCheckedCreator#createSingleton(java.lang.Object[])
*/
@Override
protected Integer createSingleton(Object... args) {
final IPerson person = (IPerson)args[0];
final IUserIdentityStore userIdentityStore = UserIdentityStoreLocator.getUserIdentityStore();
try {
return userIdentityStore.getPortalUID(person);
}
catch (Exception e) {
throw new RuntimeException("Error while finding user id for person: " + person, e);
}
}
};
/**
* Creates an empty <code>IPerson</code> implementation.
* @return an empty <code>IPerson</code> implementation
*/
public static IPerson createPerson() {
return new PersonImpl();
}
/**
* Creates a <i>system</i> user.
* @return a <i>system</i> user
*/
public static IPerson createSystemPerson() {
IPerson person = createPerson();
person.setAttribute(IPerson.USERNAME, "SYSTEM_USER");
person.setID(0);
return person;
}
/**
* Creates a <i>guest</i> user.
* @return <i>guest</i> user
* @throws Exception
*/
public static IPerson createGuestPerson() throws Exception {
IPerson person = createPerson();
person.setAttribute(IPerson.USERNAME, GUEST_USERNAME);
final int guestUserId = GUEST_USER_ID_LOADER.get(person);
person.setID(guestUserId);
person.setSecurityContext(InitialSecurityContextFactory.getInitialContext("root"));
return person;
}
/**
* Creates a <i>restricted</i> user.
* @return <i>restricted</i> user
*/
public static RestrictedPerson createRestrictedPerson() {
IPerson person = createPerson();
return new RestrictedPerson(person);
}
}
| apache-2.0 |
twalpole/selenium | java/client/src/org/openqa/selenium/json/JsonInputIterator.java | 1685 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.json;
import static java.util.Spliterator.IMMUTABLE;
import static java.util.Spliterator.ORDERED;
import java.util.Iterator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
class JsonInputIterator implements Iterator<JsonInput> {
private final JsonInput jsonInput;
JsonInputIterator(JsonInput jsonInput) {
this.jsonInput = Objects.requireNonNull(jsonInput);
}
@Override
public boolean hasNext() {
return jsonInput.hasNext();
}
@Override
public JsonInput next() {
return jsonInput;
}
public Stream<JsonInput> asStream() {
Spliterator<JsonInput> spliterator = Spliterators.spliteratorUnknownSize(
this,
ORDERED & IMMUTABLE);
return StreamSupport.stream(spliterator, false);
}
}
| apache-2.0 |
donNewtonAlpha/onos | core/api/src/main/java/org/onosproject/net/flow/criteria/Criterion.java | 6725 | /*
* Copyright 2014-present Open Networking Laboratory
*
* 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.onosproject.net.flow.criteria;
/**
* Representation of a single header field selection.
*/
public interface Criterion {
static final String SEPARATOR = ":";
/**
* Types of fields to which the selection criterion may apply.
*/
// From page 75 of OpenFlow 1.5.0 spec
enum Type {
/** Switch input port. */
IN_PORT,
/** Switch physical input port. */
IN_PHY_PORT,
/** Metadata passed between tables. */
METADATA,
/** Ethernet destination address. */
ETH_DST,
/** Ethernet destination address with masking. */
ETH_DST_MASKED,
/** Ethernet source address. */
ETH_SRC,
/** Ethernet source address with masking. */
ETH_SRC_MASKED,
/** Ethernet frame type. */
ETH_TYPE,
/** VLAN id. */
VLAN_VID,
/** VLAN priority. */
VLAN_PCP,
/**
* Inner VLAN id.
*
* Note: Some drivers may not support this.
*/
INNER_VLAN_VID,
/**
* Inner VLAN pcp.
*
* Note: Some drivers may not support this.
*/
INNER_VLAN_PCP,
/** IP DSCP (6 bits in ToS field). */
IP_DSCP,
/** IP ECN (2 bits in ToS field). */
IP_ECN,
/** IP protocol. */
IP_PROTO,
/** IPv4 source address. */
IPV4_SRC,
/** IPv4 destination address. */
IPV4_DST,
/** TCP source port. */
TCP_SRC,
/** TCP destination port. */
TCP_DST,
/** UDP source port. */
UDP_SRC,
/** UDP destination port. */
UDP_DST,
/** SCTP source port. */
SCTP_SRC,
/** SCTP destination port. */
SCTP_DST,
/** ICMP type. */
ICMPV4_TYPE,
/** ICMP code. */
ICMPV4_CODE,
/** ARP opcode. */
ARP_OP,
/** ARP source IPv4 address. */
ARP_SPA,
/** ARP target IPv4 address. */
ARP_TPA,
/** ARP source hardware address. */
ARP_SHA,
/** ARP target hardware address. */
ARP_THA,
/** IPv6 source address. */
IPV6_SRC,
/** IPv6 destination address. */
IPV6_DST,
/** IPv6 Flow Label. */
IPV6_FLABEL,
/** ICMPv6 type. */
ICMPV6_TYPE,
/** ICMPv6 code. */
ICMPV6_CODE,
/** Target address for ND. */
IPV6_ND_TARGET,
/** Source link-layer for ND. */
IPV6_ND_SLL,
/** Target link-layer for ND. */
IPV6_ND_TLL,
/** MPLS label. */
MPLS_LABEL,
/** MPLS TC. */
MPLS_TC,
/** MPLS BoS bit. */
MPLS_BOS,
/** PBB I-SID. */
PBB_ISID,
/** Logical Port Metadata. */
TUNNEL_ID,
/** IPv6 Extension Header pseudo-field. */
IPV6_EXTHDR,
/** Unassigned value: 40. */
UNASSIGNED_40,
/** PBB UCA header field. */
PBB_UCA,
/** TCP flags. */
TCP_FLAGS,
/** Output port from action set metadata. */
ACTSET_OUTPUT,
/** Packet type value. */
PACKET_TYPE,
//
// NOTE: Everything below is defined elsewhere: ONOS-specific,
// extensions, etc.
//
/** Optical channel signal ID (lambda). */
OCH_SIGID,
/** Optical channel signal type (fixed or flexible). */
OCH_SIGTYPE,
/** ODU (Optical channel Data Unit) signal ID. */
ODU_SIGID,
/** ODU (Optical channel Data Unit) signal type. */
ODU_SIGTYPE,
/** Extension criterion. */
EXTENSION,
/** An empty criterion. */
DUMMY
}
/**
* Returns the type of criterion.
*
* @return type of criterion
*/
Type type();
/**
* Bit definitions for IPv6 Extension Header pseudo-field.
* From page 79 of OpenFlow 1.5.0 spec.
*/
enum IPv6ExthdrFlags {
/** "No next header" encountered. */
NONEXT((short) (1 << 0)),
/** Encrypted Sec Payload header present. */
ESP((short) (1 << 1)),
/** Authentication header present. */
AUTH((short) (1 << 2)),
/** 1 or 2 dest headers present. */
DEST((short) (1 << 3)),
/** Fragment header present. */
FRAG((short) (1 << 4)),
/** Router header present. */
ROUTER((short) (1 << 5)),
/** Hop-by-hop header present. */
HOP((short) (1 << 6)),
/** Unexpected repeats encountered. */
UNREP((short) (1 << 7)),
/** Unexpected sequencing encountered. */
UNSEQ((short) (1 << 8));
private short value;
IPv6ExthdrFlags(short value) {
this.value = value;
}
/**
* Gets the value as an integer.
*
* @return the value as an integer
*/
public short getValue() {
return this.value;
}
}
enum TcpFlags {
/** ECN-nonce concealment protection. */
NS((short) (1 << 0)),
/** Congestion Window Reduced. */
CWR((short) (1 << 1)),
/** ECN-Echo. **/
ECE((short) (1 << 2)),
/** Urgent pointer field is significant. */
URG((short) (1 << 3)),
/** Acknowledgment field is significant. */
ACK((short) (1 << 4)),
/** Push the buffered data to the receiving application. */
PSH((short) (1 << 5)),
/** Reset the connection. */
RST((short) (1 << 6)),
/** Synchronize sequence numbers. */
SYN((short) (1 << 7)),
/** No more data from sender. */
FIN((short) (1 << 8));
private short value;
TcpFlags(short value) {
this.value = value;
}
/**
* Gets the value as an integer.
*
* @return the value as an integer
*/
public short getValue() {
return this.value;
}
}
}
| apache-2.0 |
qeist/scouter | scouter.client/src/scouter/client/actions/SetColorAction.java | 1871 | /*
* Copyright 2015 LG CNS.
*
* 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 scouter.client.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.ui.IWorkbenchWindow;
import scouter.client.Images;
import scouter.client.model.AgentColorManager;
import scouter.client.model.AgentModelThread;
import scouter.client.model.AgentObject;
import scouter.client.util.ImageUtil;
public class SetColorAction extends Action {
public final static String ID = SetColorAction.class.getName();
private final IWorkbenchWindow window;
private int objHash;
public SetColorAction(IWorkbenchWindow window, int objHash) {
this.window = window;
this.objHash = objHash;
setText("Set Color");
setId(ID);
setImageDescriptor(ImageUtil.getImageDescriptor(Images.color_swatch));
}
public void run() {
if (window != null) {
ColorDialog dlg = new ColorDialog(window.getShell());
AgentObject agent = AgentModelThread.getInstance().getAgentObject(objHash);
dlg.setRGB(agent.getColor().getRGB());
dlg.setText("Choose a Color");
RGB rgb = dlg.open();
if (rgb != null) {
Color color = AgentColorManager.getInstance().changeColor(objHash, rgb);
//agent.setColor(color);
}
}
}
}
| apache-2.0 |
siosio/intellij-community | xml/dom-openapi/src/com/intellij/util/xml/converters/QuotedValueConverter.java | 6183 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xml.converters;
import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider;
import com.intellij.codeInspection.util.InspectionMessage;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.util.xml.*;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Collections;
public abstract class QuotedValueConverter<T> extends ResolvingConverter<T> implements CustomReferenceConverter<T> {
public static final char[] QUOTE_SIGNS = new char[] {'\'', '\"', '`'};
protected char[] getQuoteSigns() {
return QUOTE_SIGNS;
}
protected char getQuoteSign(final T t, final ConvertContext context) {
return 0;
}
@Nullable
protected abstract T convertString(@Nullable final String string, final ConvertContext context);
@Nullable
protected abstract String convertValue(@Nullable final T t, final ConvertContext context);
protected abstract Object[] getReferenceVariants(final ConvertContext context, GenericDomValue<T> genericDomValue,
final TextRange rangeInElement);
protected abstract ResolveResult @NotNull [] multiResolveReference(@Nullable final T t, final ConvertContext context);
protected abstract @InspectionMessage String getUnresolvedMessage(String value);
@Override
@NotNull
public Collection<? extends T> getVariants(final ConvertContext context) {
return Collections.emptyList();
}
@Override
public T fromString(final String str, final ConvertContext context) {
return convertString(unquote(str, getQuoteSigns()), context);
}
@Override
public String toString(final T ts, final ConvertContext context) {
final char delimiter = getQuoteSign(ts, context);
final String s = convertValue(ts, context);
return delimiter > 0? delimiter + s+ delimiter : s;
}
@Override
public PsiReference @NotNull [] createReferences(final GenericDomValue<T> genericDomValue,
final PsiElement element,
final ConvertContext context) {
final String originalValue = genericDomValue.getStringValue();
if (originalValue == null) return PsiReference.EMPTY_ARRAY;
TextRange range = ElementManipulators.getValueTextRange(element);
String unquotedValue = unquote(originalValue, getQuoteSigns());
int valueOffset = range.substring(element.getText()).indexOf(unquotedValue);
if (valueOffset < 0) return PsiReference.EMPTY_ARRAY;
int start = range.getStartOffset() + valueOffset;
int end = start + unquotedValue.length();
boolean unclosedQuotation = valueOffset > 0 && end == range.getEndOffset();
return new PsiReference[]{createPsiReference(element, start, end, true, context, genericDomValue, unclosedQuotation)};
}
@Nullable
public static String unquote(final String str) {
return unquote(str, QUOTE_SIGNS);
}
@Contract("null, _ -> null")
public static String unquote(final String str, final char[] quoteSigns) {
if (str != null && str.length() > 2) {
final char c = str.charAt(0);
for (char quote : quoteSigns) {
if (quote == c) {
return str.substring(1, c == str.charAt(str.length() - 1)? str.length() - 1 : str.length());
}
}
}
return str;
}
public static boolean quotationIsNotClosed(final String str) {
return StringUtil.isNotEmpty(str) && str.charAt(0) != str.charAt(str.length()-1);
}
@NotNull
protected PsiReference createPsiReference(final PsiElement element,
int start, int end,
final boolean isSoft,
final ConvertContext context,
final GenericDomValue<T> genericDomValue,
final boolean badQuotation) {
return new MyPsiReference(element, new TextRange(start, end), isSoft, context, genericDomValue, badQuotation);
}
protected class MyPsiReference extends PsiPolyVariantReferenceBase<PsiElement> implements EmptyResolveMessageProvider {
protected final ConvertContext myContext;
protected final GenericDomValue<T> myGenericDomValue;
private final boolean myBadQuotation;
public MyPsiReference(final PsiElement element, final TextRange range, final boolean isSoft, final ConvertContext context, final GenericDomValue<T> genericDomValue,
final boolean badQuotation) {
super(element, range, isSoft);
myContext = context;
myGenericDomValue = genericDomValue;
myBadQuotation = badQuotation;
}
@Override
public ResolveResult @NotNull [] multiResolve(final boolean incompleteCode) {
if (myBadQuotation) return ResolveResult.EMPTY_ARRAY;
final String value = getValue();
return multiResolveReference(convertString(value, myContext), myContext);
}
@Override
public Object @NotNull [] getVariants() {
return getReferenceVariants(myContext, myGenericDomValue, getRangeInElement());
}
@SuppressWarnings("UnresolvedPropertyKey")
@Override
@NotNull
public String getUnresolvedMessagePattern() {
return myBadQuotation ? XmlDomBundle.message("dom.inspections.invalid.value.quotation") : getUnresolvedMessage(getValue());
}
}
}
| apache-2.0 |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/command/impl/CannotUndoReportDialog.java | 3574 | // Copyright 2000-2020 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.openapi.command.impl;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.command.undo.DocumentReference;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.SimpleListCellRenderer;
import com.intellij.util.EditSourceOnDoubleClickHandler;
import com.intellij.util.EditSourceOnEnterKeyHandler;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Collection;
public class CannotUndoReportDialog extends DialogWrapper implements DataProvider {
private static final int FILE_TEXT_PREVIEW_CHARS_LIMIT = 40;
private final Project myProject;
private JList<DocumentReference> myProblemFilesList;
private JPanel myPanel;
private JLabel myProblemMessageLabel;
public CannotUndoReportDialog(Project project, @Nls String problemText, Collection<? extends DocumentReference> files) {
super(project, false);
myProject = project;
DefaultListModel<DocumentReference> model = new DefaultListModel<>();
for (DocumentReference file : files) {
model.addElement(file);
}
myProblemFilesList.setCellRenderer(new SimpleListCellRenderer<>() {
@Override
public void customize(@NotNull JList<? extends DocumentReference> list,
DocumentReference file,
int index,
boolean selected,
boolean hasFocus) {
final VirtualFile vFile = file.getFile();
if (vFile != null) {
setText(vFile.getPresentableUrl());
}
else {
Document document = file.getDocument();
CharSequence content = document == null ? null : document.getImmutableCharSequence();
if (content != null && content.length() > FILE_TEXT_PREVIEW_CHARS_LIMIT) {
content = content.subSequence(0, FILE_TEXT_PREVIEW_CHARS_LIMIT) + "...";
}
setText(IdeBundle.message("list.item.temporary.file.0", content == null ? "" : " [" + content + "]"));
}
}
});
myProblemFilesList.setModel(model);
EditSourceOnDoubleClickHandler.install(myProblemFilesList, () -> doOKAction());
EditSourceOnEnterKeyHandler.install(myProblemFilesList, () -> doOKAction());
setTitle(IdeBundle.message("cannot.undo.title"));
myProblemMessageLabel.setText(problemText);
myProblemMessageLabel.setIcon(Messages.getErrorIcon());
init();
}
@Override
protected Action @NotNull [] createActions() {
return new Action[]{getOKAction()};
}
@Override
@Nullable
protected JComponent createCenterPanel() {
return myPanel;
}
@Nullable
@Override
public Object getData(@NotNull String dataId) {
if (CommonDataKeys.NAVIGATABLE.is(dataId)) {
DocumentReference value = myProblemFilesList.getSelectedValue();
VirtualFile file = value != null ? value.getFile() : null;
if (file != null) {
return new OpenFileDescriptor(myProject, file);
}
}
return null;
}
} | apache-2.0 |
krosenvold/selenium-git-release-candidate | java/client/src/org/openqa/selenium/support/events/internal/EventFiringTouch.java | 2217 | /*
Copyright 2007-2011 Selenium committers
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.openqa.selenium.support.events.internal;
import org.openqa.selenium.HasTouchScreen;
import org.openqa.selenium.TouchScreen;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.support.events.WebDriverEventListener;
/**
* A touch screen that fires events.
*/
public class EventFiringTouch implements TouchScreen {
private final WebDriver driver;
private final WebDriverEventListener dispatcher;
private final TouchScreen touchScreen;
public EventFiringTouch(WebDriver driver, WebDriverEventListener dispatcher) {
this.driver = driver;
this.dispatcher = dispatcher;
this.touchScreen = ((HasTouchScreen) this.driver).getTouch();
}
public void singleTap(Coordinates where) {
touchScreen.singleTap(where);
}
public void down(int x, int y) {
touchScreen.down(x, y);
}
public void up(int x, int y) {
touchScreen.up(x, y);
}
public void move(int x, int y) {
touchScreen.move(x, y);
}
public void scroll(Coordinates where, int xOffset, int yOffset) {
touchScreen.scroll(where, xOffset, yOffset);
}
public void doubleTap(Coordinates where) {
touchScreen.doubleTap(where);
}
public void longPress(Coordinates where) {
touchScreen.longPress(where);
}
public void scroll(int xOffset, int yOffset) {
touchScreen.scroll(xOffset, yOffset);
}
public void flick(int xSpeed, int ySpeed) {
touchScreen.flick(xSpeed, ySpeed);
}
public void flick(Coordinates where, int xOffset, int yOffset, int speed) {
touchScreen.flick(where, xOffset, yOffset, speed);
}
}
| apache-2.0 |
yu-yamada/presto | presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java | 15031 | /*
* 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.sql.gen;
import com.facebook.presto.byteCode.Block;
import com.facebook.presto.byteCode.ByteCodeNode;
import com.facebook.presto.byteCode.ClassDefinition;
import com.facebook.presto.byteCode.Scope;
import com.facebook.presto.byteCode.MethodDefinition;
import com.facebook.presto.byteCode.Parameter;
import com.facebook.presto.byteCode.ParameterizedType;
import com.facebook.presto.byteCode.Variable;
import com.facebook.presto.byteCode.control.ForLoop;
import com.facebook.presto.byteCode.control.IfStatement;
import com.facebook.presto.byteCode.instruction.LabelNode;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.operator.PageProcessor;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.ConstantExpression;
import com.facebook.presto.sql.relational.Expressions;
import com.facebook.presto.sql.relational.InputReferenceExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.facebook.presto.sql.relational.RowExpressionVisitor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import java.util.List;
import java.util.TreeSet;
import static com.facebook.presto.byteCode.Access.PUBLIC;
import static com.facebook.presto.byteCode.Access.a;
import static com.facebook.presto.byteCode.Parameter.arg;
import static com.facebook.presto.byteCode.OpCode.NOP;
import static com.facebook.presto.byteCode.ParameterizedType.type;
import static com.facebook.presto.sql.gen.ByteCodeUtils.generateWrite;
import static com.facebook.presto.sql.gen.ByteCodeUtils.loadConstant;
import static java.lang.String.format;
import static java.util.Collections.nCopies;
public class PageProcessorCompiler
implements BodyCompiler<PageProcessor>
{
private final Metadata metadata;
public PageProcessorCompiler(Metadata metadata)
{
this.metadata = metadata;
}
@Override
public void generateMethods(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter, List<RowExpression> projections)
{
generateProcessMethod(classDefinition, filter, projections);
generateFilterMethod(classDefinition, callSiteBinder, filter);
for (int i = 0; i < projections.size(); i++) {
generateProjectMethod(classDefinition, callSiteBinder, "project_" + i, projections.get(i));
}
}
private void generateProcessMethod(ClassDefinition classDefinition, RowExpression filter, List<RowExpression> projections)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter start = arg("start", int.class);
Parameter end = arg("end", int.class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "process", type(int.class), session, page, start, end, pageBuilder);
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
Variable position = scope.declareVariable(int.class, "position");
method.getBody()
.comment("int position = start;")
.getVariable(start)
.putVariable(position);
List<Integer> allInputChannels = getInputChannels(Iterables.concat(projections, ImmutableList.of(filter)));
for (int channel : allInputChannels) {
Variable blockVariable = scope.declareVariable(com.facebook.presto.spi.block.Block.class, "block_" + channel);
method.getBody()
.comment("Block %s = page.getBlock(%s);", blockVariable.getName(), channel)
.getVariable(page)
.push(channel)
.invokeVirtual(Page.class, "getBlock", com.facebook.presto.spi.block.Block.class, int.class)
.putVariable(blockVariable);
}
//
// for loop loop body
//
LabelNode done = new LabelNode("done");
Block loopBody = new Block();
ForLoop loop = new ForLoop()
.initialize(NOP)
.condition(new Block()
.comment("position < end")
.getVariable(position)
.getVariable(end)
.invokeStatic(CompilerOperations.class, "lessThan", boolean.class, int.class, int.class)
)
.update(new Block()
.comment("position++")
.incrementVariable(position, (byte) 1))
.body(loopBody);
loopBody.comment("if (pageBuilder.isFull()) break;")
.getVariable(pageBuilder)
.invokeVirtual(PageBuilder.class, "isFull", boolean.class)
.ifTrueGoto(done);
// if (filter(cursor))
IfStatement filterBlock = new IfStatement();
filterBlock.condition()
.append(thisVariable)
.getVariable(session)
.append(pushBlockVariables(scope, getInputChannels(filter)))
.getVariable(position)
.invokeVirtual(classDefinition.getType(),
"filter",
type(boolean.class),
ImmutableList.<ParameterizedType>builder()
.add(type(ConnectorSession.class))
.addAll(nCopies(getInputChannels(filter).size(), type(com.facebook.presto.spi.block.Block.class)))
.add(type(int.class))
.build());
filterBlock.ifTrue()
.append(pageBuilder)
.invokeVirtual(PageBuilder.class, "declarePosition", void.class);
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
List<Integer> inputChannels = getInputChannels(projections.get(projectionIndex));
filterBlock.ifTrue()
.append(thisVariable)
.append(session)
.append(pushBlockVariables(scope, inputChannels))
.getVariable(position);
filterBlock.ifTrue()
.comment("pageBuilder.getBlockBuilder(%d)", projectionIndex)
.append(pageBuilder)
.push(projectionIndex)
.invokeVirtual(PageBuilder.class, "getBlockBuilder", BlockBuilder.class, int.class);
filterBlock.ifTrue()
.comment("project_%d(session, block_%s, position, blockBuilder)", projectionIndex, inputChannels)
.invokeVirtual(classDefinition.getType(),
"project_" + projectionIndex,
type(void.class),
ImmutableList.<ParameterizedType>builder()
.add(type(ConnectorSession.class))
.addAll(nCopies(inputChannels.size(), type(com.facebook.presto.spi.block.Block.class)))
.add(type(int.class))
.add(type(BlockBuilder.class))
.build());
}
loopBody.append(filterBlock);
method.getBody()
.append(loop)
.visitLabel(done)
.comment("return position;")
.getVariable(position)
.retInt();
}
private void generateFilterMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> blocks = toBlockParameters(getInputChannels(filter));
Parameter position = arg("position", int.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(boolean.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(blocks)
.add(position)
.build());
method.comment("Filter: %s", filter.toString());
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable(type(boolean.class), "wasNull");
ByteCodeExpressionVisitor visitor = new ByteCodeExpressionVisitor(
callSiteBinder,
fieldReferenceCompiler(callSiteBinder, position, wasNullVariable),
metadata.getFunctionRegistry());
ByteCodeNode body = filter.accept(visitor, scope);
LabelNode end = new LabelNode("end");
method
.getBody()
.comment("boolean wasNull = false;")
.putVariable(wasNullVariable, false)
.append(body)
.getVariable(wasNullVariable)
.ifFalseGoto(end)
.pop(boolean.class)
.push(false)
.visitLabel(end)
.retBoolean();
}
private void generateProjectMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, String methodName, RowExpression projection)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> inputs = toBlockParameters(getInputChannels(projection));
Parameter position = arg("position", int.class);
Parameter output = arg("output", BlockBuilder.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
methodName,
type(void.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(inputs)
.add(position)
.add(output)
.build());
method.comment("Projection: %s", projection.toString());
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable(type(boolean.class), "wasNull");
Block body = method.getBody()
.comment("boolean wasNull = false;")
.putVariable(wasNullVariable, false);
ByteCodeExpressionVisitor visitor = new ByteCodeExpressionVisitor(callSiteBinder, fieldReferenceCompiler(callSiteBinder, position, wasNullVariable), metadata.getFunctionRegistry());
body.getVariable(output)
.comment("evaluate projection: " + projection.toString())
.append(projection.accept(visitor, scope))
.append(generateWrite(callSiteBinder, scope, wasNullVariable, projection.getType()))
.ret();
}
private static List<Integer> getInputChannels(Iterable<RowExpression> expressions)
{
TreeSet<Integer> channels = new TreeSet<>();
for (RowExpression expression : Expressions.subExpressions(expressions)) {
if (expression instanceof InputReferenceExpression) {
channels.add(((InputReferenceExpression) expression).getField());
}
}
return ImmutableList.copyOf(channels);
}
private static List<Integer> getInputChannels(RowExpression expression)
{
return getInputChannels(ImmutableList.of(expression));
}
private static List<Parameter> toBlockParameters(List<Integer> inputChannels)
{
ImmutableList.Builder<Parameter> parameters = ImmutableList.builder();
for (int channel : inputChannels) {
parameters.add(arg("block_" + channel, com.facebook.presto.spi.block.Block.class));
}
return parameters.build();
}
private static ByteCodeNode pushBlockVariables(Scope scope, List<Integer> inputs)
{
Block block = new Block();
for (int channel : inputs) {
block.append(scope.getVariable("block_" + channel));
}
return block;
}
private RowExpressionVisitor<Scope, ByteCodeNode> fieldReferenceCompiler(final CallSiteBinder callSiteBinder, final Variable positionVariable, final Variable wasNullVariable)
{
return new RowExpressionVisitor<Scope, ByteCodeNode>()
{
@Override
public ByteCodeNode visitInputReference(InputReferenceExpression node, Scope scope)
{
int field = node.getField();
Type type = node.getType();
Variable block = scope.getVariable("block_" + field);
Class<?> javaType = type.getJavaType();
IfStatement ifStatement = new IfStatement();
ifStatement.condition()
.setDescription(format("block_%d.get%s()", field, type))
.append(block)
.getVariable(positionVariable)
.invokeInterface(com.facebook.presto.spi.block.Block.class, "isNull", boolean.class, int.class);
ifStatement.ifTrue()
.putVariable(wasNullVariable, true)
.pushJavaDefault(javaType);
String methodName = "get" + Primitives.wrap(javaType).getSimpleName();
ifStatement.ifFalse()
.append(loadConstant(callSiteBinder.bind(type, Type.class)))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Type.class, methodName, javaType, com.facebook.presto.spi.block.Block.class, int.class);
return ifStatement;
}
@Override
public ByteCodeNode visitCall(CallExpression call, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
@Override
public ByteCodeNode visitConstant(ConstantExpression literal, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
};
}
}
| apache-2.0 |
biancini/oauth2-apis | apis-openconext-mock-war/src/main/java/org/surfnet/oaaas/conext/mock/OpenConextServlet.java | 697 | package org.surfnet.oaaas.conext.mock;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class OpenConextServlet extends HttpServlet {
private String callBackUrl;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
callBackUrl = config.getInitParameter("call-back-url");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect(callBackUrl);
}
}
| apache-2.0 |
joshualitt/DataflowJavaSDK | sdk/src/test/java/com/google/cloud/dataflow/sdk/util/DataflowPathValidatorTest.java | 3355 | /*
* Copyright (C) 2015 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.cloud.dataflow.sdk.util;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions;
import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner;
import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/** Tests for {@link DataflowPathValidator}. */
@RunWith(JUnit4.class)
public class DataflowPathValidatorTest {
@Rule public ExpectedException expectedException = ExpectedException.none();
@Mock private GcsUtil mockGcsUtil;
private DataflowPathValidator validator;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(true);
when(mockGcsUtil.isGcsPatternSupported(anyString())).thenCallRealMethod();
DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
options.setGcpCredential(new TestCredential());
options.setRunner(DataflowPipelineRunner.class);
options.setGcsUtil(mockGcsUtil);
validator = new DataflowPathValidator(options);
}
@Test
public void testValidFilePattern() {
validator.validateInputFilePatternSupported("gs://bucket/path");
}
@Test
public void testInvalidFilePattern() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
"DataflowPipelineRunner expected a valid 'gs://' path but was given '/local/path'");
validator.validateInputFilePatternSupported("/local/path");
}
@Test
public void testWhenBucketDoesNotExist() throws Exception {
when(mockGcsUtil.bucketExists(any(GcsPath.class))).thenReturn(false);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
"Could not find file gs://non-existent-bucket/location");
validator.validateInputFilePatternSupported("gs://non-existent-bucket/location");
}
@Test
public void testValidOutputPrefix() {
validator.validateOutputFilePrefixSupported("gs://bucket/path");
}
@Test
public void testInvalidOutputPrefix() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
"DataflowPipelineRunner expected a valid 'gs://' path but was given '/local/path'");
validator.validateOutputFilePrefixSupported("/local/path");
}
}
| apache-2.0 |
smartan/lucene | src/main/java/org/apache/lucene/facet/taxonomy/TaxonomyFacetSumIntAssociations.java | 3461 | package org.apache.lucene.facet.taxonomy;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.List;
import org.apache.lucene.facet.FacetsCollector;
import org.apache.lucene.facet.FacetsCollector.MatchingDocs;
import org.apache.lucene.facet.FacetsConfig;
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.BytesRef;
/** Aggregates sum of int values previously indexed with
* {@link IntAssociationFacetField}, assuming the default
* encoding.
*
* @lucene.experimental */
public class TaxonomyFacetSumIntAssociations extends IntTaxonomyFacets {
/** Create {@code TaxonomyFacetSumIntAssociations} against
* the default index field. */
public TaxonomyFacetSumIntAssociations(TaxonomyReader taxoReader, FacetsConfig config, FacetsCollector fc) throws IOException {
this(FacetsConfig.DEFAULT_INDEX_FIELD_NAME, taxoReader, config, fc);
}
/** Create {@code TaxonomyFacetSumIntAssociations} against
* the specified index field. */
public TaxonomyFacetSumIntAssociations(String indexFieldName, TaxonomyReader taxoReader, FacetsConfig config, FacetsCollector fc) throws IOException {
super(indexFieldName, taxoReader, config);
sumValues(fc.getMatchingDocs());
}
private final void sumValues(List<MatchingDocs> matchingDocs) throws IOException {
//System.out.println("count matchingDocs=" + matchingDocs + " facetsField=" + facetsFieldName);
for(MatchingDocs hits : matchingDocs) {
BinaryDocValues dv = hits.context.reader().getBinaryDocValues(indexFieldName);
if (dv == null) { // this reader does not have DocValues for the requested category list
continue;
}
DocIdSetIterator docs = hits.bits.iterator();
int doc;
while ((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
//System.out.println(" doc=" + doc);
// TODO: use OrdinalsReader? we'd need to add a
// BytesRef getAssociation()?
final BytesRef bytesRef = dv.get(doc);
byte[] bytes = bytesRef.bytes;
int end = bytesRef.offset + bytesRef.length;
int offset = bytesRef.offset;
while (offset < end) {
int ord = ((bytes[offset]&0xFF) << 24) |
((bytes[offset+1]&0xFF) << 16) |
((bytes[offset+2]&0xFF) << 8) |
(bytes[offset+3]&0xFF);
offset += 4;
int value = ((bytes[offset]&0xFF) << 24) |
((bytes[offset+1]&0xFF) << 16) |
((bytes[offset+2]&0xFF) << 8) |
(bytes[offset+3]&0xFF);
offset += 4;
values[ord] += value;
}
}
}
}
}
| apache-2.0 |
mahak/hbase | hbase-client/src/main/java/org/apache/hadoop/hbase/RegionException.java | 1342 | /**
*
* 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;
import org.apache.yetus.audience.InterfaceAudience;
/**
* Thrown when something happens related to region handling.
* Subclasses have to be more specific.
*/
@InterfaceAudience.Public
public class RegionException extends HBaseIOException {
private static final long serialVersionUID = 1473510258071111371L;
/** default constructor */
public RegionException() {
super();
}
/**
* Constructor
* @param s message
*/
public RegionException(String s) {
super(s);
}
}
| apache-2.0 |
DariusX/camel | core/camel-cloud/src/main/java/org/apache/camel/impl/cloud/PassThroughServiceFilter.java | 1149 | /*
* 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.impl.cloud;
import java.util.List;
import org.apache.camel.cloud.ServiceDefinition;
import org.apache.camel.cloud.ServiceFilter;
public class PassThroughServiceFilter implements ServiceFilter {
@Override
public List<ServiceDefinition> apply(List<ServiceDefinition> services) {
return services;
}
}
| apache-2.0 |
kjniemi/activemq-artemis | artemis-cli/src/test/java/org/apache/activemq/cli/test/StringGenerator.java | 1642 | /*
* 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.activemq.cli.test;
import java.util.Random;
/**
* Generate a random string.
*/
class StringGenerator {
private String letters = "abcdefghijklmnopqrstuvwxyz";
private String digits = "0123456789";
private String symbols = "~!@#$%^&*()_+{}|?><,./";
private String nonLatinLetters = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
String generateRandomString(int length) {
String initialString = letters + letters.toUpperCase() + nonLatinLetters + nonLatinLetters.toUpperCase()
+ symbols + digits;
StringBuilder result = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
result.append(initialString.charAt(random.nextInt(initialString.length())));
}
return result.toString();
}
}
| apache-2.0 |
nikhilvibhav/camel | core/camel-api/src/main/java/org/apache/camel/spi/DataFormatContentTypeHeader.java | 1334 | /*
* 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.spi;
/**
* Special accessor for a DataFormat
*/
public interface DataFormatContentTypeHeader {
/**
* Whether the data format should set the <tt>Content-Type</tt> header with the type from the data format if the
* data format is capable of doing so.
* <p/>
* For example <tt>application/xml</tt> for data formats marshalling to XML, or <tt>application/json</tt> for data
* formats marshalling to JSON etc.
*/
void setContentTypeHeader(boolean contentTypeHeader);
}
| apache-2.0 |
vvv1559/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/ConfigurableOptionsTopHitProvider.java | 5874 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui;
import com.intellij.ide.ui.search.BooleanOptionDescription;
import com.intellij.ide.ui.search.OptionDescription;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.ex.ConfigurableVisitor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.util.*;
/**
* @author Sergey.Malenkov
*/
public abstract class ConfigurableOptionsTopHitProvider extends OptionsTopHitProvider {
private static final Logger LOG = Logger.getInstance(ConfigurableOptionsTopHitProvider.class);
private final Deque<String> myPrefix = new ArrayDeque<>();
protected abstract Configurable getConfigurable(Project project);
/**
* Returns a name that will be added to all option names.
* This implementation returns the display name of the configurable.
*
* @param configurable the configurable to process
* @return a main prefix or {@code null} to ignore
*/
protected String getName(Configurable configurable) {
return configurable.getDisplayName();
}
/**
* Returns a section name that will be added to some option names,
* which are located within the specified container.
* This implementation returns the border title of the component.
*
* @param component the component to process
* @return a section prefix or {@code null} to ignore
*/
protected String getSection(Component component) {
if (component instanceof JComponent) {
Border border = ((JComponent)component).getBorder();
if (border instanceof TitledBorder) {
return ((TitledBorder)border).getTitle();
}
}
return null;
}
/**
* Returns an option name that will be used to create an option.
*
* @param checkbox the candidate to create an option
* @return an option prefix or {@code null} to ignore this option
*/
protected String getOptionName(JCheckBox checkbox) {
String name = StringUtil.stripHtml(checkbox.getText(), false);
if (StringUtil.isEmpty(name)) {
return null;
}
if (myPrefix.isEmpty()) {
return name;
}
StringBuilder sb = new StringBuilder();
Iterator<String> iterator = myPrefix.descendingIterator();
while (iterator.hasNext()) {
sb.append(iterator.next()).append(": ");
}
return sb.append(name).toString();
}
protected void init(Collection<BooleanOptionDescription> options, Configurable configurable, Component component) {
initRecursively(options, configurable, component);
}
private void initRecursively(Collection<BooleanOptionDescription> options, Configurable configurable, Component component) {
String section = getSection(component);
if (section != null) {
myPrefix.push(section);
}
if (component instanceof JCheckBox) {
JCheckBox checkbox = (JCheckBox)component;
String option = getOptionName(checkbox);
if (option != null) {
options.add(new Option(configurable, checkbox, option));
}
}
else if (component instanceof Container) {
Container container = (Container)component;
for (int i = 0; i < container.getComponentCount(); i++) {
initRecursively(options, configurable, container.getComponent(i));
}
}
if (section != null) {
myPrefix.pop();
}
}
@NotNull
@Override
public Collection<OptionDescription> getOptions(@Nullable Project project) {
try {
Configurable configurable = getConfigurable(project);
Component component = configurable.createComponent();
configurable.reset();
myPrefix.clear();
String name = getName(configurable);
if (name != null) {
myPrefix.push(name);
}
Collection<BooleanOptionDescription> options = new ArrayList<>();
init(options, configurable, component);
return Collections.unmodifiableCollection(options);
}
catch (Exception exception) {
LOG.debug(exception);
}
return Collections.emptyList();
}
private static final class Option extends BooleanOptionDescription implements Disposable {
private final Configurable myConfigurable;
private final JCheckBox myCheckBox;
private Option(Configurable configurable, JCheckBox checkbox, String option) {
super(option, ConfigurableVisitor.ByID.getID(configurable));
myConfigurable = configurable;
myCheckBox = checkbox;
}
@Override
public void dispose() {
myConfigurable.disposeUIResources();
}
@Override
public boolean isOptionEnabled() {
return myCheckBox.isSelected();
}
@Override
public void setOptionState(boolean selected) {
if (selected != myCheckBox.isSelected()) {
myCheckBox.setSelected(selected);
try {
myConfigurable.apply();
}
catch (ConfigurationException exception) {
LOG.debug(exception);
}
}
}
}
}
| apache-2.0 |
nikhilvibhav/camel | components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpEmptyQueryParameterTest.java | 1991 | /*
* 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.jetty;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class HttpEmptyQueryParameterTest extends BaseJettyTest {
@Test
public void testEmpty() throws Exception {
getMockEndpoint("mock:input").expectedHeaderReceived("id", 123);
String out = fluentTemplate.to("http://localhost:{{port}}/foo?id=123").request(String.class);
assertEquals("Header: 123", out);
assertMockEndpointsSatisfied();
resetMocks();
getMockEndpoint("mock:input").expectedHeaderReceived("id", "");
out = fluentTemplate.to("http://localhost:{{port}}/foo?id=").request(String.class);
assertEquals("Header: ", out);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("jetty:http://0.0.0.0:{{port}}/foo").to("mock:input").transform().simple("Header: ${header.id}");
}
};
}
}
| apache-2.0 |
mdeinum/spring-boot | spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java | 3719 | /*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.autoconfigure.metrics.export.simple;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
*
* Tests for {@link SimpleMetricsExportAutoConfiguration}.
*
* @author Andy Wilkinson
*/
class SimpleMetricsExportAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(SimpleMetricsExportAutoConfiguration.class));
@Test
void autoConfiguresConfigAndMeterRegistry() {
this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context)
.hasSingleBean(SimpleMeterRegistry.class).hasSingleBean(Clock.class).hasSingleBean(SimpleConfig.class));
}
@Test
void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() {
this.contextRunner.withUserConfiguration(BaseConfiguration.class)
.withPropertyValues("management.metrics.export.defaults.enabled=false")
.run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class)
.doesNotHaveBean(SimpleConfig.class));
}
@Test
void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() {
this.contextRunner.withUserConfiguration(BaseConfiguration.class)
.withPropertyValues("management.metrics.export.simple.enabled=false")
.run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class)
.doesNotHaveBean(SimpleConfig.class));
}
@Test
void allowsConfigToBeCustomized() {
this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class)
.run((context) -> assertThat(context).hasSingleBean(SimpleConfig.class).hasBean("customConfig"));
}
@Test
void backsOffEntirelyWithCustomMeterRegistry() {
this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context)
.hasSingleBean(MeterRegistry.class).hasBean("customRegistry").doesNotHaveBean(SimpleConfig.class));
}
@Configuration(proxyBeanMethods = false)
static class BaseConfiguration {
@Bean
Clock clock() {
return Clock.SYSTEM;
}
}
@Configuration(proxyBeanMethods = false)
@Import(BaseConfiguration.class)
static class CustomConfigConfiguration {
@Bean
SimpleConfig customConfig() {
return (key) -> null;
}
}
@Configuration(proxyBeanMethods = false)
@Import(BaseConfiguration.class)
static class CustomRegistryConfiguration {
@Bean
MeterRegistry customRegistry() {
return mock(MeterRegistry.class);
}
}
}
| apache-2.0 |
venkateshamurthy/java-quantiles | src/main/java/org/apache/commons/math3/analysis/differentiation/SparseGradient.java | 30612 | /*
* 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.analysis.differentiation;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.math3.Field;
import org.apache.commons.math3.FieldElement;
import org.apache.commons.math3.RealFieldElement;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathArrays;
import org.apache.commons.math3.util.MathUtils;
import org.apache.commons.math3.util.Precision;
/**
* First derivative computation with large number of variables.
* <p>
* This class plays a similar role to {@link DerivativeStructure}, with
* a focus on efficiency when dealing with large number of independent variables
* and most computation depend only on a few of them, and when only first derivative
* is desired. When these conditions are met, this class should be much faster than
* {@link DerivativeStructure} and use less memory.
* </p>
*
* @since 3.3
*/
public class SparseGradient implements RealFieldElement<SparseGradient>, Serializable {
/** Serializable UID. */
private static final long serialVersionUID = 20131025L;
/** Value of the calculation. */
private double value;
/** Stored derivative, each key representing a different independent variable. */
private final Map<Integer, Double> derivatives;
/** Internal constructor.
* @param value value of the function
* @param derivatives derivatives map, a deep copy will be performed,
* so the map given here will remain safe from changes in the new instance,
* may be null to create an empty derivatives map, i.e. a constant value
*/
private SparseGradient(final double value, final Map<Integer, Double> derivatives) {
this.value = value;
this.derivatives = new HashMap<Integer, Double>();
if (derivatives != null) {
this.derivatives.putAll(derivatives);
}
}
/** Internal constructor.
* @param value value of the function
* @param scale scaling factor to apply to all derivatives
* @param derivatives derivatives map, a deep copy will be performed,
* so the map given here will remain safe from changes in the new instance,
* may be null to create an empty derivatives map, i.e. a constant value
*/
private SparseGradient(final double value, final double scale,
final Map<Integer, Double> derivatives) {
this.value = value;
this.derivatives = new HashMap<Integer, Double>();
if (derivatives != null) {
for (final Map.Entry<Integer, Double> entry : derivatives.entrySet()) {
this.derivatives.put(entry.getKey(), scale * entry.getValue());
}
}
}
/** Factory method creating a constant.
* @param value value of the constant
* @return a new instance
*/
public static SparseGradient createConstant(final double value) {
return new SparseGradient(value, Collections.<Integer, Double> emptyMap());
}
/** Factory method creating an independent variable.
* @param idx index of the variable
* @param value value of the variable
* @return a new instance
*/
public static SparseGradient createVariable(final int idx, final double value) {
return new SparseGradient(value, Collections.singletonMap(idx, 1.0));
}
/**
* Find the number of variables.
* @return number of variables
*/
public int numVars() {
return derivatives.size();
}
/**
* Get the derivative with respect to a particular index variable.
*
* @param index index to differentiate with.
* @return derivative with respect to a particular index variable
*/
public double getDerivative(final int index) {
final Double out = derivatives.get(index);
return (out == null) ? 0.0 : out;
}
/**
* Get the value of the function.
* @return value of the function.
*/
public double getValue() {
return value;
}
/** {@inheritDoc} */
public double getReal() {
return value;
}
/** {@inheritDoc} */
public SparseGradient add(final SparseGradient a) {
final SparseGradient out = new SparseGradient(value + a.value, derivatives);
for (Map.Entry<Integer, Double> entry : a.derivatives.entrySet()) {
final int id = entry.getKey();
final Double old = out.derivatives.get(id);
if (old == null) {
out.derivatives.put(id, entry.getValue());
} else {
out.derivatives.put(id, old + entry.getValue());
}
}
return out;
}
/**
* Add in place.
* <p>
* This method is designed to be faster when used multiple times in a loop.
* </p>
* <p>
* The instance is changed here, in order to not change the
* instance the {@link #add(SparseGradient)} method should
* be used.
* </p>
* @param a instance to add
*/
public void addInPlace(final SparseGradient a) {
value += a.value;
for (final Map.Entry<Integer, Double> entry : a.derivatives.entrySet()) {
final int id = entry.getKey();
final Double old = derivatives.get(id);
if (old == null) {
derivatives.put(id, entry.getValue());
} else {
derivatives.put(id, old + entry.getValue());
}
}
}
/** {@inheritDoc} */
public SparseGradient add(final double c) {
final SparseGradient out = new SparseGradient(value + c, derivatives);
return out;
}
/** {@inheritDoc} */
public SparseGradient subtract(final SparseGradient a) {
final SparseGradient out = new SparseGradient(value - a.value, derivatives);
for (Map.Entry<Integer, Double> entry : a.derivatives.entrySet()) {
final int id = entry.getKey();
final Double old = out.derivatives.get(id);
if (old == null) {
out.derivatives.put(id, -entry.getValue());
} else {
out.derivatives.put(id, old - entry.getValue());
}
}
return out;
}
/** {@inheritDoc} */
public SparseGradient subtract(double c) {
return new SparseGradient(value - c, derivatives);
}
/** {@inheritDoc} */
public SparseGradient multiply(final SparseGradient a) {
final SparseGradient out =
new SparseGradient(value * a.value, Collections.<Integer, Double> emptyMap());
// Derivatives.
for (Map.Entry<Integer, Double> entry : derivatives.entrySet()) {
out.derivatives.put(entry.getKey(), a.value * entry.getValue());
}
for (Map.Entry<Integer, Double> entry : a.derivatives.entrySet()) {
final int id = entry.getKey();
final Double old = out.derivatives.get(id);
if (old == null) {
out.derivatives.put(id, value * entry.getValue());
} else {
out.derivatives.put(id, old + value * entry.getValue());
}
}
return out;
}
/**
* Multiply in place.
* <p>
* This method is designed to be faster when used multiple times in a loop.
* </p>
* <p>
* The instance is changed here, in order to not change the
* instance the {@link #add(SparseGradient)} method should
* be used.
* </p>
* @param a instance to multiply
*/
public void multiplyInPlace(final SparseGradient a) {
// Derivatives.
for (Map.Entry<Integer, Double> entry : derivatives.entrySet()) {
derivatives.put(entry.getKey(), a.value * entry.getValue());
}
for (Map.Entry<Integer, Double> entry : a.derivatives.entrySet()) {
final int id = entry.getKey();
final Double old = derivatives.get(id);
if (old == null) {
derivatives.put(id, value * entry.getValue());
} else {
derivatives.put(id, old + value * entry.getValue());
}
}
value *= a.value;
}
/** {@inheritDoc} */
public SparseGradient multiply(final double c) {
return new SparseGradient(value * c, c, derivatives);
}
/** {@inheritDoc} */
public SparseGradient multiply(final int n) {
return new SparseGradient(value * n, n, derivatives);
}
/** {@inheritDoc} */
public SparseGradient divide(final SparseGradient a) {
final SparseGradient out = new SparseGradient(value / a.value, Collections.<Integer, Double> emptyMap());
// Derivatives.
for (Map.Entry<Integer, Double> entry : derivatives.entrySet()) {
out.derivatives.put(entry.getKey(), entry.getValue() / a.value);
}
for (Map.Entry<Integer, Double> entry : a.derivatives.entrySet()) {
final int id = entry.getKey();
final Double old = out.derivatives.get(id);
if (old == null) {
out.derivatives.put(id, -out.value / a.value * entry.getValue());
} else {
out.derivatives.put(id, old - out.value / a.value * entry.getValue());
}
}
return out;
}
/** {@inheritDoc} */
public SparseGradient divide(final double c) {
return new SparseGradient(value / c, 1.0 / c, derivatives);
}
/** {@inheritDoc} */
public SparseGradient negate() {
return new SparseGradient(-value, -1.0, derivatives);
}
/** {@inheritDoc} */
public Field<SparseGradient> getField() {
return new Field<SparseGradient>() {
/** {@inheritDoc} */
public SparseGradient getZero() {
return createConstant(0);
}
/** {@inheritDoc} */
public SparseGradient getOne() {
return createConstant(1);
}
/** {@inheritDoc} */
public Class<? extends FieldElement<SparseGradient>> getRuntimeClass() {
return SparseGradient.class;
}
};
}
/** {@inheritDoc} */
public SparseGradient remainder(final double a) {
return new SparseGradient(FastMath.IEEEremainder(value, a), derivatives);
}
/** {@inheritDoc} */
public SparseGradient remainder(final SparseGradient a) {
// compute k such that lhs % rhs = lhs - k rhs
final double rem = FastMath.IEEEremainder(value, a.value);
final double k = FastMath.rint((value - rem) / a.value);
return subtract(a.multiply(k));
}
/** {@inheritDoc} */
public SparseGradient abs() {
if (Double.doubleToLongBits(value) < 0) {
// we use the bits representation to also handle -0.0
return negate();
} else {
return this;
}
}
/** {@inheritDoc} */
public SparseGradient ceil() {
return createConstant(FastMath.ceil(value));
}
/** {@inheritDoc} */
public SparseGradient floor() {
return createConstant(FastMath.floor(value));
}
/** {@inheritDoc} */
public SparseGradient rint() {
return createConstant(FastMath.rint(value));
}
/** {@inheritDoc} */
public long round() {
return FastMath.round(value);
}
/** {@inheritDoc} */
public SparseGradient signum() {
return createConstant(FastMath.signum(value));
}
/** {@inheritDoc} */
public SparseGradient copySign(final SparseGradient sign) {
final long m = Double.doubleToLongBits(value);
final long s = Double.doubleToLongBits(sign.value);
if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK
return this;
}
return negate(); // flip sign
}
/** {@inheritDoc} */
public SparseGradient copySign(final double sign) {
final long m = Double.doubleToLongBits(value);
final long s = Double.doubleToLongBits(sign);
if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK
return this;
}
return negate(); // flip sign
}
/** {@inheritDoc} */
public SparseGradient scalb(final int n) {
final SparseGradient out = new SparseGradient(FastMath.scalb(value, n), Collections.<Integer, Double> emptyMap());
for (Map.Entry<Integer, Double> entry : derivatives.entrySet()) {
out.derivatives.put(entry.getKey(), FastMath.scalb(entry.getValue(), n));
}
return out;
}
/** {@inheritDoc} */
public SparseGradient hypot(final SparseGradient y) {
if (Double.isInfinite(value) || Double.isInfinite(y.value)) {
return createConstant(Double.POSITIVE_INFINITY);
} else if (Double.isNaN(value) || Double.isNaN(y.value)) {
return createConstant(Double.NaN);
} else {
final int expX = FastMath.getExponent(value);
final int expY = FastMath.getExponent(y.value);
if (expX > expY + 27) {
// y is negligible with respect to x
return abs();
} else if (expY > expX + 27) {
// x is negligible with respect to y
return y.abs();
} else {
// find an intermediate scale to avoid both overflow and underflow
final int middleExp = (expX + expY) / 2;
// scale parameters without losing precision
final SparseGradient scaledX = scalb(-middleExp);
final SparseGradient scaledY = y.scalb(-middleExp);
// compute scaled hypotenuse
final SparseGradient scaledH =
scaledX.multiply(scaledX).add(scaledY.multiply(scaledY)).sqrt();
// remove scaling
return scaledH.scalb(middleExp);
}
}
}
/**
* Returns the hypotenuse of a triangle with sides {@code x} and {@code y}
* - sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)<br/>
* avoiding intermediate overflow or underflow.
*
* <ul>
* <li> If either argument is infinite, then the result is positive infinity.</li>
* <li> else, if either argument is NaN then the result is NaN.</li>
* </ul>
*
* @param x a value
* @param y a value
* @return sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)
*/
public static SparseGradient hypot(final SparseGradient x, final SparseGradient y) {
return x.hypot(y);
}
/** {@inheritDoc} */
public SparseGradient reciprocal() {
return new SparseGradient(1.0 / value, -1.0 / (value * value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient sqrt() {
final double sqrt = FastMath.sqrt(value);
return new SparseGradient(sqrt, 0.5 / sqrt, derivatives);
}
/** {@inheritDoc} */
public SparseGradient cbrt() {
final double cbrt = FastMath.cbrt(value);
return new SparseGradient(cbrt, 1.0 / (3 * cbrt * cbrt), derivatives);
}
/** {@inheritDoc} */
public SparseGradient rootN(final int n) {
if (n == 2) {
return sqrt();
} else if (n == 3) {
return cbrt();
} else {
final double root = FastMath.pow(value, 1.0 / n);
return new SparseGradient(root, 1.0 / (n * FastMath.pow(root, n - 1)), derivatives);
}
}
/** {@inheritDoc} */
public SparseGradient pow(final double p) {
return new SparseGradient(FastMath.pow(value, p), p * FastMath.pow(value, p - 1), derivatives);
}
/** {@inheritDoc} */
public SparseGradient pow(final int n) {
if (n == 0) {
return getField().getOne();
} else {
final double valueNm1 = FastMath.pow(value, n - 1);
return new SparseGradient(value * valueNm1, n * valueNm1, derivatives);
}
}
/** {@inheritDoc} */
public SparseGradient pow(final SparseGradient e) {
return log().multiply(e).exp();
}
/** Compute a<sup>x</sup> where a is a double and x a {@link SparseGradient}
* @param a number to exponentiate
* @param x power to apply
* @return a<sup>x</sup>
*/
public static SparseGradient pow(final double a, final SparseGradient x) {
if (a == 0) {
if (x.value == 0) {
return x.compose(1.0, Double.NEGATIVE_INFINITY);
} else if (x.value < 0) {
return x.compose(Double.NaN, Double.NaN);
} else {
return x.getField().getZero();
}
} else {
final double ax = FastMath.pow(a, x.value);
return new SparseGradient(ax, ax * FastMath.log(a), x.derivatives);
}
}
/** {@inheritDoc} */
public SparseGradient exp() {
final double e = FastMath.exp(value);
return new SparseGradient(e, e, derivatives);
}
/** {@inheritDoc} */
public SparseGradient expm1() {
return new SparseGradient(FastMath.expm1(value), FastMath.exp(value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient log() {
return new SparseGradient(FastMath.log(value), 1.0 / value, derivatives);
}
/** Base 10 logarithm.
* @return base 10 logarithm of the instance
*/
public SparseGradient log10() {
return new SparseGradient(FastMath.log10(value), 1.0 / (FastMath.log(10.0) * value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient log1p() {
return new SparseGradient(FastMath.log1p(value), 1.0 / (1.0 + value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient cos() {
return new SparseGradient(FastMath.cos(value), -FastMath.sin(value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient sin() {
return new SparseGradient(FastMath.sin(value), FastMath.cos(value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient tan() {
final double t = FastMath.tan(value);
return new SparseGradient(t, 1 + t * t, derivatives);
}
/** {@inheritDoc} */
public SparseGradient acos() {
return new SparseGradient(FastMath.acos(value), -1.0 / FastMath.sqrt(1 - value * value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient asin() {
return new SparseGradient(FastMath.asin(value), 1.0 / FastMath.sqrt(1 - value * value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient atan() {
return new SparseGradient(FastMath.atan(value), 1.0 / (1 + value * value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient atan2(final SparseGradient x) {
// compute r = sqrt(x^2+y^2)
final SparseGradient r = multiply(this).add(x.multiply(x)).sqrt();
final SparseGradient a;
if (x.value >= 0) {
// compute atan2(y, x) = 2 atan(y / (r + x))
a = divide(r.add(x)).atan().multiply(2);
} else {
// compute atan2(y, x) = +/- pi - 2 atan(y / (r - x))
final SparseGradient tmp = divide(r.subtract(x)).atan().multiply(-2);
a = tmp.add(tmp.value <= 0 ? -FastMath.PI : FastMath.PI);
}
// fix value to take special cases (+0/+0, +0/-0, -0/+0, -0/-0, +/-infinity) correctly
a.value = FastMath.atan2(value, x.value);
return a;
}
/** Two arguments arc tangent operation.
* @param y first argument of the arc tangent
* @param x second argument of the arc tangent
* @return atan2(y, x)
*/
public static SparseGradient atan2(final SparseGradient y, final SparseGradient x) {
return y.atan2(x);
}
/** {@inheritDoc} */
public SparseGradient cosh() {
return new SparseGradient(FastMath.cosh(value), FastMath.sinh(value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient sinh() {
return new SparseGradient(FastMath.sinh(value), FastMath.cosh(value), derivatives);
}
/** {@inheritDoc} */
public SparseGradient tanh() {
final double t = FastMath.tanh(value);
return new SparseGradient(t, 1 - t * t, derivatives);
}
/** {@inheritDoc} */
public SparseGradient acosh() {
return new SparseGradient(FastMath.acosh(value), 1.0 / FastMath.sqrt(value * value - 1.0), derivatives);
}
/** {@inheritDoc} */
public SparseGradient asinh() {
return new SparseGradient(FastMath.asinh(value), 1.0 / FastMath.sqrt(value * value + 1.0), derivatives);
}
/** {@inheritDoc} */
public SparseGradient atanh() {
return new SparseGradient(FastMath.atanh(value), 1.0 / (1.0 - value * value), derivatives);
}
/** Convert radians to degrees, with error of less than 0.5 ULP
* @return instance converted into degrees
*/
public SparseGradient toDegrees() {
return new SparseGradient(FastMath.toDegrees(value), FastMath.toDegrees(1.0), derivatives);
}
/** Convert degrees to radians, with error of less than 0.5 ULP
* @return instance converted into radians
*/
public SparseGradient toRadians() {
return new SparseGradient(FastMath.toRadians(value), FastMath.toRadians(1.0), derivatives);
}
/** Evaluate Taylor expansion of a sparse gradient.
* @param delta parameters offsets (Δx, Δy, ...)
* @return value of the Taylor expansion at x + Δx, y + Δy, ...
*/
public double taylor(final double ... delta) {
double y = value;
for (int i = 0; i < delta.length; ++i) {
y += delta[i] * getDerivative(i);
}
return y;
}
/** Compute composition of the instance by a univariate function.
* @param f0 value of the function at (i.e. f({@link #getValue()}))
* @param f1 first derivative of the function at
* the current point (i.e. f'({@link #getValue()}))
* @return f(this)
*/
public SparseGradient compose(final double f0, final double f1) {
return new SparseGradient(f0, f1, derivatives);
}
/** {@inheritDoc} */
public SparseGradient linearCombination(final SparseGradient[] a,
final SparseGradient[] b)
throws DimensionMismatchException {
// compute a simple value, with all partial derivatives
SparseGradient out = a[0].getField().getZero();
for (int i = 0; i < a.length; ++i) {
out = out.add(a[i].multiply(b[i]));
}
// recompute an accurate value, taking care of cancellations
final double[] aDouble = new double[a.length];
for (int i = 0; i < a.length; ++i) {
aDouble[i] = a[i].getValue();
}
final double[] bDouble = new double[b.length];
for (int i = 0; i < b.length; ++i) {
bDouble[i] = b[i].getValue();
}
out.value = MathArrays.linearCombination(aDouble, bDouble);
return out;
}
/** {@inheritDoc} */
public SparseGradient linearCombination(final double[] a, final SparseGradient[] b) {
// compute a simple value, with all partial derivatives
SparseGradient out = b[0].getField().getZero();
for (int i = 0; i < a.length; ++i) {
out = out.add(b[i].multiply(a[i]));
}
// recompute an accurate value, taking care of cancellations
final double[] bDouble = new double[b.length];
for (int i = 0; i < b.length; ++i) {
bDouble[i] = b[i].getValue();
}
out.value = MathArrays.linearCombination(a, bDouble);
return out;
}
/** {@inheritDoc} */
public SparseGradient linearCombination(final SparseGradient a1, final SparseGradient b1,
final SparseGradient a2, final SparseGradient b2) {
// compute a simple value, with all partial derivatives
SparseGradient out = a1.multiply(b1).add(a2.multiply(b2));
// recompute an accurate value, taking care of cancellations
out.value = MathArrays.linearCombination(a1.value, b1.value, a2.value, b2.value);
return out;
}
/** {@inheritDoc} */
public SparseGradient linearCombination(final double a1, final SparseGradient b1,
final double a2, final SparseGradient b2) {
// compute a simple value, with all partial derivatives
SparseGradient out = b1.multiply(a1).add(b2.multiply(a2));
// recompute an accurate value, taking care of cancellations
out.value = MathArrays.linearCombination(a1, b1.value, a2, b2.value);
return out;
}
/** {@inheritDoc} */
public SparseGradient linearCombination(final SparseGradient a1, final SparseGradient b1,
final SparseGradient a2, final SparseGradient b2,
final SparseGradient a3, final SparseGradient b3) {
// compute a simple value, with all partial derivatives
SparseGradient out = a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3));
// recompute an accurate value, taking care of cancellations
out.value = MathArrays.linearCombination(a1.value, b1.value,
a2.value, b2.value,
a3.value, b3.value);
return out;
}
/** {@inheritDoc} */
public SparseGradient linearCombination(final double a1, final SparseGradient b1,
final double a2, final SparseGradient b2,
final double a3, final SparseGradient b3) {
// compute a simple value, with all partial derivatives
SparseGradient out = b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3));
// recompute an accurate value, taking care of cancellations
out.value = MathArrays.linearCombination(a1, b1.value,
a2, b2.value,
a3, b3.value);
return out;
}
/** {@inheritDoc} */
public SparseGradient linearCombination(final SparseGradient a1, final SparseGradient b1,
final SparseGradient a2, final SparseGradient b2,
final SparseGradient a3, final SparseGradient b3,
final SparseGradient a4, final SparseGradient b4) {
// compute a simple value, with all partial derivatives
SparseGradient out = a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)).add(a4.multiply(b4));
// recompute an accurate value, taking care of cancellations
out.value = MathArrays.linearCombination(a1.value, b1.value,
a2.value, b2.value,
a3.value, b3.value,
a4.value, b4.value);
return out;
}
/** {@inheritDoc} */
public SparseGradient linearCombination(final double a1, final SparseGradient b1,
final double a2, final SparseGradient b2,
final double a3, final SparseGradient b3,
final double a4, final SparseGradient b4) {
// compute a simple value, with all partial derivatives
SparseGradient out = b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3)).add(b4.multiply(a4));
// recompute an accurate value, taking care of cancellations
out.value = MathArrays.linearCombination(a1, b1.value,
a2, b2.value,
a3, b3.value,
a4, b4.value);
return out;
}
/**
* Test for the equality of two sparse gradients.
* <p>
* Sparse gradients are considered equal if they have the same value
* and the same derivatives.
* </p>
* @param other Object to test for equality to this
* @return true if two sparse gradients are equal
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof SparseGradient) {
final SparseGradient rhs = (SparseGradient)other;
if (!Precision.equals(value, rhs.value, 1)) {
return false;
}
if (derivatives.size() != rhs.derivatives.size()) {
return false;
}
for (final Map.Entry<Integer, Double> entry : derivatives.entrySet()) {
if (!rhs.derivatives.containsKey(entry.getKey())) {
return false;
}
if (!Precision.equals(entry.getValue(), rhs.derivatives.get(entry.getKey()), 1)) {
return false;
}
}
return true;
}
return false;
}
/**
* Get a hashCode for the derivative structure.
* @return a hash code value for this object
* @since 3.2
*/
@Override
public int hashCode() {
return 743 + 809 * MathUtils.hash(value) + 167 * derivatives.hashCode();
}
}
| apache-2.0 |
fabiofumarola/elasticsearch | src/main/java/org/elasticsearch/index/analysis/NumericTokenizer.java | 3589 | /*
* 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.index.analysis;
import org.apache.lucene.analysis.NumericTokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.util.Attribute;
import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeSource;
import org.elasticsearch.common.io.Streams;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
/**
*
*/
public abstract class NumericTokenizer extends Tokenizer {
/** Make this tokenizer get attributes from the delegate token stream. */
private static final AttributeFactory delegatingAttributeFactory(final AttributeSource source) {
return new AttributeFactory() {
@Override
public AttributeImpl createAttributeInstance(Class<? extends Attribute> attClass) {
return (AttributeImpl) source.addAttribute(attClass);
}
};
}
private final NumericTokenStream numericTokenStream;
private final char[] buffer;
protected final Object extra;
private boolean started;
protected NumericTokenizer(Reader reader, NumericTokenStream numericTokenStream, char[] buffer, Object extra) throws IOException {
super(delegatingAttributeFactory(numericTokenStream), reader);
this.numericTokenStream = numericTokenStream;
// Add attributes from the numeric token stream, this works fine because the attribute factory delegates to numericTokenStream
for (Iterator<Class<? extends Attribute>> it = numericTokenStream.getAttributeClassesIterator(); it.hasNext();) {
addAttribute(it.next());
}
this.extra = extra;
this.buffer = buffer;
started = true;
}
@Override
public void reset() throws IOException {
super.reset();
started = false;
}
@Override
public final boolean incrementToken() throws IOException {
if (!started) {
// reset() must be idempotent, this is why we read data in incrementToken
final int len = Streams.readFully(input, buffer);
if (len == buffer.length && input.read() != -1) {
throw new IOException("Cannot read numeric data larger than " + buffer.length + " chars");
}
setValue(numericTokenStream, new String(buffer, 0, len));
numericTokenStream.reset();
started = true;
}
return numericTokenStream.incrementToken();
}
@Override
public void end() throws IOException {
super.end();
numericTokenStream.end();
}
@Override
public void close() throws IOException {
super.close();
numericTokenStream.close();
}
protected abstract void setValue(NumericTokenStream tokenStream, String value);
}
| apache-2.0 |
dslomov/bazel | src/test/java/com/google/devtools/build/lib/bazel/rules/ninja/NinjaLexerStepTest.java | 7779 | // Copyright 2019 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.bazel.rules.ninja;
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.bazel.rules.ninja.file.FileFragment;
import com.google.devtools.build.lib.bazel.rules.ninja.lexer.NinjaLexerStep;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link com.google.devtools.build.lib.bazel.rules.ninja.lexer.NinjaLexerStep}. */
@RunWith(JUnit4.class)
public class NinjaLexerStepTest {
@Test
public void testSkipSpaces() {
NinjaLexerStep step = step(" ");
assertThat(step.canAdvance()).isTrue();
assertThat(step.startByte()).isEqualTo(' ');
step.skipSpaces();
assertThat(step.getEnd()).isEqualTo(2);
assertThat(step.getBytes()).isEqualTo(" ".getBytes(StandardCharsets.ISO_8859_1));
assertThat(step.canAdvance()).isFalse();
}
@Test
public void testSkipComment() {
doTest("# skfdskl werj wior982438923u rekfjg wef w $ $: : |", NinjaLexerStep::skipComment);
doTest("#", NinjaLexerStep::skipComment);
doTest("# 123\n", NinjaLexerStep::skipComment, "# 123", true);
doTest("# 123\u0000118", NinjaLexerStep::skipComment, "# 123", false);
}
@Test
public void testTrySkipEscapedNewline() {
doTest("$\n", step -> assertThat(step.trySkipEscapedNewline()).isTrue());
doTest("$\n\n", step -> assertThat(step.trySkipEscapedNewline()).isTrue(), "$\n", true);
doTest("$\r\n", step -> assertThat(step.trySkipEscapedNewline()).isTrue());
doTest("$\r\na", step -> assertThat(step.trySkipEscapedNewline()).isTrue(), "$\r\n", true);
}
@Test
public void testProcessLineFeedNewLine() {
doTest("\r\n", NinjaLexerStep::processLineFeedNewLine);
doTestError(
"\ra",
NinjaLexerStep::processLineFeedNewLine,
"\ra",
false,
"Wrong newline separators: \\r should be followed by \\n.");
}
@Test
public void testTryReadVariableInBrackets() {
doTest("${abc}", step -> assertThat(step.tryReadVariableInBrackets()).isTrue());
doTest("$abc", step -> assertThat(step.tryReadVariableInBrackets()).isFalse(), "", true);
doTest("${ abc }", step -> assertThat(step.tryReadVariableInBrackets()).isTrue());
doTest(
"${abc.xyz-1_2}cde",
step -> assertThat(step.tryReadVariableInBrackets()).isTrue(),
"${abc.xyz-1_2}",
true);
doTestError(
"${abc",
step -> assertThat(step.tryReadVariableInBrackets()).isTrue(),
"${abc",
false,
"Variable end symbol '}' expected.");
doTestError(
"${abc\n",
step -> assertThat(step.tryReadVariableInBrackets()).isTrue(),
"${abc\n",
false,
"Variable end symbol '}' expected.");
doTestError(
"${}",
step -> assertThat(step.tryReadVariableInBrackets()).isTrue(),
"${}",
false,
"Variable identifier expected.");
doTestError(
"${^}",
step -> assertThat(step.tryReadVariableInBrackets()).isTrue(),
"${^",
true,
"Variable identifier expected.");
}
@Test
public void testTryReadSimpleVariable() {
doTest("$abc", step -> assertThat(step.tryReadSimpleVariable()).isTrue());
doTest("$a-b_c", step -> assertThat(step.tryReadSimpleVariable()).isTrue());
doTest("$.", step -> assertThat(step.tryReadSimpleVariable()).isFalse(), "", true);
doTest("$abc.cde", step -> assertThat(step.tryReadSimpleVariable()).isTrue(), "$abc", true);
}
@Test
public void testTryReadEscapedLiteral() {
doTest("$:", step -> assertThat(step.tryReadEscapedLiteral()).isTrue(), "$:", false);
doTest("$$", step -> assertThat(step.tryReadEscapedLiteral()).isTrue(), "$$", false);
doTest("$ ", step -> assertThat(step.tryReadEscapedLiteral()).isTrue(), "$ ", false);
doTest("$:a", step -> assertThat(step.tryReadEscapedLiteral()).isTrue(), "$:", true);
doTest("$$$", step -> assertThat(step.tryReadEscapedLiteral()).isTrue(), "$$", true);
doTest("$ ", step -> assertThat(step.tryReadEscapedLiteral()).isTrue(), "$ ", true);
doTest("$a", step -> assertThat(step.tryReadEscapedLiteral()).isFalse(), "", true);
}
@Test
public void testTryReadIdentifier() {
doTest("abc_d-18", NinjaLexerStep::tryReadIdentifier);
doTest("abc_d-18.ccc", NinjaLexerStep::tryReadIdentifier);
doTest("abc_d-18.ccc=", NinjaLexerStep::tryReadIdentifier, "abc_d-18.ccc", true);
// Have a longer text to demonstrate the error output.
doTestError(
"^abc Bazel only rebuilds what is necessary. "
+ "With advanced local and distributed caching, optimized dependency analysis "
+ "and parallel execution, you get fast and incremental builds.",
NinjaLexerStep::tryReadIdentifier,
"^",
true,
"Symbol '^' is not allowed in the identifier, the text fragment with the symbol:\n"
+ "^abc Bazel only rebuilds what is necessary. With advanced local and distributed"
+ " caching, optimized dependency analysis and parallel execution,"
+ " you get fast and incremental builds.\n");
}
@Test
public void testReadPath() {
doTest(
"this/is/the/relative/path.txt",
NinjaLexerStep::readPath,
"this/is/the/relative/path.txt",
false);
doTest(
"relative/text#.properties", NinjaLexerStep::readPath, "relative/text#.properties", false);
}
@Test
public void testTryReadDoublePipe() {
doTest("||", NinjaLexerStep::tryReadDoublePipe);
}
@Test
public void testReadText() {
doTest("text$\npart", NinjaLexerStep::readText, "text", true);
doTest("one word", NinjaLexerStep::readText, "one", true);
}
private static void doTest(String text, Consumer<NinjaLexerStep> callback) {
doTest(text, callback, text, false);
}
private static void doTest(
String text, Consumer<NinjaLexerStep> callback, String expected, boolean haveMore) {
NinjaLexerStep step = step(text);
assertThat(step.canAdvance()).isTrue();
callback.accept(step);
assertThat(step.getError()).isNull();
if (!expected.isEmpty()) {
assertThat(step.getBytes()).isEqualTo(expected.getBytes(StandardCharsets.ISO_8859_1));
}
assertThat(step.canAdvance()).isEqualTo(haveMore);
}
private static void doTestError(
String text,
Consumer<NinjaLexerStep> callback,
String expected,
boolean haveMore,
String errorText) {
NinjaLexerStep step = step(text);
assertThat(step.canAdvance()).isTrue();
callback.accept(step);
assertThat(step.getError()).isEqualTo(errorText);
assertThat(step.getBytes()).isEqualTo(expected.getBytes(StandardCharsets.ISO_8859_1));
assertThat(step.getFragment().length() > step.getEnd()).isEqualTo(haveMore);
}
private static NinjaLexerStep step(String text) {
ByteBuffer bb = ByteBuffer.wrap(text.getBytes(StandardCharsets.ISO_8859_1));
return new NinjaLexerStep(new FileFragment(bb, 0, 0, bb.limit()), 0);
}
}
| apache-2.0 |
amirsojoodi/tez | tez-tests/src/main/java/org/apache/tez/mapreduce/examples/FilterLinesByWordOneToOne.java | 10059 | /**
* 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.tez.mapreduce.examples;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import org.apache.commons.cli.ParseException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.ClassUtil;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.LocalResourceType;
import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.tez.client.TezClientUtils;
import org.apache.tez.client.TezClient;
import org.apache.tez.common.TezUtils;
import org.apache.tez.dag.api.DAG;
import org.apache.tez.dag.api.DataSinkDescriptor;
import org.apache.tez.dag.api.DataSourceDescriptor;
import org.apache.tez.dag.api.Edge;
import org.apache.tez.dag.api.OutputCommitterDescriptor;
import org.apache.tez.dag.api.OutputDescriptor;
import org.apache.tez.dag.api.ProcessorDescriptor;
import org.apache.tez.dag.api.TezConfiguration;
import org.apache.tez.dag.api.TezException;
import org.apache.tez.dag.api.TezUncheckedException;
import org.apache.tez.dag.api.UserPayload;
import org.apache.tez.dag.api.Vertex;
import org.apache.tez.dag.api.client.DAGClient;
import org.apache.tez.dag.api.client.DAGStatus;
import org.apache.tez.mapreduce.committer.MROutputCommitter;
import org.apache.tez.mapreduce.examples.FilterLinesByWord.TextLongPair;
import org.apache.tez.mapreduce.examples.helpers.SplitsInClientOptionParser;
import org.apache.tez.mapreduce.examples.processor.FilterByWordInputProcessor;
import org.apache.tez.mapreduce.examples.processor.FilterByWordOutputProcessor;
import org.apache.tez.mapreduce.hadoop.MRInputHelpers;
import org.apache.tez.mapreduce.input.MRInputLegacy;
import org.apache.tez.mapreduce.output.MROutput;
import org.apache.tez.runtime.library.conf.UnorderedKVEdgeConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FilterLinesByWordOneToOne extends Configured implements Tool {
private static Logger LOG = LoggerFactory.getLogger(FilterLinesByWordOneToOne.class);
public static final String FILTER_PARAM_NAME = "tez.runtime.examples.filterbyword.word";
private static void printUsage() {
System.err.println("Usage filterLinesByWordOneToOne <in> <out> <filter_word>"
+ " [-generateSplitsInClient true/<false>]");
ToolRunner.printGenericCommandUsage(System.err);
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args)
.getRemainingArgs();
int status = ToolRunner.run(conf, new FilterLinesByWordOneToOne(),
otherArgs);
System.exit(status);
}
@Override
public int run(String[] otherArgs) throws Exception {
boolean generateSplitsInClient = false;
SplitsInClientOptionParser splitCmdLineParser = new SplitsInClientOptionParser();
try {
generateSplitsInClient = splitCmdLineParser.parse(otherArgs, false);
otherArgs = splitCmdLineParser.getRemainingArgs();
} catch (ParseException e1) {
System.err.println("Invalid options");
printUsage();
return 2;
}
if (otherArgs.length != 3) {
printUsage();
return 2;
}
String inputPath = otherArgs[0];
String outputPath = otherArgs[1];
String filterWord = otherArgs[2];
Configuration conf = getConf();
FileSystem fs = FileSystem.get(conf);
if (fs.exists(new Path(outputPath))) {
System.err.println("Output directory : " + outputPath + " already exists");
return 2;
}
TezConfiguration tezConf = new TezConfiguration(conf);
fs.getWorkingDirectory();
Path stagingDir = new Path(fs.getWorkingDirectory(), UUID.randomUUID().toString());
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR, stagingDir.toString());
TezClientUtils.ensureStagingDirExists(tezConf, stagingDir);
String jarPath = ClassUtil.findContainingJar(FilterLinesByWordOneToOne.class);
if (jarPath == null) {
throw new TezUncheckedException("Could not find any jar containing"
+ FilterLinesByWordOneToOne.class.getName() + " in the classpath");
}
Path remoteJarPath = fs.makeQualified(new Path(stagingDir, "dag_job.jar"));
fs.copyFromLocalFile(new Path(jarPath), remoteJarPath);
FileStatus remoteJarStatus = fs.getFileStatus(remoteJarPath);
Map<String, LocalResource> commonLocalResources = new TreeMap<String, LocalResource>();
LocalResource dagJarLocalRsrc = LocalResource.newInstance(
ConverterUtils.getYarnUrlFromPath(remoteJarPath),
LocalResourceType.FILE, LocalResourceVisibility.APPLICATION,
remoteJarStatus.getLen(), remoteJarStatus.getModificationTime());
commonLocalResources.put("dag_job.jar", dagJarLocalRsrc);
TezClient tezSession = TezClient.create("FilterLinesByWordSession", tezConf,
commonLocalResources, null);
tezSession.start(); // Why do I need to start the TezSession.
Configuration stage1Conf = new JobConf(conf);
stage1Conf.set(FILTER_PARAM_NAME, filterWord);
Configuration stage2Conf = new JobConf(conf);
stage2Conf.set(FileOutputFormat.OUTDIR, outputPath);
stage2Conf.setBoolean("mapred.mapper.new-api", false);
UserPayload stage1Payload = TezUtils.createUserPayloadFromConf(stage1Conf);
// Setup stage1 Vertex
Vertex stage1Vertex = Vertex.create("stage1", ProcessorDescriptor.create(
FilterByWordInputProcessor.class.getName()).setUserPayload(stage1Payload))
.addTaskLocalFiles(commonLocalResources);
DataSourceDescriptor dsd;
if (generateSplitsInClient) {
// TODO TEZ-1406. Dont' use MRInputLegacy
stage1Conf.set(FileInputFormat.INPUT_DIR, inputPath);
stage1Conf.setBoolean("mapred.mapper.new-api", false);
dsd = MRInputHelpers.configureMRInputWithLegacySplitGeneration(stage1Conf, stagingDir, true);
} else {
dsd = MRInputLegacy.createConfigBuilder(stage1Conf, TextInputFormat.class, inputPath)
.groupSplits(false).build();
}
stage1Vertex.addDataSource("MRInput", dsd);
// Setup stage2 Vertex
Vertex stage2Vertex = Vertex.create("stage2", ProcessorDescriptor.create(
FilterByWordOutputProcessor.class.getName()).setUserPayload(TezUtils
.createUserPayloadFromConf(stage2Conf)), dsd.getNumberOfShards());
stage2Vertex.addTaskLocalFiles(commonLocalResources);
// Configure the Output for stage2
stage2Vertex.addDataSink(
"MROutput",
DataSinkDescriptor.create(OutputDescriptor.create(MROutput.class.getName())
.setUserPayload(TezUtils.createUserPayloadFromConf(stage2Conf)),
OutputCommitterDescriptor.create(MROutputCommitter.class.getName()), null));
UnorderedKVEdgeConfig edgeConf = UnorderedKVEdgeConfig
.newBuilder(Text.class.getName(), TextLongPair.class.getName())
.setFromConfiguration(tezConf).build();
DAG dag = DAG.create("FilterLinesByWord");
Edge edge =
Edge.create(stage1Vertex, stage2Vertex, edgeConf.createDefaultOneToOneEdgeProperty());
dag.addVertex(stage1Vertex).addVertex(stage2Vertex).addEdge(edge);
LOG.info("Submitting DAG to Tez Session");
DAGClient dagClient = tezSession.submitDAG(dag);
LOG.info("Submitted DAG to Tez Session");
DAGStatus dagStatus = null;
String[] vNames = { "stage1", "stage2" };
try {
while (true) {
dagStatus = dagClient.getDAGStatus(null);
if(dagStatus.getState() == DAGStatus.State.RUNNING ||
dagStatus.getState() == DAGStatus.State.SUCCEEDED ||
dagStatus.getState() == DAGStatus.State.FAILED ||
dagStatus.getState() == DAGStatus.State.KILLED ||
dagStatus.getState() == DAGStatus.State.ERROR) {
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// continue;
}
}
while (dagStatus.getState() == DAGStatus.State.RUNNING) {
try {
ExampleDriver.printDAGStatus(dagClient, vNames);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// continue;
}
dagStatus = dagClient.getDAGStatus(null);
} catch (TezException e) {
LOG.error("Failed to get application progress. Exiting");
return -1;
}
}
} finally {
fs.delete(stagingDir, true);
tezSession.stop();
}
ExampleDriver.printDAGStatus(dagClient, vNames);
LOG.info("Application completed. " + "FinalState=" + dagStatus.getState());
return dagStatus.getState() == DAGStatus.State.SUCCEEDED ? 0 : 1;
}
}
| apache-2.0 |
Salaboy/jbpm | jbpm-test-coverage/src/main/java/org/jbpm/test/tools/TrackingListenerAssert.java | 3535 | /*
* Copyright 2015 JBoss 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.jbpm.test.tools;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.jbpm.test.listener.TrackingProcessEventListener;
/**
* Asserts usable to find out if/how many times were nodes in process visited.
* Works with TrackingProcessEventListener. If correct order of visited nodes is
* known use <link>IterableListenerAssert</link>.
*/
public class TrackingListenerAssert {
public static void assertTriggeredAndLeft(TrackingProcessEventListener listener, String nodeName) {
assertTriggered(listener, nodeName);
assertLeft(listener, nodeName);
}
public static void assertTriggered(TrackingProcessEventListener listener, String nodeName) {
Assertions.assertThat(listener.wasNodeTriggered(nodeName)).isTrue();
}
public static void assertLeft(TrackingProcessEventListener listener, String nodeName) {
Assertions.assertThat(listener.wasNodeLeft(nodeName)).isTrue();
}
public static void assertProcessStarted(TrackingProcessEventListener listener, String processId) {
Assertions.assertThat(listener.wasProcessStarted(processId)).isTrue();
}
public static void assertProcessCompleted(TrackingProcessEventListener listener, String processId) {
Assertions.assertThat(listener.wasProcessCompleted(processId)).isTrue();
}
public static void assertChangedVariable(TrackingProcessEventListener listener, String variableId) {
Assertions.assertThat(listener.wasVariableChanged(variableId)).isTrue();
}
/**
* Asserts that the node with the given name was triggered <i>count</i>
* times
*
* @param listener process event listener
* @param nodeName name of the node which is tested
* @param count how many times is expected the node had been triggered
*/
public static void assertTriggered(TrackingProcessEventListener listener, String nodeName, int count) {
Assertions.assertThat(containsNode(listener.getNodesTriggered(), nodeName)).isEqualTo(count);
}
/**
* Asserts that the node with the given name was left <i>count</i> times
*
* @param listener process event listener
* @param nodeName name of the node which is tested
* @param count how many times is expected the node had been left
*/
public static void assertLeft(TrackingProcessEventListener listener, String nodeName, int count) {
Assertions.assertThat(containsNode(listener.getNodesLeft(), nodeName)).isEqualTo(count);
}
/**
* @return number of node's occurrences in given list
*/
private static int containsNode(List<String> nodes, String nodeName) {
int count = 0;
for (String node : nodes) {
if (node.equals(nodeName))
count++;
}
return count;
}
}
| apache-2.0 |
swankjesse/mysql-connector-j | src/testsuite/regression/CallableStatementRegressionTest.java | 64388 | /*
Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
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; version 2
of the License.
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., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
package testsuite.regression;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Properties;
import com.mysql.jdbc.NonRegisteringDriver;
import com.mysql.jdbc.SQLError;
import testsuite.BaseTestCase;
/**
* Tests fixes for bugs in CallableStatement code.
*/
public class CallableStatementRegressionTest extends BaseTestCase {
public CallableStatementRegressionTest(String name) {
super(name);
}
/**
* Runs all test cases in this test suite
*
* @param args
* ignored
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(CallableStatementRegressionTest.class);
}
/**
* Tests fix for BUG#3539 getProcedures() does not return any procedures in
* result set
*
* @throws Exception
* if an error occurs.
*/
public void testBug3539() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("testBug3539", "()\nBEGIN\nSELECT 1;end\n");
this.rs = this.conn.getMetaData().getProcedures(null, null, "testBug3539");
assertTrue(this.rs.next());
assertTrue("testBug3539".equals(this.rs.getString(3)));
}
/**
* Tests fix for BUG#3540 getProcedureColumns doesn't work with wildcards
* for procedure name
*
* @throws Exception
* if an error occurs.
*/
public void testBug3540() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("testBug3540", "(x int, out y int)\nBEGIN\nSELECT 1;end\n");
this.rs = this.conn.getMetaData().getProcedureColumns(null, null, "testBug3540%", "%");
assertTrue(this.rs.next());
assertEquals("testBug3540", this.rs.getString(3));
assertEquals("x", this.rs.getString(4));
assertTrue(this.rs.next());
assertEquals("testBug3540", this.rs.getString(3));
assertEquals("y", this.rs.getString(4));
assertTrue(!this.rs.next());
}
/**
* Tests fix for BUG#7026 - DBMD.getProcedures() doesn't respect catalog
* parameter
*
* @throws Exception
* if the test fails.
*/
public void testBug7026() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("testBug7026", "(x int, out y int)\nBEGIN\nSELECT 1;end\n");
//
// Should be found this time.
//
this.rs = this.conn.getMetaData().getProcedures(this.conn.getCatalog(), null, "testBug7026");
assertTrue(this.rs.next());
assertTrue("testBug7026".equals(this.rs.getString(3)));
assertTrue(!this.rs.next());
//
// This time, shouldn't be found, because not associated with this (bogus) catalog
//
this.rs = this.conn.getMetaData().getProcedures("abfgerfg", null, "testBug7026");
assertTrue(!this.rs.next());
//
// Should be found this time as well, as we haven't specified a catalog.
//
this.rs = this.conn.getMetaData().getProcedures(null, null, "testBug7026");
assertTrue(this.rs.next());
assertTrue("testBug7026".equals(this.rs.getString(3)));
assertTrue(!this.rs.next());
}
/**
* Tests fix for BUG#9319 -- Stored procedures with same name in different
* databases confuse the driver when it tries to determine parameter
* counts/types.
*
* @throws Exception
* if the test fails
*/
public void testBug9319() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
boolean doASelect = true; // SELECT currently causes the server to hang on the last execution of this testcase, filed as BUG#9405
if (isAdminConnectionConfigured()) {
Connection db2Connection = null;
Connection db1Connection = null;
db2Connection = getAdminConnection();
db1Connection = getAdminConnection();
Statement db1st = db1Connection.createStatement();
Statement db2st = db2Connection.createStatement();
createDatabase(db2st, "db_9319_2");
db2Connection.setCatalog("db_9319_2");
createProcedure(db2st, "COMPROVAR_USUARI",
"(IN p_CodiUsuari VARCHAR(10),\nIN p_contrasenya VARCHAR(10),\nOUT p_userId INTEGER,"
+ "\nOUT p_userName VARCHAR(30),\nOUT p_administrador VARCHAR(1),\nOUT p_idioma VARCHAR(2))\nBEGIN"
+ (doASelect ? "\nselect 2;" : "\nSELECT 2 INTO p_administrador;") + "\nEND");
createDatabase(db1st, "db_9319_1");
db1Connection.setCatalog("db_9319_1");
createProcedure(db1st, "COMPROVAR_USUARI",
"(IN p_CodiUsuari VARCHAR(10),\nIN p_contrasenya VARCHAR(10),\nOUT p_userId INTEGER,"
+ "\nOUT p_userName VARCHAR(30),\nOUT p_administrador VARCHAR(1))\nBEGIN"
+ (doASelect ? "\nselect 1;" : "\nSELECT 1 INTO p_administrador;") + "\nEND");
CallableStatement cstmt = db2Connection.prepareCall("{ call COMPROVAR_USUARI(?, ?, ?, ?, ?, ?) }");
cstmt.setString(1, "abc");
cstmt.setString(2, "def");
cstmt.registerOutParameter(3, java.sql.Types.INTEGER);
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR);
cstmt.execute();
if (doASelect) {
this.rs = cstmt.getResultSet();
assertTrue(this.rs.next());
assertEquals(2, this.rs.getInt(1));
} else {
assertEquals(2, cstmt.getInt(5));
}
cstmt = db1Connection.prepareCall("{ call COMPROVAR_USUARI(?, ?, ?, ?, ?, ?) }");
cstmt.setString(1, "abc");
cstmt.setString(2, "def");
cstmt.registerOutParameter(3, java.sql.Types.INTEGER);
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR);
try {
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR);
fail("Should've thrown an exception");
} catch (SQLException sqlEx) {
assertEquals(SQLError.SQL_STATE_ILLEGAL_ARGUMENT, sqlEx.getSQLState());
}
cstmt = db1Connection.prepareCall("{ call COMPROVAR_USUARI(?, ?, ?, ?, ?) }");
cstmt.setString(1, "abc");
cstmt.setString(2, "def");
cstmt.registerOutParameter(3, java.sql.Types.INTEGER);
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR);
cstmt.execute();
if (doASelect) {
this.rs = cstmt.getResultSet();
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
} else {
assertEquals(1, cstmt.getInt(5));
}
String quoteChar = db2Connection.getMetaData().getIdentifierQuoteString();
cstmt = db2Connection.prepareCall(
"{ call " + quoteChar + db1Connection.getCatalog() + quoteChar + "." + quoteChar + "COMPROVAR_USUARI" + quoteChar + "(?, ?, ?, ?, ?) }");
cstmt.setString(1, "abc");
cstmt.setString(2, "def");
cstmt.registerOutParameter(3, java.sql.Types.INTEGER);
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR);
cstmt.execute();
if (doASelect) {
this.rs = cstmt.getResultSet();
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
} else {
assertEquals(1, cstmt.getInt(5));
}
}
}
/*
* public void testBug9319() throws Exception { boolean doASelect = false;
* // SELECT currently causes the server to hang on the // last execution of
* this testcase, filed as BUG#9405
*
* if (versionMeetsMinimum(5, 0, 2)) { if (isAdminConnectionConfigured()) {
* Connection db2Connection = null; Connection db1Connection = null;
*
* try { db2Connection = getAdminConnection();
*
* db2Connection.createStatement().executeUpdate( "CREATE DATABASE IF NOT
* EXISTS db_9319"); db2Connection.setCatalog("db_9319");
*
* db2Connection.createStatement().executeUpdate( "DROP PROCEDURE IF EXISTS
* COMPROVAR_USUARI");
*
* db2Connection.createStatement().executeUpdate( "CREATE PROCEDURE
* COMPROVAR_USUARI(IN p_CodiUsuari VARCHAR(10)," + "\nIN p_contrasenya
* VARCHAR(10)," + "\nOUT p_userId INTEGER," + "\nOUT p_userName
* VARCHAR(30)," + "\nOUT p_administrador VARCHAR(1)," + "\nOUT p_idioma
* VARCHAR(2))" + "\nBEGIN" + (doASelect ? "\nselect 2;" : "\nSELECT 2 INTO
* p_administrador;" ) + "\nEND");
*
* this.stmt .executeUpdate("DROP PROCEDURE IF EXISTS COMPROVAR_USUARI");
* this.stmt .executeUpdate("CREATE PROCEDURE COMPROVAR_USUARI(IN
* p_CodiUsuari VARCHAR(10)," + "\nIN p_contrasenya VARCHAR(10)," + "\nOUT
* p_userId INTEGER," + "\nOUT p_userName VARCHAR(30)," + "\nOUT
* p_administrador VARCHAR(1))" + "\nBEGIN" + (doASelect ? "\nselect 1;" :
* "\nSELECT 1 INTO p_administrador;" ) + "\nEND");
*
* CallableStatement cstmt = db2Connection .prepareCall("{ call
* COMPROVAR_USUARI(?, ?, ?, ?, ?, ?) }"); cstmt.setString(1, "abc");
* cstmt.setString(2, "def"); cstmt.registerOutParameter(3,
* java.sql.Types.INTEGER); cstmt.registerOutParameter(4,
* java.sql.Types.VARCHAR); cstmt.registerOutParameter(5,
* java.sql.Types.VARCHAR);
*
* cstmt.registerOutParameter(6, java.sql.Types.VARCHAR);
*
* cstmt.execute();
*
* if (doASelect) { this.rs = cstmt.getResultSet();
* assertTrue(this.rs.next()); assertEquals(2, this.rs.getInt(1)); } else {
* assertEquals(2, cstmt.getInt(5)); }
*
* cstmt = this.conn .prepareCall("{ call COMPROVAR_USUARI(?, ?, ?, ?, ?, ?)
* }"); cstmt.setString(1, "abc"); cstmt.setString(2, "def");
* cstmt.registerOutParameter(3, java.sql.Types.INTEGER);
* cstmt.registerOutParameter(4, java.sql.Types.VARCHAR);
* cstmt.registerOutParameter(5, java.sql.Types.VARCHAR);
*
* try { cstmt.registerOutParameter(6, java.sql.Types.VARCHAR);
* fail("Should've thrown an exception"); } catch (SQLException sqlEx) {
* assertEquals(SQLError.SQL_STATE_ILLEGAL_ARGUMENT, sqlEx .getSQLState());
* }
*
* cstmt = this.conn .prepareCall("{ call COMPROVAR_USUARI(?, ?, ?, ?, ?)
* }"); cstmt.setString(1, "abc"); cstmt.setString(2, "def");
* cstmt.registerOutParameter(3, java.sql.Types.INTEGER);
* cstmt.registerOutParameter(4, java.sql.Types.VARCHAR);
* cstmt.registerOutParameter(5, java.sql.Types.VARCHAR);
*
* cstmt.execute();
*
* if (doASelect) { this.rs = cstmt.getResultSet();
* assertTrue(this.rs.next()); assertEquals(1, this.rs.getInt(1)); } else {
* assertEquals(1, cstmt.getInt(5)); }
*
* String quoteChar =
* db2Connection.getMetaData().getIdentifierQuoteString();
*
* cstmt = db2Connection .prepareCall("{ call " + quoteChar +
* this.conn.getCatalog() + quoteChar + "." + quoteChar + "COMPROVAR_USUARI"
* + quoteChar + "(?, ?, ?, ?, ?) }"); cstmt.setString(1, "abc");
* cstmt.setString(2, "def"); cstmt.registerOutParameter(3,
* java.sql.Types.INTEGER); cstmt.registerOutParameter(4,
* java.sql.Types.VARCHAR); cstmt.registerOutParameter(5,
* java.sql.Types.VARCHAR);
*
* cstmt.execute();
*
* if (doASelect) { this.rs = cstmt.getResultSet();
* assertTrue(this.rs.next()); assertEquals(1, this.rs.getInt(1)); } else {
* assertEquals(1, cstmt.getInt(5)); } } finally { if (db2Connection !=
* null) { db2Connection.createStatement().executeUpdate( "DROP PROCEDURE IF
* EXISTS COMPROVAR_USUARI"); //
* db2Connection.createStatement().executeUpdate( // "DROP DATABASE IF
* EXISTS db_9319"); }
*
* this.stmt .executeUpdate("DROP PROCEDURE IF EXISTS COMPROVAR_USUARI"); }
* } } }
*/
/**
* Tests fix for BUG#9682 - Stored procedures with DECIMAL parameters with
* storage specifications that contained "," in them would fail.
*
* @throws Exception
* if the test fails.
*/
public void testBug9682() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("testBug9682", "(decimalParam DECIMAL(18,0))\nBEGIN\n SELECT 1;\nEND");
CallableStatement cStmt = null;
try {
cStmt = this.conn.prepareCall("Call testBug9682(?)");
cStmt.setDouble(1, 18.0);
cStmt.execute();
} finally {
if (cStmt != null) {
cStmt.close();
}
}
}
/**
* Tests fix forBUG#10310 - Driver doesn't support {?=CALL(...)} for calling
* stored functions. This involved adding support for function retrieval to
* DatabaseMetaData.getProcedures() and getProcedureColumns() as well.
*
* @throws Exception
* if the test fails.
*/
public void testBug10310() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
CallableStatement cStmt = null;
try {
this.stmt.executeUpdate("DROP FUNCTION IF EXISTS testBug10310");
this.stmt.executeUpdate("CREATE FUNCTION testBug10310(a float, b bigint, c int) RETURNS INT NO SQL\nBEGIN\nRETURN a;\nEND");
cStmt = this.conn.prepareCall("{? = CALL testBug10310(?,?,?)}");
cStmt.registerOutParameter(1, Types.INTEGER);
cStmt.setFloat(2, 2);
cStmt.setInt(3, 1);
cStmt.setInt(4, 1);
assertEquals(4, cStmt.getParameterMetaData().getParameterCount());
assertEquals(Types.INTEGER, cStmt.getParameterMetaData().getParameterType(1));
java.sql.DatabaseMetaData dbmd = this.conn.getMetaData();
this.rs = ((com.mysql.jdbc.DatabaseMetaData) dbmd).getFunctionColumns(this.conn.getCatalog(), null, "testBug10310", "%");
ResultSetMetaData rsmd = this.rs.getMetaData();
assertEquals(17, rsmd.getColumnCount());
assertEquals("FUNCTION_CAT", rsmd.getColumnName(1));
assertEquals("FUNCTION_SCHEM", rsmd.getColumnName(2));
assertEquals("FUNCTION_NAME", rsmd.getColumnName(3));
assertEquals("COLUMN_NAME", rsmd.getColumnName(4));
assertEquals("COLUMN_TYPE", rsmd.getColumnName(5));
assertEquals("DATA_TYPE", rsmd.getColumnName(6));
assertEquals("TYPE_NAME", rsmd.getColumnName(7));
assertEquals("PRECISION", rsmd.getColumnName(8));
assertEquals("LENGTH", rsmd.getColumnName(9));
assertEquals("SCALE", rsmd.getColumnName(10));
assertEquals("RADIX", rsmd.getColumnName(11));
assertEquals("NULLABLE", rsmd.getColumnName(12));
assertEquals("REMARKS", rsmd.getColumnName(13));
assertEquals("CHAR_OCTET_LENGTH", rsmd.getColumnName(14));
assertEquals("ORDINAL_POSITION", rsmd.getColumnName(15));
assertEquals("IS_NULLABLE", rsmd.getColumnName(16));
assertEquals("SPECIFIC_NAME", rsmd.getColumnName(17));
this.rs.close();
assertFalse(cStmt.execute());
assertEquals(2f, cStmt.getInt(1), .001);
assertEquals("java.lang.Integer", cStmt.getObject(1).getClass().getName());
assertEquals(-1, cStmt.executeUpdate());
assertEquals(2f, cStmt.getInt(1), .001);
assertEquals("java.lang.Integer", cStmt.getObject(1).getClass().getName());
cStmt.setFloat("a", 4);
cStmt.setInt("b", 1);
cStmt.setInt("c", 1);
assertFalse(cStmt.execute());
assertEquals(4f, cStmt.getInt(1), .001);
assertEquals("java.lang.Integer", cStmt.getObject(1).getClass().getName());
assertEquals(-1, cStmt.executeUpdate());
assertEquals(4f, cStmt.getInt(1), .001);
assertEquals("java.lang.Integer", cStmt.getObject(1).getClass().getName());
// Check metadata while we're at it
this.rs = dbmd.getProcedures(this.conn.getCatalog(), null, "testBug10310");
this.rs.next();
assertEquals("testBug10310", this.rs.getString("PROCEDURE_NAME"));
assertEquals(java.sql.DatabaseMetaData.procedureReturnsResult, this.rs.getShort("PROCEDURE_TYPE"));
cStmt.setNull(2, Types.FLOAT);
cStmt.setInt(3, 1);
cStmt.setInt(4, 1);
assertFalse(cStmt.execute());
assertEquals(0f, cStmt.getInt(1), .001);
assertEquals(true, cStmt.wasNull());
assertEquals(null, cStmt.getObject(1));
assertEquals(true, cStmt.wasNull());
assertEquals(-1, cStmt.executeUpdate());
assertEquals(0f, cStmt.getInt(1), .001);
assertEquals(true, cStmt.wasNull());
assertEquals(null, cStmt.getObject(1));
assertEquals(true, cStmt.wasNull());
// Check with literals, not all parameters filled!
cStmt = this.conn.prepareCall("{? = CALL testBug10310(4,5,?)}");
cStmt.registerOutParameter(1, Types.INTEGER);
cStmt.setInt(2, 1);
assertFalse(cStmt.execute());
assertEquals(4f, cStmt.getInt(1), .001);
assertEquals("java.lang.Integer", cStmt.getObject(1).getClass().getName());
assertEquals(-1, cStmt.executeUpdate());
assertEquals(4f, cStmt.getInt(1), .001);
assertEquals("java.lang.Integer", cStmt.getObject(1).getClass().getName());
assertEquals(2, cStmt.getParameterMetaData().getParameterCount());
assertEquals(Types.INTEGER, cStmt.getParameterMetaData().getParameterType(1));
assertEquals(Types.INTEGER, cStmt.getParameterMetaData().getParameterType(2));
} finally {
if (this.rs != null) {
this.rs.close();
this.rs = null;
}
if (cStmt != null) {
cStmt.close();
}
this.stmt.executeUpdate("DROP FUNCTION IF EXISTS testBug10310");
}
}
/**
* Tests fix for Bug#12417 - stored procedure catalog name is case-sensitive
* on Windows (this is actually a server bug, but we have a workaround in
* place for it now).
*
* @throws Exception
* if the test fails.
*/
public void testBug12417() throws Exception {
if (serverSupportsStoredProcedures() && isServerRunningOnWindows()) {
createProcedure("testBug12417", "()\nBEGIN\nSELECT 1;end\n");
Connection ucCatalogConn = null;
try {
ucCatalogConn = getConnectionWithProps((Properties) null);
ucCatalogConn.setCatalog(this.conn.getCatalog().toUpperCase());
ucCatalogConn.prepareCall("{call testBug12417()}");
} finally {
if (ucCatalogConn != null) {
ucCatalogConn.close();
}
}
}
}
public void testBug15121() throws Exception {
if (!this.DISABLED_testBug15121 /* needs to be fixed on server */) {
if (versionMeetsMinimum(5, 0)) {
createProcedure("p_testBug15121", "()\nBEGIN\nSELECT * from idonotexist;\nEND");
Properties props = new Properties();
props.setProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY, "");
Connection noDbConn = null;
try {
noDbConn = getConnectionWithProps(props);
StringBuilder queryBuf = new StringBuilder("{call ");
String quotedId = this.conn.getMetaData().getIdentifierQuoteString();
queryBuf.append(quotedId);
queryBuf.append(this.conn.getCatalog());
queryBuf.append(quotedId);
queryBuf.append(".p_testBug15121()}");
noDbConn.prepareCall(queryBuf.toString()).execute();
} finally {
if (noDbConn != null) {
noDbConn.close();
}
}
}
}
}
/**
* Tests fix for BUG#15464 - INOUT parameter does not store IN value.
*
* @throws Exception
* if the test fails
*/
public void testBug15464() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("testInOutParam",
"(IN p1 VARCHAR(255), INOUT p2 INT)\nbegin\n DECLARE z INT;\n" + "SET z = p2 + 1;\nSET p2 = z;\nSELECT p1;\nSELECT CONCAT('zyxw', p1);\nend\n");
CallableStatement storedProc = null;
storedProc = this.conn.prepareCall("{call testInOutParam(?, ?)}");
storedProc.setString(1, "abcd");
storedProc.setInt(2, 4);
storedProc.registerOutParameter(2, Types.INTEGER);
storedProc.execute();
assertEquals(5, storedProc.getInt(2));
}
/**
* Tests fix for BUG#17898 - registerOutParameter not working when some
* parameters pre-populated. Still waiting for feedback from JDBC experts
* group to determine what correct parameter count from getMetaData() should
* be, however.
*
* @throws Exception
* if the test fails
*/
public void testBug17898() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("testBug17898", "(param1 VARCHAR(50), OUT param2 INT)\nBEGIN\nDECLARE rtn INT;\n" + "SELECT 1 INTO rtn;\nSET param2=rtn;\nEND");
CallableStatement cstmt = this.conn.prepareCall("{CALL testBug17898('foo', ?)}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.execute();
assertEquals(1, cstmt.getInt(1));
cstmt.clearParameters();
cstmt.registerOutParameter("param2", Types.INTEGER);
cstmt.execute();
assertEquals(1, cstmt.getInt(1));
}
/**
* Tests fix for BUG#21462 - JDBC (and ODBC) specifications allow
* no-parenthesis CALL statements for procedures with no arguments, MySQL
* server does not.
*
* @throws Exception
* if the test fails.
*/
public void testBug21462() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("testBug21462", "() BEGIN SELECT 1; END");
CallableStatement cstmt = null;
try {
cstmt = this.conn.prepareCall("{CALL testBug21462}");
cstmt.execute();
} finally {
if (cstmt != null) {
cstmt.close();
}
}
}
/**
* Tests fix for BUG#22024 - Newlines causing whitespace to span confuse
* procedure parser when getting parameter metadata for stored procedures.
*
* @throws Exception
* if the test fails
*/
public void testBug22024() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("testBug22024_1", "(\r\n)\r\n BEGIN SELECT 1; END");
createProcedure("testBug22024_2", "(\r\na INT)\r\n BEGIN SELECT 1; END");
CallableStatement cstmt = null;
try {
cstmt = this.conn.prepareCall("{CALL testBug22024_1()}");
cstmt.execute();
cstmt = this.conn.prepareCall("{CALL testBug22024_2(?)}");
cstmt.setInt(1, 1);
cstmt.execute();
} finally {
if (cstmt != null) {
cstmt.close();
}
}
}
/**
* Tests workaround for server crash when calling stored procedures via a
* server-side prepared statement (driver now detects prepare(stored
* procedure) and substitutes client-side prepared statement).
*
* @throws Exception
* if the test fails
*/
public void testBug22297() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createTable("tblTestBug2297_1", "(id varchar(20) NOT NULL default '',Income double(19,2) default NULL)");
createTable("tblTestBug2297_2", "(id varchar(20) NOT NULL default '',CreatedOn datetime default NULL)");
createProcedure("testBug22297", "(pcaseid INT) BEGIN\nSET @sql = \"DROP TEMPORARY TABLE IF EXISTS tmpOrders\";"
+ " PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;"
+ "\nSET @sql = \"CREATE TEMPORARY TABLE tmpOrders SELECT id, 100 AS Income FROM tblTestBug2297_1 GROUP BY id\"; PREPARE stmt FROM @sql;"
+ " EXECUTE stmt; DEALLOCATE PREPARE stmt;\n SELECT id, Income FROM (SELECT e.id AS id ,COALESCE(prof.Income,0) AS Income"
+ "\n FROM tblTestBug2297_2 e LEFT JOIN tmpOrders prof ON e.id = prof.id\n WHERE e.CreatedOn > '2006-08-01') AS Final ORDER BY id;\nEND");
this.stmt.executeUpdate("INSERT INTO tblTestBug2297_1 (`id`,`Income`) VALUES ('a',4094.00),('b',500.00),('c',3462.17), ('d',500.00), ('e',600.00)");
this.stmt.executeUpdate("INSERT INTO tblTestBug2297_2 (`id`,`CreatedOn`) VALUES ('d','2006-08-31 00:00:00'),('e','2006-08-31 00:00:00'),"
+ "('b','2006-08-31 00:00:00'),('c','2006-08-31 00:00:00'),('a','2006-08-31 00:00:00')");
this.pstmt = this.conn.prepareStatement("{CALL testBug22297(?)}");
this.pstmt.setInt(1, 1);
this.rs = this.pstmt.executeQuery();
String[] ids = new String[] { "a", "b", "c", "d", "e" };
int pos = 0;
while (this.rs.next()) {
assertEquals(ids[pos++], this.rs.getString(1));
assertEquals(100, this.rs.getInt(2));
}
assertTrue(this.pstmt.getClass().getName().indexOf("Server") == -1);
}
public void testHugeNumberOfParameters() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
StringBuilder procDef = new StringBuilder("(OUT param_0 VARCHAR(32)");
StringBuilder placeholders = new StringBuilder("?");
for (int i = 1; i < 274; i++) {
procDef.append(", OUT param_" + i + " VARCHAR(32)");
placeholders.append(",?");
}
procDef.append(")\nBEGIN\nSELECT 1;\nEND");
createProcedure("testHugeNumberOfParameters", procDef.toString());
CallableStatement cStmt = null;
try {
cStmt = this.conn.prepareCall("{call testHugeNumberOfParameters(" + placeholders.toString() + ")}");
cStmt.registerOutParameter(274, Types.VARCHAR);
cStmt.execute();
} finally {
if (cStmt != null) {
cStmt.close();
}
}
}
public void testPrepareOfMultiRs() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("p", "() begin select 1; select 2; end;");
PreparedStatement ps = null;
try {
ps = this.conn.prepareStatement("call p()");
ps.execute();
this.rs = ps.getResultSet();
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
assertTrue(ps.getMoreResults());
this.rs = ps.getResultSet();
assertTrue(this.rs.next());
assertEquals(2, this.rs.getInt(1));
assertTrue(!ps.getMoreResults());
} finally {
if (this.rs != null) {
this.rs.close();
this.rs = null;
}
if (ps != null) {
ps.close();
}
}
}
/**
* Tests fix for BUG#25379 - INOUT parameters in CallableStatements get
* doubly-escaped.
*
* @throws Exception
* if the test fails.
*/
public void testBug25379() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createTable("testBug25379", "(col char(40))");
createProcedure("sp_testBug25379", "(INOUT invalue char(255))\nBEGIN" + "\ninsert into testBug25379(col) values(invalue);\nEND");
CallableStatement cstmt = this.conn.prepareCall("{call sp_testBug25379(?)}");
cstmt.setString(1, "'john'");
cstmt.executeUpdate();
assertEquals("'john'", cstmt.getString(1));
assertEquals("'john'", getSingleValue("testBug25379", "col", "").toString());
}
/**
* Tests fix for BUG#25715 - CallableStatements with OUT/INOUT parameters
* that are "binary" have extra 7 bytes (which happens to be the _binary
* introducer!)
*
* @throws Exception
* if the test fails.
*/
public void testBug25715() throws Exception {
if (!serverSupportsStoredProcedures()) {
return; // no stored procs
}
createProcedure("spbug25715", "(INOUT mblob MEDIUMBLOB) BEGIN SELECT 1 FROM DUAL WHERE 1=0;\nEND");
CallableStatement cstmt = null;
try {
cstmt = this.conn.prepareCall("{call spbug25715(?)}");
byte[] buf = new byte[65];
for (int i = 0; i < 65; i++) {
buf[i] = 1;
}
int il = buf.length;
int[] typesToTest = new int[] { Types.BIT, Types.BINARY, Types.BLOB, Types.JAVA_OBJECT, Types.LONGVARBINARY, Types.VARBINARY };
for (int i = 0; i < typesToTest.length; i++) {
cstmt.setBinaryStream("mblob", new ByteArrayInputStream(buf), buf.length);
cstmt.registerOutParameter("mblob", typesToTest[i]);
cstmt.executeUpdate();
InputStream is = cstmt.getBlob("mblob").getBinaryStream();
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int bytesRead = 0;
byte[] readBuf = new byte[256];
while ((bytesRead = is.read(readBuf)) != -1) {
bOut.write(readBuf, 0, bytesRead);
}
byte[] fromSelectBuf = bOut.toByteArray();
int ol = fromSelectBuf.length;
assertEquals(il, ol);
}
cstmt.close();
} finally {
if (cstmt != null) {
cstmt.close();
}
}
}
protected boolean serverSupportsStoredProcedures() throws SQLException {
return versionMeetsMinimum(5, 0);
}
public void testBug26143() throws Exception {
if (!serverSupportsStoredProcedures()) {
return; // no stored procedure support
}
try {
dropProcedure("testBug26143");
this.stmt.executeUpdate("CREATE DEFINER=CURRENT_USER PROCEDURE testBug26143(I INT) COMMENT 'abcdefg'\nBEGIN\nSELECT I * 10;\nEND");
this.conn.prepareCall("{call testBug26143(?)").close();
} finally {
dropProcedure("testBug26143");
}
}
/**
* Tests fix for BUG#26959 - comments confuse procedure parser.
*
* @throws Exception
* if the test fails
*/
public void testBug26959() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createProcedure("testBug26959",
"(_ACTION varchar(20),\n`/*dumb-identifier-1*/` int,\n`#dumb-identifier-2` int,\n`--dumb-identifier-3` int,"
+ "\n_CLIENT_ID int, -- ABC\n_LOGIN_ID int, # DEF\n_WHERE varchar(2000),\n_SORT varchar(2000),"
+ "\n out _SQL varchar(/* inline right here - oh my gosh! */ 8000),\n _SONG_ID int,\n _NOTES varchar(2000),\n out _RESULT varchar(10)"
+ "\n /*\n , -- Generic result parameter"
+ "\n out _PERIOD_ID int, -- Returns the period_id. Useful when using @PREDEFLINK to return which is the last period"
+ "\n _SONGS_LIST varchar(8000),\n _COMPOSERID int,\n _PUBLISHERID int,"
+ "\n _PREDEFLINK int -- If the user is accessing through a predefined link: 0=none 1=last period\n */) BEGIN SELECT 1; END");
createProcedure("testBug26959_1", "(`/*id*/` /* before type 1 */ varchar(20),"
+ "/* after type 1 */ OUT result2 DECIMAL(/*size1*/10,/*size2*/2) /* p2 */)BEGIN SELECT action, result; END");
this.conn.prepareCall("{call testBug26959(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}").close();
this.rs = this.conn.getMetaData().getProcedureColumns(this.conn.getCatalog(), null, "testBug26959", "%");
String[] parameterNames = new String[] { "_ACTION", "/*dumb-identifier-1*/", "#dumb-identifier-2", "--dumb-identifier-3", "_CLIENT_ID", "_LOGIN_ID",
"_WHERE", "_SORT", "_SQL", "_SONG_ID", "_NOTES", "_RESULT" };
int[] parameterTypes = new int[] { Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.VARCHAR, Types.VARCHAR };
int[] direction = new int[] { java.sql.DatabaseMetaData.procedureColumnIn, java.sql.DatabaseMetaData.procedureColumnIn,
java.sql.DatabaseMetaData.procedureColumnIn, java.sql.DatabaseMetaData.procedureColumnIn, java.sql.DatabaseMetaData.procedureColumnIn,
java.sql.DatabaseMetaData.procedureColumnIn, java.sql.DatabaseMetaData.procedureColumnIn, java.sql.DatabaseMetaData.procedureColumnIn,
java.sql.DatabaseMetaData.procedureColumnOut, java.sql.DatabaseMetaData.procedureColumnIn, java.sql.DatabaseMetaData.procedureColumnIn,
java.sql.DatabaseMetaData.procedureColumnOut };
int[] precision = new int[] { 20, 10, 10, 10, 10, 10, 2000, 2000, 8000, 10, 2000, 10 };
int index = 0;
while (this.rs.next()) {
assertEquals(parameterNames[index], this.rs.getString("COLUMN_NAME"));
assertEquals(parameterTypes[index], this.rs.getInt("DATA_TYPE"));
switch (index) {
case 0:
case 6:
case 7:
case 8:
case 10:
case 11:
assertEquals(precision[index], this.rs.getInt("LENGTH"));
break;
default:
assertEquals(precision[index], this.rs.getInt("PRECISION"));
}
assertEquals(direction[index], this.rs.getInt("COLUMN_TYPE"));
index++;
}
this.rs.close();
index = 0;
parameterNames = new String[] { "/*id*/", "result2" };
parameterTypes = new int[] { Types.VARCHAR, Types.DECIMAL };
precision = new int[] { 20, 10 };
direction = new int[] { java.sql.DatabaseMetaData.procedureColumnIn, java.sql.DatabaseMetaData.procedureColumnOut };
int[] scale = new int[] { 0, 2 };
this.conn.prepareCall("{call testBug26959_1(?, ?)}").close();
this.rs = this.conn.getMetaData().getProcedureColumns(this.conn.getCatalog(), null, "testBug26959_1", "%");
while (this.rs.next()) {
assertEquals(parameterNames[index], this.rs.getString("COLUMN_NAME"));
assertEquals(parameterTypes[index], this.rs.getInt("DATA_TYPE"));
switch (index) {
case 0:
case 6:
case 7:
case 8:
case 10:
case 11:
assertEquals(precision[index], this.rs.getInt("LENGTH"));
break;
default:
assertEquals(precision[index], this.rs.getInt("PRECISION"));
}
assertEquals(scale[index], this.rs.getInt("SCALE"));
assertEquals(direction[index], this.rs.getInt("COLUMN_TYPE"));
index++;
}
}
/**
* Tests fix for BUG#27400 - CALL [comment] some_proc() doesn't work
*/
public void testBug27400() throws Exception {
if (!serverSupportsStoredProcedures()) {
return; // SPs not supported
}
createProcedure("testBug27400", "(a INT, b VARCHAR(32)) BEGIN SELECT 1; END");
CallableStatement cStmt = null;
try {
cStmt = this.conn.prepareCall("{CALL /* SOME COMMENT */ testBug27400( /* does this work too? */ ?, ?)} # and a commented ? here too");
assertTrue(cStmt.toString().indexOf("/*") != -1); // we don't want
// to strip the
// comments
cStmt.setInt(1, 1);
cStmt.setString(2, "bleh");
cStmt.execute();
} finally {
if (cStmt != null) {
cStmt.close();
}
}
}
/**
* Tests fix for BUG#28689 - CallableStatement.executeBatch() doesn't work
* when connection property "noAccessToProcedureBodies" has been set to
* "true".
*
* The fix involves changing the behavior of "noAccessToProcedureBodies", in
* that the driver will now report all paramters as "IN" paramters but allow
* callers to call registerOutParameter() on them.
*
* @throws Exception
*/
public void testBug28689() throws Exception {
if (!versionMeetsMinimum(5, 0)) {
return; // no stored procedures
}
createTable("testBug28689", "(" +
"`id` int(11) NOT NULL auto_increment,`usuario` varchar(255) default NULL,PRIMARY KEY (`id`))");
this.stmt.executeUpdate("INSERT INTO testBug28689 (usuario) VALUES ('AAAAAA')");
createProcedure("sp_testBug28689", "(tid INT)\nBEGIN\nUPDATE testBug28689 SET usuario = 'BBBBBB' WHERE id = tid;\nEND");
Connection noProcedureBodiesConn = getConnectionWithProps("noAccessToProcedureBodies=true");
CallableStatement cStmt = null;
try {
cStmt = noProcedureBodiesConn.prepareCall("{CALL sp_testBug28689(?)}");
cStmt.setInt(1, 1);
cStmt.addBatch();
cStmt.executeBatch();
assertEquals("BBBBBB", getSingleIndexedValueWithQuery(noProcedureBodiesConn, 1, "SELECT `usuario` FROM testBug28689 WHERE id=1"));
} finally {
if (cStmt != null) {
cStmt.close();
}
if (noProcedureBodiesConn != null) {
noProcedureBodiesConn.close();
}
}
}
/**
* Tests fix for Bug#31823 - CallableStatement.setNull() on a stored
* function would throw an ArrayIndexOutOfBounds when setting the last
* parameter to null when calling setNull().
*
* @throws Exception
*/
public void testBug31823() throws Exception {
if (!versionMeetsMinimum(5, 0)) {
return; // no stored functions
}
createTable("testBug31823", "(value_1 BIGINT PRIMARY KEY,value_2 VARCHAR(20))");
createFunction("f_testBug31823", "(value_1_v BIGINT,value_2_v VARCHAR(20)) RETURNS BIGINT "
+ "DETERMINISTIC MODIFIES SQL DATA BEGIN INSERT INTO testBug31823 VALUES (value_1_v,value_2_v); RETURN value_1_v; END;");
// Prepare the function call
CallableStatement callable = null;
try {
callable = this.conn.prepareCall("{? = call f_testBug31823(?,?)}");
callable.registerOutParameter(1, Types.BIGINT);
// Add row with non-null value
callable.setLong(2, 1);
callable.setString(3, "Non-null value");
callable.executeUpdate();
assertEquals(1, callable.getLong(1));
// Add row with null value
callable.setLong(2, 2);
callable.setNull(3, Types.VARCHAR);
callable.executeUpdate();
assertEquals(2, callable.getLong(1));
Method[] setters = CallableStatement.class.getMethods();
for (int i = 0; i < setters.length; i++) {
if (setters[i].getName().startsWith("set")) {
Class<?>[] args = setters[i].getParameterTypes();
if (args.length == 2 && args[0].equals(Integer.TYPE)) {
if (!args[1].isPrimitive()) {
try {
setters[i].invoke(callable, new Object[] { new Integer(2), null });
} catch (InvocationTargetException ive) {
if (!(ive.getCause() instanceof com.mysql.jdbc.NotImplemented
|| ive.getCause().getClass().getName().equals("java.sql.SQLFeatureNotSupportedException"))) {
throw ive;
}
}
} else {
if (args[1].getName().equals("boolean")) {
try {
setters[i].invoke(callable, new Object[] { new Integer(2), Boolean.FALSE });
} catch (InvocationTargetException ive) {
if (!(ive.getCause() instanceof com.mysql.jdbc.NotImplemented
|| ive.getCause().getClass().getName().equals("java.sql.SQLFeatureNotSupportedException"))) {
throw ive;
}
}
}
if (args[1].getName().equals("byte")) {
try {
setters[i].invoke(callable, new Object[] { new Integer(2), new Byte((byte) 0) });
} catch (InvocationTargetException ive) {
if (!(ive.getCause() instanceof com.mysql.jdbc.NotImplemented
|| ive.getCause().getClass().getName().equals("java.sql.SQLFeatureNotSupportedException"))) {
throw ive;
}
}
}
if (args[1].getName().equals("double")) {
try {
setters[i].invoke(callable, new Object[] { new Integer(2), new Double(0) });
} catch (InvocationTargetException ive) {
if (!(ive.getCause() instanceof com.mysql.jdbc.NotImplemented
|| ive.getCause().getClass().getName().equals("java.sql.SQLFeatureNotSupportedException"))) {
throw ive;
}
}
}
if (args[1].getName().equals("float")) {
try {
setters[i].invoke(callable, new Object[] { new Integer(2), new Float(0) });
} catch (InvocationTargetException ive) {
if (!(ive.getCause() instanceof com.mysql.jdbc.NotImplemented
|| ive.getCause().getClass().getName().equals("java.sql.SQLFeatureNotSupportedException"))) {
throw ive;
}
}
}
if (args[1].getName().equals("int")) {
try {
setters[i].invoke(callable, new Object[] { new Integer(2), new Integer(0) });
} catch (InvocationTargetException ive) {
if (!(ive.getCause() instanceof com.mysql.jdbc.NotImplemented
|| ive.getCause().getClass().getName().equals("java.sql.SQLFeatureNotSupportedException"))) {
throw ive;
}
}
}
if (args[1].getName().equals("long")) {
try {
setters[i].invoke(callable, new Object[] { new Integer(2), new Long(0) });
} catch (InvocationTargetException ive) {
if (!(ive.getCause() instanceof com.mysql.jdbc.NotImplemented
|| ive.getCause().getClass().getName().equals("java.sql.SQLFeatureNotSupportedException"))) {
throw ive;
}
}
}
if (args[1].getName().equals("short")) {
try {
setters[i].invoke(callable, new Object[] { new Integer(2), new Short((short) 0) });
} catch (InvocationTargetException ive) {
if (!(ive.getCause() instanceof com.mysql.jdbc.NotImplemented
|| ive.getCause().getClass().getName().equals("java.sql.SQLFeatureNotSupportedException"))) {
throw ive;
}
}
}
}
}
}
}
} finally {
if (callable != null) {
callable.close();
}
}
}
/**
* Tests fix for Bug#32246 - When unpacking rows directly, we don't hand off
* error message packets to the internal method which decodes them
* correctly, so no exception is rasied, and the driver than hangs trying to
* read rows that aren't there...
*
* @throws Exception
* if the test fails
*/
public void testBug32246() throws Exception {
if (!versionMeetsMinimum(5, 0)) {
return;
}
dropTable("test_table_2");
dropTable("test_table_1");
doBug32246(this.conn);
dropTable("test_table_2");
dropTable("test_table_1");
doBug32246(getConnectionWithProps("useDirectRowUnpack=false"));
}
private void doBug32246(Connection aConn) throws SQLException {
createTable("test_table_1", "(value_1 BIGINT PRIMARY KEY) ENGINE=InnoDB");
this.stmt.executeUpdate("INSERT INTO test_table_1 VALUES (1)");
createTable("test_table_2", "(value_2 BIGINT PRIMARY KEY) ENGINE=InnoDB");
this.stmt.executeUpdate("DROP FUNCTION IF EXISTS test_function");
createFunction("test_function", "() RETURNS BIGINT DETERMINISTIC MODIFIES SQL DATA BEGIN DECLARE max_value BIGINT; "
+ "SELECT MAX(value_1) INTO max_value FROM test_table_2; RETURN max_value; END;");
CallableStatement callable = null;
try {
callable = aConn.prepareCall("{? = call test_function()}");
callable.registerOutParameter(1, Types.BIGINT);
try {
callable.executeUpdate();
fail("impossible; we should never get here.");
} catch (SQLException sqlEx) {
assertEquals("42S22", sqlEx.getSQLState());
}
createTable("test_table_1", "(value_1 BIGINT PRIMARY KEY) ENGINE=InnoDB");
this.stmt.executeUpdate("INSERT INTO test_table_1 VALUES (1)");
createTable("test_table_2",
"(value_2 BIGINT PRIMARY KEY, " + " FOREIGN KEY (value_2) REFERENCES test_table_1 (value_1) ON DELETE CASCADE) ENGINE=InnoDB");
createFunction("test_function",
"(value BIGINT) RETURNS BIGINT DETERMINISTIC MODIFIES SQL DATA BEGIN " + "INSERT INTO test_table_2 VALUES (value); RETURN value; END;");
callable = aConn.prepareCall("{? = call test_function(?)}");
callable.registerOutParameter(1, Types.BIGINT);
callable.setLong(2, 1);
callable.executeUpdate();
callable.setLong(2, 2);
try {
callable.executeUpdate();
fail("impossible; we should never get here.");
} catch (SQLException sqlEx) {
assertEquals("23000", sqlEx.getSQLState());
}
} finally {
if (callable != null) {
callable.close();
}
}
}
public void testBitSp() throws Exception {
if (!versionMeetsMinimum(5, 0)) {
return;
}
createTable("`Bit_Tab`", "( `MAX_VAL` tinyint(1) default NULL, `MIN_VAL` tinyint(1) default NULL, `NULL_VAL` tinyint(1) default NULL)");
createProcedure("Bit_Proc", "(out MAX_PARAM TINYINT, out MIN_PARAM TINYINT, out NULL_PARAM TINYINT)"
+ "begin select MAX_VAL, MIN_VAL, NULL_VAL into MAX_PARAM, MIN_PARAM, NULL_PARAM from Bit_Tab; end");
Boolean minBooleanVal;
Boolean oRetVal;
String Min_Val_Query = "SELECT MIN_VAL from Bit_Tab";
//String sMaxBooleanVal = "1";
// sMaxBooleanVal = "true";
//Boolean bool = Boolean.valueOf("true");
String Min_Insert = "insert into Bit_Tab values(1,0,null)";
// System.out.println("Value to insert=" + extractVal(Min_Insert,1));
CallableStatement cstmt;
this.stmt.executeUpdate("delete from Bit_Tab");
this.stmt.executeUpdate(Min_Insert);
cstmt = this.conn.prepareCall("{call Bit_Proc(?,?,?)}");
System.out.println("register the output parameters");
cstmt.registerOutParameter(1, java.sql.Types.BIT);
cstmt.registerOutParameter(2, java.sql.Types.BIT);
cstmt.registerOutParameter(3, java.sql.Types.BIT);
System.out.println("execute the procedure");
cstmt.executeUpdate();
System.out.println("invoke getBoolean method");
boolean bRetVal = cstmt.getBoolean(2);
oRetVal = new Boolean(bRetVal);
minBooleanVal = new Boolean("false");
this.rs = this.stmt.executeQuery(Min_Val_Query);
if (oRetVal.equals(minBooleanVal)) {
System.out.println("getBoolean returns the Minimum value ");
} else {
System.out.println("getBoolean() did not return the Minimum value, getBoolean Failed!");
}
}
public void testNotReallyCallableStatement() throws Exception {
if (!versionMeetsMinimum(5, 0)) {
return;
}
CallableStatement cstmt = null;
try {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testNotReallyCallableStatement");
cstmt = this.conn.prepareCall("CREATE TABLE testNotReallyCallableStatement(field1 INT)");
} finally {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testNotReallyCallableStatement");
if (cstmt != null) {
cstmt.close();
}
}
}
public void testBug35199() throws Exception {
if (!versionMeetsMinimum(5, 0)) {
return;
}
createFunction("test_function", "(a varchar(40), b bigint(20), c varchar(80)) RETURNS bigint(20) LANGUAGE SQL DETERMINISTIC "
+ "MODIFIES SQL DATA COMMENT 'bbb' BEGIN RETURN 1; END; ");
CallableStatement callable = null;
try {
callable = this.conn.prepareCall("{? = call test_function(?,101,?)}");
callable.registerOutParameter(1, Types.BIGINT);
callable.setString(2, "FOO");
callable.setString(3, "BAR");
callable.executeUpdate();
} finally {
if (callable != null) {
callable.close();
}
}
}
public void testBug49831() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
createTable("testBug49831", "(val varchar(32))");
createProcedure("pTestBug49831", "(testval varchar(32)) BEGIN insert into testBug49831 (val) values (testval);END;");
execProcBug49831(this.conn);
this.stmt.execute("TRUNCATE TABLE testBug49831");
assertEquals(0, getRowCount("testBug49831"));
Connection noBodiesConn = getConnectionWithProps("noAccessToProcedureBodies=true,jdbcCompliantTruncation=false,characterEncoding=utf8,useUnicode=yes");
try {
execProcBug49831(noBodiesConn);
} finally {
noBodiesConn.close();
}
}
private void execProcBug49831(Connection c) throws Exception {
CallableStatement cstmt = c.prepareCall("{call pTestBug49831(?)}");
cstmt.setObject(1, "abc", Types.VARCHAR, 32);
cstmt.addBatch();
cstmt.setObject(1, "def", Types.VARCHAR, 32);
cstmt.addBatch();
cstmt.executeBatch();
assertEquals(2, getRowCount("testBug49831"));
this.rs = this.stmt.executeQuery("SELECT * from testBug49831 ORDER BY VAL ASC");
this.rs.next();
assertEquals("abc", this.rs.getString(1));
this.rs.next();
assertEquals("def", this.rs.getString(1));
}
public void testBug43576() throws Exception {
createTable("TMIX91P",
"(F01SMALLINT SMALLINT NOT NULL, F02INTEGER INTEGER,F03REAL REAL,"
+ "F04FLOAT FLOAT,F05NUMERIC31X4 NUMERIC(31,4), F06NUMERIC16X16 NUMERIC(16,16), F07CHAR_10 CHAR(10),"
+ " F08VARCHAR_10 VARCHAR(10), F09CHAR_20 CHAR(20), F10VARCHAR_20 VARCHAR(20), F11DATE DATE,"
+ " F12DATETIME DATETIME, PRIMARY KEY (F01SMALLINT))");
this.stmt.executeUpdate("INSERT INTO TMIX91P VALUES (1,1,1234567.12,1234567.12,111111111111111111111111111.1111,.111111111111111,'1234567890',"
+ "'1234567890','CHAR20CHAR20','VARCHAR20ABCD','2001-01-01','2001-01-01 01:01:01.111')");
this.stmt.executeUpdate("INSERT INTO TMIX91P VALUES (7,1,1234567.12,1234567.12,22222222222.0001,.99999999999,'1234567896','1234567896','CHAR20',"
+ "'VARCHAR20ABCD','2001-01-01','2001-01-01 01:01:01.111')");
this.stmt.executeUpdate("INSERT INTO TMIX91P VALUES (12,12,1234567.12,1234567.12,111222333.4444,.1234567890,'2234567891','2234567891','CHAR20',"
+ "'VARCHAR20VARCHAR20','2001-01-01','2001-01-01 01:01:01.111')");
createProcedure("MSQSPR100",
"\n( p1_in INTEGER , p2_in CHAR(20), OUT p3_out INTEGER, OUT p4_out CHAR(11))\nBEGIN "
+ "\n SELECT F01SMALLINT,F02INTEGER, F11DATE,F12DATETIME,F03REAL \n FROM TMIX91P WHERE F02INTEGER = p1_in; "
+ "\n SELECT F02INTEGER,F07CHAR_10,F08VARCHAR_10,F09CHAR_20 \n FROM TMIX91P WHERE F09CHAR_20 = p2_in ORDER BY F02INTEGER ; "
+ "\n SET p3_out = 144; \n SET p4_out = 'CHARACTER11'; \n SELECT p3_out, p4_out; END");
String sql = "{call MSQSPR100(1,'CHAR20',?,?)}";
CallableStatement cs = this.conn.prepareCall(sql);
cs.registerOutParameter(1, Types.INTEGER);
cs.registerOutParameter(2, Types.CHAR);
cs.execute();
cs.close();
createProcedure("bug43576_1", "(OUT nfact VARCHAR(100), IN ccuenta VARCHAR(100),\nOUT ffact VARCHAR(100),\nOUT fdoc VARCHAR(100))\nBEGIN"
+ "\nSET nfact = 'ncfact string';\nSET ffact = 'ffact string';\nSET fdoc = 'fdoc string';\nEND");
createProcedure("bug43576_2", "(IN ccuent1 VARCHAR(100), IN ccuent2 VARCHAR(100),\nOUT nfact VARCHAR(100),\nOUT ffact VARCHAR(100),"
+ "\nOUT fdoc VARCHAR(100))\nBEGIN\nSET nfact = 'ncfact string';\nSET ffact = 'ffact string';\nSET fdoc = 'fdoc string';\nEND");
Properties props = new Properties();
props.put("jdbcCompliantTruncation", "true");
props.put("useInformationSchema", "true");
Connection conn1 = null;
conn1 = getConnectionWithProps(props);
try {
CallableStatement callSt = conn1.prepareCall("{ call bug43576_1(?, ?, ?, ?) }");
callSt.setString(2, "xxx");
callSt.registerOutParameter(1, java.sql.Types.VARCHAR);
callSt.registerOutParameter(3, java.sql.Types.VARCHAR);
callSt.registerOutParameter(4, java.sql.Types.VARCHAR);
callSt.execute();
assertEquals("ncfact string", callSt.getString(1));
assertEquals("ffact string", callSt.getString(3));
assertEquals("fdoc string", callSt.getString(4));
CallableStatement callSt2 = conn1.prepareCall("{ call bug43576_2(?, ?, ?, ?, ?) }");
callSt2.setString(1, "xxx");
callSt2.setString(2, "yyy");
callSt2.registerOutParameter(3, java.sql.Types.VARCHAR);
callSt2.registerOutParameter(4, java.sql.Types.VARCHAR);
callSt2.registerOutParameter(5, java.sql.Types.VARCHAR);
callSt2.execute();
assertEquals("ncfact string", callSt2.getString(3));
assertEquals("ffact string", callSt2.getString(4));
assertEquals("fdoc string", callSt2.getString(5));
CallableStatement callSt3 = conn1.prepareCall("{ call bug43576_2(?, 'yyy', ?, ?, ?) }");
callSt3.setString(1, "xxx");
// callSt3.setString(2, "yyy");
callSt3.registerOutParameter(2, java.sql.Types.VARCHAR);
callSt3.registerOutParameter(3, java.sql.Types.VARCHAR);
callSt3.registerOutParameter(4, java.sql.Types.VARCHAR);
callSt3.execute();
assertEquals("ncfact string", callSt3.getString(2));
assertEquals("ffact string", callSt3.getString(3));
assertEquals("fdoc string", callSt3.getString(4));
} finally {
conn1.close();
}
}
/**
* Tests fix for Bug#57022 - cannot execute a store procedure with output
* parameters Problem was in CallableStatement.java, private void
* determineParameterTypes() throws SQLException if (procName.indexOf(".")
* == -1) { useCatalog = true; } The fix will be to "sanitize" db.sp call
* just like in noAccessToProcedureBodies.
*
* @throws Exception
* if the test fails
*/
public void testBug57022() throws Exception {
if (!serverSupportsStoredProcedures()) {
return;
}
String originalCatalog = this.conn.getCatalog();
createDatabase("bug57022");
createProcedure("bug57022.procbug57022", "(x int, out y int)\nbegin\ndeclare z int;\nset z = x+1, y = z;\nend\n");
CallableStatement cStmt = null;
try {
cStmt = this.conn.prepareCall("{call `bug57022`.`procbug57022`(?, ?)}");
cStmt.setInt(1, 5);
cStmt.registerOutParameter(2, Types.INTEGER);
cStmt.execute();
assertEquals(6, cStmt.getInt(2));
cStmt.clearParameters();
cStmt.close();
this.conn.setCatalog("bug57022");
cStmt = this.conn.prepareCall("{call bug57022.procbug57022(?, ?)}");
cStmt.setInt(1, 5);
cStmt.registerOutParameter(2, Types.INTEGER);
cStmt.execute();
assertEquals(6, cStmt.getInt(2));
cStmt.clearParameters();
cStmt.close();
this.conn.setCatalog("mysql");
cStmt = this.conn.prepareCall("{call `bug57022`.`procbug57022`(?, ?)}");
cStmt.setInt(1, 5);
cStmt.registerOutParameter(2, Types.INTEGER);
cStmt.execute();
assertEquals(6, cStmt.getInt(2));
} finally {
if (cStmt != null) {
cStmt.clearParameters();
cStmt.close();
}
this.conn.setCatalog(originalCatalog);
}
}
/**
* Tests fix for BUG#60816 - Cannot pass NULL to an INOUT procedure parameter
*
* @throws Exception
*/
public void testBug60816() throws Exception {
createProcedure("test60816_1", "(INOUT x INTEGER)\nBEGIN\nSET x = x + 1;\nEND");
createProcedure("test60816_2", "(x INTEGER, OUT y INTEGER)\nBEGIN\nSET y = x + 1;\nEND");
createProcedure("test60816_3", "(INOUT x INTEGER)\nBEGIN\nSET x = 10;\nEND");
CallableStatement call = this.conn.prepareCall("{ call test60816_1(?) }");
call.setInt(1, 1);
call.registerOutParameter(1, Types.INTEGER);
call.execute();
assertEquals(2, call.getInt(1));
call = this.conn.prepareCall("{ call test60816_2(?, ?) }");
call.setInt(1, 1);
call.registerOutParameter(2, Types.INTEGER);
call.execute();
assertEquals(2, call.getInt(2));
call = this.conn.prepareCall("{ call test60816_2(?, ?) }");
call.setNull(1, Types.INTEGER);
call.registerOutParameter(2, Types.INTEGER);
call.execute();
assertEquals(0, call.getInt(2));
assertTrue(call.wasNull());
call = this.conn.prepareCall("{ call test60816_1(?) }");
call.setNull(1, Types.INTEGER);
call.registerOutParameter(1, Types.INTEGER);
call.execute();
assertEquals(0, call.getInt(1));
assertTrue(call.wasNull());
call = this.conn.prepareCall("{ call test60816_3(?) }");
call.setNull(1, Types.INTEGER);
call.registerOutParameter(1, Types.INTEGER);
call.execute();
assertEquals(10, call.getInt(1));
}
} | gpl-2.0 |
siosio/intellij-community | java/java-tests/testData/codeInsight/template/postfix/templates/switch/charExprReturn.java | 80 | public class Foo {
String f(char x) {
return x.switch<caret>
}
} | apache-2.0 |
travisbrown/zipkin | zipkin-cassandra/src/main/java/org/apache/cassandra/finagle/thrift/InvalidRequestException.java | 8016 | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*/
package org.apache.cassandra.finagle.thrift;
import org.apache.commons.lang.builder.HashCodeBuilder;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.thrift.*;
import org.apache.thrift.async.*;
import org.apache.thrift.meta_data.*;
import org.apache.thrift.transport.*;
import org.apache.thrift.protocol.*;
// No additional import required for struct/union.
public class InvalidRequestException extends Exception implements TBase<InvalidRequestException, InvalidRequestException._Fields>, java.io.Serializable, Cloneable {
private static final TStruct STRUCT_DESC = new TStruct("InvalidRequestException");
private static final TField WHY_FIELD_DESC = new TField("why", TType.STRING, (short)1);
public String why;
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements TFieldIdEnum {
WHY((short)1, "why");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // WHY
return WHY;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, FieldMetaData> metaDataMap;
static {
Map<_Fields, FieldMetaData> tmpMap = new EnumMap<_Fields, FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.WHY, new FieldMetaData("why", TFieldRequirementType.REQUIRED,
new FieldValueMetaData(TType.STRING)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
FieldMetaData.addStructMetaDataMap(InvalidRequestException.class, metaDataMap);
}
public InvalidRequestException() {
}
public InvalidRequestException(
String why)
{
this();
this.why = why;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public InvalidRequestException(InvalidRequestException other) {
if (other.isSetWhy()) {
this.why = other.why;
}
}
public InvalidRequestException deepCopy() {
return new InvalidRequestException(this);
}
@Override
public void clear() {
this.why = null;
}
public String getWhy() {
return this.why;
}
public InvalidRequestException setWhy(String why) {
this.why = why;
return this;
}
public void unsetWhy() {
this.why = null;
}
/** Returns true if field why is set (has been asigned a value) and false otherwise */
public boolean isSetWhy() {
return this.why != null;
}
public void setWhyIsSet(boolean value) {
if (!value) {
this.why = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case WHY:
if (value == null) {
unsetWhy();
} else {
setWhy((String)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case WHY:
return getWhy();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been asigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case WHY:
return isSetWhy();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof InvalidRequestException)
return this.equals((InvalidRequestException)that);
return false;
}
public boolean equals(InvalidRequestException that) {
if (that == null)
return false;
boolean this_present_why = true && this.isSetWhy();
boolean that_present_why = true && that.isSetWhy();
if (this_present_why || that_present_why) {
if (!(this_present_why && that_present_why))
return false;
if (!this.why.equals(that.why))
return false;
}
return true;
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
boolean present_why = true && (isSetWhy());
builder.append(present_why);
if (present_why)
builder.append(why);
return builder.toHashCode();
}
public int compareTo(InvalidRequestException other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
InvalidRequestException typedOther = (InvalidRequestException)other;
lastComparison = Boolean.valueOf(isSetWhy()).compareTo(typedOther.isSetWhy());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetWhy()) {
lastComparison = TBaseHelper.compareTo(this.why, typedOther.why);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(TProtocol iprot) throws TException {
TField field;
iprot.readStructBegin();
while (true)
{
field = iprot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
switch (field.id) {
case 1: // WHY
if (field.type == TType.STRING) {
this.why = iprot.readString();
} else {
TProtocolUtil.skip(iprot, field.type);
}
break;
default:
TProtocolUtil.skip(iprot, field.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
validate();
}
public void write(TProtocol oprot) throws TException {
validate();
oprot.writeStructBegin(STRUCT_DESC);
if (this.why != null) {
oprot.writeFieldBegin(WHY_FIELD_DESC);
oprot.writeString(this.why);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("InvalidRequestException(");
boolean first = true;
sb.append("why:");
if (this.why == null) {
sb.append("null");
} else {
sb.append(this.why);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws TException {
// check for required fields
if (why == null) {
throw new TProtocolException("Required field 'why' was not present! Struct: " + toString());
}
}
}
| apache-2.0 |
OnePaaS/jbpm | jbpm-bpmn2-emfextmodel/src/main/java/org/jboss/drools/DocumentRoot.java | 14626 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.jboss.drools;
import java.math.BigInteger;
import org.eclipse.emf.common.util.EMap;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.FeatureMap;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Document Root</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.jboss.drools.DocumentRoot#getMixed <em>Mixed</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getXMLNSPrefixMap <em>XMLNS Prefix Map</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getXSISchemaLocation <em>XSI Schema Location</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getGlobal <em>Global</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getImport <em>Import</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getMetaData <em>Meta Data</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getOnEntryScript <em>On Entry Script</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getOnExitScript <em>On Exit Script</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getPackageName <em>Package Name</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getPriority <em>Priority</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getRuleFlowGroup <em>Rule Flow Group</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getTaskName <em>Task Name</em>}</li>
* <li>{@link org.jboss.drools.DocumentRoot#getVersion <em>Version</em>}</li>
* </ul>
* </p>
*
* @see org.jboss.drools.DroolsPackage#getDocumentRoot()
* @model extendedMetaData="name='' kind='mixed'"
* @generated
*/
public interface DocumentRoot extends EObject {
/**
* Returns the value of the '<em><b>Mixed</b></em>' attribute list.
* The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Mixed</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Mixed</em>' attribute list.
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_Mixed()
* @model unique="false" dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="true"
* extendedMetaData="kind='elementWildcard' name=':mixed'"
* @generated
*/
FeatureMap getMixed();
/**
* Returns the value of the '<em><b>XMLNS Prefix Map</b></em>' map.
* The key is of type {@link java.lang.String},
* and the value is of type {@link java.lang.String},
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>XMLNS Prefix Map</em>' map isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>XMLNS Prefix Map</em>' map.
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_XMLNSPrefixMap()
* @model mapType="org.eclipse.emf.ecore.EStringToStringMapEntry<org.eclipse.emf.ecore.EString, org.eclipse.emf.ecore.EString>" transient="true"
* extendedMetaData="kind='attribute' name='xmlns:prefix'"
* @generated
*/
EMap<String, String> getXMLNSPrefixMap();
/**
* Returns the value of the '<em><b>XSI Schema Location</b></em>' map.
* The key is of type {@link java.lang.String},
* and the value is of type {@link java.lang.String},
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>XSI Schema Location</em>' map isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>XSI Schema Location</em>' map.
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_XSISchemaLocation()
* @model mapType="org.eclipse.emf.ecore.EStringToStringMapEntry<org.eclipse.emf.ecore.EString, org.eclipse.emf.ecore.EString>" transient="true"
* extendedMetaData="kind='attribute' name='xsi:schemaLocation'"
* @generated
*/
EMap<String, String> getXSISchemaLocation();
/**
* Returns the value of the '<em><b>Global</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Global</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Global</em>' containment reference.
* @see #setGlobal(GlobalType)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_Global()
* @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
* extendedMetaData="kind='element' name='global' namespace='##targetNamespace'"
* @generated
*/
GlobalType getGlobal();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getGlobal <em>Global</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Global</em>' containment reference.
* @see #getGlobal()
* @generated
*/
void setGlobal(GlobalType value);
/**
* Returns the value of the '<em><b>Import</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Import</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Import</em>' containment reference.
* @see #setImport(ImportType)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_Import()
* @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
* extendedMetaData="kind='element' name='import' namespace='##targetNamespace'"
* @generated
*/
ImportType getImport();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getImport <em>Import</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Import</em>' containment reference.
* @see #getImport()
* @generated
*/
void setImport(ImportType value);
/**
* Returns the value of the '<em><b>Meta Data</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Meta Data</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Meta Data</em>' containment reference.
* @see #setMetaData(MetaDataType)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_MetaData()
* @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
* extendedMetaData="kind='element' name='metaData' namespace='##targetNamespace'"
* @generated
*/
MetaDataType getMetaData();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getMetaData <em>Meta Data</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Meta Data</em>' containment reference.
* @see #getMetaData()
* @generated
*/
void setMetaData(MetaDataType value);
/**
* Returns the value of the '<em><b>On Entry Script</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>On Entry Script</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>On Entry Script</em>' containment reference.
* @see #setOnEntryScript(OnEntryScriptType)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_OnEntryScript()
* @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
* extendedMetaData="kind='element' name='onEntry-script' namespace='##targetNamespace'"
* @generated
*/
OnEntryScriptType getOnEntryScript();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getOnEntryScript <em>On Entry Script</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>On Entry Script</em>' containment reference.
* @see #getOnEntryScript()
* @generated
*/
void setOnEntryScript(OnEntryScriptType value);
/**
* Returns the value of the '<em><b>On Exit Script</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>On Exit Script</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>On Exit Script</em>' containment reference.
* @see #setOnExitScript(OnExitScriptType)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_OnExitScript()
* @model containment="true" upper="-2" transient="true" volatile="true" derived="true"
* extendedMetaData="kind='element' name='onExit-script' namespace='##targetNamespace'"
* @generated
*/
OnExitScriptType getOnExitScript();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getOnExitScript <em>On Exit Script</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>On Exit Script</em>' containment reference.
* @see #getOnExitScript()
* @generated
*/
void setOnExitScript(OnExitScriptType value);
/**
* Returns the value of the '<em><b>Package Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Package Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Package Name</em>' attribute.
* @see #setPackageName(String)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_PackageName()
* @model dataType="org.jboss.drools.PackageNameType"
* extendedMetaData="kind='attribute' name='packageName' namespace='##targetNamespace'"
* @generated
*/
String getPackageName();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getPackageName <em>Package Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Package Name</em>' attribute.
* @see #getPackageName()
* @generated
*/
void setPackageName(String value);
/**
* Returns the value of the '<em><b>Priority</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Priority</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Priority</em>' attribute.
* @see #setPriority(BigInteger)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_Priority()
* @model dataType="org.jboss.drools.PriorityType"
* extendedMetaData="kind='attribute' name='priority' namespace='##targetNamespace'"
* @generated
*/
BigInteger getPriority();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getPriority <em>Priority</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Priority</em>' attribute.
* @see #getPriority()
* @generated
*/
void setPriority(BigInteger value);
/**
* Returns the value of the '<em><b>Rule Flow Group</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Rule Flow Group</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Rule Flow Group</em>' attribute.
* @see #setRuleFlowGroup(String)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_RuleFlowGroup()
* @model dataType="org.jboss.drools.RuleFlowGroupType"
* extendedMetaData="kind='attribute' name='ruleFlowGroup' namespace='##targetNamespace'"
* @generated
*/
String getRuleFlowGroup();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getRuleFlowGroup <em>Rule Flow Group</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Rule Flow Group</em>' attribute.
* @see #getRuleFlowGroup()
* @generated
*/
void setRuleFlowGroup(String value);
/**
* Returns the value of the '<em><b>Task Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Task Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Task Name</em>' attribute.
* @see #setTaskName(String)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_TaskName()
* @model dataType="org.jboss.drools.TaskNameType"
* extendedMetaData="kind='attribute' name='taskName' namespace='##targetNamespace'"
* @generated
*/
String getTaskName();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getTaskName <em>Task Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Task Name</em>' attribute.
* @see #getTaskName()
* @generated
*/
void setTaskName(String value);
/**
* Returns the value of the '<em><b>Version</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Version</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Version</em>' attribute.
* @see #setVersion(String)
* @see org.jboss.drools.DroolsPackage#getDocumentRoot_Version()
* @model dataType="org.jboss.drools.VersionType"
* extendedMetaData="kind='attribute' name='version' namespace='##targetNamespace'"
* @generated
*/
String getVersion();
/**
* Sets the value of the '{@link org.jboss.drools.DocumentRoot#getVersion <em>Version</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Version</em>' attribute.
* @see #getVersion()
* @generated
*/
void setVersion(String value);
} // DocumentRoot
| apache-2.0 |
apache/flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/rank/ConstantRankRange.java | 2481 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.runtime.operators.rank;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.List;
/** rankStart and rankEnd are inclusive, rankStart always start from one. */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeName("Constant")
public class ConstantRankRange implements RankRange {
public static final String FIELD_NAME_START = "start";
public static final String FIELD_NAME_END = "end";
private static final long serialVersionUID = 9062345289888078376L;
@JsonProperty(FIELD_NAME_START)
private final long rankStart;
@JsonProperty(FIELD_NAME_END)
private final long rankEnd;
@JsonCreator
public ConstantRankRange(
@JsonProperty(FIELD_NAME_START) long rankStart,
@JsonProperty(FIELD_NAME_END) long rankEnd) {
this.rankStart = rankStart;
this.rankEnd = rankEnd;
}
@JsonIgnore
public long getRankStart() {
return rankStart;
}
@JsonIgnore
public long getRankEnd() {
return rankEnd;
}
@Override
public String toString(List<String> inputFieldNames) {
return toString();
}
@Override
public String toString() {
return "rankStart=" + rankStart + ", rankEnd=" + rankEnd;
}
}
| apache-2.0 |
vvv1559/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ExportOptionsDialog.java | 5601 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.dialogs.browser;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.DepthCombo;
import org.jetbrains.idea.svn.SvnBundle;
import org.jetbrains.idea.svn.api.Depth;
import org.tmatesoft.svn.core.SVNURL;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class ExportOptionsDialog extends DialogWrapper implements ActionListener {
private final SVNURL myURL;
private final Project myProject;
private final File myFile;
private TextFieldWithBrowseButton myPathField;
private DepthCombo myDepth;
private JCheckBox myExternalsCheckbox;
private JCheckBox myForceCheckbox;
private JComboBox myEOLStyleBox;
public ExportOptionsDialog(Project project, SVNURL url, File target) {
super(project, true);
myURL = url;
myProject = project;
myFile = target;
setTitle("SVN Export Options");
init();
}
@NonNls
protected String getDimensionServiceKey() {
return "svn4idea.export.options";
}
public File getTarget() {
return new File(myPathField.getText());
}
public Depth getDepth() {
return myDepth.getDepth();
}
public boolean isForce() {
return myForceCheckbox.isSelected();
}
public boolean isIgnoreExternals() {
return !myExternalsCheckbox.isSelected();
}
public String getEOLStyle() {
if (myEOLStyleBox.getSelectedIndex() == 0) {
return null;
}
return (String) myEOLStyleBox.getSelectedItem();
}
@Nullable
protected JComponent createCenterPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.insets = JBUI.insets(2);
gc.gridwidth = 1;
gc.gridheight = 1;
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.WEST;
gc.fill = GridBagConstraints.NONE;
gc.weightx = 0;
gc.weighty = 0;
panel.add(new JLabel("Export:"), gc);
gc.gridx += 1;
gc.gridwidth = 2;
gc.weightx = 1;
gc.fill = GridBagConstraints.HORIZONTAL;
JLabel urlLabel = new JLabel(myURL.toString());
urlLabel.setFont(urlLabel.getFont().deriveFont(Font.BOLD));
panel.add(urlLabel, gc);
gc.gridy += 1;
gc.gridwidth = 1;
gc.gridx = 0;
gc.weightx = 0;
gc.fill = GridBagConstraints.NONE;
panel.add(new JLabel("Destination:"), gc);
gc.gridx += 1;
gc.gridwidth = 2;
gc.weightx = 1;
gc.fill = GridBagConstraints.HORIZONTAL;
myPathField = new TextFieldWithBrowseButton(this);
myPathField.setText(myFile.getAbsolutePath());
myPathField.setEditable(false);
panel.add(myPathField, gc);
gc.gridy += 1;
gc.gridx = 0;
gc.weightx = 0;
gc.gridwidth = 3;
gc.fill = GridBagConstraints.NONE;
// other options.
final JLabel depthLabel = new JLabel(SvnBundle.message("label.depth.text"));
depthLabel.setToolTipText(SvnBundle.message("label.depth.description"));
panel.add(depthLabel, gc);
++ gc.gridx;
myDepth = new DepthCombo(false);
panel.add(myDepth, gc);
depthLabel.setLabelFor(myDepth);
gc.gridx = 0;
gc.gridy += 1;
myForceCheckbox = new JCheckBox("Replace existing files");
myForceCheckbox.setSelected(true);
panel.add(myForceCheckbox, gc);
gc.gridy += 1;
myExternalsCheckbox = new JCheckBox("Include externals locations");
myExternalsCheckbox.setSelected(true);
panel.add(myExternalsCheckbox, gc);
gc.gridy += 1;
gc.gridwidth = 2;
panel.add(new JLabel("Override 'native' EOLs with:"), gc);
gc.gridx += 2;
gc.gridwidth = 1;
myEOLStyleBox = new JComboBox(new Object[] {"None", "LF", "CRLF", "CR"});
panel.add(myEOLStyleBox, gc);
gc.gridy += 1;
gc.gridwidth = 3;
gc.gridx = 0;
gc.weightx = 1;
gc.weighty = 1;
gc.anchor = GridBagConstraints.SOUTH;
gc.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JSeparator(), gc);
return panel;
}
public void actionPerformed(ActionEvent e) {
// choose directory here/
FileChooserDescriptor fcd = FileChooserDescriptorFactory.createSingleFolderDescriptor();
fcd.setShowFileSystemRoots(true);
fcd.setTitle("Export Directory");
fcd.setDescription("Select directory to export from subversion");
fcd.setHideIgnored(false);
VirtualFile file = FileChooser.chooseFile(fcd, getContentPane(), myProject, null);
if (file == null) {
return;
}
myPathField.setText(file.getPath().replace('/', File.separatorChar));
}
}
| apache-2.0 |
davidzchen/bazel | src/tools/android/java/com/google/devtools/build/android/DensitySpecificResourceFilter.java | 11572 | // Copyright 2015 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.android;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import com.google.devtools.build.android.AndroidResourceMerger.MergingException;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import javax.annotation.Nullable;
/** Filters a {@link MergedAndroidData} resource drawables to the specified densities. */
public class DensitySpecificResourceFilter {
private static class ResourceInfo {
/** Path to an actual file resource, instead of a directory. */
private Path resource;
private String restype;
private String qualifiers;
private String density;
private String resid;
public ResourceInfo(
Path resource, String restype, String qualifiers, String density, String resid) {
this.resource = resource;
this.restype = restype;
this.qualifiers = qualifiers;
this.density = density;
this.resid = resid;
}
public Path getResource() {
return this.resource;
}
public String getRestype() {
return this.restype;
}
public String getQualifiers() {
return this.qualifiers;
}
public String getDensity() {
return this.density;
}
public String getResid() {
return this.resid;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("resource", resource)
.add("restype", restype)
.add("qualifiers", qualifiers)
.add("density", density)
.add("resid", resid)
.toString();
}
}
private static class RecursiveFileCopier extends SimpleFileVisitor<Path> {
private final Path copyToPath;
private final List<Path> copiedSourceFiles = new ArrayList<>();
private Path root;
public RecursiveFileCopier(final Path copyToPath, final Path root) {
this.copyToPath = copyToPath;
this.root = root;
}
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
Path copyTo = copyToPath.resolve(root.relativize(path));
Files.createDirectories(copyTo.getParent());
Files.copy(path, copyTo, LinkOption.NOFOLLOW_LINKS);
copiedSourceFiles.add(copyTo);
return FileVisitResult.CONTINUE;
}
public List<Path> getCopiedFiles() {
return copiedSourceFiles;
}
}
private final List<String> densities;
private final Path out;
private final Path working;
private static final ImmutableMap<String, Integer> DENSITY_MAP =
new ImmutableMap.Builder<String, Integer>()
.put("nodpi", 0)
.put("ldpi", 120)
.put("mdpi", 160)
.put("tvdpi", 213)
.put("hdpi", 240)
.put("280dpi", 280)
.put("xhdpi", 320)
.put("340dpi", 340)
.put("400dpi", 400)
.put("420dpi", 420)
.put("xxhdpi", 480)
.put("560dpi", 560)
.put("xxxhdpi", 640)
.build();
private static final Function<ResourceInfo, String> GET_RESOURCE_ID =
new Function<ResourceInfo, String>() {
@Override
public String apply(ResourceInfo info) {
return info.getResid();
}
};
private static final Function<ResourceInfo, String> GET_RESOURCE_QUALIFIERS =
new Function<ResourceInfo, String>() {
@Override
public String apply(ResourceInfo info) {
return info.getQualifiers();
}
};
private static final Function<ResourceInfo, Path> GET_RESOURCE_PATH =
new Function<ResourceInfo, Path>() {
@Override
public Path apply(ResourceInfo info) {
return info.getResource();
}
};
/**
* @param densities An array of string densities to use for filtering resources
* @param out The path to use for name spacing the final resource directory.
* @param working The path of the working directory for the filtering
*/
public DensitySpecificResourceFilter(List<String> densities, Path out, Path working)
throws MergingException {
this.densities = densities;
this.out = out;
this.working = working;
for (String density : densities) {
if (!DENSITY_MAP.containsKey(density)) {
throw MergingException.withMessage(density + " is not a known density qualifier.");
}
}
}
@VisibleForTesting
List<Path> getResourceToRemove(List<Path> resourcePaths) {
Predicate<ResourceInfo> requestedDensityFilter =
new Predicate<ResourceInfo>() {
@Override
public boolean apply(@Nullable ResourceInfo info) {
return !densities.contains(info.getDensity());
}
};
List<ResourceInfo> resourceInfos = getResourceInfos(resourcePaths);
List<ResourceInfo> densityResourceInfos = filterDensityResourceInfos(resourceInfos);
List<ResourceInfo> resourceInfoToRemove = new ArrayList<>();
Multimap<String, ResourceInfo> fileGroups =
groupResourceInfos(densityResourceInfos, GET_RESOURCE_ID);
for (String key : fileGroups.keySet()) {
Multimap<String, ResourceInfo> qualifierGroups =
groupResourceInfos(fileGroups.get(key), GET_RESOURCE_QUALIFIERS);
for (String qualifiers : qualifierGroups.keySet()) {
Collection<ResourceInfo> qualifierResourceInfos = qualifierGroups.get(qualifiers);
if (qualifierResourceInfos.size() != 1) {
List<ResourceInfo> sortedResourceInfos =
Ordering.natural()
.onResultOf(
new Function<ResourceInfo, Double>() {
@Override
public Double apply(ResourceInfo info) {
return matchScore(info, densities);
}
})
.immutableSortedCopy(qualifierResourceInfos);
resourceInfoToRemove.addAll(
Collections2.filter(
sortedResourceInfos.subList(1, sortedResourceInfos.size()),
requestedDensityFilter));
}
}
}
return ImmutableList.copyOf(Lists.transform(resourceInfoToRemove, GET_RESOURCE_PATH));
}
private static void removeResources(List<Path> resourceInfoToRemove) {
for (Path resource : resourceInfoToRemove) {
resource.toFile().delete();
}
}
private static Multimap<String, ResourceInfo> groupResourceInfos(
final Collection<ResourceInfo> resourceInfos, Function<ResourceInfo, String> keyFunction) {
Multimap<String, ResourceInfo> resourceGroups = ArrayListMultimap.create();
for (ResourceInfo resourceInfo : resourceInfos) {
resourceGroups.put(keyFunction.apply(resourceInfo), resourceInfo);
}
return ImmutableMultimap.copyOf(resourceGroups);
}
private static List<ResourceInfo> getResourceInfos(final List<Path> resourcePaths) {
List<ResourceInfo> resourceInfos = new ArrayList<>();
for (Path resourcePath : resourcePaths) {
String qualifiers = resourcePath.getParent().getFileName().toString();
String density = "";
for (String densityName : DENSITY_MAP.keySet()) {
if (qualifiers.contains("-" + densityName)) {
qualifiers = qualifiers.replace("-" + densityName, "");
density = densityName;
}
}
String[] qualifierArray = qualifiers.split("-");
String restype = qualifierArray[0];
qualifiers =
(qualifierArray.length) > 0
? Joiner.on("-").join(Arrays.copyOfRange(qualifierArray, 1, qualifierArray.length))
: "";
resourceInfos.add(
new ResourceInfo(
resourcePath, restype, qualifiers, density, resourcePath.getFileName().toString()));
}
return ImmutableList.copyOf(resourceInfos);
}
private static List<ResourceInfo> filterDensityResourceInfos(
final List<ResourceInfo> resourceInfos) {
List<ResourceInfo> densityResourceInfos = new ArrayList<>();
for (ResourceInfo info : resourceInfos) {
if (info.getRestype().equals("drawable")
&& !info.getDensity().equals("")
&& !info.getDensity().equals("nodpi")
&& !info.getResid().endsWith(".xml")) {
densityResourceInfos.add(info);
}
}
return ImmutableList.copyOf(densityResourceInfos);
}
private static double matchScore(ResourceInfo resource, List<String> densities) {
double score = 0;
for (String density : densities) {
score += computeAffinity(DENSITY_MAP.get(resource.getDensity()), DENSITY_MAP.get(density));
}
return score;
}
private static double computeAffinity(int resourceDensity, int density) {
if (resourceDensity == density) {
// Exact match is the best.
return -2;
} else if (resourceDensity == 2 * density) {
// It's very efficient to downsample an image that's exactly 2x the screen
// density, so we prefer that over other non-perfect matches.
return -1;
} else {
double affinity = Math.log((double) density / resourceDensity) / Math.log(2);
// We give a slight bump to images that have the same multiplier but are higher quality.
if (affinity < 0) {
affinity = Math.abs(affinity) - 0.01;
}
return affinity;
}
}
/** Filters the contents of a resource directory. */
public Path filter(Path unFilteredResourceDir) {
// no densities to filter, so skip.
if (densities.isEmpty()) {
return unFilteredResourceDir;
}
final Path filteredResourceDir = out.resolve(working.relativize(unFilteredResourceDir));
RecursiveFileCopier fileVisitor =
new RecursiveFileCopier(filteredResourceDir, unFilteredResourceDir);
try {
Files.walkFileTree(
unFilteredResourceDir,
EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE,
fileVisitor);
} catch (IOException e) {
throw new RuntimeException(e);
}
removeResources(getResourceToRemove(fileVisitor.getCopiedFiles()));
return filteredResourceDir;
}
}
| apache-2.0 |
yunseong/reef | lang/java/reef-io/src/test/java/org/apache/reef/io/network/NetworkConnectionServiceTest.java | 14336 | /*
* 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.reef.io.network;
import org.apache.commons.lang3.StringUtils;
import org.apache.reef.exception.evaluator.NetworkException;
import org.apache.reef.io.network.util.*;
import org.apache.reef.tang.Tang;
import org.apache.reef.tang.exceptions.InjectionException;
import org.apache.reef.wake.Identifier;
import org.apache.reef.wake.IdentifierFactory;
import org.apache.reef.wake.remote.Codec;
import org.apache.reef.wake.remote.address.LocalAddressProvider;
import org.apache.reef.wake.remote.impl.ObjectSerializableCodec;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Default Network connection service test.
*/
public class NetworkConnectionServiceTest {
private static final Logger LOG = Logger.getLogger(NetworkConnectionServiceTest.class.getName());
private final LocalAddressProvider localAddressProvider;
private final String localAddress;
private final Identifier groupCommClientId;
private final Identifier shuffleClientId;
public NetworkConnectionServiceTest() throws InjectionException {
localAddressProvider = Tang.Factory.getTang().newInjector().getInstance(LocalAddressProvider.class);
localAddress = localAddressProvider.getLocalAddress();
final IdentifierFactory idFac = new StringIdentifierFactory();
this.groupCommClientId = idFac.getNewInstance("groupComm");
this.shuffleClientId = idFac.getNewInstance("shuffle");
}
@Rule
public TestName name = new TestName();
private void runMessagingNetworkConnectionService(final Codec<String> codec) throws Exception {
final int numMessages = 2000;
final Monitor monitor = new Monitor();
try (final NetworkMessagingTestService messagingTestService = new NetworkMessagingTestService(localAddress)) {
messagingTestService.registerTestConnectionFactory(groupCommClientId, numMessages, monitor, codec);
try (final Connection<String> conn = messagingTestService.getConnectionFromSenderToReceiver(groupCommClientId)) {
try {
conn.open();
for (int count = 0; count < numMessages; ++count) {
// send messages to the receiver.
conn.write("hello" + count);
}
monitor.mwait();
} catch (final NetworkException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
/**
* NetworkConnectionService messaging test.
*/
@Test
public void testMessagingNetworkConnectionService() throws Exception {
LOG.log(Level.FINEST, name.getMethodName());
runMessagingNetworkConnectionService(new StringCodec());
}
/**
* NetworkConnectionService streaming messaging test.
*/
@Test
public void testStreamingMessagingNetworkConnectionService() throws Exception {
LOG.log(Level.FINEST, name.getMethodName());
runMessagingNetworkConnectionService(new StreamingStringCodec());
}
public void runNetworkConnServiceWithMultipleConnFactories(final Codec<String> stringCodec,
final Codec<Integer> integerCodec)
throws Exception {
final ExecutorService executor = Executors.newFixedThreadPool(5);
final int groupcommMessages = 1000;
final Monitor monitor = new Monitor();
try (final NetworkMessagingTestService messagingTestService = new NetworkMessagingTestService(localAddress)) {
messagingTestService.registerTestConnectionFactory(groupCommClientId, groupcommMessages, monitor, stringCodec);
final int shuffleMessages = 2000;
final Monitor monitor2 = new Monitor();
messagingTestService.registerTestConnectionFactory(shuffleClientId, shuffleMessages, monitor2, integerCodec);
executor.submit(new Runnable() {
@Override
public void run() {
try (final Connection<String> conn =
messagingTestService.getConnectionFromSenderToReceiver(groupCommClientId)) {
conn.open();
for (int count = 0; count < groupcommMessages; ++count) {
// send messages to the receiver.
conn.write("hello" + count);
}
monitor.mwait();
} catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
});
executor.submit(new Runnable() {
@Override
public void run() {
try (final Connection<Integer> conn =
messagingTestService.getConnectionFromSenderToReceiver(shuffleClientId)) {
conn.open();
for (int count = 0; count < shuffleMessages; ++count) {
// send messages to the receiver.
conn.write(count);
}
monitor2.mwait();
} catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
});
monitor.mwait();
monitor2.mwait();
executor.shutdown();
}
}
/**
* Test NetworkService registering multiple connection factories.
*/
@Test
public void testMultipleConnectionFactoriesTest() throws Exception {
LOG.log(Level.FINEST, name.getMethodName());
runNetworkConnServiceWithMultipleConnFactories(new StringCodec(), new ObjectSerializableCodec<Integer>());
}
/**
* Test NetworkService registering multiple connection factories with Streamingcodec.
*/
@Test
public void testMultipleConnectionFactoriesStreamingTest() throws Exception {
LOG.log(Level.FINEST, name.getMethodName());
runNetworkConnServiceWithMultipleConnFactories(new StreamingStringCodec(), new StreamingIntegerCodec());
}
/**
* NetworkService messaging rate benchmark.
*/
@Test
public void testMessagingNetworkConnServiceRate() throws Exception {
LOG.log(Level.FINEST, name.getMethodName());
final int[] messageSizes = {1, 16, 32, 64, 512, 64 * 1024, 1024 * 1024};
for (final int size : messageSizes) {
final String message = StringUtils.repeat('1', size);
final int numMessages = 300000 / (Math.max(1, size / 512));
final Monitor monitor = new Monitor();
final Codec<String> codec = new StringCodec();
try (final NetworkMessagingTestService messagingTestService = new NetworkMessagingTestService(localAddress)) {
messagingTestService.registerTestConnectionFactory(groupCommClientId, numMessages, monitor, codec);
try (final Connection<String> conn =
messagingTestService.getConnectionFromSenderToReceiver(groupCommClientId)) {
final long start = System.currentTimeMillis();
try {
conn.open();
for (int count = 0; count < numMessages; ++count) {
// send messages to the receiver.
conn.write(message);
}
monitor.mwait();
} catch (final NetworkException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
final long end = System.currentTimeMillis();
final double runtime = ((double) end - start) / 1000;
LOG.log(Level.INFO, "size: " + size + "; messages/s: " + numMessages / runtime +
" bandwidth(bytes/s): " + ((double) numMessages * 2 * size) / runtime); // x2 for unicode chars
}
}
}
}
/**
* NetworkService messaging rate benchmark.
*/
@Test
public void testMessagingNetworkConnServiceRateDisjoint() throws Exception {
LOG.log(Level.FINEST, name.getMethodName());
final BlockingQueue<Object> barrier = new LinkedBlockingQueue<>();
final int numThreads = 4;
final int size = 2000;
final int numMessages = 300000 / (Math.max(1, size / 512));
final int totalNumMessages = numMessages * numThreads;
final String message = StringUtils.repeat('1', size);
final ExecutorService e = Executors.newCachedThreadPool();
for (int t = 0; t < numThreads; t++) {
final int tt = t;
e.submit(new Runnable() {
public void run() {
try (final NetworkMessagingTestService messagingTestService = new NetworkMessagingTestService(localAddress)) {
final Monitor monitor = new Monitor();
final Codec<String> codec = new StringCodec();
messagingTestService.registerTestConnectionFactory(groupCommClientId, numMessages, monitor, codec);
try (final Connection<String> conn =
messagingTestService.getConnectionFromSenderToReceiver(groupCommClientId)) {
try {
conn.open();
for (int count = 0; count < numMessages; ++count) {
// send messages to the receiver.
conn.write(message);
}
monitor.mwait();
} catch (final NetworkException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
});
}
// start and time
final long start = System.currentTimeMillis();
final Object ignore = new Object();
for (int i = 0; i < numThreads; i++) {
barrier.add(ignore);
}
e.shutdown();
e.awaitTermination(100, TimeUnit.SECONDS);
final long end = System.currentTimeMillis();
final double runtime = ((double) end - start) / 1000;
LOG.log(Level.INFO, "size: " + size + "; messages/s: " + totalNumMessages / runtime +
" bandwidth(bytes/s): " + ((double) totalNumMessages * 2 * size) / runtime); // x2 for unicode chars
}
@Test
public void testMultithreadedSharedConnMessagingNetworkConnServiceRate() throws Exception {
LOG.log(Level.FINEST, name.getMethodName());
final int[] messageSizes = {2000}; // {1,16,32,64,512,64*1024,1024*1024};
for (final int size : messageSizes) {
final String message = StringUtils.repeat('1', size);
final int numMessages = 300000 / (Math.max(1, size / 512));
final int numThreads = 2;
final int totalNumMessages = numMessages * numThreads;
final Monitor monitor = new Monitor();
final Codec<String> codec = new StringCodec();
try (final NetworkMessagingTestService messagingTestService = new NetworkMessagingTestService(localAddress)) {
messagingTestService.registerTestConnectionFactory(groupCommClientId, totalNumMessages, monitor, codec);
final ExecutorService e = Executors.newCachedThreadPool();
try (final Connection<String> conn =
messagingTestService.getConnectionFromSenderToReceiver(groupCommClientId)) {
final long start = System.currentTimeMillis();
for (int i = 0; i < numThreads; i++) {
e.submit(new Runnable() {
@Override
public void run() {
try {
conn.open();
for (int count = 0; count < numMessages; ++count) {
// send messages to the receiver.
conn.write(message);
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
});
}
e.shutdown();
e.awaitTermination(30, TimeUnit.SECONDS);
monitor.mwait();
final long end = System.currentTimeMillis();
final double runtime = ((double) end - start) / 1000;
LOG.log(Level.INFO, "size: " + size + "; messages/s: " + totalNumMessages / runtime +
" bandwidth(bytes/s): " + ((double) totalNumMessages * 2 * size) / runtime); // x2 for unicode chars
}
}
}
}
/**
* NetworkService messaging rate benchmark.
*/
@Test
public void testMessagingNetworkConnServiceBatchingRate() throws Exception {
LOG.log(Level.FINEST, name.getMethodName());
final int batchSize = 1024 * 1024;
final int[] messageSizes = {32, 64, 512};
for (final int size : messageSizes) {
final String message = StringUtils.repeat('1', batchSize);
final int numMessages = 300 / (Math.max(1, size / 512));
final Monitor monitor = new Monitor();
final Codec<String> codec = new StringCodec();
try (final NetworkMessagingTestService messagingTestService = new NetworkMessagingTestService(localAddress)) {
messagingTestService.registerTestConnectionFactory(groupCommClientId, numMessages, monitor, codec);
try (final Connection<String> conn =
messagingTestService.getConnectionFromSenderToReceiver(groupCommClientId)) {
final long start = System.currentTimeMillis();
try {
conn.open();
for (int i = 0; i < numMessages; i++) {
conn.write(message);
}
monitor.mwait();
} catch (final NetworkException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
final long end = System.currentTimeMillis();
final double runtime = ((double) end - start) / 1000;
final long numAppMessages = numMessages * batchSize / size;
LOG.log(Level.INFO, "size: " + size + "; messages/s: " + numAppMessages / runtime +
" bandwidth(bytes/s): " + ((double) numAppMessages * 2 * size) / runtime); // x2 for unicode chars
}
}
}
}
}
| apache-2.0 |
jingle1267/robolectric | robolectric-shadows/shadows-core/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java | 1936 | package org.robolectric.shadows;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.util.ReflectionHelpers;
/**
* Shadow for {@link android.nfc.NfcAdapter}.
*/
@Implements(NfcAdapter.class)
public class ShadowNfcAdapter {
@RealObject NfcAdapter nfcAdapter;
private Activity enabledActivity;
private PendingIntent intent;
private IntentFilter[] filters;
private String[][] techLists;
private Activity disabledActivity;
private NfcAdapter.CreateNdefMessageCallback callback;
@Implementation
public static NfcAdapter getNfcAdapter(Context context) {
return ReflectionHelpers.callConstructor(NfcAdapter.class);
}
@Implementation
public void enableForegroundDispatch(Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) {
this.enabledActivity = activity;
this.intent = intent;
this.filters = filters;
this.techLists = techLists;
}
@Implementation
public void disableForegroundDispatch(Activity activity) {
disabledActivity = activity;
}
@Implementation
public void setNdefPushMessageCallback(NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) {
this.callback = callback;
}
public Activity getEnabledActivity() {
return enabledActivity;
}
public PendingIntent getIntent() {
return intent;
}
public IntentFilter[] getFilters() {
return filters;
}
public String[][] getTechLists() {
return techLists;
}
public Activity getDisabledActivity() {
return disabledActivity;
}
public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() {
return callback;
}
}
| mit |
gavin57688/Mycat-Server-1.6 | src/test/java/io/mycat/memory/unsafe/sort/TestTimSort.java | 4562 | /**
* Copyright 2015 Stijn de Gouw
*
* 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.mycat.memory.unsafe.sort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* This codes generates a int array which fails the standard TimSort.
*
* The blog that reported the bug
* http://www.envisage-project.eu/timsort-specification-and-verification/
*
* This codes was originally wrote by Stijn de Gouw, modified by Evan Yu to adapt to
* our test suite.
*
* https://github.com/abstools/java-timsort-bug
* https://github.com/abstools/java-timsort-bug/blob/master/LICENSE
*/
public class TestTimSort {
private static final int MIN_MERGE = 32;
/**
* Returns an array of integers that demonstrate the bug in TimSort
*/
public static int[] getTimSortBugTestSet(int length) {
int minRun = minRunLength(length);
List<Long> runs = runsJDKWorstCase(minRun, length);
return createArray(runs, length);
}
private static int minRunLength(int n) {
int r = 0; // Becomes 1 if any 1 bits are shifted off
while (n >= MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}
private static int[] createArray(List<Long> runs, int length) {
int[] a = new int[length];
Arrays.fill(a, 0);
int endRun = -1;
for (long len : runs) {
a[endRun += len] = 1;
}
a[length - 1] = 0;
return a;
}
/**
* Fills <code>runs</code> with a sequence of run lengths of the form<br>
* Y_n x_{n,1} x_{n,2} ... x_{n,l_n} <br>
* Y_{n-1} x_{n-1,1} x_{n-1,2} ... x_{n-1,l_{n-1}} <br>
* ... <br>
* Y_1 x_{1,1} x_{1,2} ... x_{1,l_1}<br>
* The Y_i's are chosen to satisfy the invariant throughout execution,
* but the x_{i,j}'s are merged (by <code>TimSort.mergeCollapse</code>)
* into an X_i that violates the invariant.
*
* @param length The sum of all run lengths that will be added to <code>runs</code>.
*/
private static List<Long> runsJDKWorstCase(int minRun, int length) {
List<Long> runs = new ArrayList<>();
long runningTotal = 0, Y = minRun + 4, X = minRun;
while (runningTotal + Y + X <= length) {
runningTotal += X + Y;
generateJDKWrongElem(runs, minRun, X);
runs.add(0, Y);
// X_{i+1} = Y_i + x_{i,1} + 1, since runs.get(1) = x_{i,1}
X = Y + runs.get(1) + 1;
// Y_{i+1} = X_{i+1} + Y_i + 1
Y += X + 1;
}
if (runningTotal + X <= length) {
runningTotal += X;
generateJDKWrongElem(runs, minRun, X);
}
runs.add(length - runningTotal);
return runs;
}
/**
* Adds a sequence x_1, ..., x_n of run lengths to <code>runs</code> such that:<br>
* 1. X = x_1 + ... + x_n <br>
* 2. x_j >= minRun for all j <br>
* 3. x_1 + ... + x_{j-2} < x_j < x_1 + ... + x_{j-1} for all j <br>
* These conditions guarantee that TimSort merges all x_j's one by one
* (resulting in X) using only merges on the second-to-last element.
*
* @param X The sum of the sequence that should be added to runs.
*/
private static void generateJDKWrongElem(List<Long> runs, int minRun, long X) {
for (long newTotal; X >= 2 * minRun + 1; X = newTotal) {
//Default strategy
newTotal = X / 2 + 1;
//Specialized strategies
if (3 * minRun + 3 <= X && X <= 4 * minRun + 1) {
// add x_1=MIN+1, x_2=MIN, x_3=X-newTotal to runs
newTotal = 2 * minRun + 1;
} else if (5 * minRun + 5 <= X && X <= 6 * minRun + 5) {
// add x_1=MIN+1, x_2=MIN, x_3=MIN+2, x_4=X-newTotal to runs
newTotal = 3 * minRun + 3;
} else if (8 * minRun + 9 <= X && X <= 10 * minRun + 9) {
// add x_1=MIN+1, x_2=MIN, x_3=MIN+2, x_4=2MIN+2, x_5=X-newTotal to runs
newTotal = 5 * minRun + 5;
} else if (13 * minRun + 15 <= X && X <= 16 * minRun + 17) {
// add x_1=MIN+1, x_2=MIN, x_3=MIN+2, x_4=2MIN+2, x_5=3MIN+4, x_6=X-newTotal to runs
newTotal = 8 * minRun + 9;
}
runs.add(0, X - newTotal);
}
runs.add(0, X);
}
}
| gpl-2.0 |
Cougar/mirror-openhab | bundles/binding/org.openhab.binding.dmx/src/main/java/org/openhab/binding/dmx/DmxBindingProvider.java | 2044 | /**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2013, openHAB.org <admin@openhab.org>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* 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 3 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, see <http://www.gnu.org/licenses>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.binding.dmx;
import org.openhab.binding.dmx.internal.config.DmxItem;
import org.openhab.core.binding.BindingProvider;
import org.openhab.core.types.State;
/**
* DMX Binding Provider Interface.
*
* @author Davy Vanherbergen
* @since 1.2.0
*/
public interface DmxBindingProvider extends BindingProvider {
/**
* Get the BindingConfig for a given itemName.
*
* @param itemName
* the item for which to get the binding configuration.
* @return BindingConfig for the item or null.
*/
public DmxItem getBindingConfig(String itemName);
/**
* Send a status update to the openhab bus.
*
* @param itemName
* item for which to send update
* @param state
* status
*/
public void postUpdate(String itemName, State state);
}
| gpl-3.0 |
jwren/intellij-community | platform/lang-impl/src/com/intellij/openapi/roots/PlatformModifiableModelsProvider.java | 1824 | package com.intellij.openapi.roots;
import com.intellij.facet.FacetManager;
import com.intellij.facet.ModifiableFacetModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
import com.intellij.openapi.util.Disposer;
import org.jetbrains.annotations.NotNull;
/**
* @author Dennis.Ushakov
*/
public class PlatformModifiableModelsProvider implements ModifiableModelsProvider {
@Override
public ModifiableRootModel getModuleModifiableModel(@NotNull final Module module) {
return ModuleRootManager.getInstance(module).getModifiableModel();
}
@Override
public void commitModuleModifiableModel(@NotNull final ModifiableRootModel model) {
model.commit();
}
@Override
public void disposeModuleModifiableModel(@NotNull final ModifiableRootModel model) {
model.dispose();
}
@NotNull
@Override
public ModifiableFacetModel getFacetModifiableModel(@NotNull Module module) {
return FacetManager.getInstance(module).createModifiableModel();
}
@Override
public void commitFacetModifiableModel(@NotNull Module module, @NotNull ModifiableFacetModel model) {
model.commit();
}
@NotNull
@Override
public LibraryTable.ModifiableModel getLibraryTableModifiableModel() {
return LibraryTablesRegistrar.getInstance().getLibraryTable().getModifiableModel();
}
@Override
public LibraryTable.ModifiableModel getLibraryTableModifiableModel(@NotNull Project project) {
return LibraryTablesRegistrar.getInstance().getLibraryTable(project).getModifiableModel();
}
@Override
public void disposeLibraryTableModifiableModel(@NotNull LibraryTable.ModifiableModel model) {
Disposer.dispose(model);
}
}
| apache-2.0 |
apratkin/pentaho-kettle | test/org/pentaho/di/resource/ResourceDependencyTest.java | 5767 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : 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 org.pentaho.di.resource;
import java.util.List;
import junit.framework.TestCase;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.pentaho.di.trans.TransMeta;
public class ResourceDependencyTest extends TestCase {
/**
* @param args
*/
public static void main( String[] args ) {
ResourceDependencyTest test = new ResourceDependencyTest();
try {
test.setUp();
test.testJobDependencyList();
test.testTransformationDependencyList();
} catch ( Exception ex ) {
ex.printStackTrace();
} finally {
try {
test.tearDown();
} catch ( Exception ignored ) {
// Ignored
}
}
}
public void testJobDependencyList() throws Exception {
KettleEnvironment.init();
// Load the first job metadata
JobMeta jobMeta = new JobMeta( "test/org/pentaho/di/resource/processchangelog.kjb", null, null );
List<ResourceReference> resourceReferences = jobMeta.getResourceDependencies();
// printResourceReferences(resourceReferences);
assertEquals( 5, resourceReferences.size() );
for ( int i = 0; i < 5; i++ ) {
ResourceReference genRef = resourceReferences.get( i );
// System.out.println(genRef.toXml());
ResourceHolderInterface refHolder = genRef.getReferenceHolder();
boolean checkDatabaseStuff = false;
if ( i == 0 ) {
assertEquals( "TABLE_EXISTS", refHolder.getTypeId() );
checkDatabaseStuff = true;
} else if ( ( i == 1 ) || ( i == 4 ) ) {
assertEquals( "SQL", refHolder.getTypeId() );
checkDatabaseStuff = true;
} else if ( ( i == 2 ) || ( i == 3 ) ) {
assertEquals( "TRANS", refHolder.getTypeId() );
checkDatabaseStuff = false;
}
if ( checkDatabaseStuff ) {
assertEquals( 2, genRef.getEntries().size() );
for ( int j = 0; j < 2; j++ ) {
ResourceEntry entry = genRef.getEntries().get( j );
if ( j == 0 ) {
assertEquals( ResourceType.SERVER, entry.getResourcetype() );
assertEquals( "localhost", entry.getResource() );
} else {
assertEquals( ResourceType.DATABASENAME, entry.getResourcetype() );
assertEquals( "test", entry.getResource() );
}
}
} else { // Check Transform Stuff
assertEquals( 1, genRef.getEntries().size() ); // Only one entry per ref in this case.
ResourceEntry entry = genRef.getEntries().get( 0 );
assertEquals( ResourceType.ACTIONFILE, entry.getResourcetype() );
assertTrue( entry.getResource().endsWith( ".ktr" ) );
}
}
}
public void testTransformationDependencyList() throws Exception {
KettleEnvironment.init();
TransMeta transMeta = new TransMeta( "test/org/pentaho/di/resource/trans/General - Change log processing.ktr" );
List<ResourceReference> resourceReferences = transMeta.getResourceDependencies();
// printResourceReferences(resourceReferences);
assertEquals( 2, resourceReferences.size() );
ResourceReference genRef = null;
for ( ResourceReference look : resourceReferences ) {
if ( look.getReferenceHolder().getTypeId().equals( "TextFileInput" ) ) {
genRef = look;
}
}
assertNotNull( genRef );
// System.out.println(genRef.toXml());
ResourceHolderInterface refHolder = genRef.getReferenceHolder();
assertEquals( "TextFileInput", refHolder.getTypeId() );
List<ResourceEntry> entries = genRef.getEntries();
assertEquals( 1, entries.size() );
ResourceEntry theEntry = entries.get( 0 );
assertEquals( ResourceType.FILE, theEntry.getResourcetype() );
assertTrue( theEntry.getResource().endsWith( "changelog.txt" ) );
}
/**
* Private method for displaying what's coming back from the dependency call.
*
* @param resourceReferences
*/
protected void printResourceReferences( List<ResourceReference> resourceReferences ) {
for ( int i = 0; i < resourceReferences.size(); i++ ) {
ResourceReference genRef = resourceReferences.get( i );
ResourceHolderInterface refHolder = genRef.getReferenceHolder();
System.out.println( "Reference Holder Information" );
System.out.println( " Name: " + refHolder.getName() );
System.out.println( " Type Id: " + refHolder.getTypeId() );
System.out.println( " Resource Entries" );
List<ResourceEntry> entries = genRef.getEntries();
for ( int j = 0; j < entries.size(); j++ ) {
ResourceEntry resEntry = entries.get( j );
System.out.println( " Resource Entry" );
System.out.println( " Resource Type: " + resEntry.getResourcetype() );
System.out.println( " Resource: " + resEntry.getResource() );
}
}
}
}
| apache-2.0 |
NSAmelchev/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTopologyValidatorNearPartitionedTxCacheTest.java | 1518 | /*
* 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.cache;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.testframework.MvccFeatureChecker;
/**
* Topology validator test
*/
public class IgniteTopologyValidatorNearPartitionedTxCacheTest extends IgniteTopologyValidatorPartitionedTxCacheTest {
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.NEAR_CACHE);
super.beforeTestsStarted();
}
/** {@inheritDoc} */
@Override protected NearCacheConfiguration nearConfiguration() {
return new NearCacheConfiguration();
}
}
| apache-2.0 |
signed/intellij-community | plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/config/InjectionPlace.java | 2275 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.intelliLang.inject.config;
import com.intellij.patterns.ElementPattern;
import com.intellij.psi.PsiElement;
import com.intellij.util.ArrayFactory;
import org.jetbrains.annotations.NotNull;
/**
* @author Gregory.Shrago
*/
// todo inline class
public class InjectionPlace {
public static final InjectionPlace[] EMPTY_ARRAY = new InjectionPlace[0];
public static final ArrayFactory<InjectionPlace> ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new InjectionPlace[count];
private final boolean myEnabled;
private final ElementPattern<PsiElement> myElementPattern;
public InjectionPlace(final ElementPattern<PsiElement> myElementPattern, final boolean enabled) {
this.myElementPattern = myElementPattern;
myEnabled = enabled;
}
public InjectionPlace enabled(final boolean enabled) {
return new InjectionPlace(myElementPattern, enabled);
}
public String getText() {
return myElementPattern.toString();
}
public ElementPattern<PsiElement> getElementPattern() {
return myElementPattern;
}
public boolean isEnabled() {
return myEnabled;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final InjectionPlace place = (InjectionPlace)o;
if (!myElementPattern.equals(place.myElementPattern)) return false;
return true;
}
@Override
public int hashCode() {
return myElementPattern.hashCode();
}
@Override
public String toString() {
return "InjectionPlace{" +
(myEnabled ? "+ " : "- ") +
myElementPattern +
'}';
}
}
| apache-2.0 |
gnudeep/wso2-cassandra-2.x.x | src/java/org/apache/cassandra/db/compaction/AbstractCompactedRow.java | 2611 | /*
* 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.Closeable;
import java.io.DataOutput;
import java.io.IOException;
import java.security.MessageDigest;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowIndexEntry;
import org.apache.cassandra.io.sstable.ColumnStats;
import org.apache.cassandra.io.util.DataOutputPlus;
/**
* a CompactedRow is an object that takes a bunch of rows (keys + columnfamilies)
* and can write a compacted version of those rows to an output stream. It does
* NOT necessarily require creating a merged CF object in memory.
*/
public abstract class AbstractCompactedRow implements Closeable
{
public final DecoratedKey key;
public AbstractCompactedRow(DecoratedKey key)
{
this.key = key;
}
/**
* write the row (size + column index + filter + column data, but NOT row key) to @param out.
*
* write() may change internal state; it is NOT valid to call write() or update() a second time.
*
* @return index information for the written row, or null if the compaction resulted in only expired tombstones.
*/
public abstract RowIndexEntry write(long currentPosition, DataOutputPlus out) throws IOException;
/**
* update @param digest with the data bytes of the row (not including row key or row size).
* May be called even if empty.
*
* update() may change internal state; it is NOT valid to call write() or update() a second time.
*/
public abstract void update(MessageDigest digest);
/**
* @return aggregate information about the columns in this row. Some fields may
* contain default values if computing them value would require extra effort we're not willing to make.
*/
public abstract ColumnStats columnStats();
}
| apache-2.0 |
ouit0408/sakai | assignment/assignment-impl/impl/src/java/org/sakaiproject/assignment/impl/AssignmentGradeInfoProvider.java | 9669 | /**********************************************************************************
* $URL:$
* $Id:$
***********************************************************************************
*
* Copyright (c) 2011 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.assignment.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.assignment.api.Assignment;
import org.sakaiproject.assignment.api.AssignmentService;
import org.sakaiproject.assignment.impl.BaseAssignmentService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.service.gradebook.shared.ExternalAssignmentProvider;
import org.sakaiproject.service.gradebook.shared.ExternalAssignmentProviderCompat;
import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.SessionManager;
public class AssignmentGradeInfoProvider implements ExternalAssignmentProvider, ExternalAssignmentProviderCompat {
private Logger log = LoggerFactory.getLogger(AssignmentGradeInfoProvider.class);
// Sakai Service Beans
private AssignmentService assignmentService;
private SiteService siteService;
private GradebookExternalAssessmentService geaService;
private AuthzGroupService authzGroupService;
private EntityManager entityManager;
private SecurityService securityService;
private SessionManager sessionManager;
public void init() {
log.info("INIT and register AssignmentGradeInfoProvider");
geaService.registerExternalAssignmentProvider(this);
}
public void destroy() {
log.info("DESTROY and unregister AssignmentGradeInfoProvider");
geaService.unregisterExternalAssignmentProvider(getAppKey());
}
public String getAppKey() {
return "assignment";
}
//NOTE: This is pretty hackish because the AssignmentService
// does strenuous checking of current user and group access,
// while we want to be able to check for any user.
private Assignment getAssignment(String id) {
Assignment assignment = null;
String assignmentReference = assignmentService.assignmentReference(id);
Reference aref = null;
if (assignmentReference != null) {
aref = entityManager.newReference(assignmentReference);
try {
securityService.pushAdvisor(
new MySecurityAdvisor(sessionManager.getCurrentSessionUserId(),
assignmentService.SECURE_ACCESS_ASSIGNMENT,
assignmentReference));
securityService.pushAdvisor(
new MySecurityAdvisor(sessionManager.getCurrentSessionUserId(),
assignmentService.SECURE_ALL_GROUPS,
siteService.siteReference(aref.getContext())));
assignment = assignmentService.getAssignment(assignmentReference);
} catch (IdUnusedException e) {
log.info("Unexpected IdUnusedException after finding assignment with ID: " + id);
} catch (PermissionException e) {
log.info("Unexpected Permission Exception while using security advisor "
+ "for assignment with ID: " + id);
} finally {
securityService.popAdvisor();
securityService.popAdvisor();
}
} else {
if (log.isDebugEnabled()) {
log.debug("Assignment not found with ID: " + id);
}
}
return assignment;
}
public boolean isAssignmentDefined(String id) {
return getAssignment(id) != null;
}
public boolean isAssignmentGrouped(String id) {
return Assignment.AssignmentAccess.GROUPED.equals(getAssignment(id).getAccess());
}
public boolean isAssignmentVisible(String id, String userId) {
// This method is more involved than just a call to getAssignment,
// which checks visibility, because AssignmentService assumes the
// current user. Here, we do the checks for the specified user.
boolean visible = false;
Assignment a = getAssignment(id);
if (a == null) {
visible = false;
}
else if (Assignment.AssignmentAccess.GROUPED.equals(a.getAccess())) {
ArrayList<String> azgList = new ArrayList<String>( (Collection<String>) a.getGroups());
List<AuthzGroup> matched = authzGroupService.getAuthzUserGroupIds(azgList, userId);
visible = (matched.size() > 0);
}
else {
visible = securityService.unlock(userId, AssignmentService.SECURE_ACCESS_ASSIGNMENT, a.getReference());
}
return visible;
}
public List<String> getExternalAssignmentsForCurrentUser(String gradebookUid) {
List<String> externalIds = new ArrayList<String>();
List assignments = assignmentService.getListAssignmentsForContext(gradebookUid);
for (Assignment a : (List<Assignment>) assignments) {
externalIds.add(a.getReference());
}
return externalIds;
}
public List<String> getAllExternalAssignments(String gradebookUid) {
// We check and cast here on the very slim chance that something other than
// a BaseAssignmentService is registered as the service. If that is the case,
// we won't have access to the protected method to get unfiltered assignments
// and the best we can do is return the filtered list, which is exposed on
// the AssignmentService interface.
List<String> externalIds = new ArrayList<String>();
if (assignmentService instanceof BaseAssignmentService) {
List assignments = ((BaseAssignmentService) assignmentService).getUnfilteredAssignments(gradebookUid);
for (Assignment a : (List<Assignment>) assignments) {
externalIds.add(a.getReference());
}
} else {
externalIds = getExternalAssignmentsForCurrentUser(gradebookUid);
}
return externalIds;
}
public Map<String, List<String>> getAllExternalAssignments(String gradebookUid, Collection<String> studentIds) {
Map<String, List<String>> allExternals = new HashMap<String, List<String>>();
for (String studentId : studentIds) {
allExternals.put(studentId, new ArrayList<String>());
}
Map<Assignment, List<String>> submitters = assignmentService.getSubmittableAssignmentsForContext(gradebookUid);
for (Assignment assignment : submitters.keySet()) {
String externalId = assignment.getReference();
for (String userId : submitters.get(assignment)) {
if (allExternals.containsKey(userId)) {
allExternals.get(userId).add(externalId);
}
}
}
return allExternals;
}
public void setGradebookExternalAssessmentService(GradebookExternalAssessmentService geaService) {
this.geaService = geaService;
}
public GradebookExternalAssessmentService getGradebookExternalAssessmentService() {
return geaService;
}
public void setAssignmentService(AssignmentService assignmentService) {
this.assignmentService = assignmentService;
}
public AssignmentService getAssignmentService() {
return assignmentService;
}
public void setSiteService(SiteService siteService) {
this.siteService = siteService;
}
public SiteService getSiteService() {
return siteService;
}
public void setAuthzGroupService(AuthzGroupService authzGroupService) {
this.authzGroupService = authzGroupService;
}
public AuthzGroupService getAuthzGroupService() {
return authzGroupService;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setSecurityService(SecurityService securityService) {
this.securityService = securityService;
}
public SecurityService getSecurityService() {
return securityService;
}
public void setSessionManager(SessionManager sessionManager) {
this.sessionManager = sessionManager;
}
}
| apache-2.0 |
apache/flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/api/CatalogNotExistException.java | 1288 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.api;
import org.apache.flink.annotation.PublicEvolving;
/** Exception for an operation on a nonexistent catalog. */
@PublicEvolving
public class CatalogNotExistException extends RuntimeException {
public CatalogNotExistException(String catalogName) {
this(catalogName, null);
}
public CatalogNotExistException(String catalogName, Throwable cause) {
super("Catalog " + catalogName + " does not exist.", cause);
}
}
| apache-2.0 |
tkpanther/ignite | modules/core/src/main/java/org/apache/ignite/spi/discovery/DiscoverySpi.java | 6395 | /*
* 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.spi.discovery;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.lang.IgniteProductVersion;
import org.apache.ignite.spi.IgniteSpi;
import org.apache.ignite.spi.IgniteSpiException;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.jetbrains.annotations.Nullable;
/**
* Grid discovery SPI allows to discover remote nodes in grid.
* <p>
* The default discovery SPI is {@link org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi}
* with default configuration which allows all nodes in local network
* (with enabled multicast) to discover each other.
* <p>
* Ignite provides the following {@code GridDeploymentSpi} implementation:
* <ul>
* <li>{@link org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi}</li>
* </ul>
* <b>NOTE:</b> this SPI (i.e. methods in this interface) should never be used directly. SPIs provide
* internal view on the subsystem and is used internally by Ignite kernal. In rare use cases when
* access to a specific implementation of this SPI is required - an instance of this SPI can be obtained
* via {@link org.apache.ignite.Ignite#configuration()} method to check its configuration properties or call other non-SPI
* methods. Note again that calling methods from this interface on the obtained instance can lead
* to undefined behavior and explicitly not supported.
*/
public interface DiscoverySpi extends IgniteSpi {
/**
* Gets collection of remote nodes in grid or empty collection if no remote nodes found.
*
* @return Collection of remote nodes.
*/
public Collection<ClusterNode> getRemoteNodes();
/**
* Gets local node.
*
* @return Local node.
*/
public ClusterNode getLocalNode();
/**
* Gets node by ID.
*
* @param nodeId Node ID.
* @return Node with given ID or {@code null} if node is not found.
*/
@Nullable public ClusterNode getNode(UUID nodeId);
/**
* Pings the remote node to see if it's alive.
*
* @param nodeId Node Id.
* @return {@code true} if node alive, {@code false} otherwise.
*/
public boolean pingNode(UUID nodeId);
/**
* Sets node attributes and node version which will be distributed in grid during
* join process. Note that these attributes cannot be changed and set only once.
*
* @param attrs Map of node attributes.
* @param ver Product version.
*/
public void setNodeAttributes(Map<String, Object> attrs, IgniteProductVersion ver);
/**
* Sets a listener for discovery events. Refer to
* {@link org.apache.ignite.events.DiscoveryEvent} for a set of all possible
* discovery events.
* <p>
* Note that as of Ignite 3.0.2 this method is called <b>before</b>
* method {@link #spiStart(String)} is called. This is done to
* avoid potential window when SPI is started but the listener is
* not registered yet.
*
* @param lsnr Listener to discovery events or {@code null} to unset the listener.
*/
public void setListener(@Nullable DiscoverySpiListener lsnr);
/**
* Sets a handler for initial data exchange between Ignite nodes.
*
* @param exchange Discovery data exchange handler.
* @return {@code this} for chaining.
*/
public TcpDiscoverySpi setDataExchange(DiscoverySpiDataExchange exchange);
/**
* Sets discovery metrics provider. Use metrics provided by
* {@link DiscoveryMetricsProvider#metrics()} method to exchange
* dynamic metrics between nodes.
*
* @param metricsProvider Provider of metrics data.
* @return {@code this} for chaining.
*/
public TcpDiscoverySpi setMetricsProvider(DiscoveryMetricsProvider metricsProvider);
/**
* Tells discovery SPI to disconnect from topology. This is very close to calling
* {@link #spiStop()} with accounting that it is not a full stop,
* but disconnect due to segmentation.
*
* @throws IgniteSpiException If any error occurs.
*/
public void disconnect() throws IgniteSpiException;
/**
* Sets discovery SPI node authenticator. This method is called before SPI start() method.
*
* @param auth Discovery SPI authenticator.
*/
public void setAuthenticator(DiscoverySpiNodeAuthenticator auth);
/**
* Gets start time of the very first node in the grid. This value should be the same
* on all nodes in the grid and it should not change even if very first node fails
* of leaves grid.
*
* @return Start time of the first node in grid or {@code 0} if SPI implementation
* does not support this method.
*/
public long getGridStartTime();
/**
* Sends custom message across the ring.
* @param msg Custom message.
* @throws IgniteException if failed to marshal evt.
*/
public void sendCustomEvent(DiscoverySpiCustomMessage msg) throws IgniteException;
/**
* Initiates failure of provided node.
*
* @param nodeId Node ID.
* @param warning Warning to be shown on all cluster nodes.
*/
public void failNode(UUID nodeId, @Nullable String warning);
/**
* Whether or not discovery is started in client mode.
*
* @return {@code true} if node is in client mode.
* @throws IllegalStateException If discovery SPI has not started.
*/
public boolean isClientMode() throws IllegalStateException;
}
| apache-2.0 |
watsonmw/ninja | ninja-core/src/main/java/ninja/UsernamePasswordValidator.java | 1068 | /**
* Copyright (C) 2012-2015 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 ninja;
/**
* Defines a validator for authentication filters like ninja.BasicAuthFilter.
*
* @author James Moger
*
*/
public interface UsernamePasswordValidator {
/**
* Returns true if the supplied username and password are valid.
*
* @param username
* @param password
* @return true if username and password are correct
*/
boolean validateCredentials(String username, String password);
}
| apache-2.0 |
lincoln-lil/flink | flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/MutableObjectIteratorWrapper.java | 1769 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.operators.testutils;
import org.apache.flink.types.Record;
import org.apache.flink.util.MutableObjectIterator;
import java.io.IOException;
import java.util.Iterator;
/** */
public class MutableObjectIteratorWrapper implements MutableObjectIterator<Record> {
private final Iterator<Record> source;
public MutableObjectIteratorWrapper(Iterator<Record> source) {
this.source = source;
}
@Override
public Record next(Record reuse) throws IOException {
if (this.source.hasNext()) {
return this.source.next();
} else {
return null;
}
}
@Override
public Record next() throws IOException {
// copy to be on the safe side
if (this.source.hasNext()) {
Record result = new Record();
this.source.next().copyTo(result);
return result;
} else {
return null;
}
}
}
| apache-2.0 |
zstackorg/zstack | header/src/main/java/org/zstack/header/network/service/APISearchNetworkServiceProviderReply.java | 372 | package org.zstack.header.network.service;
import org.zstack.header.search.APISearchReply;
public class APISearchNetworkServiceProviderReply extends APISearchReply {
public static APISearchNetworkServiceProviderReply __example__() {
APISearchNetworkServiceProviderReply reply = new APISearchNetworkServiceProviderReply();
return reply;
}
}
| apache-2.0 |
netxillon/pig | contrib/piggybank/java/src/main/java/org/apache/pig/piggybank/storage/IndexedStorage.java | 41246 | /*
* 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.piggybank.storage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PositionedReadable;
import org.apache.hadoop.fs.Seekable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.pig.IndexableLoadFunc;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRConfiguration;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextInputFormat;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextOutputFormat;
import org.apache.pig.backend.hadoop.executionengine.shims.HadoopShims;
import org.apache.pig.piggybank.storage.IndexedStorage.IndexedStorageInputFormat.IndexedStorageRecordReader;
import org.apache.pig.piggybank.storage.IndexedStorage.IndexedStorageInputFormat.IndexedStorageRecordReader.IndexedStorageRecordReaderComparator;
import org.apache.pig.builtin.PigStorage;
import org.apache.pig.data.DataReaderWriter;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.util.StorageUtil;
import org.apache.pig.data.DataType;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.backend.hadoop.executionengine.shims.HadoopShims;
/**
* <code>IndexedStorage</code> is a form of <code>PigStorage</code> that supports a
* per record seek. <code>IndexedStorage</code> creates a separate (hidden) index file for
* every data file that is written. The format of the index file is:
* <pre>
* | Header |
* | Index Body |
* | Footer |
* </pre>
* The Header contains the list of record indices (field numbers) that represent index keys.
* The Index Body contains a <code>Tuple</code> for each record in the data.
* The fields of the <code>Tuple</code> are:
* <ul>
* <li> The index key(s) <code>Tuple</code> </li>
* <li> The number of records that share this index key. </li>
* <li> Offset into the data file to read the first matching record. </li>
* </ul>
* The Footer contains sequentially:
* <ul>
* <li> The smallest key(s) <code>Tuple</code> in the index. </li>
* <li> The largest key(s) <code>Tuple</code> in the index. </li>
* <li> The offset in bytes to the start of the footer </li>
* </ul>
*
* <code>IndexStorage</code> implements <code>IndexableLoadFunc</code> and
* can be used as the 'right table' in a PIG 'merge' or 'merge-sparse' join.
*
* <code>IndexStorage</code> does not require the data to be globally partitioned & sorted
* by index keys. Each partition (separate index) must be locally sorted.
*
* Also note IndexStorage is a loader to demonstrate "merge-sparse" join.
*/
public class IndexedStorage extends PigStorage implements IndexableLoadFunc {
/**
* Constructs a Pig Storer that uses specified regex as a field delimiter.
* @param delimiter - field delimiter to use
* @param offsetsToIndexKeys - list of offset into Tuple for index keys (comma separated)
*/
public IndexedStorage(String delimiter, String offsetsToIndexKeys) {
super(delimiter);
this.fieldDelimiter = StorageUtil.parseFieldDel(delimiter);
String[] stroffsetsToIndexKeys = offsetsToIndexKeys.split(",");
this.offsetsToIndexKeys = new int[stroffsetsToIndexKeys.length];
for (int i = 0; i < stroffsetsToIndexKeys.length; ++i) {
this.offsetsToIndexKeys[i] = Integer.parseInt(stroffsetsToIndexKeys[i]);
}
}
@Override
public OutputFormat getOutputFormat() {
return new IndexedStorageOutputFormat(fieldDelimiter, offsetsToIndexKeys);
}
/**
* Assumes this list of readers is already sorted except for the provided element.
* This element is bubbled up the array to its appropriate sort location
* (faster than doing a Utils sort).
*/
private void sortReader(int startIndex) {
int idx = startIndex;
while (idx < this.readers.length - 1) {
IndexedStorageRecordReader reader1 = this.readers[idx];
IndexedStorageRecordReader reader2 = this.readers[idx+1];
if (this.readerComparator.compare(reader1, reader2) <= 0) {
return;
}
this.readers[idx] = reader2;
this.readers[idx+1] = reader1;
idx++;
}
}
/**
* Internal OutputFormat class
*/
public static class IndexedStorageOutputFormat extends PigTextOutputFormat {
public IndexedStorageOutputFormat(byte delimiter, int[] offsetsToIndexKeys) {
/* Call the base class constructor */
super(delimiter);
this.fieldDelimiter = delimiter;
this.offsetsToIndexKeys = offsetsToIndexKeys;
}
@Override
public RecordWriter<WritableComparable, Tuple> getRecordWriter(
TaskAttemptContext context) throws IOException,
InterruptedException {
Configuration conf = context.getConfiguration();
FileSystem fs = FileSystem.get(conf);
Path file = this.getDefaultWorkFile(context, "");
FSDataOutputStream fileOut = fs.create(file, false);
IndexManager indexManager = new IndexManager(offsetsToIndexKeys);
indexManager.createIndexFile(fs, file);
return new IndexedStorageRecordWriter(fileOut, this.fieldDelimiter, indexManager);
}
/**
* Internal class to do the actual record writing and index generation
*
*/
public static class IndexedStorageRecordWriter extends PigLineRecordWriter {
public IndexedStorageRecordWriter(FSDataOutputStream fileOut, byte fieldDel, IndexManager indexManager) throws IOException {
super(fileOut, fieldDel);
this.fileOut = fileOut;
this.indexManager = indexManager;
/* Write the index header first */
this.indexManager.WriteIndexHeader();
}
@Override
public void write(WritableComparable key, Tuple value) throws IOException {
/* Write the data */
long offset = this.fileOut.getPos();
super.write(key, value);
/* Build index */
this.indexManager.BuildIndex(value, offset);
}
@Override
public void close(TaskAttemptContext context)
throws IOException {
this.indexManager.WriterIndexFooter();
this.indexManager.Close();
super.close(context);
}
/**
* Output stream for data
*/
private FSDataOutputStream fileOut;
/**
* Index builder
*/
private IndexManager indexManager = null;
}
/**
* Delimiter to use between fields
*/
final private byte fieldDelimiter;
/**
* Offsets to index keys in given tuple
*/
final protected int[] offsetsToIndexKeys;
}
@Override
public InputFormat getInputFormat() {
return new IndexedStorageInputFormat();
}
@Override
public Tuple getNext() throws IOException {
if (this.readers == null) {
return super.getNext();
}
while (currentReaderIndexStart < this.readers.length) {
IndexedStorageRecordReader r = this.readers[currentReaderIndexStart];
this.prepareToRead(r, null);
Tuple tuple = super.getNext();
if (tuple == null) {
currentReaderIndexStart++;
r.close();
continue; //next Reader
}
//if we haven't yet initialized the indexManager (by reading the first index key)
if (r.indexManager.lastIndexKeyTuple == null) {
//initialize the indexManager
if (r.indexManager.ReadIndex() == null) {
//There should never be a case where there is a non-null record - but no corresponding index.
throw new IOException("Missing Index for Tuple: " + tuple);
}
}
r.indexManager.numberOfTuples--;
if (r.indexManager.numberOfTuples == 0) {
if (r.indexManager.ReadIndex() == null) {
r.close();
currentReaderIndexStart++;
} else {
//Since the index of the current reader was increased, we may need to push the
//current reader back in the sorted list of readers.
sortReader(currentReaderIndexStart);
}
}
return tuple;
}
return null;
}
/**
* IndexableLoadFunc interface implementation
*/
@Override
public void initialize(Configuration conf) throws IOException {
try {
InputFormat inputFormat = this.getInputFormat();
TaskAttemptID id = HadoopShims.getNewTaskAttemptID();
if (System.getenv("HADOOP_TOKEN_FILE_LOCATION") != null) {
conf.set(MRConfiguration.JOB_CREDENTIALS_BINARY, System.getenv("HADOOP_TOKEN_FILE_LOCATION"));
}
List<FileSplit> fileSplits = inputFormat.getSplits(HadoopShims.createJobContext(conf, null));
this.readers = new IndexedStorageRecordReader[fileSplits.size()];
int idx = 0;
Iterator<FileSplit> it = fileSplits.iterator();
while (it.hasNext()) {
FileSplit fileSplit = it.next();
TaskAttemptContext context = HadoopShims.createTaskAttemptContext(conf, id);
IndexedStorageRecordReader r = (IndexedStorageRecordReader) inputFormat.createRecordReader(fileSplit, context);
r.initialize(fileSplit, context);
this.readers[idx] = r;
idx++;
}
Arrays.sort(this.readers, this.readerComparator);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
@Override
/* The list of readers is always sorted before and after this call. */
public void seekNear(Tuple keys) throws IOException {
/* Keeps track of the last (if any) reader where seekNear was called */
int lastIndexModified = -1;
int idx = currentReaderIndexStart;
while (idx < this.readers.length) {
IndexedStorageRecordReader r = this.readers[idx];
/* The key falls within the range of the reader index */
if (keys.compareTo(r.indexManager.maxIndexKeyTuple) <= 0 && keys.compareTo(r.indexManager.minIndexKeyTuple) >= 0) {
r.seekNear(keys);
lastIndexModified = idx;
/* The key is greater than the current range of the reader index */
} else if (keys.compareTo(r.indexManager.maxIndexKeyTuple) > 0) {
currentReaderIndexStart++;
/* DO NOTHING - The key is less than the current range of the reader index */
} else {
break;
}
idx++;
}
/*
* There is something to sort.
* We can rely on the following invariants that make the following check accurate:
* - currentReaderIndexStart is always >= 0.
* - lastIndexModified is only positive if seekNear was called.
* - lastIndexModified >= currentReaderIndexStart if lastIndexModifed >= 0. This is true because the list
* is already sorted.
*/
if (lastIndexModified - currentReaderIndexStart >= 0) {
/*
* The following logic is optimized for the (common) case where there are a tiny number of readers that
* need to be repositioned relative to the other readers in the much larger sorted list.
*/
/* First, just sort the readers that were updated relative to one another. */
Arrays.sort(this.readers, currentReaderIndexStart, lastIndexModified+1, this.readerComparator);
/* In descending order, push the updated readers back in the the sorted list. */
for (idx = lastIndexModified; idx >= currentReaderIndexStart; idx--) {
sortReader(idx);
}
}
}
@Override
public void close() throws IOException {
for (IndexedStorageRecordReader reader : this.readers) {
reader.close();
}
}
/**
* <code>IndexManager</code> manages the index file (both writing and reading)
* It keeps track of the last index read during reading.
*/
public static class IndexManager {
/**
* Constructor (called during reading)
* @param ifile index file to read
*/
public IndexManager(FileStatus ifile) {
this.indexFile = ifile;
this.offsetToFooter = -1;
}
/**
* Constructor (called during writing)
* @param offsetsToIndexKeys
*/
public IndexManager(int[] offsetsToIndexKeys) {
this.offsetsToIndexKeys = offsetsToIndexKeys;
this.offsetToFooter = -1;
}
/**
* Construct index file path for a given a data file
* @param file - Data file
* @return - Index file path for given data file
*/
private static Path getIndexFileName(Path file) {
return new Path(file.getParent(), "." + file.getName() + ".index");
}
/**
* Open the index file for writing for given data file
* @param fs
* @param file
* @throws IOException
*/
public void createIndexFile(FileSystem fs, Path file) throws IOException {
this.indexOut = fs.create(IndexManager.getIndexFileName(file), false);
}
/**
* Opens the index file.
*/
public void openIndexFile(FileSystem fs) throws IOException {
this.indexIn = fs.open(this.indexFile.getPath());
}
/**
* Close the index file
* @throws IOException
*/
public void Close() throws IOException {
this.indexOut.close();
}
/**
* Build index tuple
*
* @throws IOException
*/
private void BuildIndex(Tuple t, long offset) throws IOException {
/* Build index key tuple */
Tuple indexKeyTuple = tupleFactory.newTuple(this.offsetsToIndexKeys.length);
for (int i = 0; i < this.offsetsToIndexKeys.length; ++i) {
indexKeyTuple.set(i, t.get(this.offsetsToIndexKeys[i]));
}
/* Check if we have already seen Tuple(s) with same index keys */
if (indexKeyTuple.compareTo(this.lastIndexKeyTuple) == 0) {
/* We have seen Tuple(s) with given index keys, update the tuple count */
this.numberOfTuples += 1;
}
else {
if (this.lastIndexKeyTuple != null)
this.WriteIndex();
this.lastIndexKeyTuple = indexKeyTuple;
this.minIndexKeyTuple = ((this.minIndexKeyTuple == null) || (indexKeyTuple.compareTo(this.minIndexKeyTuple) < 0)) ? indexKeyTuple : this.minIndexKeyTuple;
this.maxIndexKeyTuple = ((this.maxIndexKeyTuple == null) || (indexKeyTuple.compareTo(this.maxIndexKeyTuple) > 0)) ? indexKeyTuple : this.maxIndexKeyTuple;
/* New index tuple for newly seen index key */
this.indexTuple = tupleFactory.newTuple(3);
/* Add index keys to index Tuple */
this.indexTuple.set(0, indexKeyTuple);
/* Reset Tuple count for index key */
this.numberOfTuples = 1;
/* Remember offset to Tuple with new index keys */
this.indexTuple.set(2, offset);
}
}
/**
* Write index header
* @param indexOut - Stream to write to
* @param ih - Index header to write
* @throws IOException
*/
public void WriteIndexHeader() throws IOException {
/* Number of index keys */
indexOut.writeInt(this.offsetsToIndexKeys.length);
/* Offset to index keys */
for (int i = 0; i < this.offsetsToIndexKeys.length; ++i) {
indexOut.writeInt(this.offsetsToIndexKeys[i]);
}
}
/**
* Read index header
* @param indexIn - Stream to read from
* @return Index header
* @throws IOException
*/
public void ReadIndexHeader() throws IOException {
/* Number of index keys */
int nkeys = this.indexIn.readInt();
/* Offset to index keys */
this.offsetsToIndexKeys = new int[nkeys];
for (int i = 0; i < nkeys; ++i) {
offsetsToIndexKeys[i] = this.indexIn.readInt();
}
}
/**
* Writes the index footer
*/
public void WriterIndexFooter() throws IOException {
/* Flush indexes for remaining records */
this.WriteIndex();
/* record the offset to footer */
this.offsetToFooter = this.indexOut.getPos();
/* Write index footer */
DataReaderWriter.writeDatum(indexOut, this.minIndexKeyTuple);
DataReaderWriter.writeDatum(indexOut, this.maxIndexKeyTuple);
/* Offset to footer */
indexOut.writeLong(this.offsetToFooter);
}
/**
* Reads the index footer
*/
public void ReadIndexFooter() throws IOException {
long currentOffset = this.indexIn.getPos();
this.SeekToIndexFooter();
this.minIndexKeyTuple = (Tuple)DataReaderWriter.readDatum(this.indexIn);
this.maxIndexKeyTuple = (Tuple)DataReaderWriter.readDatum(this.indexIn);
this.indexIn.seek(currentOffset);
}
/**
* Seeks to the index footer
*/
public void SeekToIndexFooter() throws IOException {
if (this.offsetToFooter < 0) {
/* offset to footer is at last long (8 bytes) in the file */
this.indexIn.seek(this.indexFile.getLen()-8);
this.offsetToFooter = this.indexIn.readLong();
}
this.indexIn.seek(this.offsetToFooter);
}
/**
* Writes the current index.
*/
public void WriteIndex() throws IOException {
this.indexTuple.set(1, this.numberOfTuples);
DataReaderWriter.writeDatum(this.indexOut, this.indexTuple);
}
/**
* Extracts the index key from the index tuple
*/
public Tuple getIndexKeyTuple(Tuple indexTuple) throws IOException {
if (indexTuple.size() == 3)
return (Tuple)indexTuple.get(0);
else
throw new IOException("Invalid index record with size " + indexTuple.size());
}
/**
* Extracts the number of records that share the current key from the index tuple.
*/
public long getIndexKeyTupleCount(Tuple indexTuple) throws IOException {
if (indexTuple.size() == 3)
return (Long)indexTuple.get(1);
else
throw new IOException("Invalid index record with size " + indexTuple.size());
}
/**
* Extracts the offset into the data file from the index tuple.
*/
public long getOffset(Tuple indexTuple) throws IOException {
if (indexTuple.size() == 3)
return (Long)indexTuple.get(2);
else
throw new IOException("Invalid index record with size " + indexTuple.size());
}
/**
* Reads the next index from the index file (or null if EOF) and extracts
* the index fields.
*/
public Tuple ReadIndex() throws IOException {
if (this.indexIn.getPos() < this.offsetToFooter) {
indexTuple = (Tuple)DataReaderWriter.readDatum(this.indexIn);
if (indexTuple != null) {
this.lastIndexKeyTuple = this.getIndexKeyTuple(indexTuple);
this.numberOfTuples = this.getIndexKeyTupleCount(indexTuple);
}
return indexTuple;
}
return null;
}
/**
* Scans the index looking for a given key.
* @return the matching index tuple OR the last index tuple
* greater than the requested key if no match is found.
*/
public Tuple ScanIndex(Tuple keys) throws IOException {
if (lastIndexKeyTuple != null && keys.compareTo(this.lastIndexKeyTuple) <= 0) {
return indexTuple;
}
/* Scan the index looking for given key */
while ((indexTuple = this.ReadIndex()) != null) {
if (keys.compareTo(this.lastIndexKeyTuple) > 0)
continue;
else
break;
}
return indexTuple;
}
/**
* stores the list of record indices that identify keys.
*/
private int[] offsetsToIndexKeys = null;
/**
* offset in bytes to the start of the footer of the index.
*/
private long offsetToFooter = -1;
/**
* output stream when writing the index.
*/
FSDataOutputStream indexOut;
/**
* input stream when reading the index.
*/
FSDataInputStream indexIn;
/**
* Tuple factory to create index tuples
*/
private TupleFactory tupleFactory = TupleFactory.getInstance();
/**
* Index key tuple of the form
* ((Tuple of index keys), count of tuples with index keys, offset to first tuple with index keys)
*/
private Tuple indexTuple = tupleFactory.newTuple(3);
/**
* "Smallest" index key tuple seen
*/
private Tuple minIndexKeyTuple = null;
/**
* "Biggest" index key tuple seen
*/
private Tuple maxIndexKeyTuple = null;
/**
* Last seen index key tuple
*/
private Tuple lastIndexKeyTuple = null;
/**
* Number of tuples seen for a index key
*/
private long numberOfTuples = 0;
/**
* The index file.
*/
private FileStatus indexFile;
}
/**
* Internal InputFormat class
*/
public static class IndexedStorageInputFormat extends PigTextInputFormat {
@Override
public RecordReader<LongWritable, Text> createRecordReader(InputSplit split, TaskAttemptContext context) {
IndexManager im = null;
try {
FileSystem fs = FileSystem.get(context.getConfiguration());
Path indexFile = IndexManager.getIndexFileName(((FileSplit)split).getPath());
im = new IndexManager(fs.getFileStatus(indexFile));
im.openIndexFile(fs);
im.ReadIndexHeader();
im.ReadIndexFooter();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new IndexedStorageRecordReader(im);
}
@Override
public boolean isSplitable(JobContext context, Path filename) {
return false;
}
/**
* Internal RecordReader class
*/
public static class IndexedStorageRecordReader extends RecordReader<LongWritable, Text> {
private long start;
private long pos;
private long end;
private IndexedStorageLineReader in;
private int maxLineLength;
private LongWritable key = null;
private Text value = null;
private IndexManager indexManager = null;
@Override
public String toString() {
return indexManager.minIndexKeyTuple + "|" + indexManager.lastIndexKeyTuple + "|" + indexManager.maxIndexKeyTuple;
}
public IndexedStorageRecordReader(IndexManager im) {
this.indexManager = im;
}
/**
* Class to compare record readers using underlying indexes
*
*/
public static class IndexedStorageRecordReaderComparator implements Comparator<IndexedStorageRecordReader> {
@Override
public int compare(IndexedStorageRecordReader o1, IndexedStorageRecordReader o2) {
Tuple t1 = (o1.indexManager.lastIndexKeyTuple == null) ? o1.indexManager.minIndexKeyTuple : o1.indexManager.lastIndexKeyTuple;
Tuple t2 = (o2.indexManager.lastIndexKeyTuple == null) ? o2.indexManager.minIndexKeyTuple : o2.indexManager.lastIndexKeyTuple;
return t1.compareTo(t2);
}
}
public static class IndexedStorageLineReader {
private static final int DEFAULT_BUFFER_SIZE = 64 * 1024;
private int bufferSize = DEFAULT_BUFFER_SIZE;
private InputStream in;
private byte[] buffer;
// the number of bytes of real data in the buffer
private int bufferLength = 0;
// the current position in the buffer
private int bufferPosn = 0;
private long bufferOffset = 0;
private static final byte CR = '\r';
private static final byte LF = '\n';
/**
* Create a line reader that reads from the given stream using the
* default buffer-size (64k).
* @param in The input stream
* @throws IOException
*/
public IndexedStorageLineReader(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
/**
* Create a line reader that reads from the given stream using the
* given buffer-size.
* @param in The input stream
* @param bufferSize Size of the read buffer
* @throws IOException
*/
public IndexedStorageLineReader(InputStream in, int bufferSize) {
if( !(in instanceof Seekable) || !(in instanceof PositionedReadable) ) {
throw new IllegalArgumentException(
"In is not an instance of Seekable or PositionedReadable");
}
this.in = in;
this.bufferSize = bufferSize;
this.buffer = new byte[this.bufferSize];
}
/**
* Create a line reader that reads from the given stream using the
* <code>io.file.buffer.size</code> specified in the given
* <code>Configuration</code>.
* @param in input stream
* @param conf configuration
* @throws IOException
*/
public IndexedStorageLineReader(InputStream in, Configuration conf) throws IOException {
this(in, conf.getInt("io.file.buffer.size", DEFAULT_BUFFER_SIZE));
}
/**
* Close the underlying stream.
* @throws IOException
*/
public void close() throws IOException {
in.close();
}
/**
* Read one line from the InputStream into the given Text. A line
* can be terminated by one of the following: '\n' (LF) , '\r' (CR),
* or '\r\n' (CR+LF). EOF also terminates an otherwise unterminated
* line.
*
* @param str the object to store the given line (without newline)
* @param maxLineLength the maximum number of bytes to store into str;
* the rest of the line is silently discarded.
* @param maxBytesToConsume the maximum number of bytes to consume
* in this call. This is only a hint, because if the line cross
* this threshold, we allow it to happen. It can overshoot
* potentially by as much as one buffer length.
*
* @return the number of bytes read including the (longest) newline
* found.
*
* @throws IOException if the underlying stream throws
*/
public int readLine(Text str, int maxLineLength,
int maxBytesToConsume) throws IOException {
/* We're reading data from in, but the head of the stream may be
* already buffered in buffer, so we have several cases:
* 1. No newline characters are in the buffer, so we need to copy
* everything and read another buffer from the stream.
* 2. An unambiguously terminated line is in buffer, so we just
* copy to str.
* 3. Ambiguously terminated line is in buffer, i.e. buffer ends
* in CR. In this case we copy everything up to CR to str, but
* we also need to see what follows CR: if it's LF, then we
* need consume LF as well, so next call to readLine will read
* from after that.
* We use a flag prevCharCR to signal if previous character was CR
* and, if it happens to be at the end of the buffer, delay
* consuming it until we have a chance to look at the char that
* follows.
*/
str.clear();
int txtLength = 0; //tracks str.getLength(), as an optimization
int newlineLength = 0; //length of terminating newline
boolean prevCharCR = false; //true of prev char was CR
long bytesConsumed = 0;
do {
int startPosn = bufferPosn; //starting from where we left off the last time
if (bufferPosn >= bufferLength) {
startPosn = bufferPosn = 0;
if (prevCharCR)
++bytesConsumed; //account for CR from previous read
bufferOffset = ((Seekable)in).getPos();
bufferLength = in.read(buffer);
if (bufferLength <= 0)
break; // EOF
}
for (; bufferPosn < bufferLength; ++bufferPosn) { //search for newline
if (buffer[bufferPosn] == LF) {
newlineLength = (prevCharCR) ? 2 : 1;
++bufferPosn; // at next invocation proceed from following byte
break;
}
if (prevCharCR) { //CR + notLF, we are at notLF
newlineLength = 1;
break;
}
prevCharCR = (buffer[bufferPosn] == CR);
}
int readLength = bufferPosn - startPosn;
if (prevCharCR && newlineLength == 0)
--readLength; //CR at the end of the buffer
bytesConsumed += readLength;
int appendLength = readLength - newlineLength;
if (appendLength > maxLineLength - txtLength) {
appendLength = maxLineLength - txtLength;
}
if (appendLength > 0) {
str.append(buffer, startPosn, appendLength);
txtLength += appendLength;
}
} while (newlineLength == 0 && bytesConsumed < maxBytesToConsume);
if (bytesConsumed > (long)Integer.MAX_VALUE)
throw new IOException("Too many bytes before newline: " + bytesConsumed);
return (int)bytesConsumed;
}
/**
* Read from the InputStream into the given Text.
* @param str the object to store the given line
* @param maxLineLength the maximum number of bytes to store into str.
* @return the number of bytes read including the newline
* @throws IOException if the underlying stream throws
*/
public int readLine(Text str, int maxLineLength) throws IOException {
return readLine(str, maxLineLength, Integer.MAX_VALUE);
}
/**
* Read from the InputStream into the given Text.
* @param str the object to store the given line
* @return the number of bytes read including the newline
* @throws IOException if the underlying stream throws
*/
public int readLine(Text str) throws IOException {
return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* If given offset is within the buffer, adjust the buffer position to read from
* otherwise seek to the given offset from start of the file.
* @param offset
* @throws IOException
*/
public void seek(long offset) throws IOException {
if ((offset >= bufferOffset) && (offset < (bufferOffset + bufferLength)))
bufferPosn = (int) (offset - bufferOffset);
else {
bufferPosn = bufferLength;
((Seekable)in).seek(offset);
}
}
}
@Override
public void initialize(InputSplit genericSplit, TaskAttemptContext context)
throws IOException, InterruptedException {
FileSplit split = (FileSplit) genericSplit;
Configuration job = context.getConfiguration();
this.maxLineLength = job.getInt(MRConfiguration.LINERECORDREADER_MAXLENGTH, Integer.MAX_VALUE);
start = split.getStart();
end = start + split.getLength();
final Path file = split.getPath();
FileSystem fs = file.getFileSystem(job);
FSDataInputStream fileIn = fs.open(split.getPath());
boolean skipFirstLine = false;
if (start != 0) {
skipFirstLine = true;
--start;
fileIn.seek(start);
}
in = new IndexedStorageLineReader(fileIn, job);
if (skipFirstLine) {
start += in.readLine(new Text(), 0, (int)Math.min((long)Integer.MAX_VALUE, end - start));
}
this.pos = start;
}
public void seek(long offset) throws IOException {
in.seek(offset);
pos = offset;
}
/**
* Scan the index for given key and seek to appropriate offset in the data
* @param keys to look for
* @return true if the given key was found, false otherwise
* @throws IOException
*/
public boolean seekNear(Tuple keys) throws IOException {
boolean ret = false;
Tuple indexTuple = this.indexManager.ScanIndex(keys);
if (indexTuple != null) {
long offset = this.indexManager.getOffset(indexTuple) ;
in.seek(offset);
if (keys.compareTo(this.indexManager.getIndexKeyTuple(indexTuple)) == 0) {
ret = true;
}
}
return ret;
}
@Override
public boolean nextKeyValue() throws IOException,
InterruptedException {
if (key == null) {
key = new LongWritable();
}
key.set(pos);
if (value == null) {
value = new Text();
}
int newSize = 0;
while (pos < end) {
newSize = in.readLine(value, maxLineLength,
Math.max((int)Math.min(Integer.MAX_VALUE, end-pos),
maxLineLength));
if (newSize == 0) {
break;
}
pos += newSize;
if (newSize < maxLineLength) {
break;
}
}
if (newSize == 0) {
key = null;
value = null;
return false;
} else {
return true;
}
}
@Override
public LongWritable getCurrentKey() throws IOException,
InterruptedException {
return key;
}
@Override
public Text getCurrentValue() throws IOException,
InterruptedException {
return value;
}
@Override
public float getProgress() throws IOException, InterruptedException {
if (start == end) {
return 0.0f;
} else {
return Math.min(1.0f, (pos - start) / (float)(end - start));
}
}
@Override
public void close() throws IOException {
if (in != null) {
in.close();
}
}
}
}
/**
* List of record readers.
*/
protected IndexedStorageRecordReader[] readers = null;
/**
* Index into the the list of readers to the current reader.
* Readers before this index have been fully scanned for keys.
*/
protected int currentReaderIndexStart = 0;
/**
* Delimiter to use between fields
*/
protected byte fieldDelimiter = '\t';
/**
* Offsets to index keys in tuple
*/
final protected int[] offsetsToIndexKeys;
/**
* Comparator used to compare key tuples.
*/
protected Comparator<IndexedStorageRecordReader> readerComparator = new IndexedStorageInputFormat.IndexedStorageRecordReader.IndexedStorageRecordReaderComparator();
}
| apache-2.0 |
kevinleturc/querydsl | querydsl-apt/src/test/java/com/querydsl/apt/domain/Enum3Test.java | 1424 | package com.querydsl.apt.domain;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import org.junit.Test;
public class Enum3Test {
public interface BaseInterface extends Serializable {
String getFoo();
String getBar();
}
public enum EnumImplementation implements SpecificInterface {
FOO,
BAR;
public EnumImplementation getValue() {
return this;
}
public String getFoo() {
return null;
}
public String getBar() {
return name();
}
}
public interface SpecificInterface extends BaseInterface {
EnumImplementation getValue();
}
@Entity
public static class Entity1 {
@Enumerated(javax.persistence.EnumType.STRING)
private EnumImplementation value;
public SpecificInterface getValue() {
return value;
}
}
@Entity
public static class Entity2 {
private EnumImplementation value;
@Enumerated(javax.persistence.EnumType.STRING)
public SpecificInterface getValue() {
return value;
}
}
@Entity
public static class Entity3 {
private EnumImplementation value;
public SpecificInterface getValue() {
return value;
}
}
@Test
public void test() {
}
}
| apache-2.0 |
Alvin-Lau/zstack | header/src/main/java/org/zstack/header/storage/backup/BakeImageMetadataMsg.java | 1269 | package org.zstack.header.storage.backup;
import org.zstack.header.image.ImageInventory;
import org.zstack.header.message.NeedReplyMessage;
/**
* Created by Mei Lei on 16-12-20.
*/
public class BakeImageMetadataMsg extends NeedReplyMessage implements BackupStorageMessage {
private String metadata;
private String backupStorageUuid;
private String operation;
private ImageInventory img;
private String poolName;
public String getPoolName() {
return poolName;
}
public void setPoolName(String poolName) {
this.poolName = poolName;
}
public ImageInventory getImg() {
return img;
}
public void setImg(ImageInventory img) {
this.img = img;
}
public String getMetadata() {
return metadata;
}
public void setMetadata(String metadata) {
this.metadata = metadata;
}
@Override
public String getBackupStorageUuid() {
return backupStorageUuid;
}
public void setBackupStorageUuid(String backupStorageUuid) {
this.backupStorageUuid = backupStorageUuid;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
}
| apache-2.0 |
tillrohrmann/flink | flink-connectors/flink-connector-jdbc/src/main/java/org/apache/flink/connector/jdbc/catalog/PostgresTablePath.java | 3269 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.connector.jdbc.catalog;
import org.apache.flink.util.StringUtils;
import java.util.Objects;
import static org.apache.flink.util.Preconditions.checkArgument;
/**
* Table path of PostgreSQL in Flink. Can be of formats "table_name" or "schema_name.table_name".
* When it's "table_name", the schema name defaults to "public".
*/
public class PostgresTablePath {
private static final String DEFAULT_POSTGRES_SCHEMA_NAME = "public";
private final String pgSchemaName;
private final String pgTableName;
public PostgresTablePath(String pgSchemaName, String pgTableName) {
checkArgument(!StringUtils.isNullOrWhitespaceOnly(pgSchemaName));
checkArgument(!StringUtils.isNullOrWhitespaceOnly(pgTableName));
this.pgSchemaName = pgSchemaName;
this.pgTableName = pgTableName;
}
public static PostgresTablePath fromFlinkTableName(String flinkTableName) {
if (flinkTableName.contains(".")) {
String[] path = flinkTableName.split("\\.");
checkArgument(
path != null && path.length == 2,
String.format(
"Table name '%s' is not valid. The parsed length is %d",
flinkTableName, path.length));
return new PostgresTablePath(path[0], path[1]);
} else {
return new PostgresTablePath(DEFAULT_POSTGRES_SCHEMA_NAME, flinkTableName);
}
}
public static String toFlinkTableName(String schema, String table) {
return new PostgresTablePath(schema, table).getFullPath();
}
public String getFullPath() {
return String.format("%s.%s", pgSchemaName, pgTableName);
}
public String getPgTableName() {
return pgTableName;
}
public String getPgSchemaName() {
return pgSchemaName;
}
@Override
public String toString() {
return getFullPath();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PostgresTablePath that = (PostgresTablePath) o;
return Objects.equals(pgSchemaName, that.pgSchemaName)
&& Objects.equals(pgTableName, that.pgTableName);
}
@Override
public int hashCode() {
return Objects.hash(pgSchemaName, pgTableName);
}
}
| apache-2.0 |
brycecurtis/phonegap-simjs | src/com/phonegap/file/NoModificationAllowedException.java | 174 | package com.phonegap.file;
public class NoModificationAllowedException extends Exception {
public NoModificationAllowedException(String message) {
super(message);
}
}
| mit |
xkollar/spacewalk | java/code/src/com/redhat/rhn/frontend/action/systems/audit/ScapDownloadAction.java | 2373 | /**
* Copyright (c) 2013--2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.action.systems.audit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;
import com.redhat.rhn.domain.audit.ScapFactory;
import com.redhat.rhn.domain.audit.XccdfTestResult;
import com.redhat.rhn.domain.server.Server;
import com.redhat.rhn.domain.user.User;
import com.redhat.rhn.frontend.struts.RequestContext;
import com.redhat.rhn.manager.audit.scap.file.ScapResultFile;
import com.redhat.rhn.manager.system.SystemManager;
/**
* ScapDownloadAction
*/
public class ScapDownloadAction extends DownloadAction {
@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
Logger log = Logger.getLogger(ScapDownloadAction.class);
RequestContext context = new RequestContext(request);
User user = context.getCurrentUser();
Long sid = context.getRequiredParam("sid");
Server server = SystemManager.lookupByIdAndUser(sid, user);
Long xid = context.getRequiredParam("xid");
XccdfTestResult testResult = ScapFactory.lookupTestResultByIdAndSid(xid,
server.getId());
String filename = context.getRequiredParamAsString("name");
ScapResultFile file = new ScapResultFile(testResult, filename);
log.debug("Serving " + file);
if (!file.getHTML()) {
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
}
return file;
}
}
| gpl-2.0 |
Zhengzl15/onos-securearp | core/api/src/main/java/org/onosproject/net/IndexedLambda.java | 1949 | /*
* Copyright 2015 Open Networking Laboratory
*
* 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.onosproject.net;
import com.google.common.base.MoreObjects;
/**
* Implementation of Lambda simply designated by an index number of wavelength.
*/
public class IndexedLambda implements Lambda {
private final long index;
/**
* Creates an instance representing the wavelength specified by the given index number.
* It is recommended to use {@link Lambda#indexedLambda(long)} unless you want to use the
* concrete type, IndexedLambda, directly.
*
* @param index index number of wavelength
*/
public IndexedLambda(long index) {
this.index = index;
}
/**
* Returns the index number of lambda.
*
* @return the index number of lambda
*/
public long index() {
return index;
}
@Override
public int hashCode() {
return Long.hashCode(index);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof IndexedLambda)) {
return false;
}
final IndexedLambda that = (IndexedLambda) obj;
return this.index == that.index;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("lambda", index)
.toString();
}
}
| apache-2.0 |
jialinsun/cat | cat-home/src/main/java/com/dianping/cat/report/page/database/GraphCreator.java | 4710 | package com.dianping.cat.report.page.database;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.dianping.cat.consumer.metric.model.entity.MetricReport;
import com.dianping.cat.helper.Chinese;
import com.dianping.cat.helper.TimeHelper;
import com.dianping.cat.report.alert.AlertInfo.AlertMetric;
import com.dianping.cat.report.alert.MetricType;
import com.dianping.cat.report.graph.LineChart;
import com.dianping.cat.report.graph.metric.AbstractGraphCreator;
public class GraphCreator extends AbstractGraphCreator {
private Map<String, LineChart> buildChartData(String productLine, final Map<String, double[]> datas, Date startDate,
Date endDate, final Map<String, double[]> dataWithOutFutures) {
Map<String, LineChart> charts = new LinkedHashMap<String, LineChart>();
List<AlertMetric> alertKeys = m_alertInfo.queryLastestAlarmKey(5);
int step = m_dataExtractor.getStep();
for (Entry<String, double[]> entry : dataWithOutFutures.entrySet()) {
String key = entry.getKey();
double[] value = entry.getValue();
LineChart lineChart = new LineChart();
buildLineChartTitle(alertKeys, lineChart, key);
lineChart.setStart(startDate);
lineChart.setSize(value.length);
lineChart.setUnit("Value/秒");
lineChart.setMinYlable(lineChart.queryMinYlable(value));
lineChart.setStep(step * TimeHelper.ONE_MINUTE);
Map<Long, Double> all = convertToMap(datas.get(key), startDate, 1);
Map<Long, Double> current = convertToMap(dataWithOutFutures.get(key), startDate, step);
addLastMinuteData(current, all, m_lastMinute, endDate);
lineChart.add(Chinese.CURRENT_VALUE, current);
charts.put(key, lineChart);
}
return charts;
}
public Map<String, LineChart> buildChartsByProductLine(String group, String productLine, Date startDate, Date endDate) {
Map<String, double[]> oldCurrentValues = prepareAllData(group, productLine, startDate, endDate);
Map<String, double[]> allCurrentValues = m_dataExtractor.extract(oldCurrentValues);
Map<String, double[]> dataWithOutFutures = removeFutureData(endDate, allCurrentValues);
return buildChartData(productLine, oldCurrentValues, startDate, endDate, dataWithOutFutures);
}
private Map<String, double[]> buildGraphData(MetricReport metricReport) {
Map<String, double[]> datas = m_pruductDataFetcher.buildGraphData(metricReport);
Map<String, double[]> values = new LinkedHashMap<String, double[]>();
for (Entry<String, double[]> entry : datas.entrySet()) {
String key = entry.getKey();
if (key.endsWith(MetricType.SUM.name())) {
putKey(datas, values, key);
}
}
return values;
}
private void buildLineChartTitle(List<AlertMetric> alertKeys, LineChart chart, String key) {
int index = key.lastIndexOf(":");
String type = key.substring(index + 1);
String des = queryMetricItemDes(type);
String[] strs = key.split(":");
String title = strs[2] + des;
chart.setTitle(title);
chart.setHtmlTitle(title);
chart.setId(key);
}
private Map<String, double[]> prepareAllData(String group, String productLine, Date startDate, Date endDate) {
long start = startDate.getTime(), end = endDate.getTime();
int totalSize = (int) ((end - start) / TimeHelper.ONE_MINUTE);
Map<String, double[]> oldCurrentValues = new LinkedHashMap<String, double[]>();
int index = 0;
for (; start < end; start += TimeHelper.ONE_HOUR) {
Map<String, double[]> currentValues = queryMetricValueByDate(group, productLine, start);
mergeMap(oldCurrentValues, currentValues, totalSize, index);
index++;
}
return oldCurrentValues;
}
private String queryMetricItemDes(String type) {
String des = "";
if (MetricType.AVG.name().equals(type)) {
des = Chinese.Suffix_AVG;
} else if (MetricType.SUM.name().equals(type)) {
des = Chinese.Suffix_SUM;
} else if (MetricType.COUNT.name().equals(type)) {
des = Chinese.Suffix_COUNT;
}
return des;
}
private Map<String, double[]> queryMetricValueByDate(String group, String productLine, long start) {
MetricReport metricReport = m_metricReportService.queryMetricReport(productLine, new Date(start));
List<String> keys = DatabaseGroup.KEY_GROUPS.get(group);
DatabaseReportFilter filter = new DatabaseReportFilter(keys);
filter.visitMetricReport(metricReport);
metricReport = filter.getReport();
Map<String, double[]> currentValues = buildGraphData(metricReport);
double sum = 0;
for (Entry<String, double[]> entry : currentValues.entrySet()) {
double[] value = entry.getValue();
int length = value.length;
for (int i = 0; i < length; i++) {
sum = sum + value[i];
}
}
return currentValues;
}
}
| apache-2.0 |
siosio/intellij-community | platform/platform-impl/src/com/intellij/openapi/editor/actions/AddRectangularSelectionOnMouseDragAction.java | 1104 | /*
* 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.openapi.editor.actions;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import org.jetbrains.annotations.NotNull;
public class AddRectangularSelectionOnMouseDragAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
// actual logic is implemented in EditorImpl
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(false);
}
}
| apache-2.0 |
GlenRSmith/elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/audit/AuditTrailService.java | 15654 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.security.audit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.xpack.core.security.authc.Authentication;
import org.elasticsearch.xpack.core.security.authc.AuthenticationToken;
import org.elasticsearch.xpack.core.security.authz.AuthorizationEngine.AuthorizationInfo;
import org.elasticsearch.xpack.security.Security;
import org.elasticsearch.xpack.security.transport.filter.SecurityIpFilterRule;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class AuditTrailService {
private static final Logger logger = LogManager.getLogger(AuditTrailService.class);
private static final AuditTrail NOOP_AUDIT_TRAIL = new NoopAuditTrail();
private final CompositeAuditTrail compositeAuditTrail;
private final XPackLicenseState licenseState;
private final Duration minLogPeriod = Duration.ofMinutes(30);
protected AtomicReference<Instant> nextLogInstantAtomic = new AtomicReference<>(Instant.EPOCH);
public AuditTrailService(List<AuditTrail> auditTrails, XPackLicenseState licenseState) {
this.compositeAuditTrail = new CompositeAuditTrail(Collections.unmodifiableList(auditTrails));
this.licenseState = licenseState;
}
public AuditTrail get() {
if (compositeAuditTrail.isEmpty() == false) {
if (Security.AUDITING_FEATURE.check(licenseState)) {
return compositeAuditTrail;
} else {
maybeLogAuditingDisabled();
return NOOP_AUDIT_TRAIL;
}
} else {
return NOOP_AUDIT_TRAIL;
}
}
// TODO: this method only exists for access to LoggingAuditTrail in a Node for testing.
// DO NOT USE IT, IT WILL BE REMOVED IN THE FUTURE
public List<AuditTrail> getAuditTrails() {
return compositeAuditTrail.auditTrails;
}
private void maybeLogAuditingDisabled() {
Instant nowInstant = Instant.now();
Instant nextLogInstant = nextLogInstantAtomic.get();
if (nextLogInstant.isBefore(nowInstant)) {
if (nextLogInstantAtomic.compareAndSet(nextLogInstant, nowInstant.plus(minLogPeriod))) {
logger.warn(
"Auditing logging is DISABLED because the currently active license ["
+ licenseState.getOperationMode()
+ "] does not permit it"
);
}
}
}
private static class NoopAuditTrail implements AuditTrail {
@Override
public String name() {
return "noop";
}
@Override
public void authenticationSuccess(String requestId, Authentication authentication, RestRequest request) {}
@Override
public void authenticationSuccess(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest
) {}
@Override
public void anonymousAccessDenied(String requestId, String action, TransportRequest transportRequest) {}
@Override
public void anonymousAccessDenied(String requestId, RestRequest request) {}
@Override
public void authenticationFailed(String requestId, RestRequest request) {}
@Override
public void authenticationFailed(String requestId, String action, TransportRequest transportRequest) {}
@Override
public void authenticationFailed(String requestId, AuthenticationToken token, String action, TransportRequest transportRequest) {}
@Override
public void authenticationFailed(String requestId, AuthenticationToken token, RestRequest request) {}
@Override
public void authenticationFailed(
String requestId,
String realm,
AuthenticationToken token,
String action,
TransportRequest transportRequest
) {}
@Override
public void authenticationFailed(String requestId, String realm, AuthenticationToken token, RestRequest request) {}
@Override
public void accessGranted(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest,
AuthorizationInfo authorizationInfo
) {}
@Override
public void accessDenied(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest,
AuthorizationInfo authorizationInfo
) {}
@Override
public void tamperedRequest(String requestId, RestRequest request) {}
@Override
public void tamperedRequest(String requestId, String action, TransportRequest transportRequest) {}
@Override
public void tamperedRequest(String requestId, Authentication authentication, String action, TransportRequest transportRequest) {}
@Override
public void connectionGranted(InetAddress inetAddress, String profile, SecurityIpFilterRule rule) {}
@Override
public void connectionDenied(InetAddress inetAddress, String profile, SecurityIpFilterRule rule) {}
@Override
public void runAsGranted(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest,
AuthorizationInfo authorizationInfo
) {}
@Override
public void runAsDenied(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest,
AuthorizationInfo authorizationInfo
) {}
@Override
public void runAsDenied(
String requestId,
Authentication authentication,
RestRequest request,
AuthorizationInfo authorizationInfo
) {}
@Override
public void explicitIndexAccessEvent(
String requestId,
AuditLevel eventType,
Authentication authentication,
String action,
String indices,
String requestName,
InetSocketAddress remoteAddress,
AuthorizationInfo authorizationInfo
) {}
@Override
public void coordinatingActionResponse(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest,
TransportResponse transportResponse
) {}
}
private static class CompositeAuditTrail implements AuditTrail {
private final List<AuditTrail> auditTrails;
private CompositeAuditTrail(List<AuditTrail> auditTrails) {
this.auditTrails = auditTrails;
}
boolean isEmpty() {
return auditTrails.isEmpty();
}
@Override
public String name() {
return "service";
}
@Override
public void authenticationSuccess(String requestId, Authentication authentication, RestRequest request) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationSuccess(requestId, authentication, request);
}
}
@Override
public void authenticationSuccess(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest
) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationSuccess(requestId, authentication, action, transportRequest);
}
}
@Override
public void anonymousAccessDenied(String requestId, String action, TransportRequest transportRequest) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.anonymousAccessDenied(requestId, action, transportRequest);
}
}
@Override
public void anonymousAccessDenied(String requestId, RestRequest request) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.anonymousAccessDenied(requestId, request);
}
}
@Override
public void authenticationFailed(String requestId, RestRequest request) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(requestId, request);
}
}
@Override
public void authenticationFailed(String requestId, String action, TransportRequest transportRequest) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(requestId, action, transportRequest);
}
}
@Override
public void authenticationFailed(String requestId, AuthenticationToken token, String action, TransportRequest transportRequest) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(requestId, token, action, transportRequest);
}
}
@Override
public void authenticationFailed(
String requestId,
String realm,
AuthenticationToken token,
String action,
TransportRequest transportRequest
) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(requestId, realm, token, action, transportRequest);
}
}
@Override
public void authenticationFailed(String requestId, AuthenticationToken token, RestRequest request) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(requestId, token, request);
}
}
@Override
public void authenticationFailed(String requestId, String realm, AuthenticationToken token, RestRequest request) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.authenticationFailed(requestId, realm, token, request);
}
}
@Override
public void accessGranted(
String requestId,
Authentication authentication,
String action,
TransportRequest msg,
AuthorizationInfo authorizationInfo
) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.accessGranted(requestId, authentication, action, msg, authorizationInfo);
}
}
@Override
public void accessDenied(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest,
AuthorizationInfo authorizationInfo
) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.accessDenied(requestId, authentication, action, transportRequest, authorizationInfo);
}
}
@Override
public void coordinatingActionResponse(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest,
TransportResponse transportResponse
) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.coordinatingActionResponse(requestId, authentication, action, transportRequest, transportResponse);
}
}
@Override
public void tamperedRequest(String requestId, RestRequest request) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.tamperedRequest(requestId, request);
}
}
@Override
public void tamperedRequest(String requestId, String action, TransportRequest transportRequest) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.tamperedRequest(requestId, action, transportRequest);
}
}
@Override
public void tamperedRequest(String requestId, Authentication authentication, String action, TransportRequest transportRequest) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.tamperedRequest(requestId, authentication, action, transportRequest);
}
}
@Override
public void connectionGranted(InetAddress inetAddress, String profile, SecurityIpFilterRule rule) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.connectionGranted(inetAddress, profile, rule);
}
}
@Override
public void connectionDenied(InetAddress inetAddress, String profile, SecurityIpFilterRule rule) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.connectionDenied(inetAddress, profile, rule);
}
}
@Override
public void runAsGranted(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest,
AuthorizationInfo authorizationInfo
) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.runAsGranted(requestId, authentication, action, transportRequest, authorizationInfo);
}
}
@Override
public void runAsDenied(
String requestId,
Authentication authentication,
String action,
TransportRequest transportRequest,
AuthorizationInfo authorizationInfo
) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.runAsDenied(requestId, authentication, action, transportRequest, authorizationInfo);
}
}
@Override
public void runAsDenied(String requestId, Authentication authentication, RestRequest request, AuthorizationInfo authorizationInfo) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.runAsDenied(requestId, authentication, request, authorizationInfo);
}
}
@Override
public void explicitIndexAccessEvent(
String requestId,
AuditLevel eventType,
Authentication authentication,
String action,
String indices,
String requestName,
InetSocketAddress remoteAddress,
AuthorizationInfo authorizationInfo
) {
for (AuditTrail auditTrail : auditTrails) {
auditTrail.explicitIndexAccessEvent(
requestId,
eventType,
authentication,
action,
indices,
requestName,
remoteAddress,
authorizationInfo
);
}
}
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/drools-master/drools-core/src/main/java/org/drools/core/time/impl/CompositeMaxDurationTimer.java | 5275 | /*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.time.impl;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.rule.ConditionalElement;
import org.drools.core.rule.Declaration;
import org.drools.core.spi.Activation;
import org.drools.core.spi.Tuple;
import org.drools.core.time.Trigger;
import org.kie.api.runtime.Calendars;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* While a rule might have multiple DurationTimers, due to LHS CEP rules, there can only ever
* be one timer attribute. Duration rules should be considered a priority over the one timer rule.
* So the Timer cannot fire, until the maximum duration has passed.
*/
public class CompositeMaxDurationTimer extends BaseTimer
implements
Timer {
private static final long serialVersionUID = -2531364489959820962L;
private List<DurationTimer> durations;
private Timer timer;
public CompositeMaxDurationTimer() {
}
public Declaration[][] getTimerDeclarations(Map<String, Declaration> outerDeclrs) {
return null;
}
public void addDurationTimer( final DurationTimer durationTimer ) {
if ( this.durations == null ) {
this.durations = new LinkedList<DurationTimer>();
}
this.durations.add( durationTimer );
}
public void setTimer( Timer timer ) {
this.timer = timer;
}
public Trigger createTrigger( Activation item, InternalWorkingMemory wm ) {
long timestamp = wm.getTimerService().getCurrentTime();
String[] calendarNames = item.getRule().getCalendars();
Calendars calendars = wm.getCalendars();
return createTrigger( getMaxTimestamp(item.getTuple(), timestamp), calendarNames, calendars );
}
public Trigger createTrigger(long timestamp,
Tuple leftTuple,
DefaultJobHandle jh,
String[] calendarNames,
Calendars calendars,
Declaration[][] declrs,
InternalWorkingMemory wm) {
return createTrigger( getMaxTimestamp(leftTuple, timestamp), calendarNames, calendars );
}
public Trigger createTrigger( long timestamp, // current time
String[] calendarNames,
Calendars calendars ) {
if ( this.durations == null ) {
throw new IllegalStateException( "CompositeMaxDurationTimer cannot have no durations" );
}
Date maxDurationDate = new Date( timer != null ? getMaxDuration() + timestamp : timestamp );
return new CompositeMaxDurationTrigger( maxDurationDate,
timer != null ? timer.createTrigger( timestamp,
calendarNames,
calendars ) : null );
}
private long getMaxTimestamp(Tuple leftTuple, long timestamp) {
if (timer != null) {
return timestamp;
}
long result = 0;
for ( DurationTimer durationTimer : durations ) {
result = Math.max( result,
durationTimer.getDuration() + durationTimer.getEventTimestamp(leftTuple, timestamp) );
}
return result;
}
private long getMaxDuration() {
long result = 0;
for ( DurationTimer durationTimer : durations ) {
result = Math.max( result,
durationTimer.getDuration() );
}
return result;
}
@Override
public ConditionalElement clone() {
CompositeMaxDurationTimer clone = new CompositeMaxDurationTimer();
if ( durations != null && !durations.isEmpty() ) {
for ( DurationTimer timer : durations ) {
clone.addDurationTimer(timer);
}
}
if ( timer != null) {
clone.timer = timer;
}
return clone;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject( durations );
out.writeObject( timer );
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
durations = ( List<DurationTimer> ) in.readObject();
timer = ( Timer )in.readObject();
}
}
| mit |
DariusX/camel | core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedThrottler.java | 2519 | /*
* 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.management.mbean;
import org.apache.camel.CamelContext;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.api.management.mbean.ManagedThrottlerMBean;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.processor.Throttler;
import static org.apache.camel.builder.Builder.constant;
@ManagedResource(description = "Managed Throttler")
public class ManagedThrottler extends ManagedProcessor implements ManagedThrottlerMBean {
private final Throttler throttler;
public ManagedThrottler(CamelContext context, Throttler throttler, ProcessorDefinition<?> definition) {
super(context, throttler, definition);
this.throttler = throttler;
}
public Throttler getThrottler() {
return throttler;
}
@Override
public long getMaximumRequestsPerPeriod() {
return throttler.getCurrentMaximumRequestsPerPeriod();
}
@Override
public void setMaximumRequestsPerPeriod(long maximumRequestsPerPeriod) {
throttler.setMaximumRequestsPerPeriodExpression(constant(maximumRequestsPerPeriod));
}
@Override
public long getTimePeriodMillis() {
return throttler.getTimePeriodMillis();
}
@Override
public void setTimePeriodMillis(long timePeriodMillis) {
throttler.setTimePeriodMillis(timePeriodMillis);
}
@Override
public Boolean isAsyncDelayed() {
return throttler.isAsyncDelayed();
}
@Override
public Boolean isCallerRunsWhenRejected() {
return throttler.isCallerRunsWhenRejected();
}
@Override
public Boolean isRejectExecution() {
return throttler.isRejectExecution();
}
}
| apache-2.0 |
siosio/intellij-community | plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/Config.java | 4082 | /*
* Copyright 2002-2005 Sascha Weinreuter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.xpathView;
import com.intellij.openapi.editor.markup.TextAttributes;
import org.intellij.plugins.xpathView.search.SearchScope;
import java.awt.*;
/**
* Class that holds the plugin's configuration. All customizable settings are accessible via property getters/setters.
* The configuration itself can be acquired with {@code getConfig()} in {@link XPathAppComponent}.
*/
public class Config {
public boolean SHOW_IN_TOOLBAR = true;
public boolean SHOW_IN_MAIN_MENU = true;
public boolean OPEN_NEW_TAB = false;
public boolean HIGHLIGHT_RESULTS = true;
public boolean SHOW_USAGE_VIEW = false;
public SearchScope SEARCH_SCOPE = new SearchScope();
public boolean MATCH_RECURSIVELY = false;
private final TextAttributes attributes = new TextAttributes(null, new Color(255, 213, 120), null, null, Font.PLAIN);
private final TextAttributes contextAttributes = new TextAttributes(null, new Color(194, 255, 212), null, null, Font.PLAIN);
public boolean scrollToFirst = true;
public boolean bUseContextAtCursor = true;
public boolean bHighlightStartTagOnly = true;
public boolean bAddErrorStripe = true;
public boolean isScrollToFirst() {
return scrollToFirst;
}
public TextAttributes getAttributes() {
return attributes;
}
public TextAttributes getContextAttributes() {
return contextAttributes;
}
public void setScrollToFirst(boolean b) {
scrollToFirst = b;
}
public boolean isUseContextAtCursor() {
return bUseContextAtCursor;
}
public void setUseContextAtCursor(boolean b) {
bUseContextAtCursor = b;
}
public boolean isHighlightStartTagOnly() {
return bHighlightStartTagOnly;
}
public void setHighlightStartTagOnly(boolean b) {
bHighlightStartTagOnly = b;
}
public boolean isAddErrorStripe() {
return bAddErrorStripe;
}
public void setAddErrorStripe(boolean b) {
bAddErrorStripe = b;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Config config = (Config)o;
if (HIGHLIGHT_RESULTS != config.HIGHLIGHT_RESULTS) return false;
if (OPEN_NEW_TAB != config.OPEN_NEW_TAB) return false;
if (SHOW_IN_MAIN_MENU != config.SHOW_IN_MAIN_MENU) return false;
if (SHOW_IN_TOOLBAR != config.SHOW_IN_TOOLBAR) return false;
if (SHOW_USAGE_VIEW != config.SHOW_USAGE_VIEW) return false;
if (bAddErrorStripe != config.bAddErrorStripe) return false;
if (bHighlightStartTagOnly != config.bHighlightStartTagOnly) return false;
if (bUseContextAtCursor != config.bUseContextAtCursor) return false;
if (scrollToFirst != config.scrollToFirst) return false;
if (!attributes.equals(config.attributes)) return false;
return contextAttributes.equals(config.contextAttributes);
}
public int hashCode() {
int result = (SHOW_IN_TOOLBAR ? 1 : 0);
result = 29 * result + (SHOW_IN_MAIN_MENU ? 1 : 0);
result = 29 * result + (OPEN_NEW_TAB ? 1 : 0);
result = 29 * result + (HIGHLIGHT_RESULTS ? 1 : 0);
result = 29 * result + (SHOW_USAGE_VIEW ? 1 : 0);
result = 29 * result + attributes.hashCode();
result = 29 * result + contextAttributes.hashCode();
result = 29 * result + (scrollToFirst ? 1 : 0);
result = 29 * result + (bUseContextAtCursor ? 1 : 0);
result = 29 * result + (bHighlightStartTagOnly ? 1 : 0);
result = 29 * result + (bAddErrorStripe ? 1 : 0);
return result;
}
}
| apache-2.0 |
maxkondr/onos-porta | core/api/src/main/java/org/onosproject/store/service/ConsistentMapException.java | 1357 | /*
* Copyright 2015 Open Networking Laboratory
*
* 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.onosproject.store.service;
/**
* Top level exception for ConsistentMap failures.
*/
@SuppressWarnings("serial")
public class ConsistentMapException extends StorageException {
public ConsistentMapException() {
}
public ConsistentMapException(Throwable t) {
super(t);
}
/**
* ConsistentMap operation timeout.
*/
public static class Timeout extends ConsistentMapException {
}
/**
* ConsistentMap update conflicts with an in flight transaction.
*/
public static class ConcurrentModification extends ConsistentMapException {
}
/**
* ConsistentMap operation interrupted.
*/
public static class Interrupted extends ConsistentMapException {
}
}
| apache-2.0 |
mawanjin/guqi | src/main/java/com/thinkgem/jeesite/modules/act/service/ActModelService.java | 6842 | /**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.act.service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ModelQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
/**
* 流程模型相关Controller
* @author ThinkGem
* @version 2013-11-03
*/
@Service
@Transactional(readOnly = true)
public class ActModelService extends BaseService {
@Autowired
private RepositoryService repositoryService;
/**
* 流程模型列表
*/
public Page<org.activiti.engine.repository.Model> modelList(Page<org.activiti.engine.repository.Model> page, String category) {
ModelQuery modelQuery = repositoryService.createModelQuery().latestVersion().orderByLastUpdateTime().desc();
if (StringUtils.isNotEmpty(category)){
modelQuery.modelCategory(category);
}
page.setCount(modelQuery.count());
page.setList(modelQuery.listPage(page.getFirstResult(), page.getMaxResults()));
return page;
}
/**
* 创建模型
* @throws UnsupportedEncodingException
*/
@Transactional(readOnly = false)
public org.activiti.engine.repository.Model create(String name, String key, String description, String category) throws UnsupportedEncodingException {
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode editorNode = objectMapper.createObjectNode();
editorNode.put("id", "canvas");
editorNode.put("resourceId", "canvas");
ObjectNode stencilSetNode = objectMapper.createObjectNode();
stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
editorNode.put("stencilset", stencilSetNode);
org.activiti.engine.repository.Model modelData = repositoryService.newModel();
description = StringUtils.defaultString(description);
modelData.setKey(StringUtils.defaultString(key));
modelData.setName(name);
modelData.setCategory(category);
modelData.setVersion(Integer.parseInt(String.valueOf(repositoryService.createModelQuery().modelKey(modelData.getKey()).count()+1)));
ObjectNode modelObjectNode = objectMapper.createObjectNode();
modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, modelData.getVersion());
modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
modelData.setMetaInfo(modelObjectNode.toString());
repositoryService.saveModel(modelData);
repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
return modelData;
}
/**
* 根据Model部署流程
*/
@Transactional(readOnly = false)
public String deploy(String id) {
String message = "";
try {
org.activiti.engine.repository.Model modelData = repositoryService.getModel(id);
BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);
String processName = modelData.getName();
if (!StringUtils.endsWith(processName, ".bpmn20.xml")){
processName += ".bpmn20.xml";
}
// System.out.println("========="+processName+"============"+modelData.getName());
ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
Deployment deployment = repositoryService.createDeployment().name(modelData.getName())
.addInputStream(processName, in).deploy();
// .addString(processName, new String(bpmnBytes)).deploy();
// 设置流程分类
List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list();
for (ProcessDefinition processDefinition : list) {
repositoryService.setProcessDefinitionCategory(processDefinition.getId(), modelData.getCategory());
message = "部署成功,流程ID=" + processDefinition.getId();
}
if (list.size() == 0){
message = "部署失败,没有流程。";
}
} catch (Exception e) {
throw new ActivitiException("设计模型图不正确,检查模型正确性,模型ID="+id, e);
}
return message;
}
/**
* 导出model的xml文件
* @throws IOException
* @throws JsonProcessingException
*/
public void export(String id, HttpServletResponse response) {
try {
org.activiti.engine.repository.Model modelData = repositoryService.getModel(id);
BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);
ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
IOUtils.copy(in, response.getOutputStream());
String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
response.flushBuffer();
} catch (Exception e) {
throw new ActivitiException("导出model的xml文件失败,模型ID="+id, e);
}
}
/**
* 更新Model分类
*/
@Transactional(readOnly = false)
public void updateCategory(String id, String category) {
org.activiti.engine.repository.Model modelData = repositoryService.getModel(id);
modelData.setCategory(category);
repositoryService.saveModel(modelData);
}
/**
* 删除模型
* @param id
* @return
*/
@Transactional(readOnly = false)
public void delete(String id) {
repositoryService.deleteModel(id);
}
}
| apache-2.0 |
wenjixin/druid | integration-tests/src/main/java/io/druid/testing/ConfigFileConfigProvider.java | 3108 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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.druid.testing;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class ConfigFileConfigProvider implements IntegrationTestingConfigProvider
{
private String routerHost = "";
private String brokerHost = "";
private String coordinatorHost = "";
private String indexerHost = "";
private String middleManagerHost = "";
private String zookeeperHosts = "";
private Map<String, String> props = null;
@JsonCreator
ConfigFileConfigProvider(@JsonProperty("configFile") String configFile){
loadProperties(configFile);
}
private void loadProperties(String configFile)
{
ObjectMapper jsonMapper = new ObjectMapper();
try {
props = jsonMapper.readValue(
new File(configFile), new TypeReference<Map<String, String>>()
{
}
);
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
routerHost = props.get("router_host") + ":" + props.get("router_port");
brokerHost = props.get("broker_host") + ":" + props.get("broker_port");
coordinatorHost = props.get("coordinator_host") + ":" + props.get("coordinator_port");
indexerHost = props.get("indexer_host") + ":" + props.get("indexer_port");
middleManagerHost = props.get("middle_manager_host");
zookeeperHosts = props.get("zookeeper_hosts");
}
@Override
public IntegrationTestingConfig get()
{
return new IntegrationTestingConfig()
{
@Override
public String getCoordinatorHost()
{
return coordinatorHost;
}
@Override
public String getIndexerHost()
{
return indexerHost;
}
@Override
public String getRouterHost()
{
return routerHost;
}
@Override
public String getBrokerHost()
{
return brokerHost;
}
@Override
public String getMiddleManagerHost()
{
return middleManagerHost;
}
@Override
public String getZookeeperHosts()
{
return zookeeperHosts;
}
};
}
}
| apache-2.0 |
shirleyyoung0812/airpal | src/main/java/com/airbnb/airpal/sql/beans/JobUsageCountRow.java | 1071 | package com.airbnb.airpal.sql.beans;
import com.airbnb.airpal.presto.Table;
import lombok.Data;
import org.skife.jdbi.v2.FoldController;
import org.skife.jdbi.v2.Folder3;
import org.skife.jdbi.v2.StatementContext;
import java.sql.SQLException;
import java.util.Map;
@Data
public class JobUsageCountRow
{
private long count;
private String connectorId;
private String schema;
private String table;
public Table toTable()
{
return new Table(getConnectorId(), getSchema(), getTable());
}
public static class CountFolder implements Folder3<Map<Table, Long>, JobUsageCountRow>
{
@Override
public Map<Table, Long> fold(Map<Table, Long> accumulator, JobUsageCountRow rs, FoldController control, StatementContext ctx)
throws SQLException
{
Table table = rs.toTable();
long currentCount = accumulator.containsKey(table) ? accumulator.get(table) : 0;
accumulator.put(table, currentCount + rs.getCount());
return accumulator;
}
}
}
| apache-2.0 |
allotria/intellij-community | platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/lineIndent/FormatterBasedLineIndentProvider.java | 1956 | /*
* Copyright 2000-2016 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.source.codeStyle.lineIndent;
import com.intellij.formatting.FormattingMode;
import com.intellij.lang.Language;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.lineIndent.LineIndentProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Formatter-based line indent provider which calculates indent using formatting model.
*/
public class FormatterBasedLineIndentProvider implements LineIndentProvider {
@Nullable
@Override
public String getLineIndent(@NotNull Project project, @NotNull Editor editor, Language language, int offset) {
Document document = editor.getDocument();
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
documentManager.commitDocument(document);
PsiFile file = documentManager.getPsiFile(document);
if (file == null) return "";
return CodeStyleManager.getInstance(project).getLineIndent(file, offset, FormattingMode.ADJUST_INDENT_ON_ENTER);
}
@Override
public boolean isSuitableFor(@Nullable Language language) {
return true;
}
}
| apache-2.0 |
PhaedrusTheGreek/elasticsearch | core/src/main/java/org/elasticsearch/common/util/CancellableThreads.java | 5460 | /*
* 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.common.util;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* A utility class for multi threaded operation that needs to be cancellable via interrupts. Every cancellable operation should be
* executed via {@link #execute(Interruptable)}, which will capture the executing thread and make sure it is interrupted in the case
* cancellation.
*/
public class CancellableThreads {
private final Set<Thread> threads = new HashSet<>();
private boolean cancelled = false;
private String reason;
public synchronized boolean isCancelled() {
return cancelled;
}
/** call this will throw an exception if operation was cancelled. Override {@link #onCancel(String, java.lang.Throwable)} for custom failure logic */
public synchronized void checkForCancel() {
if (isCancelled()) {
onCancel(reason, null);
}
}
/**
* called if {@link #checkForCancel()} was invoked after the operation was cancelled.
* the default implementation always throws an {@link ExecutionCancelledException}, suppressing
* any other exception that occurred before cancellation
*
* @param reason reason for failure supplied by the caller of {@link #cancel}
* @param suppressedException any error that was encountered during the execution before the operation was cancelled.
*/
protected void onCancel(String reason, @Nullable Throwable suppressedException) {
RuntimeException e = new ExecutionCancelledException("operation was cancelled reason [" + reason + "]");
if (suppressedException != null) {
e.addSuppressed(suppressedException);
}
throw e;
}
private synchronized boolean add() {
checkForCancel();
threads.add(Thread.currentThread());
// capture and clean the interrupted thread before we start, so we can identify
// our own interrupt. we do so under lock so we know we don't clear our own.
return Thread.interrupted();
}
/**
* run the Interruptable, capturing the executing thread. Concurrent calls to {@link #cancel(String)} will interrupt this thread
* causing the call to prematurely return.
*
* @param interruptable code to run
*/
public void execute(Interruptable interruptable) {
boolean wasInterrupted = add();
RuntimeException throwable = null;
try {
interruptable.run();
} catch (InterruptedException e) {
// assume this is us and ignore
} catch (RuntimeException t) {
throwable = t;
} finally {
remove();
}
// we are now out of threads collection so we can't be interrupted any more by this class
// restore old flag and see if we need to fail
if (wasInterrupted) {
Thread.currentThread().interrupt();
} else {
// clear the flag interrupted flag as we are checking for failure..
Thread.interrupted();
}
synchronized (this) {
if (isCancelled()) {
onCancel(reason, throwable);
} else if (throwable != null) {
// if we're not canceling, we throw the original exception
throw throwable;
}
}
}
private synchronized void remove() {
threads.remove(Thread.currentThread());
}
/** cancel all current running operations. Future calls to {@link #checkForCancel()} will be failed with the given reason */
public synchronized void cancel(String reason) {
if (cancelled) {
// we were already cancelled, make sure we don't interrupt threads twice
// this is important in order to make sure that we don't mark
// Thread.interrupted without handling it
return;
}
cancelled = true;
this.reason = reason;
for (Thread thread : threads) {
thread.interrupt();
}
threads.clear();
}
public interface Interruptable {
void run() throws InterruptedException;
}
public static class ExecutionCancelledException extends ElasticsearchException {
public ExecutionCancelledException(String msg) {
super(msg);
}
public ExecutionCancelledException(StreamInput in) throws IOException {
super(in);
}
}
}
| apache-2.0 |
robin13/elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/node/stats/NodesStatsRequest.java | 6417 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.admin.cluster.node.stats;
import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags;
import org.elasticsearch.action.support.nodes.BaseNodesRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.tasks.CancellableTask;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.tasks.TaskId;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* A request to get node (cluster) level stats.
*/
public class NodesStatsRequest extends BaseNodesRequest<NodesStatsRequest> {
private CommonStatsFlags indices = new CommonStatsFlags();
private final Set<String> requestedMetrics = new HashSet<>();
public NodesStatsRequest() {
super((String[]) null);
}
public NodesStatsRequest(StreamInput in) throws IOException {
super(in);
indices = new CommonStatsFlags(in);
requestedMetrics.clear();
requestedMetrics.addAll(in.readStringList());
}
/**
* Get stats from nodes based on the nodes ids specified. If none are passed, stats
* for all nodes will be returned.
*/
public NodesStatsRequest(String... nodesIds) {
super(nodesIds);
}
/**
* Sets all the request flags.
*/
public NodesStatsRequest all() {
this.indices.all();
this.requestedMetrics.addAll(Metric.allMetrics());
return this;
}
/**
* Clears all the request flags.
*/
public NodesStatsRequest clear() {
this.indices.clear();
this.requestedMetrics.clear();
return this;
}
/**
* Get indices. Handles separately from other metrics because it may or
* may not have submetrics.
* @return flags indicating which indices stats to return
*/
public CommonStatsFlags indices() {
return indices;
}
/**
* Set indices. Handles separately from other metrics because it may or
* may not involve submetrics.
* @param indices flags indicating which indices stats to return
* @return This object, for request chaining.
*/
public NodesStatsRequest indices(CommonStatsFlags indices) {
this.indices = indices;
return this;
}
/**
* Should indices stats be returned.
*/
public NodesStatsRequest indices(boolean indices) {
if (indices) {
this.indices.all();
} else {
this.indices.clear();
}
return this;
}
/**
* Get the names of requested metrics, excluding indices, which are
* handled separately.
*/
public Set<String> requestedMetrics() {
return Set.copyOf(requestedMetrics);
}
/**
* Add metric
*/
public NodesStatsRequest addMetric(String metric) {
if (Metric.allMetrics().contains(metric) == false) {
throw new IllegalStateException("Used an illegal metric: " + metric);
}
requestedMetrics.add(metric);
return this;
}
/**
* Add an array of metric names
*/
public NodesStatsRequest addMetrics(String... metrics) {
// use sorted set for reliable ordering in error messages
SortedSet<String> metricsSet = new TreeSet<>(Set.of(metrics));
if (Metric.allMetrics().containsAll(metricsSet) == false) {
metricsSet.removeAll(Metric.allMetrics());
String plural = metricsSet.size() == 1 ? "" : "s";
throw new IllegalStateException("Used illegal metric" + plural + ": " + metricsSet);
}
requestedMetrics.addAll(metricsSet);
return this;
}
/**
* Remove metric
*/
public NodesStatsRequest removeMetric(String metric) {
if (Metric.allMetrics().contains(metric) == false) {
throw new IllegalStateException("Used an illegal metric: " + metric);
}
requestedMetrics.remove(metric);
return this;
}
/**
* Helper method for adding metrics during deserialization.
* @param includeMetric Whether or not to include a metric.
* @param metricName Name of the metric to add.
*/
private void optionallyAddMetric(boolean includeMetric, String metricName) {
if (includeMetric) {
requestedMetrics.add(metricName);
}
}
@Override
public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) {
return new CancellableTask(id, type, action, "", parentTaskId, headers);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
indices.writeTo(out);
out.writeStringArray(requestedMetrics.toArray(String[]::new));
}
/**
* An enumeration of the "core" sections of metrics that may be requested
* from the nodes stats endpoint. Eventually this list will be pluggable.
*/
public enum Metric {
OS("os"),
PROCESS("process"),
JVM("jvm"),
THREAD_POOL("thread_pool"),
FS("fs"),
TRANSPORT("transport"),
HTTP("http"),
BREAKER("breaker"),
SCRIPT("script"),
DISCOVERY("discovery"),
INGEST("ingest"),
ADAPTIVE_SELECTION("adaptive_selection"),
SCRIPT_CACHE("script_cache"),
INDEXING_PRESSURE("indexing_pressure"),;
private String metricName;
Metric(String name) {
this.metricName = name;
}
public String metricName() {
return this.metricName;
}
boolean containedIn(Set<String> metricNames) {
return metricNames.contains(this.metricName());
}
static Set<String> allMetrics() {
return Arrays.stream(values()).map(Metric::metricName).collect(Collectors.toSet());
}
}
}
| apache-2.0 |