repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
rudolfbono/NAIM | src/main/java/org/encog/ensemble/ml/mlp/factory/MultiLayerPerceptronFactory.java | 2197 | /*
* Encog(tm) Core v3.3 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2014 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.ensemble.ml.mlp.factory;
import java.util.Collection;
import org.encog.engine.network.activation.ActivationFunction;
import org.encog.ensemble.EnsembleMLMethodFactory;
import org.encog.ml.MLMethod;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.layers.BasicLayer;
public class MultiLayerPerceptronFactory implements EnsembleMLMethodFactory {
Collection<Integer> layers;
ActivationFunction activation;
public void setParameters(Collection<Integer> layers, ActivationFunction activation){
this.layers=layers;
this.activation=activation;
}
@Override
public MLMethod createML(int inputs, int outputs) {
BasicNetwork network = new BasicNetwork();
network.addLayer(new BasicLayer(activation,false,inputs)); //(inputs));
for (Integer layerSize: layers)
network.addLayer(new BasicLayer(activation,true,layerSize));
network.addLayer(new BasicLayer(activation,true,outputs));
network.getStructure().finalizeStructure();
network.reset();
return network;
}
@Override
public String getLabel() {
String ret = "mlp{";
for (int i=0; i < layers.size() - 1; i++)
ret = ret + layers.toArray()[i] + ",";
return ret + layers.toArray()[layers.size() - 1] + "}";
}
@Override
public void reInit(MLMethod ml) {
((BasicNetwork) ml).reset();
}
}
| gpl-3.0 |
yugecin/opsu | src/itdelatrisu/opsu/video/FFmpeg.java | 5296 | /*
* opsu! - an open-source osu! client
* Copyright (C) 2014-2017 Jeffrey Han
*
* opsu! 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.
*
* opsu! 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 opsu!. If not, see <http://www.gnu.org/licenses/>.
*/
package itdelatrisu.opsu.video;
import itdelatrisu.opsu.Utils;
import itdelatrisu.opsu.options.Options;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import craterstudio.io.Streams;
import craterstudio.streams.NullOutputStream;
import craterstudio.text.RegexUtil;
import craterstudio.text.TextValues;
import net.indiespot.media.impl.Extractor;
import net.indiespot.media.impl.VideoMetadata;
/**
* FFmpeg utilities.
*
* @author Riven (base)
*/
public class FFmpeg {
/** The default file name of the FFmpeg shared library. */
public static final String DEFAULT_NATIVE_FILENAME = getDefaultNativeFilename();
/** The FFmpeg shared library location. */
private static File FFMPEG_PATH = null;
/** Whether to print FFmpeg errors to stderr. */
private static final boolean FFMPEG_VERBOSE = false;
/**
* Returns the expected file name of the FFmpeg shared library, based on
* the current operating system and architecture.
*/
private static String getDefaultNativeFilename() {
String resourceName = "ffmpeg";
if (Extractor.isMac)
resourceName += "-mac";
else {
resourceName += Extractor.is64bit ? "64" : "32";
if (Extractor.isWindows)
resourceName += ".exe";
}
return resourceName;
}
/** Returns the FFmpeg shared library location. */
private static File getNativeLocation() {
File customLocation = Options.getFFmpegLocation();
if (customLocation != null && customLocation.isFile())
return customLocation;
else
return FFMPEG_PATH;
}
/** Sets the directory in which to look for the FFmpeg shared library. */
public static void setNativeDir(File dir) {
FFMPEG_PATH = new File(dir, DEFAULT_NATIVE_FILENAME);
}
/** Returns whether the FFmpeg shared library could be found. */
public static boolean exists() {
File location = getNativeLocation();
return location != null && location.isFile();
}
/**
* Extracts the metadata for a video file.
* @param srcMovieFile the source video file
*/
public static VideoMetadata extractMetadata(File srcMovieFile) throws IOException {
File ffmpegFile = getNativeLocation();
Utils.setExecutable(ffmpegFile);
Process process = new ProcessBuilder().command(
ffmpegFile.getAbsolutePath(),
"-i", srcMovieFile.getAbsolutePath(),
"-f", "null"
).start();
Streams.asynchronousTransfer(process.getInputStream(), System.out, true, false);
int width = -1, height = -1;
float framerate = -1;
try {
InputStream stderr = process.getErrorStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stderr));
for (String line; (line = br.readLine()) != null;) {
// Look for:
// " Stream #0:0: Video: vp6f, yuv420p, 320x240, 314 kb/s, 30 tbr, 1k tbn, 1k tbc"
// ----------------------------------------------------------^
if (line.trim().startsWith("Stream #") && line.contains("Video:")) {
// Parse framerate
// Note: Can contain 'k' suffix (*1000), see dump.c#print_fps.
// https://www.ffmpeg.org/doxygen/3.1/dump_8c_source.html#l00119
String[] fr = RegexUtil.find(line, Pattern.compile("\\s(\\d+(\\.\\d+)?)(k?)\\stbr,"), 1, 3);
framerate = Float.parseFloat(fr[0]);
if (!fr[1].isEmpty())
framerate *= 1000f;
// Parse width/height
int[] wh = TextValues.parseInts(RegexUtil.find(line, Pattern.compile("\\s(\\d+)x(\\d+)[\\s,]"), 1, 2));
width = wh[0];
height = wh[1];
}
}
if (framerate == -1)
throw new IOException("Failed to find framerate of video.");
return new VideoMetadata(width, height, framerate);
} finally {
Streams.safeClose(process);
}
}
/**
* Returns an RGB24 video stream.
* @param srcMovieFile the source video file
* @param msec the time offset (in milliseconds)
*/
public static InputStream extractVideoAsRGB24(File srcMovieFile, int msec) throws IOException {
File ffmpegFile = getNativeLocation();
Utils.setExecutable(ffmpegFile);
return streamData(new ProcessBuilder().command(
ffmpegFile.getAbsolutePath(),
"-ss", String.format("%d.%d", msec / 1000, msec % 1000),
"-i", srcMovieFile.getAbsolutePath(),
"-f", "rawvideo",
"-pix_fmt", "rgb24",
"-"
));
}
/** Returns a stream. */
private static InputStream streamData(ProcessBuilder pb) throws IOException {
Process process = pb.start();
Streams.asynchronousTransfer(process.getErrorStream(), FFMPEG_VERBOSE ? System.err : new NullOutputStream(), true, false);
return process.getInputStream();
}
}
| gpl-3.0 |
DanVanAtta/triplea | game-core/src/test/java/games/strategy/triplea/delegate/power/calculator/MainOffenseCombatValueTest.java | 13586 | package games.strategy.triplea.delegate.power.calculator;
import static games.strategy.triplea.Constants.TERRITORYEFFECT_ATTACHMENT_NAME;
import static games.strategy.triplea.Constants.UNIT_ATTACHMENT_NAME;
import static games.strategy.triplea.delegate.battle.steps.MockGameData.givenGameData;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import games.strategy.engine.data.GameData;
import games.strategy.engine.data.GamePlayer;
import games.strategy.engine.data.TerritoryEffect;
import games.strategy.engine.data.Unit;
import games.strategy.engine.data.UnitType;
import games.strategy.engine.data.gameparser.GameParseException;
import games.strategy.triplea.attachments.TerritoryEffectAttachment;
import games.strategy.triplea.attachments.UnitAttachment;
import games.strategy.triplea.attachments.UnitSupportAttachment;
import games.strategy.triplea.delegate.battle.BattleState;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.triplea.java.collections.IntegerMap;
class MainOffenseCombatValueTest {
@Nested
class MainOffenseRollTest {
@Test
void calculatesValue() throws GameParseException {
final GamePlayer player = mock(GamePlayer.class);
final GameData gameData = givenGameData().build();
final UnitType unitType = new UnitType("test", gameData);
final UnitAttachment unitAttachment = new UnitAttachment("attachment", unitType, gameData);
unitType.addAttachment(UNIT_ATTACHMENT_NAME, unitAttachment);
final Unit unit = unitType.createTemp(1, player).get(0);
unit.getUnitAttachment().setAttackRolls(3);
final Unit supportUnit = unitType.createTemp(1, player).get(0);
final UnitSupportAttachment unitSupportAttachment =
givenUnitOffenseSupportAttachment(gameData, unitType, "test")
.setBonus(2)
.setPlayers(List.of(player))
.setUnitType(Set.of(unitType));
final AvailableSupports friendlySupport =
AvailableSupports.getSupport(
new SupportCalculator(
List.of(supportUnit),
Set.of(unitSupportAttachment),
BattleState.Side.OFFENSE,
true));
final Unit enemySupportUnit = unitType.createTemp(1, player).get(0);
final UnitSupportAttachment enemyUnitSupportAttachment =
givenUnitDefenseSupportAttachment(gameData, unitType, "test2")
.setBonus(-1)
.setPlayers(List.of(player))
.setUnitType(Set.of(unitType));
final AvailableSupports enemySupport =
AvailableSupports.getSupport(
new SupportCalculator(
List.of(enemySupportUnit),
Set.of(enemyUnitSupportAttachment),
BattleState.Side.DEFENSE,
false));
final MainOffenseCombatValue.MainOffenseRoll roll =
new MainOffenseCombatValue.MainOffenseRoll(friendlySupport, enemySupport);
assertThat(
"Roll starts at 3, friendly adds 2, enemy removes 1: total 4",
roll.getRoll(unit).getValue(),
is(4));
}
UnitSupportAttachment givenUnitOffenseSupportAttachment(
final GameData gameData, final UnitType unitType, final String name)
throws GameParseException {
return new UnitSupportAttachment("rule" + name, unitType, gameData)
.setBonus(1)
.setBonusType("bonus" + name)
.setDice("roll")
.setNumber(1)
.setSide("offence")
.setFaction("allied");
}
UnitSupportAttachment givenUnitDefenseSupportAttachment(
final GameData gameData, final UnitType unitType, final String name)
throws GameParseException {
return new UnitSupportAttachment("rule" + name, unitType, gameData)
.setBonus(1)
.setBonusType("bonus" + name)
.setDice("roll")
.setNumber(1)
.setSide("defence")
.setFaction("enemy");
}
@Test
void calculatesSupportUsed() throws GameParseException {
final GamePlayer player = mock(GamePlayer.class);
final GameData gameData = givenGameData().build();
final UnitType unitType = new UnitType("test", gameData);
final UnitAttachment unitAttachment = new UnitAttachment("attachment", unitType, gameData);
unitType.addAttachment(UNIT_ATTACHMENT_NAME, unitAttachment);
final Unit unit = unitType.createTemp(1, player).get(0);
unit.getUnitAttachment().setAttackRolls(3);
final Unit supportUnit = unitType.createTemp(1, player).get(0);
final UnitSupportAttachment unitSupportAttachment =
givenUnitOffenseSupportAttachment(gameData, unitType, "test")
.setBonus(2)
.setPlayers(List.of(player))
.setUnitType(Set.of(unitType));
final AvailableSupports friendlySupport =
AvailableSupports.getSupport(
new SupportCalculator(
List.of(supportUnit),
Set.of(unitSupportAttachment),
BattleState.Side.OFFENSE,
true));
final Unit enemySupportUnit = unitType.createTemp(1, player).get(0);
final UnitSupportAttachment enemyUnitSupportAttachment =
givenUnitDefenseSupportAttachment(gameData, unitType, "test2")
.setBonus(-1)
.setPlayers(List.of(player))
.setUnitType(Set.of(unitType));
final AvailableSupports enemySupport =
AvailableSupports.getSupport(
new SupportCalculator(
List.of(enemySupportUnit),
Set.of(enemyUnitSupportAttachment),
BattleState.Side.DEFENSE,
false));
final MainOffenseCombatValue.MainOffenseRoll roll =
new MainOffenseCombatValue.MainOffenseRoll(friendlySupport, enemySupport);
roll.getRoll(unit);
assertThat(
"Friendly gave 2 and enemy gave -1",
roll.getSupportGiven(),
is(
Map.of(
supportUnit,
IntegerMap.of(Map.of(unit, 2)),
enemySupportUnit,
IntegerMap.of(Map.of(unit, -1)))));
}
}
@Nested
class MainOffenseStrengthTest {
@Test
void calculatesValue() throws GameParseException {
final GamePlayer player = mock(GamePlayer.class);
final GameData gameData = givenGameData().withDiceSides(6).build();
final UnitType unitType = new UnitType("test", gameData);
final UnitAttachment unitAttachment = new UnitAttachment("attachment", unitType, gameData);
unitType.addAttachment(UNIT_ATTACHMENT_NAME, unitAttachment);
final Unit unit = unitType.createTemp(1, player).get(0);
unit.getUnitAttachment().setAttack(3);
final Unit supportUnit = unitType.createTemp(1, player).get(0);
final UnitSupportAttachment unitSupportAttachment =
givenUnitSupportAttachment(gameData, unitType, "test")
.setBonus(3)
.setPlayers(List.of(player))
.setUnitType(Set.of(unitType));
final AvailableSupports friendlySupport =
AvailableSupports.getSupport(
new SupportCalculator(
List.of(supportUnit),
Set.of(unitSupportAttachment),
BattleState.Side.OFFENSE,
true));
final Unit enemySupportUnit = unitType.createTemp(1, player).get(0);
final UnitSupportAttachment enemyUnitSupportAttachment =
givenUnitSupportAttachment(gameData, unitType, "test2")
.setBonus(-2)
.setPlayers(List.of(player))
.setUnitType(Set.of(unitType));
final AvailableSupports enemySupport =
AvailableSupports.getSupport(
new SupportCalculator(
List.of(enemySupportUnit),
Set.of(enemyUnitSupportAttachment),
BattleState.Side.OFFENSE,
true));
final TerritoryEffect territoryEffect = new TerritoryEffect("territoryEffect", gameData);
final TerritoryEffectAttachment territoryEffectAttachment =
new TerritoryEffectAttachment("territoryEffectAttachment", territoryEffect, gameData);
territoryEffect.addAttachment(TERRITORYEFFECT_ATTACHMENT_NAME, territoryEffectAttachment);
territoryEffectAttachment.setCombatOffenseEffect(new IntegerMap<>(Map.of(unit.getType(), 1)));
final MainOffenseCombatValue.MainOffenseStrength strength =
new MainOffenseCombatValue.MainOffenseStrength(
6, List.of(territoryEffect), friendlySupport, enemySupport);
assertThat(
"Strength starts at 3, friendly adds 3, enemy removes 2, territory adds 1: total 5",
strength.getStrength(unit).getValue(),
is(5));
}
UnitSupportAttachment givenUnitSupportAttachment(
final GameData gameData, final UnitType unitType, final String name)
throws GameParseException {
return new UnitSupportAttachment("rule" + name, unitType, gameData)
.setBonus(1)
.setBonusType("bonus" + name)
.setDice("strength")
.setNumber(1)
.setSide("offence")
.setFaction("allied");
}
@Test
void addsMarineBonusIfAmphibious() {
final GamePlayer player = mock(GamePlayer.class);
final GameData gameData = givenGameData().withDiceSides(6).build();
final UnitType unitType = new UnitType("test", gameData);
final UnitAttachment unitAttachment = new UnitAttachment("attachment", unitType, gameData);
unitType.addAttachment(UNIT_ATTACHMENT_NAME, unitAttachment);
final Unit unit = unitType.createTemp(1, player).get(0);
unit.setWasAmphibious(true).getUnitAttachment().setAttack(3).setIsMarine(1);
final MainOffenseCombatValue.MainOffenseStrength strength =
new MainOffenseCombatValue.MainOffenseStrength(
6, List.of(), AvailableSupports.EMPTY_RESULT, AvailableSupports.EMPTY_RESULT);
assertThat(
"Strength starts at 3, marine adds 1: total 4",
strength.getStrength(unit).getValue(),
is(4));
}
@Test
void ignoresMarineBonusIfNotAmphibious() {
final GamePlayer player = mock(GamePlayer.class);
final GameData gameData = givenGameData().withDiceSides(6).build();
final UnitType unitType = new UnitType("test", gameData);
final UnitAttachment unitAttachment = new UnitAttachment("attachment", unitType, gameData);
unitType.addAttachment(UNIT_ATTACHMENT_NAME, unitAttachment);
final Unit unit = unitType.createTemp(1, player).get(0);
unit.getUnitAttachment().setAttack(3).setIsMarine(1);
final MainOffenseCombatValue.MainOffenseStrength strength =
new MainOffenseCombatValue.MainOffenseStrength(
6, List.of(), AvailableSupports.EMPTY_RESULT, AvailableSupports.EMPTY_RESULT);
assertThat(
"Strength starts at 3 and marine is not added: total 3",
strength.getStrength(unit).getValue(),
is(3));
}
@Test
void calculatesSupportUsed() throws GameParseException {
final GamePlayer player = mock(GamePlayer.class);
final GameData gameData = givenGameData().withDiceSides(6).build();
final UnitType unitType = new UnitType("test", gameData);
final UnitAttachment unitAttachment = new UnitAttachment("attachment", unitType, gameData);
unitType.addAttachment(UNIT_ATTACHMENT_NAME, unitAttachment);
final Unit unit = unitType.createTemp(1, player).get(0);
unit.getUnitAttachment().setAttack(3);
final Unit supportUnit = unitType.createTemp(1, player).get(0);
final UnitSupportAttachment unitSupportAttachment =
givenUnitSupportAttachment(gameData, unitType, "test")
.setBonus(2)
.setPlayers(List.of(player))
.setUnitType(Set.of(unitType));
final AvailableSupports friendlySupport =
AvailableSupports.getSupport(
new SupportCalculator(
List.of(supportUnit),
Set.of(unitSupportAttachment),
BattleState.Side.OFFENSE,
true));
final Unit enemySupportUnit = unitType.createTemp(1, player).get(0);
final UnitSupportAttachment enemyUnitSupportAttachment =
givenUnitSupportAttachment(gameData, unitType, "test2")
.setBonus(-1)
.setPlayers(List.of(player))
.setUnitType(Set.of(unitType));
final AvailableSupports enemySupport =
AvailableSupports.getSupport(
new SupportCalculator(
List.of(enemySupportUnit),
Set.of(enemyUnitSupportAttachment),
BattleState.Side.OFFENSE,
true));
final MainOffenseCombatValue.MainOffenseStrength strength =
new MainOffenseCombatValue.MainOffenseStrength(
6, List.of(), friendlySupport, enemySupport);
strength.getStrength(unit);
assertThat(
"Friendly gave 2 and enemy gave -1",
strength.getSupportGiven(),
is(
Map.of(
supportUnit,
IntegerMap.of(Map.of(unit, 2)),
enemySupportUnit,
IntegerMap.of(Map.of(unit, -1)))));
}
}
}
| gpl-3.0 |
geowe/geowe-core | src/main/java/org/geowe/client/local/main/tool/spatial/geoprocess/GeoprocessValidator.java | 3168 | /*
* #%L
* GeoWE Project
* %%
* Copyright (C) 2015 - 2016 GeoWE.org
* %%
* This file is part of GeoWE.org.
*
* GeoWE 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.
*
* GeoWE 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 GeoWE. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.geowe.client.local.main.tool.spatial.geoprocess;
import javax.enterprise.context.ApplicationScoped;
import org.geowe.client.local.messages.UIMessages;
import org.geowe.client.local.model.vector.VectorLayer;
import org.geowe.client.local.ui.MessageDialogBuilder;
import org.gwtopenmaps.openlayers.client.feature.VectorFeature;
import com.google.inject.Inject;
/**
* Geoprocess validator representa al responsable de realizar las validaciones mínimas para poder llevar a cabo
* el análisis de las operaciones de geoprocesamiento. En función del tipo de geoproceso se realizará una validación
* parcial o total de los datos de entrada.
*
* @author jose@geowe.org
*
*/
@ApplicationScoped
public class GeoprocessValidator {
@Inject
private MessageDialogBuilder messageDialogBuilder;
private IInputGeoprocess inputGeoprocess;
public boolean validate(final IGeoprocess geoprocess) {
this.inputGeoprocess = geoprocess.getInputGeoprocess();
boolean isValid = true;
if (geoprocess.isBufferGeoprocess()) {
isValid = isPartiallyValid();
} else {
isValid = isCompletelyValid();
}
return isValid;
}
private boolean isPartiallyValid() {
boolean valid = true;
if (inputGeoprocess == null) {
messageDialogBuilder.createWarning(UIMessages.INSTANCE.fail(),
UIMessages.INSTANCE.noInputDataSpecified()).show();
valid = false;
} else {
valid = isValid(inputGeoprocess.getInputLayer());
}
return valid;
}
private boolean isCompletelyValid() {
boolean valid = false;
if (isPartiallyValid()) {
valid = isValid(inputGeoprocess.getOverlayLayer());
}
return valid;
}
public boolean isValid(final VectorLayer layer) {
boolean valid = true;
if (layer == null) {
messageDialogBuilder.createWarning(UIMessages.INSTANCE.fail(),
UIMessages.INSTANCE.noVectorLayerSpecify()).show();
valid = false;
} else if (isEmptyLayer(layer)) {
messageDialogBuilder.createWarning(UIMessages.INSTANCE.fail(),
UIMessages.INSTANCE.emptyVectorLayer()).show();
valid = false;
}
return valid;
}
private boolean isEmptyLayer(final VectorLayer layer) {
boolean empty = false;
final VectorFeature[] features = layer.getFeatures();
if(features == null || features != null && features.length == 0) {
empty = true;
}
return empty;
}
} | gpl-3.0 |
dacopan/PhotoWord | android/Aviary-SDK/src/com/aviary/android/feather/effects/StickersPanel.java | 45958 | package com.aviary.android.feather.effects;
import it.sephiroth.android.library.imagezoom.ImageViewTouchBase.DisplayType;
import it.sephiroth.android.library.widget.AdapterView.OnItemClickListener;
import it.sephiroth.android.library.widget.AdapterView.OnItemLongClickListener;
import it.sephiroth.android.library.widget.HListView;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import junit.framework.Assert;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.aviary.android.feather.AviaryMainController.FeatherContext;
import com.aviary.android.feather.R;
import com.aviary.android.feather.cds.AviaryCds;
import com.aviary.android.feather.cds.AviaryCds.PackType;
import com.aviary.android.feather.cds.AviaryCds.Size;
import com.aviary.android.feather.cds.CdsUtils;
import com.aviary.android.feather.cds.PacksItemsColumns;
import com.aviary.android.feather.cds.TrayColumns;
import com.aviary.android.feather.common.AviaryIntent;
import com.aviary.android.feather.common.utils.IOUtils;
import com.aviary.android.feather.common.utils.PackageManagerUtils;
import com.aviary.android.feather.effects.BordersPanel.ViewHolder;
import com.aviary.android.feather.effects.BordersPanel.ViewHolderExternal;
import com.aviary.android.feather.effects.SimpleStatusMachine.OnStatusChangeListener;
import com.aviary.android.feather.headless.moa.MoaActionFactory;
import com.aviary.android.feather.headless.moa.MoaActionList;
import com.aviary.android.feather.library.content.ToolEntry;
import com.aviary.android.feather.library.filters.StickerFilter;
import com.aviary.android.feather.library.graphics.drawable.FeatherDrawable;
import com.aviary.android.feather.library.graphics.drawable.StickerDrawable;
import com.aviary.android.feather.library.services.BadgeService;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.DragControllerService;
import com.aviary.android.feather.library.services.DragControllerService.DragListener;
import com.aviary.android.feather.library.services.DragControllerService.DragSource;
import com.aviary.android.feather.library.services.IAviaryController;
import com.aviary.android.feather.library.services.drag.DragView;
import com.aviary.android.feather.library.services.drag.DropTarget;
import com.aviary.android.feather.library.services.drag.DropTarget.DropTargetListener;
import com.aviary.android.feather.library.tracking.Tracker;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.MatrixUtils;
import com.aviary.android.feather.library.utils.UIConfiguration;
import com.aviary.android.feather.utils.PackIconCallable;
import com.aviary.android.feather.widget.DrawableHighlightView;
import com.aviary.android.feather.widget.DrawableHighlightView.OnDeleteClickListener;
import com.aviary.android.feather.widget.IAPDialogMain;
import com.aviary.android.feather.widget.IAPDialogMain.IAPUpdater;
import com.aviary.android.feather.widget.IAPDialogMain.OnCloseListener;
import com.aviary.android.feather.widget.ImageViewDrawableOverlay;
import com.squareup.picasso.Picasso;
public class StickersPanel extends AbstractContentPanel implements OnStatusChangeListener, OnItemClickListener, DragListener, DragSource, DropTargetListener,
OnLoadCompleteListener<Cursor> {
// TODO: implements tracking
private static final int STATUS_NULL = SimpleStatusMachine.INVALID_STATUS;
private static final int STATUS_PACKS = 1;
private static final int STATUS_STICKERS = 2;
/** panel's status */
private SimpleStatusMachine mStatus;
/** horizontal listview for stickers packs */
private HListView mListPacks;
/** horizontal listview for stickers items */
private HListView mListStickers;
/** view flipper for switching between lists */
private ViewFlipper mViewFlipper;
private Picasso mPicassoLib;
/** canvas used to draw stickers */
private Canvas mCanvas;
private int mPackCellWidth;
private int mStickerCellWidth;
/** installed plugins */
private List<String> mInstalledPackages;
/** required services */
private ConfigService mConfigService;
private DragControllerService mDragControllerService;
private BadgeService mBadgeService;
/** iap dialog for inline previews */
private IAPDialogMain mIapDialog;
private MoaActionList mActionList;
private StickerFilter mCurrentFilter;
private int mPackThumbSize;
private int mStickerThumbSize;
private boolean mFirstTimeRenderer = true;
protected CursorAdapter mAdapterPacks;
protected CursorAdapter mAdapterStickers;
protected CursorLoader mCursorLoaderPacks;
protected ContentObserver mContentObserver;
// for status_sticker
private StickerPackInfo mPackInfo;
@Override
public void onLoadComplete( Loader<Cursor> loader, Cursor cursor ) {
mLogger.info( "onLoadComplete: " + cursor + ", currentStatus: " + mStatus.getCurrentStatus() );
int firstValidIndex = -1;
int newStatus = STATUS_PACKS;
int index = 0;
int cursorSize = 0;
if ( null != cursor ) {
index = cursor.getPosition();
while ( cursor.moveToNext() ) {
int type = cursor.getInt( TrayColumns.TYPE_COLUMN_INDEX );
if ( type == TrayColumns.TYPE_PACK_INTERNAL ) {
firstValidIndex = cursor.getPosition();
break;
}
}
cursorSize = cursor.getCount();
cursor.moveToPosition( index );
}
if( firstValidIndex == 0 && cursorSize == 1 && null != cursor && mStatus.getCurrentStatus() != STATUS_STICKERS ) {
// we have only 1 installed pack and nothing else, so just
// display its content
index = cursor.getPosition();
if( cursor.moveToFirst() ) {
int id_index = cursor.getColumnIndex( TrayColumns._ID );
int identifier_index = cursor.getColumnIndex( TrayColumns.IDENTIFIER );
int type_index = cursor.getColumnIndex( TrayColumns.TYPE );
if( id_index > -1 && identifier_index > -1 && type_index > -1 ) {
int packType = cursor.getInt( type_index );
if( packType == StickerPacksAdapter.TYPE_DIVIDER ) {
mLogger.log( "one pack only, show it" );
mPackInfo = new StickerPackInfo( cursor.getLong( id_index ), cursor.getString( identifier_index ) );
newStatus = STATUS_STICKERS;
}
}
}
cursor.moveToPosition( index );
}
mStatus.setStatus( newStatus );
mAdapterPacks.changeCursor( cursor );
onStickersPackListUpdated( cursor, firstValidIndex );
// check optional messaging
long iapPackageId = -1;
if ( hasOptions() ) {
Bundle options = getOptions();
if ( options.containsKey( AviaryIntent.OptionBundle.SHOW_IAP_DIALOG ) ) {
iapPackageId = options.getLong( AviaryIntent.OptionBundle.SHOW_IAP_DIALOG );
}
// ok, we display the IAP dialog only the first time
options.remove( AviaryIntent.OptionBundle.SHOW_IAP_DIALOG );
// display the iap dialog
if ( iapPackageId > -1 ) {
IAPUpdater iapData = new IAPUpdater.Builder().setPackId( iapPackageId ).setPackType( PackType.STICKER ).build();
displayIAPDialog( iapData );
}
}
}
public StickersPanel ( IAviaryController context, ToolEntry entry ) {
super( context, entry );
}
@Override
public void onCreate( Bitmap bitmap, Bundle options ) {
super.onCreate( bitmap, options );
mStatus = new SimpleStatusMachine();
// init layout components
mListPacks = (HListView) getOptionView().findViewById( R.id.aviary_list_packs );
mListStickers = (HListView) getOptionView().findViewById( R.id.aviary_list_stickers );
mViewFlipper = (ViewFlipper) getOptionView().findViewById( R.id.aviary_flipper );
mImageView = (ImageViewDrawableOverlay) getContentView().findViewById( R.id.aviary_overlay );
// init services
mConfigService = getContext().getService( ConfigService.class );
mBadgeService = getContext().getService( BadgeService.class );
// setup the main imageview
( (ImageViewDrawableOverlay) mImageView ).setDisplayType( DisplayType.FIT_IF_BIGGER );
( (ImageViewDrawableOverlay) mImageView ).setForceSingleSelection( false );
( (ImageViewDrawableOverlay) mImageView ).setDropTargetListener( this );
( (ImageViewDrawableOverlay) mImageView ).setScaleWithContent( true );
// create the default action list
mActionList = MoaActionFactory.actionList();
mPicassoLib = Picasso.with( getContext().getBaseContext() );
// create the preview for the main imageview
createAndConfigurePreview();
DragControllerService dragger = getContext().getService( DragControllerService.class );
dragger.addDropTarget( (DropTarget) mImageView );
dragger.setMoveTarget( mImageView );
dragger.setDragListener( this );
setDragController( dragger );
}
@Override
public void onActivate() {
super.onActivate();
mImageView.setImageBitmap( mPreview, null, -1, UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
mPackCellWidth = mConfigService.getDimensionPixelSize( R.dimen.aviary_sticker_pack_width );
mPackThumbSize = mConfigService.getDimensionPixelSize( R.dimen.aviary_sticker_pack_image_width );
mStickerCellWidth = mConfigService.getDimensionPixelSize( R.dimen.aviary_sticker_single_item_width );
mStickerThumbSize = mConfigService.getDimensionPixelSize( R.dimen.aviary_sticker_single_item_image_width );
mInstalledPackages = Collections.synchronizedList( new ArrayList<String>() );
// register to status change
mStatus.setOnStatusChangeListener( this );
updateInstalledPacks( true );
getContentView().setVisibility( View.VISIBLE );
contentReady();
}
@Override
public boolean onBackPressed() {
mLogger.info( "onBackPressed" );
if ( null != mIapDialog ) {
if ( mIapDialog.onBackPressed() ) return true;
removeIapDialog();
return true;
}
// we're in the packs status
if ( mStatus.getCurrentStatus() == STATUS_PACKS ) {
if ( stickersOnScreen() ) {
askToLeaveWithoutApply();
return true;
}
return false;
}
// we're in the stickers status
if ( mStatus.getCurrentStatus() == STATUS_STICKERS ) {
int packsCount = 0;
if( null != mAdapterPacks ) {
packsCount = mAdapterPacks.getCount();
}
mLogger.log( "packsCount: %d", packsCount );
if( packsCount > 1 ) {
mStatus.setStatus( STATUS_PACKS );
return true;
} else {
if ( stickersOnScreen() ) {
askToLeaveWithoutApply();
return true;
}
return false;
}
}
return super.onBackPressed();
}
@Override
public boolean onCancel() {
mLogger.info( "onCancel" );
// if there's an active sticker on screen
// then ask if we really want to exit this panel
// and discard changes
if ( stickersOnScreen() ) {
askToLeaveWithoutApply();
return true;
}
return super.onCancel();
}
@Override
public void onDeactivate() {
super.onDeactivate();
// disable the drag controller
if ( null != getDragController() ) {
getDragController().deactivate();
getDragController().removeDropTarget( (DropTarget) mImageView );
getDragController().setDragListener( null );
}
setDragController( null );
if ( null != mAdapterPacks ) {
mAdapterPacks.changeCursor( null );
}
if ( null != mAdapterStickers ) {
mAdapterStickers.changeCursor( null );
}
mListPacks.setAdapter( null );
mListStickers.setAdapter( null );
// mPluginService.removeOnUpdateListener( this );
mStatus.setOnStatusChangeListener( null );
mListPacks.setOnItemClickListener( null );
mListStickers.setOnItemClickListener( null );
mListStickers.setOnItemLongClickListener( null );
removeIapDialog();
Context context = getContext().getBaseContext();
if( null != mContentObserver ) {
context.getContentResolver().unregisterContentObserver( mContentObserver );
}
if ( null != mCursorLoaderPacks ) {
mLogger.info( "stop load cursorloader..." );
mCursorLoaderPacks.unregisterListener( this );
mCursorLoaderPacks.stopLoading();
}
}
@Override
public void onDestroy() {
super.onDestroy();
( (ImageViewDrawableOverlay) mImageView ).clearOverlays();
mCurrentFilter = null;
mActionList = null;
mBadgeService = null;
if ( null != mCursorLoaderPacks ) {
mLogger.info( "disposing cursorloader..." );
mCursorLoaderPacks.abandon();
mCursorLoaderPacks.reset();
}
if ( null != mAdapterPacks ) {
IOUtils.closeSilently( mAdapterPacks.getCursor() );
}
if ( null != mAdapterStickers ) {
IOUtils.closeSilently( mAdapterStickers.getCursor() );
}
mAdapterPacks = null;
mAdapterStickers = null;
mCursorLoaderPacks = null;
}
@Override
protected void onDispose() {
super.onDispose();
if ( null != mInstalledPackages ) {
mInstalledPackages.clear();
}
mCanvas = null;
}
@Override
protected void onGenerateResult() {
onApplyCurrent();
super.onGenerateResult( mActionList );
}
@Override
public void onConfigurationChanged( Configuration newConfig, Configuration oldConfig ) {
mLogger.info( "onConfigurationChanged: " + newConfig );
if ( mIapDialog != null ) {
mIapDialog.onConfigurationChanged( newConfig );
}
super.onConfigurationChanged( newConfig, oldConfig );
}
@Override
protected View generateContentView( LayoutInflater inflater ) {
return inflater.inflate( R.layout.aviary_content_stickers, null );
}
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.aviary_panel_stickers, null );
}
// /////////////////////////
// OnStatusChangeListener //
// /////////////////////////
@Override
public void OnStatusChanged( int oldStatus, int newStatus ) {
mLogger.info( "OnStatusChange: " + oldStatus + " >> " + newStatus );
switch ( newStatus ) {
case STATUS_PACKS:
// deactivate listeners for the stickers list
mListStickers.setOnItemClickListener( null );
mListStickers.setOnItemLongClickListener( null );
if( mViewFlipper.getDisplayedChild() != 1 ) {
mViewFlipper.setDisplayedChild( 1 );
}
if ( oldStatus == STATUS_NULL ) {
// NULL
} else if ( oldStatus == STATUS_STICKERS ) {
restoreToolbarTitle();
if ( getDragController() != null ) {
getDragController().deactivate();
}
if ( null != mAdapterStickers ) {
mAdapterStickers.changeCursor( null );
}
}
break;
case STATUS_STICKERS:
loadStickers();
if( mViewFlipper.getDisplayedChild() != 2 ) {
mViewFlipper.setDisplayedChild( 2 );
}
if ( getDragController() != null ) {
getDragController().activate();
}
break;
default:
mLogger.error( "unmanaged status change: " + oldStatus + " >> " + newStatus );
break;
}
}
@Override
public void OnStatusUpdated( int status ) {
}
// //////////////////////
// OnItemClickListener //
// //////////////////////
@Override
public void onItemClick( it.sephiroth.android.library.widget.AdapterView<?> parent, View view, int position, long id ) {
mLogger.info( "onItemClick: " + position );
if ( !isActive() ) return;
if ( mStatus.getCurrentStatus() == STATUS_PACKS ) {
ViewHolder holder = (ViewHolder) view.getTag();
if ( null != holder ) {
// get more
if ( holder.type == StickerPacksAdapter.TYPE_LEFT_GETMORE || holder.type == StickerPacksAdapter.TYPE_RIGHT_GETMORE ) {
if ( holder.type == StickerPacksAdapter.TYPE_LEFT_GETMORE ) {
Tracker.recordTag( "(Stickers) LeftSupplyShop: Clicked" );
} else if ( holder.type == StickerPacksAdapter.TYPE_RIGHT_GETMORE ) {
Tracker.recordTag( "(Stickers) RightSupplyShop: Clicked" );
}
IAPUpdater iapData = new IAPUpdater.Builder().setPackType( PackType.STICKER ).build();
displayIAPDialog( iapData );
// external
} else if ( holder.type == StickerPacksAdapter.TYPE_EXTERNAL ) {
ViewHolderExternal holder_ext = (ViewHolderExternal) holder;
if ( null != holder_ext ) {
holder_ext.badgeIcon.setVisibility( View.GONE );
holder_ext.externalIcon.setVisibility( View.VISIBLE );
}
IAPUpdater iapData = new IAPUpdater.Builder().setPackType( PackType.STICKER ).setPackId( holder.id ).build();
displayIAPDialog( iapData );
if ( position > 0 ) {
if ( mListPacks.getChildCount() > 0 ) {
int left = view.getLeft();
int right = view.getRight();
int center = ( ( right - left ) / 2 + left );
final int delta = mListPacks.getWidth() / 2 - center;
mListPacks.postDelayed( new Runnable() {
@Override
public void run() {
mListPacks.smoothScrollBy( -delta, 500 );
}
}, 300 );
}
}
} else if ( holder.type == StickerPacksAdapter.TYPE_DIVIDER ) {
removeIapDialog();
mPackInfo = new StickerPackInfo( holder.id, holder.identifier );
mStatus.setStatus( STATUS_STICKERS );
}
}
}
}
// ////////////////////////
// Drag and Drop methods //
// ////////////////////////
/**
* Starts the drag and drop operation
*
* @param parent
* - the parent list
* @param view
* - the current view clicked
* @param position
* - the position in the list
* @param id
* - the item id
* @param nativeClick
* - it's a native click
* @return
*/
private boolean startDrag( it.sephiroth.android.library.widget.AdapterView<?> parent, View view, int position, long id, boolean animate ) {
mLogger.info( "startDrag" );
if ( android.os.Build.VERSION.SDK_INT < 9 ) return false;
if ( parent == null || view == null || parent.getAdapter() == null ) {
return false;
}
if ( mStatus.getCurrentStatus() != STATUS_STICKERS ) return false;
if ( null != view ) {
View image = view.findViewById( R.id.image );
if ( null != image ) {
if ( null == parent.getAdapter() ) return false;
StickersAdapter adapter = (StickersAdapter) parent.getAdapter();
if ( null == adapter ) return false;
final String identifier = adapter.getItemIdentifier( position );
final String contentPath = adapter.getContentPath();
if ( null == identifier || null == contentPath ) return false;
final String iconPath = contentPath + "/" + AviaryCds.getPackItemFilename( identifier, PackType.STICKER, Size.Small );
Bitmap bitmap;
try {
bitmap = new StickerThumbnailCallable( iconPath, mStickerThumbSize ).call();
int offsetx = Math.abs( image.getWidth() - bitmap.getWidth() ) / 2;
int offsety = Math.abs( image.getHeight() - bitmap.getHeight() ) / 2;
return getDragController().startDrag( image, bitmap, offsetx, offsety, StickersPanel.this, new StickerDragInfo( contentPath, identifier ),
DragControllerService.DRAG_ACTION_MOVE, animate );
} catch ( Exception e ) {
e.printStackTrace();
}
return getDragController().startDrag( image, StickersPanel.this, new StickerDragInfo( contentPath, identifier ),
DragControllerService.DRAG_ACTION_MOVE, animate );
}
}
return false;
}
@Override
public void setDragController( DragControllerService controller ) {
mDragControllerService = controller;
}
@Override
public DragControllerService getDragController() {
return mDragControllerService;
}
public void onDropCompleted( View arg0, boolean arg1 ) {}
@Override
public boolean onDragEnd() {
return false;
}
@Override
public void onDragStart( DragSource arg0, Object arg1, int arg2 ) {}
@Override
public boolean acceptDrop( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo ) {
return source == this;
}
@Override
public void onDrop( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo ) {
mLogger.info( "onDrop. source=" + source + ", dragInfo=" + dragInfo );
if ( !isActive() ) return;
if ( dragInfo != null && dragInfo instanceof StickerDragInfo ) {
StickerDragInfo info = (StickerDragInfo) dragInfo;
onApplyCurrent();
float scaleFactor = dragView.getScaleFactor();
float w = dragView.getWidth();
float h = dragView.getHeight();
int width = (int) ( w / scaleFactor );
int height = (int) ( h / scaleFactor );
int targetX = (int) ( x - xOffset );
int targetY = (int) ( y - yOffset );
RectF rect = new RectF( targetX, targetY, targetX + width, targetY + height );
addSticker( info.contentPath, info.identifier, rect );
}
}
// /////////////////////////
// Stickers panel methods //
// /////////////////////////
/**
* Ask to leave without apply changes.
*/
void askToLeaveWithoutApply() {
new AlertDialog.Builder( getContext().getBaseContext() ).setTitle( R.string.feather_attention ).setMessage( R.string.feather_tool_leave_question )
.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
getContext().cancel();
}
} ).setNegativeButton( android.R.string.no, null ).show();
}
/**
* Initialize the preview bitmap and canvas.
*/
private void createAndConfigurePreview() {
if ( mPreview != null && !mPreview.isRecycled() ) {
mPreview.recycle();
mPreview = null;
}
mPreview = BitmapUtils.copy( mBitmap, Bitmap.Config.ARGB_8888 );
mCanvas = new Canvas( mPreview );
}
protected void updateInstalledPacks( boolean firstTime ) {
mLogger.info( "updateInstalledPacks: " + firstTime );
// display the loader
if ( mViewFlipper.getDisplayedChild() != 0 ) {
mViewFlipper.setDisplayedChild( 0 );
}
mAdapterPacks = createPacksAdapter( getContext().getBaseContext(), null );
mListPacks.setAdapter( mAdapterPacks );
Context context = getContext().getBaseContext();
if ( null == mCursorLoaderPacks ) {
final String uri = String.format( Locale.US, "packTray/%d/%d/%d/%s", 3, 0, 0, AviaryCds.PACKTYPE_STICKER );
Uri baseUri = PackageManagerUtils.getCDSProviderContentUri( context, uri );
mCursorLoaderPacks = new CursorLoader( context, baseUri, null, null, null, null );
mCursorLoaderPacks.registerListener( 1, this );
mContentObserver = new ContentObserver( new Handler() ) {
@Override
public void onChange( boolean selfChange ) {
mLogger.info( "mContentObserver::onChange" );
super.onChange( selfChange );
if ( isActive() && null != mCursorLoaderPacks && mCursorLoaderPacks.isStarted() ) {
mCursorLoaderPacks.onContentChanged();
}
}
};
context.getContentResolver().registerContentObserver( PackageManagerUtils.getCDSProviderContentUri( context, "packTray/" + AviaryCds.PACKTYPE_STICKER ), false,
mContentObserver );
}
mCursorLoaderPacks.startLoading();
mListPacks.setOnItemClickListener( this );
}
private StickerPacksAdapter createPacksAdapter( Context context, Cursor cursor ) {
return new StickerPacksAdapter( context, R.layout.aviary_sticker_item, R.layout.aviary_frame_item_external, R.layout.aviary_sticker_item_more, cursor );
}
private final void displayIAPDialog( IAPUpdater data ) {
if ( null != mIapDialog ) {
if ( mIapDialog.isValid() ) {
mIapDialog.update( data );
setApplyEnabled( false );
return;
} else {
mIapDialog.dismiss( false );
mIapDialog = null;
}
}
IAPDialogMain dialog = IAPDialogMain.create( (FeatherContext) getContext().getBaseContext(), data );
if ( dialog != null ) {
dialog.setOnCloseListener( new OnCloseListener() {
@Override
public void onClose() {
removeIapDialog();
}
} );
}
mIapDialog = dialog;
setApplyEnabled( false );
}
private boolean removeIapDialog() {
setApplyEnabled( true );
if ( null != mIapDialog ) {
mIapDialog.dismiss( true );
mIapDialog = null;
return true;
}
return false;
}
/**
* Loads the list of available stickers for the current selected pack
*/
protected void loadStickers() {
mLogger.info( "loadStickers" );
final Context context = getContext().getBaseContext();
if ( null == mPackInfo ) return;
// retrieve the pack content path
final String packContentPath = CdsUtils.getPackContentPath( context, mPackInfo.packId );
// acquire the items cursor
Cursor cursor = context.getContentResolver().query(
PackageManagerUtils.getCDSProviderContentUri( context, "pack/" + mPackInfo.packId + "/item/list" ),
new String[] { PacksItemsColumns._ID + " as _id", PacksItemsColumns._ID, PacksItemsColumns.PACK_ID, PacksItemsColumns.IDENTIFIER,
PacksItemsColumns.DISPLAY_NAME }, null, null, null );
if ( null == mAdapterStickers ) {
mAdapterStickers = new StickersAdapter( context, R.layout.aviary_sticker_item_single, cursor );
( (StickersAdapter) mAdapterStickers ).setContentPath( packContentPath );
mListStickers.setAdapter( mAdapterStickers );
} else {
( (StickersAdapter) mAdapterStickers ).setContentPath( packContentPath );
mAdapterStickers.changeCursor( cursor );
}
mListStickers.setOnItemClickListener( new OnItemClickListener() {
@Override
public void onItemClick( it.sephiroth.android.library.widget.AdapterView<?> parent, View view, int position, long id ) {
mLogger.info( "onItemClick: " + position );
StickersAdapter adapter = ( (StickersAdapter) parent.getAdapter() );
final Cursor cursor = (Cursor) adapter.getItem( position );
final String sticker = cursor.getString( cursor.getColumnIndex( PacksItemsColumns.IDENTIFIER ) );
removeIapDialog();
addSticker( adapter.getContentPath(), sticker, null );
}
} );
mListStickers.setOnItemLongClickListener( new OnItemLongClickListener() {
@Override
public boolean onItemLongClick( it.sephiroth.android.library.widget.AdapterView<?> parent, View view, int position, long id ) {
return startDrag( parent, view, position, id, false );
}
} );
}
private void addSticker( String contentPath, String identifier, RectF position ) {
mLogger.info( "addSticker: %s - %s", contentPath, identifier );
onApplyCurrent();
Assert.assertNotNull( mPackInfo );
Assert.assertNotNull( contentPath );
File file = new File( contentPath, AviaryCds.getPackItemFilename( identifier, PackType.STICKER, Size.Medium ) );
mLogger.log( "file: " + file.getAbsolutePath() );
if ( file.exists() ) {
StickerDrawable drawable = new StickerDrawable( getContext().getBaseContext().getResources(), file.getAbsolutePath(), identifier,
mPackInfo.packIdentifier );
drawable.setAntiAlias( true );
mCurrentFilter = new StickerFilter( contentPath, identifier );
mCurrentFilter.setSize( drawable.getBitmapWidth(), drawable.getBitmapHeight() );
Tracker.recordTag( identifier + ": Selected" );
addSticker( drawable, position );
} else {
mLogger.warn( "file does not exists" );
Toast.makeText( getContext().getBaseContext(), "Error loading the selected sticker", Toast.LENGTH_SHORT ).show();
}
}
private void addSticker( FeatherDrawable drawable, RectF positionRect ) {
mLogger.info( "addSticker: " + drawable + ", position: " + positionRect );
setIsChanged( true );
DrawableHighlightView hv = new DrawableHighlightView( mImageView, ( (ImageViewDrawableOverlay) mImageView ).getOverlayStyleId(), drawable );
hv.setOnDeleteClickListener( new OnDeleteClickListener() {
@Override
public void onDeleteClick() {
onClearCurrent( true );
}
} );
Matrix mImageMatrix = mImageView.getImageViewMatrix();
int cropWidth, cropHeight;
int x, y;
final int width = mImageView.getWidth();
final int height = mImageView.getHeight();
// width/height of the sticker
if ( positionRect != null ) {
cropWidth = (int) positionRect.width();
cropHeight = (int) positionRect.height();
} else {
cropWidth = (int) drawable.getCurrentWidth();
cropHeight = (int) drawable.getCurrentHeight();
}
final int cropSize = Math.max( cropWidth, cropHeight );
final int screenSize = Math.min( mImageView.getWidth(), mImageView.getHeight() );
if ( cropSize > screenSize ) {
float ratio;
float widthRatio = (float) mImageView.getWidth() / cropWidth;
float heightRatio = (float) mImageView.getHeight() / cropHeight;
if ( widthRatio < heightRatio ) {
ratio = widthRatio;
} else {
ratio = heightRatio;
}
cropWidth = (int) ( (float) cropWidth * ( ratio / 2 ) );
cropHeight = (int) ( (float) cropHeight * ( ratio / 2 ) );
if ( positionRect == null ) {
int w = mImageView.getWidth();
int h = mImageView.getHeight();
positionRect = new RectF( w / 2 - cropWidth / 2, h / 2 - cropHeight / 2, w / 2 + cropWidth / 2, h / 2 + cropHeight / 2 );
}
positionRect.inset( ( positionRect.width() - cropWidth ) / 2, ( positionRect.height() - cropHeight ) / 2 );
}
if ( positionRect != null ) {
x = (int) positionRect.left;
y = (int) positionRect.top;
} else {
x = ( width - cropWidth ) / 2;
y = ( height - cropHeight ) / 2;
}
Matrix matrix = new Matrix( mImageMatrix );
matrix.invert( matrix );
float[] pts = new float[] { x, y, x + cropWidth, y + cropHeight };
MatrixUtils.mapPoints( matrix, pts );
RectF cropRect = new RectF( pts[0], pts[1], pts[2], pts[3] );
Rect imageRect = new Rect( 0, 0, width, height );
// hv.setRotateAndScale( rotateAndResize );
hv.setup( getContext().getBaseContext(), mImageMatrix, imageRect, cropRect, false );
( (ImageViewDrawableOverlay) mImageView ).addHighlightView( hv );
( (ImageViewDrawableOverlay) mImageView ).setSelectedHighlightView( hv );
}
private void onApplyCurrent() {
mLogger.info( "onApplyCurrent" );
if ( !stickersOnScreen() ) return;
final DrawableHighlightView hv = ( (ImageViewDrawableOverlay) mImageView ).getHighlightViewAt( 0 );
if ( hv != null ) {
final StickerDrawable stickerDrawable = ( (StickerDrawable) hv.getContent() );
RectF cropRect = hv.getCropRectF();
Rect rect = new Rect( (int) cropRect.left, (int) cropRect.top, (int) cropRect.right, (int) cropRect.bottom );
Matrix rotateMatrix = hv.getCropRotationMatrix();
Matrix matrix = new Matrix( mImageView.getImageMatrix() );
if ( !matrix.invert( matrix ) ) {
}
int saveCount = mCanvas.save( Canvas.MATRIX_SAVE_FLAG );
mCanvas.concat( rotateMatrix );
stickerDrawable.setDropShadow( false );
hv.getContent().setBounds( rect );
hv.getContent().draw( mCanvas );
mCanvas.restoreToCount( saveCount );
mImageView.invalidate();
if ( mCurrentFilter != null ) {
final int w = mBitmap.getWidth();
final int h = mBitmap.getHeight();
mCurrentFilter.setTopLeft( cropRect.left / w, cropRect.top / h );
mCurrentFilter.setBottomRight( cropRect.right / w, cropRect.bottom / h );
mCurrentFilter.setRotation( Math.toRadians( hv.getRotation() ) );
int dw = stickerDrawable.getBitmapWidth();
int dh = stickerDrawable.getBitmapHeight();
float scalew = cropRect.width() / dw;
float scaleh = cropRect.height() / dh;
mCurrentFilter.setCenter( cropRect.centerX() / w, cropRect.centerY() / h );
mCurrentFilter.setScale( scalew, scaleh );
mActionList.add( mCurrentFilter.getActions().get( 0 ) );
Tracker.recordTag( stickerDrawable.getPackIdentifier() + ": Applied" );
mCurrentFilter = null;
}
}
onClearCurrent( false );
onPreviewChanged( mPreview, false, false );
}
/**
* Remove the current sticker.
*
* @param removed
* - true if the current sticker is being removed, otherwise it was
* flattened
*/
private void onClearCurrent( boolean removed ) {
mLogger.info( "onClearCurrent. removed=" + removed );
if ( stickersOnScreen() ) {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
final DrawableHighlightView hv = image.getHighlightViewAt( 0 );
onClearCurrent( hv, removed );
}
}
/**
* Removes the current active sticker.
*
* @param hv
* - the {@link DrawableHighlightView} of the active sticker
* @param removed
* - current sticker is removed
*/
private void onClearCurrent( DrawableHighlightView hv, boolean removed ) {
mLogger.info( "onClearCurrent. hv=" + hv + ", removed=" + removed );
if ( mCurrentFilter != null ) {
mCurrentFilter = null;
}
if ( null != hv ) {
FeatherDrawable content = hv.getContent();
if ( removed ) {
if ( content instanceof StickerDrawable ) {
String name = ( (StickerDrawable) content ).getIdentifier();
String packname = ( (StickerDrawable) content ).getPackIdentifier();
Tracker.recordTag( name + ": Cancelled" );
Tracker.recordTag( packname + ": Cancelled" );
}
}
}
hv.setOnDeleteClickListener( null );
( (ImageViewDrawableOverlay) mImageView ).removeHightlightView( hv );
( (ImageViewDrawableOverlay) mImageView ).invalidate();
}
/**
* Return true if there's at least one active sticker on screen.
*
* @return true, if successful
*/
private boolean stickersOnScreen() {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
return image.getHighlightCount() > 0;
}
private void onStickersPackListUpdated( Cursor cursor, int firstIndex ) {
mLogger.info( "onStickersPackListUpdated: " + cursor + ", firstIndex: " + firstIndex );
int mListFirstValidPosition = firstIndex > 0 ? firstIndex : 0;
if ( mFirstTimeRenderer ) {
if ( mListFirstValidPosition > 0 ) {
mListPacks.setSelectionFromLeft( mListFirstValidPosition - 1, mPackCellWidth / 2 );
}
}
mFirstTimeRenderer = false;
}
/**
* Sticker pack listview adapter class
*
* @author alessandro
*/
class StickerPacksAdapter extends CursorAdapter {
static final int TYPE_INVALID = -1;
static final int TYPE_LEFT_GETMORE = 5;
static final int TYPE_RIGHT_GETMORE = 6;
static final int TYPE_NORMAL = TrayColumns.TYPE_CONTENT;
static final int TYPE_EXTERNAL = TrayColumns.TYPE_PACK_EXTERNAL;
static final int TYPE_DIVIDER = TrayColumns.TYPE_PACK_INTERNAL;
static final int TYPE_LEFT_DIVIDER = TrayColumns.TYPE_LEFT_DIVIDER;
static final int TYPE_RIGHT_DIVIDER = TrayColumns.TYPE_RIGHT_DIVIDER;
private int mLayoutResId;
private int mExternalLayoutResId;
private int mMoreResId;
private LayoutInflater mInflater;
int mIdColumnIndex;
int mPackageNameColumnIndex;
int mIdentifierColumnIndex;
int mTypeColumnIndex;
int mDisplayNameColumnIndex;
int mPathColumnIndex;
public StickerPacksAdapter ( Context context, int mainResId, int externalResId, int moreResId, Cursor cursor ) {
super( context, cursor, 0 );
initColumns( cursor );
mLayoutResId = mainResId;
mExternalLayoutResId = externalResId;
mMoreResId = moreResId;
mInflater = LayoutInflater.from( context );
}
@Override
public Cursor swapCursor( Cursor newCursor ) {
mLogger.info( "swapCursor" );
initColumns( newCursor );
return super.swapCursor( newCursor );
}
private void initColumns( Cursor cursor ) {
if ( null != cursor ) {
mIdColumnIndex = cursor.getColumnIndex( TrayColumns._ID );
mPackageNameColumnIndex = cursor.getColumnIndex( TrayColumns.PACKAGE_NAME );
mIdentifierColumnIndex = cursor.getColumnIndex( TrayColumns.IDENTIFIER );
mTypeColumnIndex = cursor.getColumnIndex( TrayColumns.TYPE );
mDisplayNameColumnIndex = cursor.getColumnIndex( TrayColumns.DISPLAY_NAME );
mPathColumnIndex = cursor.getColumnIndex( TrayColumns.PATH );
}
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getViewTypeCount() {
return 7;
}
@Override
public int getItemViewType( int position ) {
Cursor cursor = (Cursor) getItem( position );
if ( null != cursor ) {
return cursor.getInt( mTypeColumnIndex );
}
return TYPE_INVALID;
}
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
if ( !mDataValid ) {
throw new IllegalStateException( "this should only be called when the cursor is valid" );
}
View v;
if ( convertView == null ) {
v = newView( mContext, mCursor, parent, position );
} else {
v = convertView;
}
bindView( v, mContext, mCursor, position );
return v;
}
private View newView( Context context, Cursor cursor, ViewGroup parent, int position ) {
View view;
ViewHolder holder;
int layoutWidth = mPackCellWidth;
final int type = getItemViewType( position );
switch ( type ) {
case TYPE_LEFT_GETMORE:
view = mInflater.inflate( mMoreResId, parent, false );
layoutWidth = mPackCellWidth;
break;
case TYPE_RIGHT_GETMORE:
view = mInflater.inflate( mMoreResId, parent, false );
layoutWidth = mPackCellWidth;
if ( mPackCellWidth * cursor.getCount() < parent.getWidth() * 2 ) {
view.setVisibility( View.INVISIBLE );
layoutWidth = 1;
} else {
if ( parent.getChildCount() > 0 && mListPacks.getFirstVisiblePosition() == 0 ) {
View lastView = parent.getChildAt( parent.getChildCount() - 1 );
if ( lastView.getRight() < parent.getWidth() ) {
view.setVisibility( View.INVISIBLE );
layoutWidth = 1;
}
}
}
break;
case TYPE_DIVIDER:
view = mInflater.inflate( mLayoutResId, parent, false );
layoutWidth = mPackCellWidth;
break;
case TYPE_EXTERNAL:
view = mInflater.inflate( mExternalLayoutResId, parent, false );
layoutWidth = mPackCellWidth;
break;
case TYPE_LEFT_DIVIDER:
view = mInflater.inflate( R.layout.aviary_thumb_divider_right, parent, false );
layoutWidth = LayoutParams.WRAP_CONTENT;
break;
case TYPE_RIGHT_DIVIDER:
view = mInflater.inflate( R.layout.aviary_thumb_divider_left, parent, false );
layoutWidth = LayoutParams.WRAP_CONTENT;
if ( mPackCellWidth * cursor.getCount() < parent.getWidth() * 2 ) {
view.setVisibility( View.INVISIBLE );
layoutWidth = 1;
} else {
if ( parent.getChildCount() > 0 && mListPacks.getFirstVisiblePosition() == 0 ) {
View lastView = parent.getChildAt( parent.getChildCount() - 1 );
if ( lastView.getRight() < parent.getWidth() ) {
view.setVisibility( View.INVISIBLE );
layoutWidth = 1;
}
}
}
break;
case TYPE_NORMAL:
default:
mLogger.error( "TYPE_NORMAL" );
view = null;
break;
}
view.setLayoutParams( new LayoutParams( layoutWidth, LayoutParams.MATCH_PARENT ) );
if ( type == TYPE_EXTERNAL ) {
holder = new ViewHolderExternal();
( (ViewHolderExternal) holder ).badgeIcon = view.findViewById( R.id.aviary_badge );
( (ViewHolderExternal) holder ).externalIcon = view.findViewById( R.id.aviary_image2 );
} else {
holder = new ViewHolder();
}
holder.type = type;
holder.image = (ImageView) view.findViewById( R.id.aviary_image );
holder.text = (TextView) view.findViewById( R.id.aviary_text );
if ( holder.image != null ) {
LayoutParams params = holder.image.getLayoutParams();
params.height = mPackThumbSize;
params.width = mPackThumbSize;
holder.image.setLayoutParams( params );
}
view.setTag( holder );
return view;
}
void bindView( View view, Context context, Cursor cursor, int position ) {
final ViewHolder holder = (ViewHolder) view.getTag();
String displayName;
String identifier;
long id = -1;
if ( !cursor.isAfterLast() && !cursor.isBeforeFirst() ) {
id = cursor.getLong( mIdColumnIndex );
}
if ( holder.type == TYPE_NORMAL ) {
} else if ( holder.type == TYPE_EXTERNAL ) {
identifier = cursor.getString( mIdentifierColumnIndex );
displayName = cursor.getString( mDisplayNameColumnIndex );
String icon = cursor.getString( mPathColumnIndex );
holder.text.setText( displayName );
holder.identifier = identifier;
if ( mBadgeService.getIsActive( identifier ) ) {
( (ViewHolderExternal) holder ).badgeIcon.setVisibility( View.VISIBLE );
( (ViewHolderExternal) holder ).externalIcon.setVisibility( View.GONE );
} else {
( (ViewHolderExternal) holder ).badgeIcon.setVisibility( View.GONE );
( (ViewHolderExternal) holder ).externalIcon.setVisibility( View.VISIBLE );
}
if ( holder.id != id ) {
mPicassoLib
.load( icon )
.resize( mPackThumbSize, mPackThumbSize, true )
.transform( new PackIconCallable( getContext().getBaseContext().getResources(), PackType.STICKER, icon ) )
.noFade()
.error( R.drawable.aviary_ic_na )
.into( holder.image );
}
} else if ( holder.type == TYPE_DIVIDER ) {
displayName = cursor.getString( mDisplayNameColumnIndex );
identifier = cursor.getString( mIdentifierColumnIndex );
String icon = cursor.getString( mPathColumnIndex );
holder.text.setText( displayName );
holder.identifier = identifier;
if ( holder.id != id ) {
mPicassoLib
.load( new File( icon ) )
.fit()
.transform( new PackIconCallable( getContext().getBaseContext().getResources(), PackType.STICKER, icon ) )
.noFade()
.error( R.drawable.aviary_ic_na )
.into( holder.image );
}
}
holder.id = id;
}
@Override
public View newView( Context arg0, Cursor arg1, ViewGroup arg2 ) {
return null;
}
@Override
public void bindView( View arg0, Context arg1, Cursor arg2 ) {}
}
/**
* Sticker pack element
*
* @author alessandro
*/
static class StickerEffectPack {
static enum StickerEffectPackType {
GET_MORE_FIRST, GET_MORE_LAST, EXTERNAL, INTERNAL, LEFT_DIVIDER, RIGHT_DIVIDER
}
CharSequence mPackageName;
CharSequence mTitle;
int mPluginStatus;
StickerEffectPackType mType;
public StickerEffectPack ( StickerEffectPackType type ) {
mType = type;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}
//
// Stickers list adapter
//
class StickersAdapter extends CursorAdapter {
LayoutInflater mLayoutInflater;
int mStickerResourceId;
String mContentPath;
int idColumnIndex, identifierColumnIndex, packIdColumnIndex;
public StickersAdapter ( Context context, int resId, Cursor cursor ) {
super( context, cursor, 0 );
mStickerResourceId = resId;
mLayoutInflater = LayoutInflater.from( context );
initCursor( cursor );
}
public void setContentPath( String path ) {
mContentPath = path;
}
public String getContentPath() {
return mContentPath;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public Cursor swapCursor( Cursor newCursor ) {
initCursor( newCursor );
return super.swapCursor( newCursor );
}
private void initCursor( Cursor cursor ) {
if ( null != cursor ) {
idColumnIndex = cursor.getColumnIndex( PacksItemsColumns._ID );
identifierColumnIndex = cursor.getColumnIndex( PacksItemsColumns.IDENTIFIER );
packIdColumnIndex = cursor.getColumnIndex( PacksItemsColumns.PACK_ID );
}
}
@Override
public View newView( Context context, Cursor cursor, ViewGroup parent ) {
View view = mLayoutInflater.inflate( mStickerResourceId, null );
LayoutParams params = new LayoutParams( mStickerCellWidth, LayoutParams.MATCH_PARENT );
view.setLayoutParams( params );
return view;
}
@Override
public void bindView( View view, Context context, Cursor cursor ) {
ImageView image = (ImageView) view.findViewById( R.id.image );
String identifier = cursor.getString( identifierColumnIndex );
final String iconPath = mContentPath + "/" + AviaryCds.getPackItemFilename( identifier, PackType.STICKER, Size.Small );
mPicassoLib
.load( iconPath )
.skipMemoryCache()
.resize( mStickerThumbSize, mStickerThumbSize, true )
.noFade()
.into( image );
}
public String getItemIdentifier( int position ) {
Cursor cursor = (Cursor) getItem( position );
return cursor.getString( identifierColumnIndex );
}
}
/**
* Downloads and renders the sticker thumbnail
*
* @author alessandro
*/
static class StickerThumbnailCallable implements Callable<Bitmap> {
int mFinalSize;
String mUrl;
public StickerThumbnailCallable ( String path, int maxSize ) {
mUrl = path;
mFinalSize = maxSize;
}
@Override
public Bitmap call() throws Exception {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile( mUrl, options );
if ( mFinalSize > 0 && null != bitmap ) {
Bitmap result = BitmapUtils.resizeBitmap( bitmap, mFinalSize, mFinalSize );
if ( result != bitmap ) {
bitmap.recycle();
bitmap = result;
}
}
return bitmap;
}
}
static class StickerPackInfo {
long packId;
String packIdentifier;
StickerPackInfo ( long packId, String packIdentifier ) {
this.packId = packId;
this.packIdentifier = packIdentifier;
}
}
static class StickerDragInfo {
String contentPath;
String identifier;
StickerDragInfo ( String contentPath, String identifier ) {
this.contentPath = contentPath;
this.identifier = identifier;
}
}
}
| gpl-3.0 |
zheguang/BerkeleyDB | lang/java/src/com/sleepycat/bind/RecordNumberBinding.java | 1835 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2000, 2014 Oracle and/or its affiliates. All rights reserved.
*
*/
package com.sleepycat.bind;
import com.sleepycat.compat.DbCompat;
import com.sleepycat.db.DatabaseEntry;
/**
* An <code>EntryBinding</code> that treats a record number key entry as a
* <code>Long</code> key object.
*
* <p>Record numbers are returned as <code>Long</code> objects, although on
* input any <code>Number</code> object may be used.</p>
*
* @author Mark Hayes
*/
public class RecordNumberBinding implements EntryBinding {
/**
* Creates a byte array binding.
*/
public RecordNumberBinding() {
}
// javadoc is inherited
public Long entryToObject(DatabaseEntry entry) {
return Long.valueOf(entryToRecordNumber(entry));
}
// javadoc is inherited
public void objectToEntry(Object object, DatabaseEntry entry) {
recordNumberToEntry(((Number) object).longValue(), entry);
}
/**
* Utility method for use by bindings to translate a entry buffer to an
* record number integer.
*
* @param entry the entry buffer.
*
* @return the record number.
*/
public static long entryToRecordNumber(DatabaseEntry entry) {
return DbCompat.getRecordNumber(entry) & 0xFFFFFFFFL;
}
/**
* Utility method for use by bindings to translate a record number integer
* to a entry buffer.
*
* @param recordNumber the record number.
*
* @param entry the entry buffer to hold the record number.
*/
public static void recordNumberToEntry(long recordNumber,
DatabaseEntry entry) {
entry.setData(new byte[4], 0, 4);
DbCompat.setRecordNumber(entry, (int) recordNumber);
}
}
| agpl-3.0 |
martindale/thundernetwork | thunder-client/src/main/java/network/thunder/client/communications/objects/UpdateChannelResponseThree.java | 964 | /*
* ThunderNetwork - Server Client Architecture to send Off-Chain Bitcoin Payments
* Copyright (C) 2015 Mats Jerratsch <matsjj@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package network.thunder.client.communications.objects;
public class UpdateChannelResponseThree {
public String transactionHash;
}
| agpl-3.0 |
inspectIT/inspectIT | inspectit.ui.rcp/src/main/java/rocks/inspectit/ui/rcp/validation/ValidationControlDecoration.java | 13011 | package rocks.inspectit.ui.rcp.validation;
import java.util.Collection;
import java.util.HashSet;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.forms.IMessageManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract class for all {@link ValidationControlDecoration}s.
*
* @author Ivan Senic
*
* @param <T>
* Type of control to decorate.
*/
public abstract class ValidationControlDecoration<T extends Control> {
/**
* Logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ValidationControlDecoration.class);
/**
* Control.
*/
private final T control;
/**
* {@link IMessageManager} that can be provided for reporting the validation of the input.
*/
private IMessageManager messageManager;
/**
* Control decoration to be created when the {@link #messageManager} is not provided.
*/
private ControlDecoration controlDecoration;
/**
* Description text.
*/
private String descriptionText;
/**
* Color of the control background.
*/
private final Color controlBackground;
/**
* Color to highlight the widget when input is not valid.
*/
private final Color nonValidBackground;
/**
* If control holds valid values.
*/
private boolean valid = true;
/**
* Defines if the control background should be changed to/from valid/invalid color. Defaults to
* <code>true</code>. If set to <code>false</code> no background will be changed on the control
* being validated.
*/
private boolean alterControlBackround = true;
/**
* Validation listeners.
*/
private final Collection<IControlValidationListener> validationListeners = new HashSet<>();
/**
* Listener used to be hooked to the events.
*/
private final Listener listener = new Listener() {
@Override
public void handleEvent(Event event) {
executeValidation();
}
};
/**
* Simple constructor. Control decoration will be handled by message manager if one is supplied.
*
* @param control
* Control to decorate.
* @param messageManager
* {@link IMessageManager} to use for reporting messages. Can be <code>null</code>
*/
public ValidationControlDecoration(T control, IMessageManager messageManager) {
this(control, messageManager, true);
}
/**
* Simple constructor. Control decoration will not be handled by message manager.Registers
* listener to the list of validation listeners.
*
* @param control
* Control to decorate.
* @param listener
* {@link IControlValidationListener}.
*/
public ValidationControlDecoration(T control, IControlValidationListener listener) {
this(control, listener, true);
}
/**
* Simple constructor. Control decoration will not be handled by message manager.Registers
* listener to the list of validation listeners.
*
* @param control
* Control to decorate.
* @param listener
* {@link IControlValidationListener}.
* @param startupValidation
* Defines whether the control shall be validated during construction of the
* ValidationControlDecoration.
*/
public ValidationControlDecoration(T control, IControlValidationListener listener, boolean startupValidation) {
this(control, (IMessageManager) null, true, startupValidation);
addControlValidationListener(listener);
}
/**
* Default constructor that allows setting of the {@link #alterControlBackround}. Control
* decoration will be handled by message manager if one is supplied.
*
* @param control
* Control to decorate.
* @param messageManager
* {@link IMessageManager} to use for reporting messages. Can be <code>null</code>
* @param alterControlBackround
* Defines if the control background should be changed to/from valid/invalid color.
* Defaults to <code>true</code>. If set to <code>false</code> no background will be
* changed on the control being validated.
*/
public ValidationControlDecoration(T control, IMessageManager messageManager, boolean alterControlBackround) {
this(control, messageManager, alterControlBackround, true);
}
/**
* Default constructor that allows setting of the {@link #alterControlBackround}. Control
* decoration will be handled by message manager if one is supplied.
*
* @param control
* Control to decorate.
* @param messageManager
* {@link IMessageManager} to use for reporting messages. Can be <code>null</code>
* @param alterControlBackround
* Defines if the control background should be changed to/from valid/invalid color.
* Defaults to <code>true</code>. If set to <code>false</code> no background will be
* changed on the control being validated.
* @param startupValidation
* Defines whether the control shall be validated during construction of the
* ValidationControlDecoration.
*/
public ValidationControlDecoration(T control, IMessageManager messageManager, boolean alterControlBackround, boolean startupValidation) {
this.control = control;
this.messageManager = messageManager;
this.alterControlBackround = alterControlBackround;
this.controlBackground = control.getBackground();
this.nonValidBackground = new Color(control.getDisplay(), 255, 200, 200);
// must be added before creating the decoration
this.control.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
try {
hide();
} catch (Exception exception) {
// ignore exception on purpose
// SWT exception is thrown when one of the sibling elements is disposed in the
// process that one of the parent UI elements is disposed.
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Ignoring Exception on ValidationControlDecoration disposal.", exception);
}
}
dispose();
}
});
// must be added before creating the decoration
// ensures that decoration is moved with the control on layout events
this.control.addControlListener(new ControlListener() {
@Override
public void controlResized(ControlEvent e) {
Composite c = ValidationControlDecoration.this.control.getParent();
while (null != c) {
c.redraw();
c = c.getParent();
}
}
@Override
public void controlMoved(ControlEvent e) {
Composite c = ValidationControlDecoration.this.control.getParent();
while (null != c) {
c.redraw();
c = c.getParent();
}
}
});
if (null == messageManager) {
this.controlDecoration = new ControlDecoration(control, SWT.LEFT | SWT.BOTTOM);
this.controlDecoration.setImage(FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_ERROR).getImage());
}
if (startupValidation) {
startupValidation();
} else {
// hide decoration per default
hide();
}
}
/**
* Constructor. Registers listener to the list of validation listeners.
*
* @param control
* Control to decorate.
* @param messageManager
* {@link IMessageManager} to use for reporting messages.
* @param listener
* {@link IControlValidationListener}.
*/
public ValidationControlDecoration(T control, IMessageManager messageManager, IControlValidationListener listener) {
this(control, messageManager);
addControlValidationListener(listener);
}
/**
* Constructor allowing setting of all fields. Registers listener to the list of validation
* listeners.
*
* @param control
* Control to decorate.
* @param messageManager
* {@link IMessageManager} to use for reporting messages.
* @param alterControlBackround
* Defines if the control background should be changed to/from valid/invalid color.
* Defaults to <code>true</code>. If set to <code>false</code> no background will be
* changed on the control being validated.
* @param listener
* {@link IControlValidationListener}.
*/
public ValidationControlDecoration(T control, IMessageManager messageManager, boolean alterControlBackround, IControlValidationListener listener) {
this(control, messageManager, alterControlBackround);
addControlValidationListener(listener);
}
/**
* Executes validation on the startup.
*/
protected final void startupValidation() {
this.valid = !controlActive() || validate(control);
if (this.valid) {
hide();
} else {
show();
}
}
/**
* Validates the current value in the control.
*
* @param control
* {@link Control}
* @return <code>true</code> if validation passed, false otherwise.
*/
protected abstract boolean validate(T control);
/**
* Executes the validation, shows or hides the decoration and informs the
* {@link #validationListeners} only if the validation value changed.
*/
public void executeValidation() {
executeValidation(false);
}
/**
* Executes the validation, shows or hides the decoration and informs the
* {@link #validationListeners}.
*
* @param informListenerAlways
* Always inform the listener even if the results of the validation did not change.
*/
public void executeValidation(boolean informListenerAlways) {
boolean tmp = valid;
if (controlActive()) {
valid = validate(control);
} else {
valid = true;
}
if (tmp != valid) {
if (valid) {
hide();
} else {
show();
}
}
if (informListenerAlways || (tmp != valid)) {
for (IControlValidationListener listener : validationListeners) {
listener.validationStateChanged(valid, ValidationControlDecoration.this);
}
}
}
/**
* Shows error.
*/
private void show() {
if (null != controlDecoration) {
controlDecoration.show();
} else if (null != messageManager) {
messageManager.addMessage(this, descriptionText, null, IMessageProvider.ERROR, control);
}
if (alterControlBackround) {
control.setBackground(nonValidBackground);
}
}
/**
* Hides error.
*/
private void hide() {
if (null != controlDecoration) {
controlDecoration.hide();
} else if (null != messageManager) {
messageManager.removeMessage(this, control);
}
if (alterControlBackround) {
control.setBackground(controlBackground);
}
}
/**
* Register event type when validation should kick in.
*
* @param eventType
* Event type.
*/
public void registerListener(int eventType) {
registerListener(control, eventType);
}
/**
* Register event type when validation should kick in with any arbitrary control.
*
* @param control
* to register validation to
* @param eventType
* Event type.
*/
public void registerListener(Control control, int eventType) {
Assert.isNotNull(control);
control.addListener(eventType, listener);
}
/**
* Adds {@link IControlValidationListener} to the list of listeners.
*
* @param validationListener
* {@link IControlValidationListener}.
*/
public final void addControlValidationListener(IControlValidationListener validationListener) {
if (null != validationListener) {
validationListeners.add(validationListener);
}
}
/**
* Returns if control is active. No validation will be process when control is not active.
*
* @return Returns if control is active. No validation will be process when control is not
* active.
*/
private boolean controlActive() {
return control.isEnabled();
}
/**
* Gets {@link #valid}.
*
* @return {@link #valid}
*/
public boolean isValid() {
return valid;
}
/**
* Gets {@link #control}.
*
* @return {@link #control}
*/
public T getControl() {
return control;
}
/**
* Gets {@link #descriptionText}.
*
* @return {@link #descriptionText}
*/
public String getDescriptionText() {
return descriptionText;
}
/**
* Sets {@link #descriptionText}.
*
* @param descriptionText
* New value for {@link #descriptionText}
*/
public void setDescriptionText(String descriptionText) {
this.descriptionText = descriptionText;
if (null != controlDecoration) {
controlDecoration.setDescriptionText(descriptionText);
}
}
/**
* Disposes the {@link #nonValidBackground} and the {@link #controlDecoration}.
*/
private void dispose() {
nonValidBackground.dispose();
if (null != controlDecoration) {
controlDecoration.dispose();
}
}
}
| agpl-3.0 |
brtonnies/rapidminer-studio | src/main/java/com/rapidminer/tools/expression/internal/function/trigonometric/HyperbolicSine.java | 1414 | /**
* Copyright (C) 2001-2015 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.tools.expression.internal.function.trigonometric;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.expression.internal.function.Abstract1DoubleInputFunction;
/**
*
* A {@link Function} computing the trigonometric hyperbolic sine of an angle.
*
* @author Denis Schernov
*
*/
public class HyperbolicSine extends Abstract1DoubleInputFunction {
public HyperbolicSine() {
super("trigonometrical.sinh", Ontology.NUMERICAL);
}
@Override
protected double compute(double value) {
return Double.isNaN(value) ? Double.NaN : Math.sinh(value);
}
}
| agpl-3.0 |
roskens/opennms-pre-github | opennms-dao/src/test/java/org/opennms/netmgt/dao/hibernate/AnnotationTest.java | 12523 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao.hibernate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.spring.BeanUtils;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.test.db.annotations.JUnitTemporaryDatabase;
import org.opennms.netmgt.dao.DatabasePopulator;
import org.opennms.netmgt.model.OnmsAlarm;
import org.opennms.netmgt.model.OnmsAssetRecord;
import org.opennms.netmgt.model.OnmsCategory;
import org.opennms.netmgt.model.OnmsDistPoller;
import org.opennms.netmgt.model.OnmsEvent;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsMonitoredService;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsNotification;
import org.opennms.netmgt.model.OnmsOutage;
import org.opennms.netmgt.model.OnmsServiceType;
import org.opennms.netmgt.model.OnmsSnmpInterface;
import org.opennms.netmgt.model.OnmsUserNotification;
import org.opennms.test.JUnitConfigurationEnvironment;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"classpath:/META-INF/opennms/applicationContext-soa.xml",
"classpath:/META-INF/opennms/applicationContext-dao.xml",
"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml",
"classpath:/META-INF/opennms/applicationContext-setupIpLike-enabled.xml",
"classpath*:/META-INF/opennms/component-dao.xml",
"classpath:/META-INF/opennms/applicationContext-minimal-conf.xml",
"classpath:/META-INF/opennms/applicationContext-commonConfigs.xml"
})
@JUnitConfigurationEnvironment
@JUnitTemporaryDatabase
public class AnnotationTest implements InitializingBean {
@Autowired
private SessionFactory m_sessionFactory;
@Autowired
private DatabasePopulator m_databasePopulator;
@Override
public void afterPropertiesSet() throws Exception {
BeanUtils.assertAutowiring(this);
}
@Before
public void setUp() {
m_databasePopulator.populateDatabase();
}
public interface Checker<T> {
public void checkCollection(Collection<T> collection);
public void check(T entity);
}
public class NullChecker<T> implements Checker<T> {
@Override
public void check(T entity) {
}
@Override
public void checkCollection(Collection<T> collection) {
}
}
public abstract class EmptyChecker<T> implements Checker<T> {
@Override
public void checkCollection(Collection<T> collection) {
assertFalse("collection should not be empty", collection.isEmpty());
}
}
@Test
@Transactional
public void testDistPoller() {
assertLoadAll(OnmsDistPoller.class, new EmptyChecker<OnmsDistPoller>() {
@Override
public void check(OnmsDistPoller entity) {
assertNotNull("name not should be null", entity.getName());
}
});
}
@Test
@Transactional
public void testAssetRecord() {
assertLoadAll(OnmsAssetRecord.class, new EmptyChecker<OnmsAssetRecord>() {
@Override
public void check(OnmsAssetRecord entity) {
assertNotNull("node should not be null", entity.getNode());
assertNotNull("node label should not be null", entity.getNode().getLabel());
}
});
}
@Test
@Transactional
public void testNode() {
assertLoadAll(OnmsNode.class, new EmptyChecker<OnmsNode>() {
@Override
public void check(OnmsNode entity) {
assertNotNull("asset record should not be null", entity.getAssetRecord());
assertNotNull("asset record ID should not be null", entity.getAssetRecord().getId());
assertNotNull("dist poller should not be null", entity.getDistPoller());
assertNotNull("dist poller name should not be null", entity.getDistPoller().getName());
assertNotNull("categories list should not be null", entity.getCategories());
entity.getCategories().size();
assertNotNull("ip interfaces list should not be null", entity.getIpInterfaces());
assertTrue("ip interfaces list size should be greater than zero", entity.getIpInterfaces().size() > 0);
assertNotNull("snmp interfaces list should not be null", entity.getSnmpInterfaces());
assertTrue("snmp interfaces list should be greater than or equal to zero", entity.getSnmpInterfaces().size() >= 0);
}
});
}
@Test
@Transactional
public void testIpInterfaces() {
assertLoadAll(OnmsIpInterface.class, new EmptyChecker<OnmsIpInterface>() {
@Override
public void check(OnmsIpInterface entity) {
assertNotNull("ip address should not be null", entity.getIpAddress());
assertNotNull("node should not be null", entity.getNode());
assertNotNull("node label should not be null", entity.getNode().getLabel());
assertNotNull("monitored services list should not be null", entity.getMonitoredServices());
assertTrue("number of monitored services should be greater than or equal to zero", entity.getMonitoredServices().size() >= 0);
}
});
}
@Test
@Transactional
public void testSnmpInterfaces() {
assertLoadAll(OnmsSnmpInterface.class, new EmptyChecker<OnmsSnmpInterface>() {
@Override
public void check(OnmsSnmpInterface entity) {
assertNotNull("ifindex should not be null", entity.getIfIndex());
assertNotNull("node should not be null", entity.getNode());
assertNotNull("node label should not be null", entity.getNode().getLabel());
assertNotNull("collect should not by null", entity.getCollect());
assertNotNull("ip interfaces list should not be null", entity.getIpInterfaces());
assertTrue("ip interfaces list size should be greater than 0", entity.getIpInterfaces().size() > 0);
}
});
}
@Test
@Transactional
public void testCategories() {
assertLoadAll(OnmsCategory.class, new EmptyChecker<OnmsCategory>() {
@Override
public void check(OnmsCategory entity) {
assertNotNull("name should not be null", entity.getName());
}
});
}
@Test
@Transactional
public void testMonitoredServices() {
assertLoadAll(OnmsMonitoredService.class, new EmptyChecker<OnmsMonitoredService>() {
@Override
public void check(OnmsMonitoredService entity) {
assertNotNull("ip interface should be null", entity.getIpInterface());
assertNotNull("ip address should not be null", entity.getIpAddress());
assertNotNull("node ID should not be null", entity.getNodeId());
assertNotNull("current outages list should not be null", entity.getCurrentOutages());
assertTrue("current outage count should be greater than or equal to zero", entity.getCurrentOutages().size() >= 0);
assertNotNull("service type should not be null", entity.getServiceType());
assertNotNull("service name should not be null", entity.getServiceName());
}
});
}
@Test
@Transactional
public void testServiceTypes() {
assertLoadAll(OnmsServiceType.class, new EmptyChecker<OnmsServiceType>() {
@Override
public void check(OnmsServiceType entity) {
assertNotNull("id should not be null", entity.getId());
assertNotNull("name should not be null", entity.getName());
}
});
}
@Test
@Transactional
public void testOutages() {
assertLoadAll(OnmsOutage.class, new EmptyChecker<OnmsOutage>() {
@Override
public void check(OnmsOutage entity) {
assertNotNull("monitored service should not be null", entity.getMonitoredService());
assertNotNull("ip address should not be null", entity.getIpAddress());
assertNotNull("node ID should not be null", entity.getNodeId());
assertNotNull("service lost event should not be null", entity.getServiceLostEvent());
assertNotNull("service lost event UEI should not be null", entity.getServiceLostEvent().getEventUei());
if (entity.getIfRegainedService() != null) {
assertNotNull("outage has ended (ifregainedservice) so service regained event should not be null", entity.getServiceRegainedEvent());
assertNotNull("outage has ended (ifregainedservice) so service regained event UEI should not be null", entity.getServiceRegainedEvent().getEventUei());
}
}
});
}
@Test
@Transactional
public void testEvents() {
assertLoadAll(OnmsEvent.class, new EmptyChecker<OnmsEvent>() {
@Override
public void check(OnmsEvent entity) {
if (entity.getAlarm() != null) {
assertEquals("event UEI should equal the alarm UEI", entity.getEventUei(), entity.getAlarm().getUei());
}
assertNotNull("associated service lost outages list should not be null", entity.getAssociatedServiceLostOutages());
assertTrue("there should be zero or more associated service lost outages", entity.getAssociatedServiceLostOutages().size() >= 0);
assertNotNull("associated service regained outages list should not be null", entity.getAssociatedServiceRegainedOutages());
assertTrue("there should be zero or more associated service regained outages", entity.getAssociatedServiceRegainedOutages().size() >= 0);
assertNotNull("dist poller should not be null", entity.getDistPoller());
assertNotNull("dist poller name should not be null", entity.getDistPoller().getName());
assertNotNull("notifications list should not be null", entity.getNotifications());
assertTrue("notifications list size should be greater than or equal to zero", entity.getNotifications().size() >= 0);
}
});
}
@Test
@Transactional
public void testAlarms() {
assertLoadAll(OnmsAlarm.class, new EmptyChecker<OnmsAlarm>() {
@Override
public void check(OnmsAlarm entity) {
assertNotNull("last event should not be null", entity.getLastEvent());
assertEquals("alarm UEI should match the last event UEI", entity.getUei(), entity.getLastEvent().getEventUei());
assertNotNull("dist poller should not be null", entity.getDistPoller());
assertNotNull("dist poller name should not be null", entity.getDistPoller().getName());
}
});
}
@Test
@Transactional
public void testNotifacations() {
assertLoadAll(OnmsNotification.class, new NullChecker<OnmsNotification>());
}
@Test
@Transactional
public void testUsersNotified() {
assertLoadAll(OnmsUserNotification.class, new NullChecker<OnmsUserNotification>());
}
private <T> void assertLoadAll(Class<T> annotatedClass, Checker<T> checker) {
HibernateTemplate template = new HibernateTemplate(m_sessionFactory);
Collection<T> results = template.loadAll(annotatedClass);
assertNotNull(results);
checker.checkCollection(results);
for (T t : results) {
checker.check(t);
// we only need to check one
break;
}
}
}
| agpl-3.0 |
nvoron23/rstudio | src/gwt/src/org/rstudio/core/client/jsonrpc/RpcError.java | 2888 | /*
* RpcError.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.core.client.jsonrpc;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
public class RpcError extends JavaScriptObject
{
public static final native RpcError create(int code, String message) /*-{
var error = new Object();
error.code = code ;
error.message = message ;
return error ;
}-*/;
protected RpcError()
{
}
// no error
public final static int SUCCESS = 0 ;
// couldn't connect to service (method not executed)
public final static int CONNECTION_ERROR = 1 ;
// service is currently unavailable
public final static int UNAVAILABLE = 2;
// not authorized to access service or method (method not executed)
public final static int UNAUTHORIZED = 3 ;
// provided client id is invalid (method not executed)
public final static int INVALID_CLIENT_ID = 4;
// protocol errors (method not executed)
public final static int PARSE_ERROR = 5 ;
public final static int INVALID_REQUEST = 6 ;
public final static int METHOD_NOT_FOUND = 7 ;
public final static int PARAM_MISSING = 8 ;
public final static int PARAM_TYPE_MISMATCH = 9;
public final static int PARAM_INVALID = 10;
public final static int METHOD_UNEXEPECTED = 11 ;
public final static int INVALID_CLIENT_VERSION = 12;
public final static int SERVER_OFFLINE = 13;
// execution error (method was executed and returned known error state)
public final static int EXECUTION_ERROR = 100;
// transmission error (application state indeterminate)
public final static int TRANSMISSION_ERROR = 200;
public final native int getCode() /*-{
return this.code;
}-*/;
public final native String getMessage() /*-{
return this.message;
}-*/;
public final native RpcUnderlyingError getError() /*-{
return this.error;
}-*/;
public final JSONValue getClientInfo()
{
return new JSONObject(this).get("client_info");
}
public final String getEndUserMessage()
{
RpcUnderlyingError underlyingError = getError();
if (underlyingError != null)
return underlyingError.getMessage();
else
return getMessage();
}
}
| agpl-3.0 |
inspectIT/inspectIT | inspectit.agent.java/src/test/java/rocks/inspectit/agent/java/core/impl/PlatformManagerTest.java | 4499 | package rocks.inspectit.agent.java.core.impl;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.slf4j.Logger;
import org.testng.annotations.Test;
import rocks.inspectit.agent.java.config.IConfigurationStorage;
import rocks.inspectit.agent.java.config.impl.RepositoryConfig;
import rocks.inspectit.agent.java.connection.IConnection;
import rocks.inspectit.shared.all.instrumentation.config.impl.AgentConfig;
import rocks.inspectit.shared.all.testbase.TestBase;
import rocks.inspectit.shared.all.version.VersionService;
@SuppressWarnings("PMD")
public class PlatformManagerTest extends TestBase {
@InjectMocks
PlatformManager platformManager;
@Mock
Logger log;
@Mock
IConfigurationStorage configurationStorage;
@Mock
IConnection connection;
@Mock
VersionService versionService;
@Mock
AgentConfig agentConfiguration;
public class AfterPropertiesSet extends PlatformManagerTest {
@Test
public void connectAndRetrievePlatformId() throws Exception {
String host = "localhost";
int port = 1099;
RepositoryConfig repositoryConfig = mock(RepositoryConfig.class);
when(repositoryConfig.getHost()).thenReturn(host);
when(repositoryConfig.getPort()).thenReturn(port);
when(configurationStorage.getRepositoryConfig()).thenReturn(repositoryConfig);
when(configurationStorage.getAgentName()).thenReturn("testAgent");
when(versionService.getVersionAsString()).thenReturn("dummyVersion");
long fakePlatformId = 7L;
when(connection.isConnected()).thenReturn(false);
when(connection.register("testAgent", "dummyVersion")).thenReturn(agentConfiguration);
when(agentConfiguration.getPlatformId()).thenReturn(fakePlatformId);
platformManager.afterPropertiesSet();
long platformId = platformManager.getPlatformId();
assertThat(platformId, is(equalTo(fakePlatformId)));
verify(connection, times(1)).connect(host, port);
}
@Test
public void retrievePlatformId() throws Exception {
long fakePlatformId = 3L;
when(connection.isConnected()).thenReturn(true);
when(configurationStorage.getAgentName()).thenReturn("testAgent");
when(versionService.getVersionAsString()).thenReturn("dummyVersion");
when(connection.register("testAgent", "dummyVersion")).thenReturn(agentConfiguration);
when(agentConfiguration.getPlatformId()).thenReturn(fakePlatformId);
platformManager.afterPropertiesSet();
long platformId = platformManager.getPlatformId();
assertThat(platformId, is(equalTo(fakePlatformId)));
verify(connection, times(0)).connect(anyString(), anyInt());
}
}
public class UnregisterPlatform extends PlatformManagerTest {
/**
* Tests that unregister of platform is executed if connection to the server is established
* and registration is performed.
*/
@Test
public void unregisterPlatform() throws Exception {
// first simulate connect
long fakePlatformId = 3L;
when(connection.isConnected()).thenReturn(true);
when(configurationStorage.getAgentName()).thenReturn("testAgent");
when(versionService.getVersionAsString()).thenReturn("dummyVersion");
when(connection.register("testAgent", "dummyVersion")).thenReturn(agentConfiguration);
when(agentConfiguration.getPlatformId()).thenReturn(fakePlatformId);
platformManager.afterPropertiesSet();
platformManager.getPlatformId();
platformManager.unregisterPlatform();
verify(connection, times(1)).unregister(fakePlatformId);
verify(connection, times(1)).disconnect();
}
/**
* Test that unregister will not be called if there is no active connection to the server
* and registration is not done at first place.
*/
@Test
public void noUnregisterPlatform() throws Exception {
// no unregister if no connection
when(connection.isConnected()).thenReturn(false);
platformManager.unregisterPlatform();
// no unregister if registration is not done at the first place
when(connection.isConnected()).thenReturn(true);
platformManager.unregisterPlatform();
verify(connection, times(0)).unregister(anyLong());
}
}
}
| agpl-3.0 |
fhuertas/torodb | torod/db-executor/src/main/java/com/torodb/torod/db/executor/jobs/MaxElementsCallable.java | 1453 |
package com.torodb.torod.db.executor.jobs;
import com.torodb.torod.core.cursors.CursorId;
import com.torodb.torod.core.dbWrapper.Cursor;
import com.torodb.torod.core.dbWrapper.DbWrapper;
import com.torodb.torod.core.exceptions.ToroException;
import com.torodb.torod.core.exceptions.ToroRuntimeException;
/**
*
*/
public class MaxElementsCallable extends Job<Integer> {
private final DbWrapper dbWrapper;
private final CursorId cursorId;
private final MaxElementsCallable.Report report;
public MaxElementsCallable(DbWrapper dbWrapper, Report report, CursorId cursorId) {
this.dbWrapper = dbWrapper;
this.cursorId = cursorId;
this.report = report;
}
@Override
protected Integer failableCall() throws ToroException,
ToroRuntimeException {
Cursor cursor = dbWrapper.getGlobalCursor(cursorId);
int maxElements = cursor.getMaxElements();
report.maxElementsExecuted(cursorId, maxElements);
return maxElements;
}
@Override
protected Integer onFail(Throwable t) throws
ToroException, ToroRuntimeException {
if (t instanceof ToroException) {
throw (ToroException) t;
}
throw new ToroRuntimeException(t);
}
public static interface Report {
public void maxElementsExecuted(
CursorId cursorId,
int result);
}
}
| agpl-3.0 |
deadcyclo/nuxeo-features | localconf/nuxeo-localconf-simple/src/main/java/org/nuxeo/ecm/localconf/SetSimpleConfParamVar.java | 2751 | /*
* (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Thomas Roger <troger@nuxeo.com>
*/
package org.nuxeo.ecm.localconf;
import static org.nuxeo.ecm.automation.core.Constants.CAT_LOCAL_CONFIGURATION;
import static org.nuxeo.ecm.localconf.SimpleConfiguration.SIMPLE_CONFIGURATION_FACET;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.automation.core.annotations.Context;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.nuxeo.ecm.automation.core.annotations.Param;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.localconfiguration.LocalConfigurationService;
/**
* Operation to set a context variable with the value of the given parameter
* name of the SimpleConfiguration retrieve from the input Document.
*
* @author <a href="mailto:troger@nuxeo.com">Thomas Roger</a>
* @since 5.5
*/
@Operation(id = SetSimpleConfParamVar.ID, category = CAT_LOCAL_CONFIGURATION, label = "Set Context Variable From a Simple Configuration Parameter", description = "Set a context variable "
+ "that points to the value of the given parameter name in "
+ "the SimpleConfiguration from the input Document. "
+ "You must give a name for the variable.")
public class SetSimpleConfParamVar {
public static final String ID = "LocalConfiguration.SetSimpleConfigurationParameterAsVar";
@Context
protected OperationContext ctx;
@Context
protected LocalConfigurationService localConfigurationService;
@Param(name = "name")
protected String name;
@Param(name = "parameterName")
protected String parameterName;
@Param(name = "defaultValue", required = false)
protected String defaultValue;
@OperationMethod
public DocumentModel run(DocumentModel doc) throws Exception {
SimpleConfiguration simpleConfiguration = localConfigurationService.getConfiguration(
SimpleConfiguration.class, SIMPLE_CONFIGURATION_FACET, doc);
String value = simpleConfiguration.get(parameterName, defaultValue);
ctx.put(name, value);
return doc;
}
}
| lgpl-2.1 |
zsimoes/jvstm | examples/pertxboxes/TestPerTxBoxes.java | 2094 | import jvstm.CommitException;
import jvstm.Transaction;
import jvstm.VBox;
public class TestPerTxBoxes {
protected static final int INITIAL_X = 4;
protected static final int INITIAL_Y = 2;
protected static final VBox<Integer> normalVBox = new VBox<Integer>(0);
protected static final SwapperPerTxBox swapper = new SwapperPerTxBox(INITIAL_X, INITIAL_Y);
protected static final CounterPerTxBox counter = new CounterPerTxBox(0L);
protected static final int OPERATIONS = 1000;
protected static final int WORKERS = 4;
public static void main(String[] args) throws InterruptedException {
Thread[] workers = new Thread[WORKERS];
for (int i = 0; i < WORKERS; i++) {
workers[i] = new Worker();
workers[i].start();
}
for (int i = 0; i < WORKERS; i++) {
workers[i].join();
}
if (
normalVBox.get() != (WORKERS * OPERATIONS) ||
swapper.getX() != INITIAL_X || swapper.getY() != INITIAL_Y ||
counter.getCount() != (WORKERS * OPERATIONS)
) {
System.out.println("Error: WORKERS * OPS: " + (WORKERS * OPERATIONS) + " vbox: " + normalVBox.get() + " counter "
+ counter.getCount() + " x: " + swapper.getX() + " y: " + swapper.getY());
} else {
System.out.println("Ok");
}
}
protected static class Worker extends Thread {
public void run() {
for (int i = 0; i < OPERATIONS; i++) {
while (true) {
Transaction tx = null;
try {
tx = Transaction.begin();
normalVBox.put(normalVBox.get() + 1);
counter.inc();
swapper.swapXY();
Transaction.commit();
tx = null;
break;
} catch (CommitException ce) {
if (tx != null) {
tx.abort();
}
}
}
// int x, y = 0;
// Transaction.begin(true);
// x = swapper.getX();
// y = swapper.getY();
// Transaction.commit();
// if ((x == INITIAL_X && y == INITIAL_Y) || (x == INITIAL_Y && y == INITIAL_X)) {
//
// } else {
// System.out.println("Inconsistency after " + i + " iterations x: " + x + " y: " + y);
// System.exit(1);
// }
}
}
}
}
| lgpl-2.1 |
PaoloP74/Arduino | app/src/processing/app/Editor.java | 85609 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-09 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
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 processing.app;
import cc.arduino.packages.BoardPort;
import cc.arduino.packages.MonitorFactory;
import cc.arduino.packages.Uploader;
import cc.arduino.packages.uploaders.SerialUploader;
import cc.arduino.view.GoToLineNumber;
import cc.arduino.view.StubMenuListener;
import cc.arduino.view.findreplace.FindReplace;
import com.jcraft.jsch.JSchException;
import jssc.SerialPortException;
import processing.app.debug.RunnerException;
import processing.app.forms.PasswordAuthorizationDialog;
import processing.app.helpers.Keys;
import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMapException;
import processing.app.legacy.PApplet;
import processing.app.syntax.PdeKeywords;
import processing.app.tools.MenuScroller;
import processing.app.tools.Tool;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.BadLocationException;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.List;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static processing.app.I18n.tr;
import static processing.app.Theme.scale;
/**
* Main editor panel for the Processing Development Environment.
*/
@SuppressWarnings("serial")
public class Editor extends JFrame implements RunnerListener {
public static final int MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR = 10000;
final Platform platform;
private JMenu recentSketchesMenu;
private JMenu programmersMenu;
private final Box upper;
private ArrayList<EditorTab> tabs = new ArrayList<>();
private int currentTabIndex = -1;
private static class ShouldSaveIfModified
implements Predicate<SketchController> {
@Override
public boolean test(SketchController controller) {
return PreferencesData.getBoolean("editor.save_on_verify")
&& controller.getSketch().isModified()
&& !controller.isReadOnly(
BaseNoGui.librariesIndexer
.getInstalledLibraries(),
BaseNoGui.getExamplesPath());
}
}
private static class ShouldSaveReadOnly implements Predicate<SketchController> {
@Override
public boolean test(SketchController sketch) {
return sketch.isReadOnly(BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath());
}
}
private final static List<String> BOARD_PROTOCOLS_ORDER = Arrays.asList("serial", "network");
private final static List<String> BOARD_PROTOCOLS_ORDER_TRANSLATIONS = Arrays.asList(tr("Serial ports"), tr("Network ports"));
final Base base;
// otherwise, if the window is resized with the message label
// set to blank, it's preferredSize() will be fukered
private static final String EMPTY =
" " +
" " +
" ";
/** Command on Mac OS X, Ctrl on Windows and Linux */
private static final int SHORTCUT_KEY_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** Command-W on Mac OS X, Ctrl-W on Windows and Linux */
static final KeyStroke WINDOW_CLOSE_KEYSTROKE =
KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK);
/** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */
static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK |
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/**
* true if this file has not yet been given a name by the user
*/
boolean untitled;
private PageFormat pageFormat;
// file, sketch, and tools menus for re-inserting items
private JMenu fileMenu;
private JMenu toolsMenu;
private int numTools = 0;
public boolean avoidMultipleOperations = false;
private final EditorToolbar toolbar;
// these menus are shared so that they needn't be rebuilt for all windows
// each time a sketch is created, renamed, or moved.
static JMenu toolbarMenu;
static JMenu sketchbookMenu;
static JMenu examplesMenu;
static JMenu importMenu;
private static JMenu portMenu;
static volatile AbstractMonitor serialMonitor;
static AbstractMonitor serialPlotter;
final EditorHeader header;
EditorStatus status;
EditorConsole console;
private JSplitPane splitPane;
// currently opened program
SketchController sketchController;
Sketch sketch;
EditorLineStatus lineStatus;
//JEditorPane editorPane;
/** Contains all EditorTabs, of which only one will be visible */
private JPanel codePanel;
//Runner runtime;
private JMenuItem saveMenuItem;
private JMenuItem saveAsMenuItem;
//boolean presenting;
private boolean uploading;
// undo fellers
private JMenuItem undoItem;
private JMenuItem redoItem;
protected UndoAction undoAction;
protected RedoAction redoAction;
private FindReplace find;
Runnable runHandler;
Runnable presentHandler;
private Runnable runAndSaveHandler;
private Runnable presentAndSaveHandler;
Runnable exportHandler;
private Runnable exportAppHandler;
private Runnable timeoutUploadHandler;
public Editor(Base ibase, File file, int[] storedLocation, int[] defaultLocation, Platform platform) throws Exception {
super("Arduino");
this.base = ibase;
this.platform = platform;
Base.setIcon(this);
// Install default actions for Run, Present, etc.
resetHandlers();
// add listener to handle window close box hit event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
base.handleClose(Editor.this);
}
});
// don't close the window when clicked, the app will take care
// of that via the handleQuitInternal() methods
// http://dev.processing.org/bugs/show_bug.cgi?id=440
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// When bringing a window to front, let the Base know
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
base.handleActivated(Editor.this);
}
// added for 1.0.5
// http://dev.processing.org/bugs/show_bug.cgi?id=1260
public void windowDeactivated(WindowEvent e) {
fileMenu.remove(sketchbookMenu);
fileMenu.remove(examplesMenu);
List<Component> toolsMenuItemsToRemove = new LinkedList<Component>();
for (Component menuItem : toolsMenu.getMenuComponents()) {
if (menuItem instanceof JComponent) {
Object removeOnWindowDeactivation = ((JComponent) menuItem).getClientProperty("removeOnWindowDeactivation");
if (removeOnWindowDeactivation != null && Boolean.valueOf(removeOnWindowDeactivation.toString())) {
toolsMenuItemsToRemove.add(menuItem);
}
}
}
for (Component menuItem : toolsMenuItemsToRemove) {
toolsMenu.remove(menuItem);
}
toolsMenu.remove(portMenu);
}
});
//PdeKeywords keywords = new PdeKeywords();
//sketchbook = new Sketchbook(this);
buildMenuBar();
// For rev 0120, placing things inside a JPanel
Container contentPain = getContentPane();
contentPain.setLayout(new BorderLayout());
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
contentPain.add(pane, BorderLayout.CENTER);
Box box = Box.createVerticalBox();
upper = Box.createVerticalBox();
if (toolbarMenu == null) {
toolbarMenu = new JMenu();
base.rebuildToolbarMenu(toolbarMenu);
}
toolbar = new EditorToolbar(this, toolbarMenu);
upper.add(toolbar);
header = new EditorHeader(this);
upper.add(header);
// assemble console panel, consisting of status area and the console itself
JPanel consolePanel = new JPanel();
consolePanel.setLayout(new BorderLayout());
status = new EditorStatus(this);
consolePanel.add(status, BorderLayout.NORTH);
console = new EditorConsole();
console.setName("console");
// windows puts an ugly border on this guy
console.setBorder(null);
consolePanel.add(console, BorderLayout.CENTER);
lineStatus = new EditorLineStatus();
consolePanel.add(lineStatus, BorderLayout.SOUTH);
codePanel = new JPanel(new BorderLayout());
upper.add(codePanel);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel);
// repaint child panes while resizing
splitPane.setContinuousLayout(true);
// if window increases in size, give all of increase to
// the textarea in the uppper pane
splitPane.setResizeWeight(1D);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
splitPane.setBorder(null);
// By default, the split pane binds Ctrl-Tab and Ctrl-Shift-Tab for changing
// focus. Since we do not use that, but want to use these shortcuts for
// switching tabs, remove the bindings from the split pane. This allows the
// events to bubble up and be handled by the EditorHeader.
Keys.killBinding(splitPane, Keys.ctrl(KeyEvent.VK_TAB));
Keys.killBinding(splitPane, Keys.ctrlShift(KeyEvent.VK_TAB));
splitPane.setDividerSize(scale(splitPane.getDividerSize()));
// the following changed from 600, 400 for netbooks
// http://code.google.com/p/arduino/issues/detail?id=52
splitPane.setMinimumSize(scale(new Dimension(600, 100)));
box.add(splitPane);
// hopefully these are no longer needed w/ swing
// (har har har.. that was wishful thinking)
// listener = new EditorListener(this, textarea);
pane.add(box);
pane.setTransferHandler(new FileDropHandler());
// Set the minimum size for the editor window
setMinimumSize(scale(new Dimension(
PreferencesData.getInteger("editor.window.width.min"),
PreferencesData.getInteger("editor.window.height.min"))));
// Bring back the general options for the editor
applyPreferences();
// Finish preparing Editor (formerly found in Base)
pack();
// Set the window bounds and the divider location before setting it visible
setPlacement(storedLocation, defaultLocation);
// Open the document that was passed in
boolean loaded = handleOpenInternal(file);
if (!loaded) sketchController = null;
}
/**
* Handles files dragged & dropped from the desktop and into the editor
* window. Dragging files into the editor window is the same as using
* "Sketch → Add File" for each file.
*/
private class FileDropHandler extends TransferHandler {
public boolean canImport(JComponent dest, DataFlavor[] flavors) {
return true;
}
@SuppressWarnings("unchecked")
public boolean importData(JComponent src, Transferable transferable) {
int successful = 0;
try {
DataFlavor uriListFlavor =
new DataFlavor("text/uri-list;class=java.lang.String");
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> list = (List<File>)
transferable.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : list) {
if (sketchController.addFile(file)) {
successful++;
}
}
} else if (transferable.isDataFlavorSupported(uriListFlavor)) {
// Some platforms (Mac OS X and Linux, when this began) preferred
// this method of moving files.
String data = (String)transferable.getTransferData(uriListFlavor);
String[] pieces = PApplet.splitTokens(data, "\r\n");
for (String piece : pieces) {
if (piece.startsWith("#")) continue;
String path = null;
if (piece.startsWith("file:///")) {
path = piece.substring(7);
} else if (piece.startsWith("file:/")) {
path = piece.substring(5);
}
if (sketchController.addFile(new File(path))) {
successful++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
if (successful == 0) {
statusError(tr("No files were added to the sketch."));
} else if (successful == 1) {
statusNotice(tr("One file added to the sketch."));
} else {
statusNotice(
I18n.format(tr("{0} files added to the sketch."), successful));
}
return true;
}
}
private void setPlacement(int[] storedLocation, int[] defaultLocation) {
if (storedLocation.length > 5 && storedLocation[5] != 0) {
setExtendedState(storedLocation[5]);
setPlacement(defaultLocation);
} else {
setPlacement(storedLocation);
}
}
private void setPlacement(int[] location) {
setBounds(location[0], location[1], location[2], location[3]);
if (location[4] != 0) {
splitPane.setDividerLocation(location[4]);
}
}
protected int[] getPlacement() {
int[] location = new int[6];
// Get the dimensions of the Frame
Rectangle bounds = getBounds();
location[0] = bounds.x;
location[1] = bounds.y;
location[2] = bounds.width;
location[3] = bounds.height;
// Get the current placement of the divider
location[4] = splitPane.getDividerLocation();
location[5] = getExtendedState() & MAXIMIZED_BOTH;
return location;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Read and apply new values from the preferences, either because
* the app is just starting up, or the user just finished messing
* with things in the Preferences window.
*/
public void applyPreferences() {
boolean external = PreferencesData.getBoolean("editor.external");
saveMenuItem.setEnabled(!external);
saveAsMenuItem.setEnabled(!external);
for (EditorTab tab: tabs)
tab.applyPreferences();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
private void buildMenuBar() {
JMenuBar menubar = new JMenuBar();
final JMenu fileMenu = buildFileMenu();
fileMenu.addMenuListener(new StubMenuListener() {
@Override
public void menuSelected(MenuEvent e) {
List<Component> components = Arrays.asList(fileMenu.getComponents());
if (!components.contains(sketchbookMenu)) {
fileMenu.insert(sketchbookMenu, 3);
}
if (!components.contains(sketchbookMenu)) {
fileMenu.insert(examplesMenu, 4);
}
fileMenu.revalidate();
validate();
}
});
menubar.add(fileMenu);
menubar.add(buildEditMenu());
final JMenu sketchMenu = new JMenu(tr("Sketch"));
sketchMenu.setMnemonic(KeyEvent.VK_S);
sketchMenu.addMenuListener(new StubMenuListener() {
@Override
public void menuSelected(MenuEvent e) {
buildSketchMenu(sketchMenu);
sketchMenu.revalidate();
validate();
}
});
buildSketchMenu(sketchMenu);
menubar.add(sketchMenu);
final JMenu toolsMenu = buildToolsMenu();
toolsMenu.addMenuListener(new StubMenuListener() {
@Override
public void menuSelected(MenuEvent e) {
List<Component> components = Arrays.asList(toolsMenu.getComponents());
int offset = 0;
for (JMenu menu : base.getBoardsCustomMenus()) {
if (!components.contains(menu)) {
toolsMenu.insert(menu, numTools + offset);
offset++;
}
}
if (!components.contains(portMenu)) {
toolsMenu.insert(portMenu, numTools + offset);
}
programmersMenu.removeAll();
base.getProgrammerMenus().forEach(programmersMenu::add);
toolsMenu.revalidate();
validate();
}
});
menubar.add(toolsMenu);
menubar.add(buildHelpMenu());
setJMenuBar(menubar);
}
private JMenu buildFileMenu() {
JMenuItem item;
fileMenu = new JMenu(tr("File"));
fileMenu.setMnemonic(KeyEvent.VK_F);
item = newJMenuItem(tr("New"), 'N');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleNew();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
item = Editor.newJMenuItem(tr("Open..."), 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleOpenPrompt();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
base.rebuildRecentSketchesMenuItems();
recentSketchesMenu = new JMenu(tr("Open Recent"));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
rebuildRecentSketchesMenu();
}
});
fileMenu.add(recentSketchesMenu);
if (sketchbookMenu == null) {
sketchbookMenu = new JMenu(tr("Sketchbook"));
MenuScroller.setScrollerFor(sketchbookMenu);
base.rebuildSketchbookMenu(sketchbookMenu);
}
fileMenu.add(sketchbookMenu);
if (examplesMenu == null) {
examplesMenu = new JMenu(tr("Examples"));
MenuScroller.setScrollerFor(examplesMenu);
base.rebuildExamplesMenu(examplesMenu);
}
fileMenu.add(examplesMenu);
item = Editor.newJMenuItem(tr("Close"), 'W');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleClose(Editor.this);
}
});
fileMenu.add(item);
saveMenuItem = newJMenuItem(tr("Save"), 'S');
saveMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSave(false);
}
});
fileMenu.add(saveMenuItem);
saveAsMenuItem = newJMenuItemShift(tr("Save As..."), 'S');
saveAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSaveAs();
}
});
fileMenu.add(saveAsMenuItem);
fileMenu.addSeparator();
item = newJMenuItemShift(tr("Page Setup"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePageSetup();
}
});
fileMenu.add(item);
item = newJMenuItem(tr("Print"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePrint();
}
});
fileMenu.add(item);
// macosx already has its own preferences and quit menu
if (!OSUtils.isMacOS()) {
fileMenu.addSeparator();
item = newJMenuItem(tr("Preferences"), ',');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handlePrefs();
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItem(tr("Quit"), 'Q');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleQuit();
}
});
fileMenu.add(item);
}
return fileMenu;
}
public void rebuildRecentSketchesMenu() {
recentSketchesMenu.removeAll();
for (JMenuItem recentSketchMenuItem : base.getRecentSketchesMenuItems()) {
recentSketchesMenu.add(recentSketchMenuItem);
}
}
private void buildSketchMenu(JMenu sketchMenu) {
sketchMenu.removeAll();
JMenuItem item = newJMenuItem(tr("Verify/Compile"), 'R');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleRun(false, Editor.this.presentHandler, Editor.this.runHandler);
}
});
sketchMenu.add(item);
item = newJMenuItem(tr("Upload"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(false);
}
});
sketchMenu.add(item);
item = newJMenuItemShift(tr("Upload Using Programmer"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(true);
}
});
sketchMenu.add(item);
item = newJMenuItemAlt(tr("Export compiled Binary"), 'S');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (new ShouldSaveReadOnly().test(sketchController) && !handleSave(true)) {
System.out.println(tr("Export canceled, changes must first be saved."));
return;
}
handleRun(false, new ShouldSaveReadOnly(), Editor.this.presentAndSaveHandler, Editor.this.runAndSaveHandler);
}
});
sketchMenu.add(item);
// item = new JMenuItem("Stop");
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleStop();
// }
// });
// sketchMenu.add(item);
sketchMenu.addSeparator();
item = newJMenuItem(tr("Show Sketch Folder"), 'K');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openFolder(sketch.getFolder());
}
});
sketchMenu.add(item);
item.setEnabled(Base.openFolderAvailable());
if (importMenu == null) {
importMenu = new JMenu(tr("Include Library"));
MenuScroller.setScrollerFor(importMenu);
base.rebuildImportMenu(importMenu);
}
sketchMenu.add(importMenu);
item = new JMenuItem(tr("Add File..."));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sketchController.handleAddFile();
}
});
sketchMenu.add(item);
}
private JMenu buildToolsMenu() {
toolsMenu = new JMenu(tr("Tools"));
toolsMenu.setMnemonic(KeyEvent.VK_T);
addInternalTools(toolsMenu);
JMenuItem item = newJMenuItemShift(tr("Serial Monitor"), 'M');
item.addActionListener(e -> handleSerial());
toolsMenu.add(item);
item = newJMenuItemShift(tr("Serial Plotter"), 'L');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePlotter();
}
});
toolsMenu.add(item);
addTools(toolsMenu, BaseNoGui.getToolsFolder());
File sketchbookTools = new File(BaseNoGui.getSketchbookFolder(), "tools");
addTools(toolsMenu, sketchbookTools);
toolsMenu.addSeparator();
numTools = toolsMenu.getItemCount();
// XXX: DAM: these should probably be implemented using the Tools plugin
// API, if possible (i.e. if it supports custom actions, etc.)
base.getBoardsCustomMenus().stream().forEach(toolsMenu::add);
if (portMenu == null)
portMenu = new JMenu(tr("Port"));
populatePortMenu();
toolsMenu.add(portMenu);
item = new JMenuItem(tr("Get Board Info"));
item.addActionListener(e -> handleBoardInfo());
toolsMenu.add(item);
toolsMenu.addSeparator();
base.rebuildProgrammerMenu();
programmersMenu = new JMenu(tr("Programmer"));
base.getProgrammerMenus().stream().forEach(programmersMenu::add);
toolsMenu.add(programmersMenu);
item = new JMenuItem(tr("Burn Bootloader"));
item.addActionListener(e -> handleBurnBootloader());
toolsMenu.add(item);
toolsMenu.addMenuListener(new StubMenuListener() {
public void menuSelected(MenuEvent e) {
//System.out.println("Tools menu selected.");
populatePortMenu();
for (Component c : toolsMenu.getMenuComponents()) {
if ((c instanceof JMenu) && c.isVisible()) {
JMenu menu = (JMenu)c;
String name = menu.getText();
if (name == null) continue;
String basename = name;
int index = name.indexOf(':');
if (index > 0) basename = name.substring(0, index);
String sel = null;
int count = menu.getItemCount();
for (int i=0; i < count; i++) {
JMenuItem item = menu.getItem(i);
if (item != null && item.isSelected()) {
sel = item.getText();
if (sel != null) break;
}
}
if (sel == null) {
if (!name.equals(basename)) menu.setText(basename);
} else {
if (sel.length() > 50) sel = sel.substring(0, 50) + "...";
String newname = basename + ": \"" + sel + "\"";
if (!name.equals(newname)) menu.setText(newname);
}
}
}
}
});
return toolsMenu;
}
private void addTools(JMenu menu, File sourceFolder) {
if (sourceFolder == null)
return;
Map<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>();
File[] folders = sourceFolder.listFiles(new FileFilter() {
public boolean accept(File folder) {
if (folder.isDirectory()) {
//System.out.println("checking " + folder);
File subfolder = new File(folder, "tool");
return subfolder.exists();
}
return false;
}
});
if (folders == null || folders.length == 0) {
return;
}
for (File folder : folders) {
File toolDirectory = new File(folder, "tool");
try {
// add dir to classpath for .classes
//urlList.add(toolDirectory.toURL());
// add .jar files to classpath
File[] archives = toolDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".jar") ||
name.toLowerCase().endsWith(".zip"));
}
});
URL[] urlList = new URL[archives.length];
for (int j = 0; j < urlList.length; j++) {
urlList[j] = archives[j].toURI().toURL();
}
URLClassLoader loader = new URLClassLoader(urlList);
String className = null;
for (File archive : archives) {
className = findClassInZipFile(folder.getName(), archive);
if (className != null) break;
}
/*
// Alternatively, could use manifest files with special attributes:
// http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html
// Example code for loading from a manifest file:
// http://forums.sun.com/thread.jspa?messageID=3791501
File infoFile = new File(toolDirectory, "tool.txt");
if (!infoFile.exists()) continue;
String[] info = PApplet.loadStrings(infoFile);
//Main-Class: org.poo.shoe.AwesomerTool
//String className = folders[i].getName();
String className = null;
for (int k = 0; k < info.length; k++) {
if (info[k].startsWith(";")) continue;
String[] pieces = PApplet.splitTokens(info[k], ": ");
if (pieces.length == 2) {
if (pieces[0].equals("Main-Class")) {
className = pieces[1];
}
}
}
*/
// If no class name found, just move on.
if (className == null) continue;
Class<?> toolClass = Class.forName(className, true, loader);
final Tool tool = (Tool) toolClass.newInstance();
tool.init(Editor.this);
String title = tool.getMenuTitle();
JMenuItem item = new JMenuItem(title);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
//new Thread(tool).start();
}
});
//menu.add(item);
toolItems.put(title, item);
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<String> toolList = new ArrayList<String>(toolItems.keySet());
if (toolList.size() == 0) return;
menu.addSeparator();
Collections.sort(toolList);
for (String title : toolList) {
menu.add(toolItems.get(title));
}
}
private String findClassInZipFile(String base, File file) {
// Class file to search for
String classFileName = "/" + base + ".class";
ZipFile zipFile = null;
try {
zipFile = new ZipFile(file);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (!entry.isDirectory()) {
String name = entry.getName();
//System.out.println("entry: " + name);
if (name.endsWith(classFileName)) {
//int slash = name.lastIndexOf('/');
//String packageName = (slash == -1) ? "" : name.substring(0, slash);
// Remove .class and convert slashes to periods.
return name.substring(0, name.length() - 6).replace('/', '.');
}
}
}
} catch (IOException e) {
//System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
e.printStackTrace();
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
// noop
}
}
}
return null;
}
public void updateKeywords(PdeKeywords keywords) {
for (EditorTab tab : tabs)
tab.updateKeywords(keywords);
}
JMenuItem createToolMenuItem(String className) {
try {
Class<?> toolClass = Class.forName(className);
final Tool tool = (Tool) toolClass.newInstance();
JMenuItem item = new JMenuItem(tool.getMenuTitle());
tool.init(Editor.this);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
}
});
return item;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void addInternalTools(JMenu menu) {
JMenuItem item;
item = createToolMenuItem("cc.arduino.packages.formatter.AStyle");
if (item == null) {
throw new NullPointerException("Tool cc.arduino.packages.formatter.AStyle unavailable");
}
item.setName("menuToolsAutoFormat");
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers));
menu.add(item);
//menu.add(createToolMenuItem("processing.app.tools.CreateFont"));
//menu.add(createToolMenuItem("processing.app.tools.ColorSelector"));
menu.add(createToolMenuItem("processing.app.tools.Archiver"));
menu.add(createToolMenuItem("processing.app.tools.FixEncoding"));
}
class SerialMenuListener implements ActionListener {
private final String serialPort;
public SerialMenuListener(String serialPort) {
this.serialPort = serialPort;
}
public void actionPerformed(ActionEvent e) {
selectSerialPort(serialPort);
base.onBoardOrPortChange();
}
}
private void selectSerialPort(String name) {
if(portMenu == null) {
System.out.println(tr("serialMenu is null"));
return;
}
if (name == null) {
System.out.println(tr("name is null"));
return;
}
JCheckBoxMenuItem selection = null;
for (int i = 0; i < portMenu.getItemCount(); i++) {
JMenuItem menuItem = portMenu.getItem(i);
if (!(menuItem instanceof JCheckBoxMenuItem)) {
continue;
}
JCheckBoxMenuItem checkBoxMenuItem = ((JCheckBoxMenuItem) menuItem);
checkBoxMenuItem.setState(false);
if (name.equals(checkBoxMenuItem.getText())) selection = checkBoxMenuItem;
}
if (selection != null) selection.setState(true);
//System.out.println(item.getLabel());
BaseNoGui.selectSerialPort(name);
if (serialMonitor != null) {
try {
serialMonitor.close();
serialMonitor.setVisible(false);
} catch (Exception e) {
// ignore
}
}
if (serialPlotter != null) {
try {
serialPlotter.close();
serialPlotter.setVisible(false);
} catch (Exception e) {
// ignore
}
}
onBoardOrPortChange();
base.onBoardOrPortChange();
//System.out.println("set to " + get("serial.port"));
}
private void populatePortMenu() {
portMenu.removeAll();
String selectedPort = PreferencesData.get("serial.port");
List<BoardPort> ports = Base.getDiscoveryManager().discovery();
ports = platform.filterPorts(ports, PreferencesData.getBoolean("serial.ports.showall"));
Collections.sort(ports, new Comparator<BoardPort>() {
@Override
public int compare(BoardPort o1, BoardPort o2) {
return BOARD_PROTOCOLS_ORDER.indexOf(o1.getProtocol()) - BOARD_PROTOCOLS_ORDER.indexOf(o2.getProtocol());
}
});
String lastProtocol = null;
String lastProtocolTranslated;
for (BoardPort port : ports) {
if (lastProtocol == null || !port.getProtocol().equals(lastProtocol)) {
if (lastProtocol != null) {
portMenu.addSeparator();
}
lastProtocol = port.getProtocol();
if (BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol()) != -1) {
lastProtocolTranslated = BOARD_PROTOCOLS_ORDER_TRANSLATIONS.get(BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol()));
} else {
lastProtocolTranslated = port.getProtocol();
}
JMenuItem lastProtocolMenuItem = new JMenuItem(tr(lastProtocolTranslated));
lastProtocolMenuItem.setEnabled(false);
portMenu.add(lastProtocolMenuItem);
}
String address = port.getAddress();
String label = port.getLabel();
JCheckBoxMenuItem item = new JCheckBoxMenuItem(label, address.equals(selectedPort));
item.addActionListener(new SerialMenuListener(address));
portMenu.add(item);
}
portMenu.setEnabled(portMenu.getMenuComponentCount() > 0);
}
private JMenu buildHelpMenu() {
// To deal with a Mac OS X 10.5 bug, add an extra space after the name
// so that the OS doesn't try to insert its slow help menu.
JMenu menu = new JMenu(tr("Help"));
menu.setMnemonic(KeyEvent.VK_H);
JMenuItem item;
/*
// testing internal web server to serve up docs from a zip file
item = new JMenuItem("Web Server Test");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//WebServer ws = new WebServer();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
int port = WebServer.launch("/Users/fry/coconut/processing/build/shared/reference.zip");
Base.openURL("http://127.0.0.1:" + port + "/reference/setup_.html");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
});
menu.add(item);
*/
/*
item = new JMenuItem("Browser Test");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Base.openURL("http://processing.org/learning/gettingstarted/");
//JFrame browserFrame = new JFrame("Browser");
BrowserStartup bs = new BrowserStartup("jar:file:/Users/fry/coconut/processing/build/shared/reference.zip!/reference/setup_.html");
bs.initUI();
bs.launch();
}
});
menu.add(item);
*/
item = new JMenuItem(tr("Getting Started"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showArduinoGettingStarted();
}
});
menu.add(item);
item = new JMenuItem(tr("Environment"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showEnvironment();
}
});
menu.add(item);
item = new JMenuItem(tr("Troubleshooting"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showTroubleshooting();
}
});
menu.add(item);
item = new JMenuItem(tr("Reference"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showReference();
}
});
menu.add(item);
menu.addSeparator();
item = new JMenuItem(tr("Galileo Help"));
item.setEnabled(false);
menu.add(item);
item = new JMenuItem(tr("Getting Started"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showReference("reference/Galileo_help_files", "ArduinoIDE_guide_galileo");
}
});
menu.add(item);
item = new JMenuItem(tr("Troubleshooting"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showReference("reference/Galileo_help_files", "Guide_Troubleshooting_Galileo");
}
});
menu.add(item);
menu.addSeparator();
item = new JMenuItem(tr("Edison Help"));
item.setEnabled(false);
menu.add(item);
item = new JMenuItem(tr("Getting Started"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showReference("reference/Edison_help_files", "ArduinoIDE_guide_edison");
}
});
menu.add(item);
item = new JMenuItem(tr("Troubleshooting"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showReference("reference/Edison_help_files", "Guide_Troubleshooting_Edison");
}
});
menu.add(item);
menu.addSeparator();
item = newJMenuItemShift(tr("Find in Reference"), 'F');
item.addActionListener(this::handleFindReference);
menu.add(item);
item = new JMenuItem(tr("Frequently Asked Questions"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showFAQ();
}
});
menu.add(item);
item = new JMenuItem(tr("Visit Arduino.cc"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openURL(tr("http://www.arduino.cc/"));
}
});
menu.add(item);
// macosx already has its own about menu
if (!OSUtils.isMacOS()) {
menu.addSeparator();
item = new JMenuItem(tr("About Arduino"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleAbout();
}
});
menu.add(item);
}
return menu;
}
private JMenu buildEditMenu() {
JMenu menu = new JMenu(tr("Edit"));
menu.setName("menuEdit");
menu.setMnemonic(KeyEvent.VK_E);
undoItem = newJMenuItem(tr("Undo"), 'Z');
undoItem.setName("menuEditUndo");
undoItem.addActionListener(undoAction = new UndoAction());
menu.add(undoItem);
if (!OSUtils.isMacOS()) {
redoItem = newJMenuItem(tr("Redo"), 'Y');
} else {
redoItem = newJMenuItemShift(tr("Redo"), 'Z');
}
redoItem.setName("menuEditRedo");
redoItem.addActionListener(redoAction = new RedoAction());
menu.add(redoItem);
menu.addSeparator();
JMenuItem cutItem = newJMenuItem(tr("Cut"), 'X');
cutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getCurrentTab().handleCut();
}
});
menu.add(cutItem);
JMenuItem copyItem = newJMenuItem(tr("Copy"), 'C');
copyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getCurrentTab().getTextArea().copy();
}
});
menu.add(copyItem);
JMenuItem copyForumItem = newJMenuItemShift(tr("Copy for Forum"), 'C');
copyForumItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getCurrentTab().handleHTMLCopy();
}
});
menu.add(copyForumItem);
JMenuItem copyHTMLItem = newJMenuItemAlt(tr("Copy as HTML"), 'C');
copyHTMLItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getCurrentTab().handleDiscourseCopy();
}
});
menu.add(copyHTMLItem);
JMenuItem pasteItem = newJMenuItem(tr("Paste"), 'V');
pasteItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getCurrentTab().handlePaste();
}
});
menu.add(pasteItem);
JMenuItem selectAllItem = newJMenuItem(tr("Select All"), 'A');
selectAllItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getCurrentTab().handleSelectAll();
}
});
menu.add(selectAllItem);
JMenuItem gotoLine = newJMenuItem(tr("Go to line..."), 'L');
gotoLine.addActionListener(e -> {
GoToLineNumber goToLineNumber = new GoToLineNumber(Editor.this);
goToLineNumber.setLocationRelativeTo(Editor.this);
goToLineNumber.setVisible(true);
});
menu.add(gotoLine);
menu.addSeparator();
JMenuItem commentItem = newJMenuItem(tr("Comment/Uncomment"), '/');
commentItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getCurrentTab().handleCommentUncomment();
}
});
menu.add(commentItem);
JMenuItem increaseIndentItem = new JMenuItem(tr("Increase Indent"));
increaseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
increaseIndentItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getCurrentTab().handleIndentOutdent(true);
}
});
menu.add(increaseIndentItem);
JMenuItem decreseIndentItem = new JMenuItem(tr("Decrease Indent"));
decreseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK));
decreseIndentItem.setName("menuDecreaseIndent");
decreseIndentItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getCurrentTab().handleIndentOutdent(false);
}
});
menu.add(decreseIndentItem);
menu.addSeparator();
JMenuItem findItem = newJMenuItem(tr("Find..."), 'F');
findItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find == null) {
find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE);
}
if (!OSUtils.isMacOS()) {
find.setFindText(getCurrentTab().getSelectedText());
}
find.setLocationRelativeTo(Editor.this);
find.setVisible(true);
}
});
menu.add(findItem);
JMenuItem findNextItem = newJMenuItem(tr("Find Next"), 'G');
findNextItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find != null) {
find.findNext();
}
}
});
menu.add(findNextItem);
JMenuItem findPreviousItem = newJMenuItemShift(tr("Find Previous"), 'G');
findPreviousItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find != null) {
find.findPrevious();
}
}
});
menu.add(findPreviousItem);
if (OSUtils.isMacOS()) {
JMenuItem useSelectionForFindItem = newJMenuItem(tr("Use Selection For Find"), 'E');
useSelectionForFindItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find == null) {
find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE);
}
find.setFindText(getCurrentTab().getSelectedText());
}
});
menu.add(useSelectionForFindItem);
}
menu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
boolean enabled = getCurrentTab().getSelectedText() != null;
cutItem.setEnabled(enabled);
copyItem.setEnabled(enabled);
}
@Override
public void menuDeselected(MenuEvent e) {}
@Override
public void menuCanceled(MenuEvent e) {}
});
return menu;
}
/**
* A software engineer, somewhere, needs to have his abstraction
* taken away. In some countries they jail or beat people for writing
* the sort of API that would require a five line helper function
* just to set the command key for a menu item.
*/
static public JMenuItem newJMenuItem(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK));
return menuItem;
}
/**
* Like newJMenuItem() but adds shift as a modifier for the key command.
*/
static public JMenuItem newJMenuItemShift(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK | ActionEvent.SHIFT_MASK));
return menuItem;
}
/**
* Same as newJMenuItem(), but adds the ALT (on Linux and Windows)
* or OPTION (on Mac OS X) key as a modifier.
*/
private static JMenuItem newJMenuItemAlt(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK));
return menuItem;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
class UndoAction extends AbstractAction {
public UndoAction() {
super("Undo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
getCurrentTab().handleUndo();
} catch (CannotUndoException ex) {
//System.out.println("Unable to undo: " + ex);
//ex.printStackTrace();
}
}
protected void updateUndoState() {
UndoManager undo = getCurrentTab().getUndoManager();
if (undo.canUndo()) {
this.setEnabled(true);
undoItem.setEnabled(true);
undoItem.setText(undo.getUndoPresentationName());
putValue(Action.NAME, undo.getUndoPresentationName());
} else {
this.setEnabled(false);
undoItem.setEnabled(false);
undoItem.setText(tr("Undo"));
putValue(Action.NAME, "Undo");
}
}
}
class RedoAction extends AbstractAction {
public RedoAction() {
super("Redo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
getCurrentTab().handleRedo();
} catch (CannotRedoException ex) {
//System.out.println("Unable to redo: " + ex);
//ex.printStackTrace();
}
}
protected void updateRedoState() {
UndoManager undo = getCurrentTab().getUndoManager();
if (undo.canRedo()) {
redoItem.setEnabled(true);
redoItem.setText(undo.getRedoPresentationName());
putValue(Action.NAME, undo.getRedoPresentationName());
} else {
this.setEnabled(false);
redoItem.setEnabled(false);
redoItem.setText(tr("Redo"));
putValue(Action.NAME, "Redo");
}
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// these will be done in a more generic way soon, more like:
// setHandler("action name", Runnable);
// but for the time being, working out the kinks of how many things to
// abstract from the editor in this fashion.
private void resetHandlers() {
runHandler = new BuildHandler();
presentHandler = new BuildHandler(true);
runAndSaveHandler = new BuildHandler(false, true);
presentAndSaveHandler = new BuildHandler(true, true);
exportHandler = new DefaultExportHandler();
exportAppHandler = new DefaultExportAppHandler();
timeoutUploadHandler = new TimeoutUploadHandler();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Gets the current sketch controller.
*/
public SketchController getSketchController() {
return sketchController;
}
/**
* Gets the current sketch.
*/
public Sketch getSketch() {
return sketch;
}
/**
* Gets the currently displaying tab.
*/
public EditorTab getCurrentTab() {
return tabs.get(currentTabIndex);
}
/**
* Gets the index of the currently displaying tab.
*/
public int getCurrentTabIndex() {
return currentTabIndex;
}
/**
* Returns an (unmodifiable) list of currently opened tabs.
*/
public List<EditorTab> getTabs() {
return Collections.unmodifiableList(tabs);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Change the currently displayed tab.
* Note that the GUI might not update immediately, since this needs
* to run in the Event dispatch thread.
* @param index The index of the tab to select
*/
public void selectTab(final int index) {
currentTabIndex = index;
undoAction.updateUndoState();
redoAction.updateRedoState();
updateTitle();
header.rebuild();
getCurrentTab().activated();
// This must be run in the GUI thread
SwingUtilities.invokeLater(() -> {
codePanel.removeAll();
codePanel.add(tabs.get(index), BorderLayout.CENTER);
tabs.get(index).requestFocusInWindow(); // get the caret blinking
// For some reason, these are needed. Revalidate says it should be
// automatically called when components are added or removed, but without
// it, the component switched to is not displayed. repaint() is needed to
// clear the entire text area of any previous text.
codePanel.revalidate();
codePanel.repaint();
});
}
public void selectNextTab() {
selectTab((currentTabIndex + 1) % tabs.size());
}
public void selectPrevTab() {
selectTab((currentTabIndex - 1 + tabs.size()) % tabs.size());
}
public EditorTab findTab(final SketchFile file) {
return tabs.get(findTabIndex(file));
}
/**
* Finds the index of the tab showing the given file. Matches the file against
* EditorTab.getSketchFile() using ==.
*
* @returns The index of the tab for the given file, or -1 if no such tab was
* found.
*/
public int findTabIndex(final SketchFile file) {
for (int i = 0; i < tabs.size(); ++i) {
if (tabs.get(i).getSketchFile() == file)
return i;
}
return -1;
}
/**
* Finds the index of the tab showing the given file. Matches the file against
* EditorTab.getSketchFile().getFile() using equals.
*
* @returns The index of the tab for the given file, or -1 if no such tab was
* found.
*/
public int findTabIndex(final File file) {
for (int i = 0; i < tabs.size(); ++i) {
if (tabs.get(i).getSketchFile().getFile().equals(file))
return i;
}
return -1;
}
/**
* Create tabs for each of the current sketch's files, removing any existing
* tabs.
*/
public void createTabs() {
tabs.clear();
currentTabIndex = -1;
tabs.ensureCapacity(sketch.getCodeCount());
for (SketchFile file : sketch.getFiles()) {
try {
addTab(file, null);
} catch(IOException e) {
// TODO: Improve / move error handling
System.err.println(e);
}
}
selectTab(0);
}
/**
* Add a new tab.
*
* @param file
* The file to show in the tab.
* @param contents
* The contents to show in the tab, or null to load the contents from
* the given file.
* @throws IOException
*/
protected void addTab(SketchFile file, String contents) throws IOException {
EditorTab tab = new EditorTab(this, file, contents);
tabs.add(tab);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
void handleFindReference(ActionEvent e) {
String text = getCurrentTab().getCurrentKeyword();
String referenceFile = base.getPdeKeywords().getReference(text);
if (referenceFile == null) {
statusNotice(I18n.format(tr("No reference available for \"{0}\""), text));
} else {
if (referenceFile.startsWith("Serial_")) {
Base.showReference("Serial/" + referenceFile.substring("Serial_".length()));
} else {
Base.showReference("Reference/" + referenceFile);
}
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Implements Sketch → Run.
* @param verbose Set true to run with verbose output.
* @param verboseHandler
* @param nonVerboseHandler
*/
public void handleRun(final boolean verbose, Runnable verboseHandler, Runnable nonVerboseHandler) {
handleRun(verbose, new ShouldSaveIfModified(), verboseHandler, nonVerboseHandler);
}
private void handleRun(final boolean verbose, Predicate<SketchController> shouldSavePredicate, Runnable verboseHandler, Runnable nonVerboseHandler) {
if (shouldSavePredicate.test(sketchController)) {
handleSave(true);
}
toolbar.activateRun();
status.progress(tr("Compiling sketch..."));
// do this to advance/clear the terminal window / dos prompt / etc
for (int i = 0; i < 10; i++) System.out.println();
// clear the console on each run, unless the user doesn't want to
if (PreferencesData.getBoolean("console.auto_clear")) {
console.clear();
}
// Cannot use invokeLater() here, otherwise it gets
// placed on the event thread and causes a hang--bad idea all around.
new Thread(verbose ? verboseHandler : nonVerboseHandler).start();
}
class BuildHandler implements Runnable {
private final boolean verbose;
private final boolean saveHex;
public BuildHandler() {
this(false);
}
public BuildHandler(boolean verbose) {
this(verbose, false);
}
public BuildHandler(boolean verbose, boolean saveHex) {
this.verbose = verbose;
this.saveHex = saveHex;
}
@Override
public void run() {
try {
removeAllLineHighlights();
sketchController.build(verbose, saveHex);
statusNotice(tr("Done compiling."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
tr("Error while compiling: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (Exception e) {
status.unprogress();
statusError(e);
}
status.unprogress();
toolbar.deactivateRun();
avoidMultipleOperations = false;
}
}
public void removeAllLineHighlights() {
for (EditorTab tab : tabs)
tab.getTextArea().removeAllLineHighlights();
}
public void addLineHighlight(int line) throws BadLocationException {
getCurrentTab().getTextArea().addLineHighlight(line, new Color(1, 0, 0, 0.2f));
getCurrentTab().getTextArea().setCaretPosition(getCurrentTab().getTextArea().getLineStartOffset(line));
}
/**
* Implements Sketch → Stop, or pressing Stop on the toolbar.
*/
private void handleStop() { // called by menu or buttons
// toolbar.activate(EditorToolbar.STOP);
toolbar.deactivateRun();
// toolbar.deactivate(EditorToolbar.STOP);
// focus the PDE again after quitting presentation mode [toxi 030903]
toFront();
}
/**
* Check if the sketch is modified and ask user to save changes.
* @return false if canceling the close/quit operation
*/
protected boolean checkModified() {
if (!sketch.isModified())
return true;
// As of Processing 1.0.10, this always happens immediately.
// http://dev.processing.org/bugs/show_bug.cgi?id=1456
toFront();
String prompt = I18n.format(tr("Save changes to \"{0}\"? "),
sketch.getName());
if (!OSUtils.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(this, prompt, tr("Close"),
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
switch (result) {
case JOptionPane.YES_OPTION:
return handleSave(true);
case JOptionPane.NO_OPTION:
return true; // ok to continue
case JOptionPane.CANCEL_OPTION:
case JOptionPane.CLOSED_OPTION: // Escape key pressed
return false;
default:
throw new IllegalStateException();
}
} else {
// This code is disabled unless Java 1.5 is being used on Mac OS X
// because of a Java bug that prevents the initial value of the
// dialog from being set properly (at least on my MacBook Pro).
// The bug causes the "Don't Save" option to be the highlighted,
// blinking, default. This sucks. But I'll tell you what doesn't
// suck--workarounds for the Mac and Apple's snobby attitude about it!
// I think it's nifty that they treat their developers like dirt.
JOptionPane pane =
new JOptionPane(tr("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Do you want to save changes to this sketch<BR>" +
" before closing?</b>" +
"<p>If you don't save, your changes will be lost."),
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
tr("Save"), tr("Cancel"), tr("Don't Save")
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
JDialog dialog = pane.createDialog(this, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) { // save (and close/quit)
return handleSave(true);
} else {
return result == options[2];
}
}
}
/**
* Second stage of open, occurs after having checked to see if the
* modifications (if any) to the previous sketch need to be saved.
*/
protected boolean handleOpenInternal(File sketchFile) {
// check to make sure that this .pde file is
// in a folder of the same name
String fileName = sketchFile.getName();
File file = Sketch.checkSketchFile(sketchFile);
if (file == null) {
if (!fileName.endsWith(".ino") && !fileName.endsWith(".pde")) {
Base.showWarning(tr("Bad file selected"), tr("Arduino can only open its own sketches\n" +
"and other files ending in .ino or .pde"), null);
return false;
} else {
String properParent = fileName.substring(0, fileName.length() - 4);
Object[] options = {tr("OK"), tr("Cancel")};
String prompt = I18n.format(tr("The file \"{0}\" needs to be inside\n" +
"a sketch folder named \"{1}\".\n" +
"Create this folder, move the file, and continue?"),
fileName,
properParent);
int result = JOptionPane.showOptionDialog(this, prompt, tr("Moving"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (result != JOptionPane.YES_OPTION) {
return false;
}
// create properly named folder
File properFolder = new File(sketchFile.getParent(), properParent);
if (properFolder.exists()) {
Base.showWarning(tr("Error"), I18n.format(tr("A folder named \"{0}\" already exists. " +
"Can't open sketch."), properParent), null);
return false;
}
if (!properFolder.mkdirs()) {
//throw new IOException("Couldn't create sketch folder");
Base.showWarning(tr("Error"), tr("Could not create the sketch folder."), null);
return false;
}
// copy the sketch inside
File properPdeFile = new File(properFolder, sketchFile.getName());
try {
Base.copyFile(sketchFile, properPdeFile);
} catch (IOException e) {
Base.showWarning(tr("Error"), tr("Could not copy to a proper location."), e);
return false;
}
// remove the original file, so user doesn't get confused
sketchFile.delete();
// update with the new path
file = properPdeFile;
}
}
try {
sketch = new Sketch(file);
} catch (IOException e) {
Base.showWarning(tr("Error"), tr("Could not create the sketch."), e);
return false;
}
sketchController = new SketchController(this, sketch);
createTabs();
// Disable untitled setting from previous document, if any
untitled = false;
// opening was successful
return true;
}
private void updateTitle() {
if (sketchController == null) {
return;
}
SketchFile current = getCurrentTab().getSketchFile();
if (current.isPrimary()) {
setTitle(I18n.format(tr("{0} | Arduino {1}"), sketch.getName(),
BaseNoGui.VERSION_NAME_LONG));
} else {
setTitle(I18n.format(tr("{0} - {1} | Arduino {2}"), sketch.getName(),
current.getFileName(), BaseNoGui.VERSION_NAME_LONG));
}
}
/**
* Actually handle the save command. If 'immediately' is set to false,
* this will happen in another thread so that the message area
* will update and the save button will stay highlighted while the
* save is happening. If 'immediately' is true, then it will happen
* immediately. This is used during a quit, because invokeLater()
* won't run properly while a quit is happening. This fixes
* <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=276">Bug 276</A>.
*/
public boolean handleSave(boolean immediately) {
//stopRunner();
handleStop(); // 0136
removeAllLineHighlights();
if (untitled) {
return handleSaveAs();
// need to get the name, user might also cancel here
} else if (immediately) {
return handleSave2();
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
handleSave2();
}
});
}
return true;
}
private boolean handleSave2() {
toolbar.activateSave();
statusNotice(tr("Saving..."));
boolean saved = false;
try {
boolean wasReadOnly = sketchController.isReadOnly(BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath());
String previousMainFilePath = sketch.getMainFilePath();
saved = sketchController.save();
if (saved) {
statusNotice(tr("Done Saving."));
if (wasReadOnly) {
base.removeRecentSketchPath(previousMainFilePath);
}
base.storeRecentSketches(sketchController);
base.rebuildRecentSketchesMenuItems();
} else {
statusEmpty();
}
// rebuild sketch menu in case a save-as was forced
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenus();
//sketchbook.rebuildMenusAsync();
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
// zero out the current action,
// so that checkModified2 will just do nothing
//checkModifiedMode = 0;
// this is used when another operation calls a save
}
//toolbar.clear();
toolbar.deactivateSave();
return saved;
}
public boolean handleSaveAs() {
//stopRunner(); // formerly from 0135
handleStop();
toolbar.activateSave();
//SwingUtilities.invokeLater(new Runnable() {
//public void run() {
statusNotice(tr("Saving..."));
try {
if (sketchController.saveAs()) {
base.storeRecentSketches(sketchController);
base.rebuildRecentSketchesMenuItems();
statusNotice(tr("Done Saving."));
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenusAsync();
} else {
statusNotice(tr("Save Canceled."));
return false;
}
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
} finally {
// make sure the toolbar button deactivates
toolbar.deactivateSave();
}
return true;
}
private boolean serialPrompt() {
int count = portMenu.getItemCount();
Object[] names = new Object[count];
for (int i = 0; i < count; i++) {
names[i] = portMenu.getItem(i).getText();
}
String result = (String)
JOptionPane.showInputDialog(this,
I18n.format(
tr("Serial port {0} not found.\n" +
"Retry the upload with another serial port?"),
PreferencesData.get("serial.port")
),
"Serial port not found",
JOptionPane.PLAIN_MESSAGE,
null,
names,
0);
if (result == null) return false;
selectSerialPort(result);
base.onBoardOrPortChange();
return true;
}
/**
* Called by Sketch → Export.
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
* <p/>
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
/**
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
*
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
synchronized public void handleExport(final boolean usingProgrammer) {
if (PreferencesData.getBoolean("editor.save_on_verify")) {
if (sketch.isModified()
&& !sketchController.isReadOnly(
BaseNoGui.librariesIndexer
.getInstalledLibraries(),
BaseNoGui.getExamplesPath())) {
handleSave(true);
}
}
toolbar.activateExport();
console.clear();
status.progress(tr("Uploading to I/O Board..."));
new Thread(timeoutUploadHandler).start();
new Thread(usingProgrammer ? exportAppHandler : exportHandler).start();
}
// DAM: in Arduino, this is upload
class DefaultExportHandler implements Runnable {
public void run() {
try {
removeAllLineHighlights();
if (serialMonitor != null) {
serialMonitor.suspend();
}
if (serialPlotter != null) {
serialPlotter.suspend();
}
uploading = true;
boolean success = sketchController.exportApplet(false);
if (success) {
statusNotice(tr("Done uploading."));
}
} catch (SerialNotFoundException e) {
if (portMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice(tr("Upload canceled."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
tr("Error while uploading: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
} finally {
populatePortMenu();
avoidMultipleOperations = false;
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivateExport();
resumeOrCloseSerialMonitor();
resumeOrCloseSerialPlotter();
base.onBoardOrPortChange();
}
}
private void resumeOrCloseSerialMonitor() {
// Return the serial monitor window to its initial state
if (serialMonitor != null) {
BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port"));
long sleptFor = 0;
while (boardPort == null && sleptFor < MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR) {
try {
Thread.sleep(100);
sleptFor += 100;
boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port"));
} catch (InterruptedException e) {
// noop
}
}
try {
if (serialMonitor != null) {
serialMonitor.resume(boardPort);
if (boardPort == null) {
serialMonitor.close();
handleSerial();
} else {
serialMonitor.resume(boardPort);
}
}
} catch (Exception e) {
statusError(e);
}
}
}
private void resumeOrCloseSerialPlotter() {
// Return the serial plotter window to its initial state
if (serialPlotter != null) {
BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port"));
try {
if (serialPlotter != null)
serialPlotter.resume(boardPort);
if (boardPort == null) {
serialPlotter.close();
handlePlotter();
} else {
serialPlotter.resume(boardPort);
}
} catch (Exception e) {
statusError(e);
}
}
}
// DAM: in Arduino, this is upload (with verbose output)
class DefaultExportAppHandler implements Runnable {
public void run() {
try {
if (serialMonitor != null) {
serialMonitor.suspend();
}
if (serialPlotter != null) {
serialPlotter.suspend();
}
uploading = true;
boolean success = sketchController.exportApplet(true);
if (success) {
statusNotice(tr("Done uploading."));
}
} catch (SerialNotFoundException e) {
if (portMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice(tr("Upload canceled."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
tr("Error while uploading: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
} finally {
avoidMultipleOperations = false;
populatePortMenu();
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivateExport();
resumeOrCloseSerialMonitor();
resumeOrCloseSerialPlotter();
base.onBoardOrPortChange();
}
}
class TimeoutUploadHandler implements Runnable {
public void run() {
try {
//10 seconds, than reactivate upload functionality and let the programmer pid being killed
Thread.sleep(1000 * 10);
if (uploading) {
avoidMultipleOperations = false;
}
} catch (InterruptedException e) {
// noop
}
}
}
public void handleSerial() {
if(serialPlotter != null) {
if(serialPlotter.isClosed()) {
serialPlotter = null;
} else {
statusError(tr("Serial monitor not available while plotter is open"));
return;
}
}
if (serialMonitor != null) {
// The serial monitor already exists
if (serialMonitor.isClosed()) {
serialMonitor.dispose();
// If it's closed, clear the refrence to the existing
// monitor and create a new one
serialMonitor = null;
}
else {
// If it's not closed, give it the focus
try {
serialMonitor.toFront();
serialMonitor.requestFocus();
return;
} catch (Exception e) {
// noop
}
}
}
BoardPort port = Base.getDiscoveryManager().find(PreferencesData.get("serial.port"));
if (port == null) {
statusError(I18n.format(tr("Board at {0} is not available"), PreferencesData.get("serial.port")));
return;
}
serialMonitor = new MonitorFactory().newMonitor(port);
Base.setIcon(serialMonitor);
// If currently uploading, disable the monitor (it will be later
// enabled when done uploading)
if (uploading || avoidMultipleOperations) {
try {
serialMonitor.suspend();
} catch (Exception e) {
statusError(e);
}
}
boolean success = false;
do {
if (serialMonitor.requiresAuthorization() && !PreferencesData.has(serialMonitor.getAuthorizationKey())) {
PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, tr("Type board password to access its console"));
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if (dialog.isCancelled()) {
statusNotice(tr("Unable to open serial monitor"));
return;
}
PreferencesData.set(serialMonitor.getAuthorizationKey(), dialog.getPassword());
}
try {
serialMonitor.setVisible(true);
if (!avoidMultipleOperations) {
serialMonitor.open();
}
success = true;
} catch (ConnectException e) {
statusError(tr("Unable to connect: is the sketch using the bridge?"));
} catch (JSchException e) {
statusError(tr("Unable to connect: wrong password?"));
} catch (SerialException e) {
String errorMessage = e.getMessage();
if (e.getCause() != null && e.getCause() instanceof SerialPortException) {
errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")";
}
statusError(errorMessage);
try {
serialMonitor.close();
} catch (Exception e1) {
// noop
}
} catch (Exception e) {
statusError(e);
} finally {
if (serialMonitor.requiresAuthorization() && !success) {
PreferencesData.remove(serialMonitor.getAuthorizationKey());
}
}
} while (serialMonitor.requiresAuthorization() && !success);
}
public void handlePlotter() {
if(serialMonitor != null) {
if(serialMonitor.isClosed()) {
serialMonitor = null;
} else {
statusError(tr("Plotter not available while serial monitor is open"));
return;
}
}
if (serialPlotter != null) {
// The serial plotter already exists
if (serialPlotter.isClosed()) {
// If it's closed, clear the refrence to the existing
// plotter and create a new one
serialPlotter = null;
}
else {
// If it's not closed, give it the focus
try {
serialPlotter.toFront();
serialPlotter.requestFocus();
return;
} catch (Exception e) {
// noop
}
}
}
BoardPort port = Base.getDiscoveryManager().find(PreferencesData.get("serial.port"));
if (port == null) {
statusError(I18n.format(tr("Board at {0} is not available"), PreferencesData.get("serial.port")));
return;
}
serialPlotter = new SerialPlotter(port);
Base.setIcon(serialPlotter);
// If currently uploading, disable the plotter (it will be later
// enabled when done uploading)
if (uploading) {
try {
serialPlotter.suspend();
} catch (Exception e) {
statusError(e);
}
}
boolean success = false;
do {
if (serialPlotter.requiresAuthorization() && !PreferencesData.has(serialPlotter.getAuthorizationKey())) {
PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, tr("Type board password to access its console"));
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if (dialog.isCancelled()) {
statusNotice(tr("Unable to open serial plotter"));
return;
}
PreferencesData.set(serialPlotter.getAuthorizationKey(), dialog.getPassword());
}
try {
serialPlotter.open();
serialPlotter.setVisible(true);
success = true;
} catch (ConnectException e) {
statusError(tr("Unable to connect: is the sketch using the bridge?"));
} catch (JSchException e) {
statusError(tr("Unable to connect: wrong password?"));
} catch (SerialException e) {
String errorMessage = e.getMessage();
if (e.getCause() != null && e.getCause() instanceof SerialPortException) {
errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")";
}
statusError(errorMessage);
} catch (Exception e) {
statusError(e);
} finally {
if (serialPlotter.requiresAuthorization() && !success) {
PreferencesData.remove(serialPlotter.getAuthorizationKey());
}
}
} while (serialPlotter.requiresAuthorization() && !success);
}
private void handleBurnBootloader() {
console.clear();
statusNotice(tr("Burning bootloader to I/O Board (this may take a minute)..."));
new Thread(() -> {
try {
Uploader uploader = new SerialUploader();
if (uploader.burnBootloader()) {
SwingUtilities.invokeLater(() -> statusNotice(tr("Done burning bootloader.")));
} else {
SwingUtilities.invokeLater(() -> statusError(tr("Error while burning bootloader.")));
// error message will already be visible
}
} catch (PreferencesMapException e) {
SwingUtilities.invokeLater(() -> {
statusError(I18n.format(
tr("Error while burning bootloader: missing '{0}' configuration parameter"),
e.getMessage()));
});
} catch (RunnerException e) {
SwingUtilities.invokeLater(() -> statusError(e.getMessage()));
} catch (Exception e) {
SwingUtilities.invokeLater(() -> statusError(tr("Error while burning bootloader.")));
e.printStackTrace();
}
}).start();
}
private void handleBoardInfo() {
console.clear();
String selectedPort = PreferencesData.get("serial.port");
List<BoardPort> ports = Base.getDiscoveryManager().discovery();
String label = "";
String vid = "";
String pid = "";
String iserial = "";
String protocol = "";
boolean found = false;
for (BoardPort port : ports) {
if (port.getAddress().equals(selectedPort)) {
label = port.getBoardName();
vid = port.getVID();
pid = port.getPID();
iserial = port.getISerial();
protocol = port.getProtocol();
found = true;
break;
}
}
if (!found) {
statusNotice(tr("Please select a port to obtain board info"));
return;
}
if (protocol.equals("network")) {
statusNotice(tr("Network port, can't obtain info"));
return;
}
if (vid == null || vid.equals("") || vid.equals("0000")) {
statusNotice(tr("Native serial port, can't obtain info"));
return;
}
if (iserial == null || iserial.equals("")) {
iserial = tr("Upload any sketch to obtain it");
}
if (label == null) {
label = tr("Unknown board");
}
String infos = I18n.format("BN: {0}\nVID: {1}\nPID: {2}\nSN: {3}", label, vid, pid, iserial);
JTextArea textArea = new JTextArea(infos);
JOptionPane.showMessageDialog(this, textArea, tr("Board Info"), JOptionPane.PLAIN_MESSAGE);
}
/**
* Handler for File → Page Setup.
*/
private void handlePageSetup() {
PrinterJob printerJob = PrinterJob.getPrinterJob();
if (pageFormat == null) {
pageFormat = printerJob.defaultPage();
}
pageFormat = printerJob.pageDialog(pageFormat);
}
/**
* Handler for File → Print.
*/
private void handlePrint() {
statusNotice(tr("Printing..."));
//printerJob = null;
PrinterJob printerJob = PrinterJob.getPrinterJob();
if (pageFormat != null) {
//System.out.println("setting page format " + pageFormat);
printerJob.setPrintable(getCurrentTab().getTextArea(), pageFormat);
} else {
printerJob.setPrintable(getCurrentTab().getTextArea());
}
// set the name of the job to the code name
printerJob.setJobName(getCurrentTab().getSketchFile().getPrettyName());
if (printerJob.printDialog()) {
try {
printerJob.print();
statusNotice(tr("Done printing."));
} catch (PrinterException pe) {
statusError(tr("Error while printing."));
pe.printStackTrace();
}
} else {
statusNotice(tr("Printing canceled."));
}
//printerJob = null; // clear this out?
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Show an error int the status bar.
*/
public void statusError(String what) {
System.err.println(what);
status.error(what);
//new Exception("deactivating RUN").printStackTrace();
toolbar.deactivateRun();
}
/**
* Show an exception in the editor status bar.
*/
public void statusError(Exception e) {
e.printStackTrace();
// if (e == null) {
// System.err.println("Editor.statusError() was passed a null exception.");
// return;
// }
if (e instanceof RunnerException) {
RunnerException re = (RunnerException) e;
if (re.hasCodeFile()) {
selectTab(findTabIndex(re.getCodeFile()));
}
if (re.hasCodeLine()) {
int line = re.getCodeLine();
// subtract one from the end so that the \n ain't included
if (line >= getCurrentTab().getTextArea().getLineCount()) {
// The error is at the end of this current chunk of code,
// so the last line needs to be selected.
line = getCurrentTab().getTextArea().getLineCount() - 1;
if (getCurrentTab().getLineText(line).length() == 0) {
// The last line may be zero length, meaning nothing to select.
// If so, back up one more line.
line--;
}
}
if (line < 0 || line >= getCurrentTab().getTextArea().getLineCount()) {
System.err.println(I18n.format(tr("Bad error line: {0}"), line));
} else {
try {
addLineHighlight(line);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
}
// Since this will catch all Exception types, spend some time figuring
// out which kind and try to give a better error message to the user.
String mess = e.getMessage();
if (mess != null) {
String javaLang = "java.lang.";
if (mess.indexOf(javaLang) == 0) {
mess = mess.substring(javaLang.length());
}
String rxString = "RuntimeException: ";
if (mess.indexOf(rxString) == 0) {
mess = mess.substring(rxString.length());
}
statusError(mess);
}
// e.printStackTrace();
}
/**
* Show a notice message in the editor status bar.
*/
public void statusNotice(String msg) {
status.notice(msg);
}
/**
* Clear the status area.
*/
private void statusEmpty() {
statusNotice(EMPTY);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
protected void onBoardOrPortChange() {
Map<String, String> boardPreferences = BaseNoGui.getBoardPreferences();
if (boardPreferences != null)
lineStatus.setBoardName(boardPreferences.get("name"));
else
lineStatus.setBoardName("-");
lineStatus.setSerialPort(PreferencesData.get("serial.port"));
lineStatus.repaint();
}
}
| lgpl-2.1 |
dana-i2cat/opennaas | utils/old-cim/SwitchPortSpanningTreeStatistics.java | 2333 | /**
* This file was auto-generated by mofcomp -j version 1.0.0 on Wed Jan 12
* 09:21:06 CET 2011.
*/
package org.opennaas.extensions.router.model;
import java.io.*;
import java.lang.Exception;
/**
* This Class contains accessor and mutator methods for all properties defined in the CIM class SwitchPortSpanningTreeStatistics as well as methods
* comparable to the invokeMethods defined for this class. This Class implements the SwitchPortSpanningTreeStatisticsBean Interface. The CIM class
* SwitchPortSpanningTreeStatistics is described as follows:
*
* Statistical information regarding a SwitchPort participating in the spanning tree.
*/
public class SwitchPortSpanningTreeStatistics extends
SAPStatisticalInformation implements Serializable {
/**
* This constructor creates a SwitchPortSpanningTreeStatisticsBeanImpl Class which implements the SwitchPortSpanningTreeStatisticsBean Interface,
* and encapsulates the CIM class SwitchPortSpanningTreeStatistics in a Java Bean. The CIM class SwitchPortSpanningTreeStatistics is described as
* follows:
*
* Statistical information regarding a SwitchPort participating in the spanning tree.
*/
public SwitchPortSpanningTreeStatistics() {
};
/**
* The following constants are defined for use with the ValueMap/Values qualified property forwardTransitions.
*/
private long forwardTransitions;
/**
* This method returns the SwitchPortSpanningTreeStatistics.forwardTransitions property value. This property is described as follows:
*
* The number of times the port has transitioned from the Learning state to the Forwarding state.
*
* @return long current forwardTransitions property value
* @exception Exception
*/
public long getForwardTransitions() {
return this.forwardTransitions;
} // getForwardTransitions
/**
* This method sets the SwitchPortSpanningTreeStatistics.forwardTransitions property value. This property is described as follows:
*
* The number of times the port has transitioned from the Learning state to the Forwarding state.
*
* @param long new forwardTransitions property value
* @exception Exception
*/
public void setForwardTransitions(long forwardTransitions) {
this.forwardTransitions = forwardTransitions;
} // setForwardTransitions
} // Class SwitchPortSpanningTreeStatistics
| lgpl-3.0 |
MesquiteProject/MesquiteCore | Source/mesquite/lib/TreeReference.java | 2086 | /* Mesquite source code. Copyright 1997 and onward, W. Maddison and D. Maddison.
Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code.
The commenting leaves much to be desired. Please approach this source code with the spirit of helping out.
Perhaps with your help we can be more than a few, and make Mesquite better.
Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
Mesquite's web site is http://mesquiteproject.org
This source code and its compiled class files are free and modifiable under the terms of
GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html)
*/
package mesquite.lib;
import java.awt.*;
import java.math.*;
public class TreeReference {
long id, versionNumber, topologyVersion, branchLengthsVersion;
public TreeReference(){
}
public long getID(){
return id;
}
public long getVersionNumber(){
return versionNumber;
}
public long getTopologyVersion(){
return topologyVersion;
}
public long getBranchLengthsVersion(){
return branchLengthsVersion;
}
public void setID(long n){
id = n;
}
public void setVersionNumber(long n){
versionNumber = n;
}
public void setTopologyVersion(long n){
topologyVersion = n;
}
public void setBranchLengthsVersion(long n){
branchLengthsVersion = n;
}
public String toString(){
return ("Tree id " + id + " version number: " + versionNumber + " topology version: " + topologyVersion + " branch lengths version: " + branchLengthsVersion);
}
/*-----------------------------------------*/
/* Returns whether tree is the same id, topology, branch lengths and or full version */
public boolean equals(TreeReference tr){
if (tr==null)
return false;
if (tr.getID() != getID())
return false;
if (tr.getTopologyVersion() != getTopologyVersion())
return false;
if ((tr.getBranchLengthsVersion() != getBranchLengthsVersion()))
return false;
if ((tr.getVersionNumber() != getVersionNumber()))
return false;
return true;
}
}
| lgpl-3.0 |
SparkyTheFox/Sparkys-Mod-1.11.2-1.4.0-Alpha-SourceCode | common/mod/sparkyfox/servermod/item/ingots/ItemMagnesiumIngot.java | 830 | package mod.sparkyfox.servermod.item.ingots;
import mod.sparkyfox.servermod.ServerMod;
import mod.sparkyfox.servermod.init.ModBlocks;
import mod.sparkyfox.servermod.lib.ModNames;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class ItemMagnesiumIngot extends Item {
public ItemMagnesiumIngot() {
this.setCreativeTab(CreativeTabs.MATERIALS);
}
@Override
public String getUnlocalizedName(ItemStack stack) {
return "MagnesiumIngot" + ServerMod.RESOURCE_PREFIX + ModNames.MagnesiumIngot;
}
//Crafting Recipe\\
public void addRecipes() {
GameRegistry.addShapelessRecipe(new ItemStack(this, 9), ModBlocks.MagnesiumBlock);
}
}
| lgpl-3.0 |
MesquiteProject/MesquiteCore | Source/mesquite/lib/characters/MCharactersHistory.java | 1483 | /* Mesquite source code. Copyright 1997 and onward, W. Maddison and D. Maddison.
Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code.
The commenting leaves much to be desired. Please approach this source code with the spirit of helping out.
Perhaps with your help we can be more than a few, and make Mesquite better.
Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
Mesquite's web site is http://mesquiteproject.org
This source code and its compiled class files are free and modifiable under the terms of
GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html)
*/
package mesquite.lib.characters;
import java.awt.*;
import mesquite.lib.duties.*;
/*Last documented: April 2003 */
/* ======================================================================== */
/**Stores the reconstructed or simulated states at each of the nodes of a tree, for each of many characters.
See general discussion of character storage classes under CharacterState*/
public interface MCharactersHistory extends MAdjustableDistribution {
/**return CharacterHistory object for character ic */
public abstract CharacterHistory getCharacterHistory (int ic);//TODO: pass existing to save instantiations
/*------------*/
/** obtain the states of character ic from the given CharacterDistribution*/
public abstract void transferFrom(int ic, CharacterHistory s);
}
| lgpl-3.0 |
Alfresco/community-edition | projects/repository/source/test-java/org/alfresco/repo/lock/mem/AbstractLockStoreTxTest.java | 24097 | /*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.lock.mem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.util.Date;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.lock.LockType;
import org.alfresco.service.cmr.lock.UnableToAquireLockException;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.ConcurrencyFailureException;
/**
* Integration tests that check transaction related functionality of {@link LockStore} implementations.
* @author Matt Ward
*/
public abstract class AbstractLockStoreTxTest<T extends LockStore>
{
/**
* Instance of the Class Under Test.
*/
protected T lockStore;
protected static ApplicationContext ctx;
/**
* Concrete subclasses must implement this method to provide the tests with a LockStore instance.
*
* @return LockStore to test
*/
protected abstract T createLockStore();
@BeforeClass
public static void setUpSpringContext()
{
ctx = ApplicationContextHelper.getApplicationContext();
}
@Before
public void setUpLockStore()
{
lockStore = createLockStore();
}
@Test
public void testRepeatableReadsInTransaction() throws NotSupportedException, SystemException
{
final TransactionService txService = (TransactionService) ctx.getBean("TransactionService");
UserTransaction txA = txService.getUserTransaction();
final NodeRef nodeRef = new NodeRef("workspace://SpacesStore/UUID-1");
final NodeRef nodeRef2 = new NodeRef("workspace://SpacesStore/UUID-2");
Date now = new Date();
Date expires = new Date(now.getTime() + 180000);
final LockState lockState1 = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
"jbloggs", expires, Lifetime.EPHEMERAL, null);
Thread txB = new Thread("TxB")
{
@Override
public void run()
{
Object main = AbstractLockStoreTxTest.this;
UserTransaction tx = txService.getUserTransaction();
try
{
tx.begin();
try
{
// txB read lock state
LockState lockState = lockStore.get(nodeRef);
assertEquals("jbloggs", lockState.getOwner());
assertEquals(Lifetime.EPHEMERAL, lockState.getLifetime());
// Wait, while txA changes the lock state
passControl(this, main);
// assert txB still sees state A
lockState = lockStore.get(nodeRef);
assertEquals("jbloggs", lockState.getOwner());
// Wait, while txA checks whether it can see lock for nodeRef2 (though it doesn't exist yet)
passControl(this, main);
// txB sets a value, already seen as non-existent lock by txA
lockStore.set(nodeRef2, LockState.createLock(nodeRef2, LockType.WRITE_LOCK,
"csmith", null, Lifetime.EPHEMERAL, null));
}
finally
{
tx.rollback();
}
}
catch (Throwable e)
{
throw new RuntimeException("Error in transaction B", e);
}
finally
{
// Stop 'main' from waiting
synchronized(main)
{
main.notifyAll();
}
}
}
};
txA.begin();
try
{
// txA set lock state 1
lockStore.set(nodeRef, lockState1);
// Wait while txB reads and checks the LockState
txB.setDaemon(true);
txB.start();
passControl(this, txB);
// txA set different lock state
AuthenticationUtil.setFullyAuthenticatedUser("jbloggs"); // Current lock owner needed to change lock.
final LockState lockState2 = LockState.createWithOwner(lockState1, "another");
lockStore.set(nodeRef, lockState2);
// Wait while txB reads/checks the LockState again for nodeRef
passControl(this, txB);
// Another update
AuthenticationUtil.setFullyAuthenticatedUser("another"); // Current lock owner needed to change lock.
final LockState lockState3 = LockState.createWithOwner(lockState2, "bsmith");
lockStore.set(nodeRef, lockState3);
// Check we can see the update.
assertEquals("bsmith", lockStore.get(nodeRef).getOwner());
// Perform a read, that we know will retrieve a null value
assertNull("nodeRef2 LockState", lockStore.get(nodeRef2));
// Wait while txB populates the store with a value for nodeRef2
passControl(this, txB);
// Perform the read again - update should not be visible in this transaction
assertNull("nodeRef2 LockState", lockStore.get(nodeRef2));
}
finally
{
txA.rollback();
}
}
protected void passControl(Object from, Object to)
{
synchronized(to)
{
to.notifyAll();
}
synchronized(from)
{
try
{
// TODO: wait should be called in a loop with repeated wait condition check,
// but what's the condition we're waiting on?
from.wait(10000);
}
catch (InterruptedException error)
{
throw new RuntimeException(error);
}
}
}
// - only run by HazelcastLockStoreTxTest - fails a lot in HazelcastLockStoreTxTest
// @Test
// public void testReadsWhenNoTransaction() throws NotSupportedException, SystemException
// {
// final NodeRef nodeRef = new NodeRef("workspace://SpacesStore/UUID-1");
// final NodeRef nodeRef2 = new NodeRef("workspace://SpacesStore/UUID-2");
// Date now = new Date();
// Date expires = new Date(now.getTime() + 180000);
// final LockState lockState1 = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
// "jbloggs", expires, Lifetime.EPHEMERAL, null);
//
//
// assertFalse("Transaction present, but should not be. Leak?",
// TransactionSynchronizationManager.isSynchronizationActive());
//
// Thread thread2 = new Thread("Thread2")
// {
// @Override
// public void run()
// {
// assertFalse("Transaction present, but should not be. Leak?",
// TransactionSynchronizationManager.isSynchronizationActive());
//
// Object main = AbstractLockStoreTxTest.this;
// try
// {
// // Thread2 read lock state
// LockState lockState = lockStore.get(nodeRef);
// assertEquals("jbloggs", lockState.getOwner());
// assertEquals(Lifetime.EPHEMERAL, lockState.getLifetime());
//
// // Wait, while Thread1 changes the lock state
// passControl(this, main);
//
// // assert Thread2 sees the updated state
// lockState = lockStore.get(nodeRef);
// assertEquals("another", lockState.getOwner());
//
// // Thread2 sets lock state B
// AuthenticationUtil.setFullyAuthenticatedUser("another"); // Current lock owner
// lockStore.set(nodeRef, LockState.createUnlocked(nodeRef));
//
// // Check it is still visible for this thread
// lockState = lockStore.get(nodeRef);
// assertFalse(lockState.isLockInfo());
// assertNull(lockState.getOwner());
//
// // Wait, while Thread1 checks initial LockState value for nodeRef2 (null)
// passControl(this, main);
//
// // Thread2 sets a value, already seen as null by Thread1 - the update will be seen by Thread1
// lockStore.set(nodeRef2, LockState.createLock(nodeRef2, LockType.WRITE_LOCK,
// "not-null-lockstate", null, Lifetime.EPHEMERAL, null));
// }
// finally
// {
// // Stop 'main' from waiting
// synchronized(main)
// {
// main.notifyAll();
// }
// }
// }
// };
//
//
// // Thread1 set lock state 1
// lockStore.set(nodeRef, lockState1);
//
// // Wait while Thread2 reads and checks the LockState
// thread2.setDaemon(true);
// thread2.start();
// passControl(this, thread2);
//
// // Thread1 sets different lock state
// AuthenticationUtil.setFullyAuthenticatedUser("jbloggs"); // Current lock owner needed to change lock
// final LockState lockState2 = LockState.createWithOwner(lockState1, "another");
// lockStore.set(nodeRef, lockState2);
//
// // Wait while Thread2 reads the LockState again for nodeRef
// passControl(this, thread2);
//
// // Thread2 has unlocked the node, we should see the result
// assertFalse("Node still locked, but shouldn't be", lockStore.get(nodeRef).isLockInfo());
// assertNull(lockStore.get(nodeRef).getOwner());
// assertNull(lockStore.get(nodeRef).getExpires());
//
// // Another update
// AuthenticationUtil.setFullyAuthenticatedUser("jbloggs"); // Current lock owner
// final LockState lockState3 = LockState.createWithOwner(lockState2, "bsmith");
// lockStore.set(nodeRef, lockState3);
// // Check we can see the update.
// assertEquals("bsmith", lockStore.get(nodeRef).getOwner());
//
// // Perform a read, that we know will retrieve a null value
// assertNull("Lock state should be null.", lockStore.get(nodeRef2));
//
// // Wait while Thread2 populates the store with a value for nodeRef2
// passControl(this, thread2);
//
// // Perform the read again - we should see Thread2's update
// assertNotNull("Lock state should NOT be null.", lockStore.get(nodeRef2));
// assertEquals("not-null-lockstate", lockStore.get(nodeRef2).getOwner());
// }
//
@Test
public void testCannotSetLockWhenChangedByAnotherTx() throws NotSupportedException, SystemException
{
final TransactionService txService = (TransactionService) ctx.getBean("TransactionService");
UserTransaction txA = txService.getUserTransaction();
final NodeRef nodeRef = new NodeRef("workspace://SpacesStore/UUID-1");
Date now = new Date();
Date expires = new Date(now.getTime() + 180000);
final LockState lockState1 = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
"jbloggs", expires, Lifetime.EPHEMERAL, null);
Thread txB = new Thread("TxB")
{
@Override
public void run()
{
Object main = AbstractLockStoreTxTest.this;
UserTransaction tx = txService.getUserTransaction();
try
{
tx.begin();
try
{
// txB read lock state
LockState lockState = lockStore.get(nodeRef);
assertEquals("jbloggs", lockState.getOwner());
assertEquals(Lifetime.EPHEMERAL, lockState.getLifetime());
// Wait, while txA changes the lock state
passControl(this, main);
try
{
// Attempt to change the lock state for a NodeRef should fail
// when it has been modified by another tx since this tx last inspected it.
AuthenticationUtil.setFullyAuthenticatedUser("jbloggs"); // Current lock owner
lockStore.set(nodeRef, LockState.createLock(nodeRef, LockType.WRITE_LOCK,
"csmith", null, Lifetime.EPHEMERAL, null));
fail("Exception should have been thrown but was not.");
}
catch (ConcurrencyFailureException e)
{
// Good!
}
}
finally
{
tx.rollback();
}
}
catch (Throwable e)
{
throw new RuntimeException("Error in transaction B", e);
}
finally
{
// Stop 'main' from waiting
synchronized(main)
{
main.notifyAll();
}
}
}
};
txA.begin();
try
{
// txA set lock state 1
lockStore.set(nodeRef, lockState1);
// Wait while txB reads and checks the LockState
txB.setDaemon(true);
txB.start();
passControl(this, txB);
// txA set different lock state
AuthenticationUtil.setFullyAuthenticatedUser("jbloggs"); // Current lock owner needed to change lock.
final LockState lockState2 = LockState.createWithOwner(lockState1, "another");
lockStore.set(nodeRef, lockState2);
// Wait while txB attempts to modify the lock info
passControl(this, txB);
// Lock shouldn't have changed since this tx updated it.
assertEquals(lockState2, lockStore.get(nodeRef));
}
finally
{
txA.rollback();
}
}
@Test
public void testCanChangeLockIfLatestValueIsHeldEvenIfAlreadyChangedByAnotherTx() throws NotSupportedException, SystemException
{
final TransactionService txService = (TransactionService) ctx.getBean("TransactionService");
UserTransaction txA = txService.getUserTransaction();
final NodeRef nodeRef = new NodeRef("workspace://SpacesStore/UUID-1");
final Date now = new Date();
Date expired = new Date(now.getTime() - 180000);
final LockState lockState1 = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
"jbloggs", expired, Lifetime.EPHEMERAL, null);
final LockState lockState2 = LockState.createWithOwner(lockState1, "another");
Thread txB = new Thread("TxB")
{
@Override
public void run()
{
Object main = AbstractLockStoreTxTest.this;
UserTransaction tx = txService.getUserTransaction();
try
{
tx.begin();
try
{
AuthenticationUtil.setFullyAuthenticatedUser("new-user");
// txB read lock state
LockState readLockState = lockStore.get(nodeRef);
assertEquals(lockState2, readLockState);
// Set new value, even though txA has already set new values
// (but not since this tx's initial read)
Date expiresFuture = new Date(now.getTime() + 180000);
final LockState newUserLockState = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
"new-user", expiresFuture, Lifetime.EPHEMERAL, null);
lockStore.set(nodeRef, newUserLockState);
// Read
assertEquals(newUserLockState, lockStore.get(nodeRef));
}
finally
{
tx.rollback();
}
}
catch (Throwable e)
{
throw new RuntimeException("Error in transaction B", e);
}
finally
{
// Stop 'main' from waiting
synchronized(main)
{
main.notifyAll();
}
}
}
};
txA.begin();
try
{
AuthenticationUtil.setFullyAuthenticatedUser("jbloggs"); // Current lock owner needed to change lock.
// txA set lock state 1
lockStore.set(nodeRef, lockState1);
assertEquals(lockState1, lockStore.get(nodeRef));
// txA set different lock state
lockStore.set(nodeRef, lockState2);
assertEquals(lockState2, lockStore.get(nodeRef));
// Wait while txB modifies the lock info
txB.setDaemon(true);
txB.start();
passControl(this, txB);
// This tx should still see the same state, though it has been changed by txB.
assertEquals(lockState2, lockStore.get(nodeRef));
}
finally
{
txA.rollback();
}
}
@Test
public void testNotOnlyCurrentLockOwnerCanChangeInfo() throws NotSupportedException, SystemException
{
final TransactionService txService = (TransactionService) ctx.getBean("TransactionService");
UserTransaction txA = txService.getUserTransaction();
final NodeRef nodeRef = new NodeRef("workspace://SpacesStore/UUID-1");
Date now = new Date();
Date expires = new Date(now.getTime() + 180000);
final LockState lockState1 = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
"jbloggs", expires, Lifetime.EPHEMERAL, null);
txA.begin();
try
{
AuthenticationUtil.setFullyAuthenticatedUser("jbloggs");
// Set initial lock state
lockStore.set(nodeRef, lockState1);
// Set different lock state
// Current lock owner is still authenticated (jbloggs)
final LockState lockState2 = LockState.createWithOwner(lockState1, "csmith");
lockStore.set(nodeRef, lockState2);
// Check update
assertEquals(lockState2, lockStore.get(nodeRef));
// Incorrect lock owner - this shouldn't fail. See ACE-2181
final LockState lockState3 = LockState.createWithOwner(lockState1, "dsmithers");
lockStore.set(nodeRef, lockState3);
// Check update.
assertEquals(lockState3, lockStore.get(nodeRef));
}
finally
{
txA.rollback();
}
}
@Test
public void testOtherUserCanChangeLockInfoOnceExpired() throws NotSupportedException, SystemException
{
final TransactionService txService = (TransactionService) ctx.getBean("TransactionService");
UserTransaction txA = txService.getUserTransaction();
final NodeRef nodeRef = new NodeRef("workspace://SpacesStore/UUID-1");
Date now = new Date();
Date expired = new Date(now.getTime() - 900);
final LockState lockState1 = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
"jbloggs", expired, Lifetime.EPHEMERAL, null);
txA.begin();
try
{
AuthenticationUtil.setFullyAuthenticatedUser("jbloggs");
// Set initial lock state
lockStore.set(nodeRef, lockState1);
// Set different lock state
AuthenticationUtil.setFullyAuthenticatedUser("csmith");
Date expiresFuture = new Date(now.getTime() + 180000);
final LockState lockState2 = LockState.createLock(nodeRef, LockType.WRITE_LOCK,
"csmith", expiresFuture, Lifetime.EPHEMERAL, null);
lockStore.set(nodeRef, lockState2);
// Updated, since lock had expired.
assertEquals(lockState2, lockStore.get(nodeRef));
// Incorrect lock owner - this shouldn't fail
// LockStore does not check for lock owning
// and is owned by csmith.
AuthenticationUtil.setFullyAuthenticatedUser("dsmithers");
final LockState lockState3 = LockState.createWithOwner(lockState2, "dsmithers");
lockStore.set(nodeRef, lockState3);
// Check update.
assertEquals(lockState3, lockStore.get(nodeRef));
}
finally
{
txA.rollback();
}
}
}
| lgpl-3.0 |
F1r3w477/CustomWorldGen | build/tmp/recompileMc/sources/net/minecraftforge/items/VanillaInventoryCodeHooks.java | 5568 | /*
* Minecraft Forge
* Copyright (c) 2016.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.items;
import net.minecraft.block.BlockDropper;
import net.minecraft.block.BlockHopper;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.IHopper;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityDispenser;
import net.minecraft.tileentity.TileEntityHopper;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
public class VanillaInventoryCodeHooks
{
//Return: Null if we did nothing {no IItemHandler}, True if we moved an item, False if we moved no items
public static Boolean extractHook(IHopper dest)
{
TileEntity tileEntity = dest.getWorld().getTileEntity(new BlockPos(dest.getXPos(), dest.getYPos() + 1, dest.getZPos()));
if (tileEntity == null || !tileEntity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN))
return null;
IItemHandler handler = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN);
for (int i = 0; i < handler.getSlots(); i++)
{
ItemStack extractItem = handler.extractItem(i, 1, true);
if (extractItem != null)
{
for (int j = 0; j < dest.getSizeInventory(); j++)
{
ItemStack destStack = dest.getStackInSlot(j);
if (dest.isItemValidForSlot(j, extractItem) && (destStack == null || destStack.stackSize < destStack.getMaxStackSize() && destStack.stackSize < dest.getInventoryStackLimit() && ItemHandlerHelper.canItemStacksStack(extractItem, destStack)))
{
extractItem = handler.extractItem(i, 1, false);
if (destStack == null)
dest.setInventorySlotContents(j, extractItem);
else
{
destStack.stackSize++;
dest.setInventorySlotContents(j, destStack);
}
dest.markDirty();
return true;
}
}
}
}
return false;
}
public static boolean dropperInsertHook(World world, BlockPos pos, TileEntityDispenser dropper, int slot, ItemStack stack)
{
EnumFacing enumfacing = world.getBlockState(pos).getValue(BlockDropper.FACING);
BlockPos offsetPos = pos.offset(enumfacing);
TileEntity tileEntity = world.getTileEntity(offsetPos);
if (tileEntity == null)
return true;
if (!tileEntity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, enumfacing.getOpposite()))
return true;
IItemHandler capability = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, enumfacing.getOpposite());
ItemStack result = ItemHandlerHelper.insertItem(capability, ItemHandlerHelper.copyStackWithSize(stack, 1), false);
if (result == null)
{
result = stack.copy();
if (--result.stackSize == 0)
{
result = null;
}
}
else
{
result = stack.copy();
}
dropper.setInventorySlotContents(slot, result);
dropper.markDirty();
return false;
}
public static boolean insertHook(TileEntityHopper hopper)
{
return insertHook(hopper, BlockHopper.getFacing(hopper.getBlockMetadata()));
}
public static boolean insertHook(IHopper hopper, EnumFacing facing)
{
TileEntity tileEntity = hopper.getWorld().getTileEntity(
new BlockPos(hopper.getXPos(), hopper.getYPos(), hopper.getZPos()).offset(facing));
if (tileEntity == null)
return false;
if (!tileEntity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite()))
return false;
IItemHandler handler = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite());
for (int i = 0; i < hopper.getSizeInventory(); i++)
{
ItemStack stackInSlot = hopper.getStackInSlot(i);
if (stackInSlot != null)
{
ItemStack insert = stackInSlot.copy();
insert.stackSize = 1;
ItemStack newStack = ItemHandlerHelper.insertItem(handler, insert, true);
if (newStack == null || newStack.stackSize == 0)
{
ItemHandlerHelper.insertItem(handler, hopper.decrStackSize(i, 1), false);
hopper.markDirty();
return true;
}
}
}
return true;
}
} | lgpl-3.0 |
FoudroyantFactotum/The-Capricious-Production-Line-of-Wayward-Devices | src/main/java/mod/steamnsteel/client/model/opengex/OpenGEXAnimationFrameProperty.java | 683 | package mod.steamnsteel.client.model.opengex;
import net.minecraftforge.common.property.IUnlistedProperty;
/**
* Created by codew on 4/11/2015.
*/
public enum OpenGEXAnimationFrameProperty implements IUnlistedProperty<OpenGEXState>
{
instance;
@Override
public String getName()
{
return "OpenGEXAnimationTime";
}
@Override
public boolean isValid(OpenGEXState value)
{
return value instanceof OpenGEXState;
}
@Override
public Class<OpenGEXState> getType()
{
return OpenGEXState.class;
}
@Override
public String valueToString(OpenGEXState value)
{
return value.toString();
}
}
| lgpl-3.0 |
triplein/plsql-encfs | src/org/mrpdaemon/sec/encfs/EncFSConfigWriter.java | 5350 | /*
* EncFS Java Library
* Copyright (C) 2011-2012 Mark R. Pariente
*
* This program 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.
*
* 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 Lesser General Public License for more details.
*/
package org.mrpdaemon.sec.encfs;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
/**
* Writer methods that write an EncFSConfig into a file
*/
public class EncFSConfigWriter {
// Version to use if the properties file can't be read
private static final String ENCFS_JAVA_LIB_VERSION_DEV = "dev";
// Property file
private static final String ENCFS_JAVA_LIB_PROPERTY_FILE = "library.properties";
// Property key for version
private static final String ENCFS_JAVA_LIB_VERSION_KEY = "library.version";
// Retrieve library version
private static String getLibraryVersion() {
Properties prop = new Properties();
InputStream in = EncFSConfigWriter.class
.getResourceAsStream(ENCFS_JAVA_LIB_PROPERTY_FILE);
if (in != null) {
try {
prop.load(in);
String version = prop.getProperty(ENCFS_JAVA_LIB_VERSION_KEY);
if (version != null) {
return version;
} else {
return ENCFS_JAVA_LIB_VERSION_DEV;
}
} catch (IOException e) {
return ENCFS_JAVA_LIB_VERSION_DEV;
}
} else {
return ENCFS_JAVA_LIB_VERSION_DEV;
}
}
// Create config file contents from a given EncFSConfig / password
private static String createConfigFileContents(EncFSConfig config) {
// XXX: This implementation is pretty horrible, but it works :)
String result = "";
result += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
result += "<!DOCTYPE boost_serialization>\n";
result += "<boost_serialization signature=\"serialization::archive\" version=\"9\">\n";
result += " <cfg class_id=\"0\" tracking_level=\"0\" version=\"20\">\n";
result += "\t<version>20100713</version>\n";
result += "\t<creator>encfs-java " + getLibraryVersion()
+ "</creator>\n";
result += "\t<cipherAlg class_id=\"1\" tracking_level=\"0\" version=\"0\">\n";
result += "\t\t<name>ssl/aes</name>\n";
result += "\t\t<major>3</major>\n";
result += "\t\t<minor>0</minor>\n";
result += "\t</cipherAlg>\n";
result += "\t<nameAlg>\n";
EncFSFilenameEncryptionAlgorithm algorithm = config
.getFilenameAlgorithm();
result += "\t\t<name>" + algorithm.getIdentifier() + "</name>\n";
result += "\t\t<major>" + algorithm.getMajor() + "</major>\n";
result += "\t\t<minor>" + algorithm.getMinor() + "</minor>\n";
result += "\t</nameAlg>\n";
result += "\t<keySize>"
+ Integer.toString(config.getVolumeKeySizeInBits())
+ "</keySize>\n";
result += "\t<blockSize>"
+ Integer.toString(config.getEncryptedFileBlockSizeInBytes())
+ "</blockSize>\n";
result += "\t<uniqueIV>" + (config.isUseUniqueIV() ? "1" : "0")
+ "</uniqueIV>\n";
result += "\t<chainedNameIV>" + (config.isChainedNameIV() ? "1" : "0")
+ "</chainedNameIV>\n";
result += "\t<externalIVChaining>"
+ (config.isSupportedExternalIVChaining() ? "1" : "0")
+ "</externalIVChaining>\n";
result += "\t<blockMACBytes>"
+ Integer
.toString(config.getNumberOfMACBytesForEachFileBlock())
+ "</blockMACBytes>\n";
result += "\t<blockMACRandBytes>"
+ Integer.toString(config
.getNumberOfRandomBytesInEachMACHeader())
+ "</blockMACRandBytes>\n";
result += "\t<allowHoles>"
+ (config.isHolesAllowedInFiles() ? "1" : "0")
+ "</allowHoles>\n";
result += "\t<encodedKeySize>"
+ Integer.toString(config.getEncodedKeyLengthInBytes())
+ "</encodedKeySize>\n";
result += "\t<encodedKeyData>" + config.getBase64EncodedVolumeKey()
+ "\n</encodedKeyData>\n";
result += "\t<saltLen>" + Integer.toString(config.getSaltLengthBytes())
+ "</saltLen>\n";
result += "\t<saltData>" + config.getBase64Salt() + "\n</saltData>\n";
result += "\t<kdfIterations>"
+ Integer.toString(config
.getIterationForPasswordKeyDerivationCount())
+ "</kdfIterations>\n";
// XXX: We don't support custom KDF durations
result += "\t<desiredKDFDuration>500</desiredKDFDuration>\n";
result += " </cfg>\n";
result += "</boost_serialization>\n";
return result;
}
/**
* Create a configuration file from the given EncFSConfig and write it to
* the root directory of the given EncFSFileProvider
*/
public static void writeConfig(EncFSFileProvider fileProvider,
EncFSConfig config) throws EncFSUnsupportedException, IOException {
String configFileName = fileProvider.getFilesystemRootPath()
+ EncFSVolume.CONFIG_FILE_NAME;
if (fileProvider.exists(configFileName)) {
throw new EncFSUnsupportedException("Config file already exists");
}
String configFileContents = createConfigFileContents(config);
OutputStream os = fileProvider.openOutputStream(configFileName,
configFileContents.length());
os.write(configFileContents.getBytes());
os.close();
}
}
| lgpl-3.0 |
tcmoore32/sheer-madness | ij-compiler-api/src/main/java/gw/compiler/ij/processors/IDependencyCollector.java | 248 | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.compiler.ij.processors;
import gw.lang.parser.IParsedElement;
public interface IDependencyCollector<T extends IParsedElement> {
void collect(T parsedElement, DependencySink sink);
}
| apache-2.0 |
mdrillin/modeshape | persistence/modeshape-persistence-relational/src/main/java/org/modeshape/persistence/relational/TransactionalCaches.java | 6178 | /*
* ModeShape (http://www.modeshape.org)
*
* 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.modeshape.persistence.relational;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import org.modeshape.common.annotation.ThreadSafe;
import org.modeshape.schematic.document.Document;
import org.modeshape.schematic.internal.document.BasicDocument;
/**
* Class which provides a set of in-memory caches for each ongoing transaction, attempting to relieve some of the "read pressure"
* for transactions.
*
* @author Horia Chiorean (hchiorea@redhat.com)
* @since 5.0
*/
@ThreadSafe
public final class TransactionalCaches {
protected static final Document REMOVED = new BasicDocument() {
@Override
public String toString() {
return "DOCUMENT_REMOVED";
}
};
private final Map<String, TransactionalCache> cachesByTxId;
protected TransactionalCaches() {
this.cachesByTxId = new ConcurrentHashMap<>();
}
protected Document search(String key) {
TransactionalCache cache = cacheForTransaction();
Document doc = cache.getFromWriteCache(key);
if (doc != null) {
return doc;
}
return cache.getFromReadCache(key);
}
protected boolean hasBeenRead(String key) {
return cacheForTransaction().readCache().containsKey(key);
}
protected Document getForWriting(String key) {
return cacheForTransaction().getFromWriteCache(key);
}
protected void putForReading(String key, Document doc) {
if (!TransactionsHolder.hasActiveTransaction()) {
return;
}
cacheForTransaction().putForReading(key, doc);
}
protected Document putForWriting(String key, Document doc) {
return cacheForTransaction().putForWriting(key, doc);
}
protected Set<String> documentKeys() {
TransactionalCache transactionalCache = cacheForTransaction();
return transactionalCache.writeCache().entrySet()
.stream()
.filter(entry -> !transactionalCache.isRemoved(entry.getKey()))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
protected ConcurrentMap<String, Document> writeCache() {
return cacheForTransaction().writeCache();
}
protected boolean isRemoved(String key) {
return cacheForTransaction().isRemoved(key);
}
protected void remove(String key) {
cacheForTransaction().remove(key);
}
protected boolean isNew(String key) {
return cacheForTransaction().isNew(key);
}
protected void putNew(String key) {
if (!TransactionsHolder.hasActiveTransaction()) {
return;
}
cacheForTransaction().putNew(key);
}
protected void putNew(Collection<String> keys) {
if (!TransactionsHolder.hasActiveTransaction()) {
return;
}
cacheForTransaction().putNew(keys);
}
protected void clearCache() {
cachesByTxId.computeIfPresent(TransactionsHolder.requireActiveTransaction(), (id, readWriteCache) -> {
readWriteCache.clear();
return null;
});
}
protected void stop() {
cachesByTxId.clear();
}
private TransactionalCache cacheForTransaction() {
return cachesByTxId.computeIfAbsent(TransactionsHolder.requireActiveTransaction(), TransactionalCache::new);
}
private static class TransactionalCache {
private final ConcurrentMap<String, Document> read = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Document> write = new ConcurrentHashMap<>();
private final Set<String> newIds = Collections.newSetFromMap(new ConcurrentHashMap<>());
protected TransactionalCache(String txId) {
}
protected Document getFromReadCache(String id) {
return read.get(id);
}
protected Document getFromWriteCache(String id) {
return write.get(id);
}
protected void putForReading(String id, Document doc) {
read.put(id, doc);
}
protected Document putForWriting(String id, Document doc) {
if (write.replace(id, doc) == null) {
// when storing a value for the first time, clone it for the write cache
write.putIfAbsent(id, doc.clone());
}
return write.get(id);
}
protected void putNew(String id) {
newIds.add(id);
}
protected void putNew(Collection<String> ids) {
newIds.addAll(ids);
}
protected boolean isNew(String id) {
return newIds.contains(id);
}
protected boolean isRemoved(String id) {
return write.get(id) == REMOVED;
}
protected void remove(String id) {
write.put(id, REMOVED);
}
protected ConcurrentMap<String, Document> writeCache() {
return write;
}
protected ConcurrentMap<String, Document> readCache() {
return read;
}
protected void clear() {
read.clear();
write.clear();
newIds.clear();
}
}
}
| apache-2.0 |
google/guava | android/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java | 47693 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Maps.ViewCachingAbstractMap;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Basic implementation of the {@link Multimap} interface. This class represents a multimap as a map
* that associates each key with a collection of values. All methods of {@link Multimap} are
* supported, including those specified as optional in the interface.
*
* <p>To implement a multimap, a subclass must define the method {@link #createCollection()}, which
* creates an empty collection of values for a key.
*
* <p>The multimap constructor takes a map that has a single entry for each distinct key. When you
* insert a key-value pair with a key that isn't already in the multimap, {@code
* AbstractMapBasedMultimap} calls {@link #createCollection()} to create the collection of values
* for that key. The subclass should not call {@link #createCollection()} directly, and a new
* instance should be created every time the method is called.
*
* <p>For example, the subclass could pass a {@link java.util.TreeMap} during construction, and
* {@link #createCollection()} could return a {@link java.util.TreeSet}, in which case the
* multimap's iterators would propagate through the keys and values in sorted order.
*
* <p>Keys and values may be null, as long as the underlying collection classes support null
* elements.
*
* <p>The collections created by {@link #createCollection()} may or may not allow duplicates. If the
* collection, such as a {@link Set}, does not support duplicates, an added key-value pair will
* replace an existing pair with the same key and value, if such a pair is present. With collections
* like {@link List} that allow duplicates, the collection will keep the existing key-value pairs
* while adding a new pair.
*
* <p>This class is not threadsafe when any concurrent operations update the multimap, even if the
* underlying map and {@link #createCollection()} method return threadsafe classes. Concurrent read
* operations will work correctly. To allow concurrent update operations, wrap your multimap with a
* call to {@link Multimaps#synchronizedMultimap}.
*
* <p>For serialization to work, the subclass must specify explicit {@code readObject} and {@code
* writeObject} methods.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
abstract class AbstractMapBasedMultimap<K extends @Nullable Object, V extends @Nullable Object>
extends AbstractMultimap<K, V> implements Serializable {
/*
* Here's an outline of the overall design.
*
* The map variable contains the collection of values associated with each
* key. When a key-value pair is added to a multimap that didn't previously
* contain any values for that key, a new collection generated by
* createCollection is added to the map. That same collection instance
* remains in the map as long as the multimap has any values for the key. If
* all values for the key are removed, the key and collection are removed
* from the map.
*
* The get method returns a WrappedCollection, which decorates the collection
* in the map (if the key is present) or an empty collection (if the key is
* not present). When the collection delegate in the WrappedCollection is
* empty, the multimap may contain subsequently added values for that key. To
* handle that situation, the WrappedCollection checks whether map contains
* an entry for the provided key, and if so replaces the delegate.
*/
private transient Map<K, Collection<V>> map;
private transient int totalSize;
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding values
* @throws IllegalArgumentException if {@code map} is not empty
*/
protected AbstractMapBasedMultimap(Map<K, Collection<V>> map) {
checkArgument(map.isEmpty());
this.map = map;
}
/** Used during deserialization only. */
final void setMap(Map<K, Collection<V>> map) {
this.map = map;
totalSize = 0;
for (Collection<V> values : map.values()) {
checkArgument(!values.isEmpty());
totalSize += values.size();
}
}
/**
* Creates an unmodifiable, empty collection of values.
*
* <p>This is used in {@link #removeAll} on an empty key.
*/
Collection<V> createUnmodifiableEmptyCollection() {
return unmodifiableCollectionSubclass(createCollection());
}
/**
* Creates the collection of values for a single key.
*
* <p>Collections with weak, soft, or phantom references are not supported. Each call to {@code
* createCollection} should create a new instance.
*
* <p>The returned collection class determines whether duplicate key-value pairs are allowed.
*
* @return an empty collection of values
*/
abstract Collection<V> createCollection();
/**
* Creates the collection of values for an explicitly provided key. By default, it simply calls
* {@link #createCollection()}, which is the correct behavior for most implementations. The {@link
* LinkedHashMultimap} class overrides it.
*
* @param key key to associate with values in the collection
* @return an empty collection of values
*/
Collection<V> createCollection(@ParametricNullness K key) {
return createCollection();
}
Map<K, Collection<V>> backingMap() {
return map;
}
// Query Operations
@Override
public int size() {
return totalSize;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return map.containsKey(key);
}
// Modification Operations
@Override
public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
if (collection.add(value)) {
totalSize++;
map.put(key, collection);
return true;
} else {
throw new AssertionError("New Collection violated the Collection spec");
}
} else if (collection.add(value)) {
totalSize++;
return true;
} else {
return false;
}
}
private Collection<V> getOrCreateCollection(@ParametricNullness K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
map.put(key, collection);
}
return collection;
}
// Bulk Operations
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
Iterator<? extends V> iterator = values.iterator();
if (!iterator.hasNext()) {
return removeAll(key);
}
// TODO(lowasser): investigate atomic failure?
Collection<V> collection = getOrCreateCollection(key);
Collection<V> oldValues = createCollection();
oldValues.addAll(collection);
totalSize -= collection.size();
collection.clear();
while (iterator.hasNext()) {
if (collection.add(iterator.next())) {
totalSize++;
}
}
return unmodifiableCollectionSubclass(oldValues);
}
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> removeAll(@CheckForNull Object key) {
Collection<V> collection = map.remove(key);
if (collection == null) {
return createUnmodifiableEmptyCollection();
}
Collection<V> output = createCollection();
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
return unmodifiableCollectionSubclass(output);
}
<E extends @Nullable Object> Collection<E> unmodifiableCollectionSubclass(
Collection<E> collection) {
return Collections.unmodifiableCollection(collection);
}
@Override
public void clear() {
// Clear each collection, to make previously returned collections empty.
for (Collection<V> collection : map.values()) {
collection.clear();
}
map.clear();
totalSize = 0;
}
// Views
/**
* {@inheritDoc}
*
* <p>The returned collection is not serializable.
*/
@Override
public Collection<V> get(@ParametricNullness K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
}
return wrapCollection(key, collection);
}
/**
* Generates a decorated collection that remains consistent with the values in the multimap for
* the provided key. Changes to the multimap may alter the returned collection, and vice versa.
*/
Collection<V> wrapCollection(@ParametricNullness K key, Collection<V> collection) {
return new WrappedCollection(key, collection, null);
}
final List<V> wrapList(
@ParametricNullness K key, List<V> list, @CheckForNull WrappedCollection ancestor) {
return (list instanceof RandomAccess)
? new RandomAccessWrappedList(key, list, ancestor)
: new WrappedList(key, list, ancestor);
}
/**
* Collection decorator that stays in sync with the multimap values for a key. There are two kinds
* of wrapped collections: full and subcollections. Both have a delegate pointing to the
* underlying collection class.
*
* <p>Full collections, identified by a null ancestor field, contain all multimap values for a
* given key. Its delegate is a value in {@link AbstractMapBasedMultimap#map} whenever the
* delegate is non-empty. The {@code refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap}
* methods ensure that the {@code WrappedCollection} and map remain consistent.
*
* <p>A subcollection, such as a sublist, contains some of the values for a given key. Its
* ancestor field points to the full wrapped collection with all values for the key. The
* subcollection {@code refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} methods call
* the corresponding methods of the full wrapped collection.
*/
@WeakOuter
class WrappedCollection extends AbstractCollection<V> {
@ParametricNullness final K key;
Collection<V> delegate;
@CheckForNull final WrappedCollection ancestor;
@CheckForNull final Collection<V> ancestorDelegate;
WrappedCollection(
@ParametricNullness K key,
Collection<V> delegate,
@CheckForNull WrappedCollection ancestor) {
this.key = key;
this.delegate = delegate;
this.ancestor = ancestor;
this.ancestorDelegate = (ancestor == null) ? null : ancestor.getDelegate();
}
/**
* If the delegate collection is empty, but the multimap has values for the key, replace the
* delegate with the new collection for the key.
*
* <p>For a subcollection, refresh its ancestor and validate that the ancestor delegate hasn't
* changed.
*/
void refreshIfEmpty() {
if (ancestor != null) {
ancestor.refreshIfEmpty();
if (ancestor.getDelegate() != ancestorDelegate) {
throw new ConcurrentModificationException();
}
} else if (delegate.isEmpty()) {
Collection<V> newDelegate = map.get(key);
if (newDelegate != null) {
delegate = newDelegate;
}
}
}
/**
* If collection is empty, remove it from {@code AbstractMapBasedMultimap.this.map}. For
* subcollections, check whether the ancestor collection is empty.
*/
void removeIfEmpty() {
if (ancestor != null) {
ancestor.removeIfEmpty();
} else if (delegate.isEmpty()) {
map.remove(key);
}
}
@ParametricNullness
K getKey() {
return key;
}
/**
* Add the delegate to the map. Other {@code WrappedCollection} methods should call this method
* after adding elements to a previously empty collection.
*
* <p>Subcollection add the ancestor's delegate instead.
*/
void addToMap() {
if (ancestor != null) {
ancestor.addToMap();
} else {
map.put(key, delegate);
}
}
@Override
public int size() {
refreshIfEmpty();
return delegate.size();
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object == this) {
return true;
}
refreshIfEmpty();
return delegate.equals(object);
}
@Override
public int hashCode() {
refreshIfEmpty();
return delegate.hashCode();
}
@Override
public String toString() {
refreshIfEmpty();
return delegate.toString();
}
Collection<V> getDelegate() {
return delegate;
}
@Override
public Iterator<V> iterator() {
refreshIfEmpty();
return new WrappedIterator();
}
/** Collection iterator for {@code WrappedCollection}. */
class WrappedIterator implements Iterator<V> {
final Iterator<V> delegateIterator;
final Collection<V> originalDelegate = delegate;
WrappedIterator() {
delegateIterator = iteratorOrListIterator(delegate);
}
WrappedIterator(Iterator<V> delegateIterator) {
this.delegateIterator = delegateIterator;
}
/**
* If the delegate changed since the iterator was created, the iterator is no longer valid.
*/
void validateIterator() {
refreshIfEmpty();
if (delegate != originalDelegate) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
validateIterator();
return delegateIterator.hasNext();
}
@Override
@ParametricNullness
public V next() {
validateIterator();
return delegateIterator.next();
}
@Override
public void remove() {
delegateIterator.remove();
totalSize--;
removeIfEmpty();
}
Iterator<V> getDelegateIterator() {
validateIterator();
return delegateIterator;
}
}
@Override
public boolean add(@ParametricNullness V value) {
refreshIfEmpty();
boolean wasEmpty = delegate.isEmpty();
boolean changed = delegate.add(value);
if (changed) {
totalSize++;
if (wasEmpty) {
addToMap();
}
}
return changed;
}
@CheckForNull
WrappedCollection getAncestor() {
return ancestor;
}
// The following methods are provided for better performance.
@Override
public boolean addAll(Collection<? extends V> collection) {
if (collection.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.addAll(collection);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override
public boolean contains(@CheckForNull Object o) {
refreshIfEmpty();
return delegate.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
refreshIfEmpty();
return delegate.containsAll(c);
}
@Override
public void clear() {
int oldSize = size(); // calls refreshIfEmpty
if (oldSize == 0) {
return;
}
delegate.clear();
totalSize -= oldSize;
removeIfEmpty(); // maybe shouldn't be removed if this is a sublist
}
@Override
public boolean remove(@CheckForNull Object o) {
refreshIfEmpty();
boolean changed = delegate.remove(o);
if (changed) {
totalSize--;
removeIfEmpty();
}
return changed;
}
@Override
public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.removeAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
@Override
public boolean retainAll(Collection<?> c) {
checkNotNull(c);
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.retainAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
private static <E extends @Nullable Object> Iterator<E> iteratorOrListIterator(
Collection<E> collection) {
return (collection instanceof List)
? ((List<E>) collection).listIterator()
: collection.iterator();
}
/** Set decorator that stays in sync with the multimap values for a key. */
@WeakOuter
class WrappedSet extends WrappedCollection implements Set<V> {
WrappedSet(@ParametricNullness K key, Set<V> delegate) {
super(key, delegate, null);
}
@Override
public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
// Guava issue 1013: AbstractSet and most JDK set implementations are
// susceptible to quadratic removeAll performance on lists;
// use a slightly smarter implementation here
boolean changed = Sets.removeAllImpl((Set<V>) delegate, c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
/** SortedSet decorator that stays in sync with the multimap values for a key. */
@WeakOuter
class WrappedSortedSet extends WrappedCollection implements SortedSet<V> {
WrappedSortedSet(
@ParametricNullness K key,
SortedSet<V> delegate,
@CheckForNull WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
SortedSet<V> getSortedSetDelegate() {
return (SortedSet<V>) getDelegate();
}
@Override
@CheckForNull
public Comparator<? super V> comparator() {
return getSortedSetDelegate().comparator();
}
@Override
@ParametricNullness
public V first() {
refreshIfEmpty();
return getSortedSetDelegate().first();
}
@Override
@ParametricNullness
public V last() {
refreshIfEmpty();
return getSortedSetDelegate().last();
}
@Override
public SortedSet<V> headSet(@ParametricNullness V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(),
getSortedSetDelegate().headSet(toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> subSet(@ParametricNullness V fromElement, @ParametricNullness V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(),
getSortedSetDelegate().subSet(fromElement, toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> tailSet(@ParametricNullness V fromElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(),
getSortedSetDelegate().tailSet(fromElement),
(getAncestor() == null) ? this : getAncestor());
}
}
@WeakOuter
class WrappedNavigableSet extends WrappedSortedSet implements NavigableSet<V> {
WrappedNavigableSet(
@ParametricNullness K key,
NavigableSet<V> delegate,
@CheckForNull WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
@Override
NavigableSet<V> getSortedSetDelegate() {
return (NavigableSet<V>) super.getSortedSetDelegate();
}
@Override
@CheckForNull
public V lower(@ParametricNullness V v) {
return getSortedSetDelegate().lower(v);
}
@Override
@CheckForNull
public V floor(@ParametricNullness V v) {
return getSortedSetDelegate().floor(v);
}
@Override
@CheckForNull
public V ceiling(@ParametricNullness V v) {
return getSortedSetDelegate().ceiling(v);
}
@Override
@CheckForNull
public V higher(@ParametricNullness V v) {
return getSortedSetDelegate().higher(v);
}
@Override
@CheckForNull
public V pollFirst() {
return Iterators.pollNext(iterator());
}
@Override
@CheckForNull
public V pollLast() {
return Iterators.pollNext(descendingIterator());
}
private NavigableSet<V> wrap(NavigableSet<V> wrapped) {
return new WrappedNavigableSet(key, wrapped, (getAncestor() == null) ? this : getAncestor());
}
@Override
public NavigableSet<V> descendingSet() {
return wrap(getSortedSetDelegate().descendingSet());
}
@Override
public Iterator<V> descendingIterator() {
return new WrappedIterator(getSortedSetDelegate().descendingIterator());
}
@Override
public NavigableSet<V> subSet(
@ParametricNullness V fromElement,
boolean fromInclusive,
@ParametricNullness V toElement,
boolean toInclusive) {
return wrap(
getSortedSetDelegate().subSet(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<V> headSet(@ParametricNullness V toElement, boolean inclusive) {
return wrap(getSortedSetDelegate().headSet(toElement, inclusive));
}
@Override
public NavigableSet<V> tailSet(@ParametricNullness V fromElement, boolean inclusive) {
return wrap(getSortedSetDelegate().tailSet(fromElement, inclusive));
}
}
/** List decorator that stays in sync with the multimap values for a key. */
@WeakOuter
class WrappedList extends WrappedCollection implements List<V> {
WrappedList(
@ParametricNullness K key, List<V> delegate, @CheckForNull WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
List<V> getListDelegate() {
return (List<V>) getDelegate();
}
@Override
public boolean addAll(int index, Collection<? extends V> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = getListDelegate().addAll(index, c);
if (changed) {
int newSize = getDelegate().size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override
@ParametricNullness
public V get(int index) {
refreshIfEmpty();
return getListDelegate().get(index);
}
@Override
@ParametricNullness
public V set(int index, @ParametricNullness V element) {
refreshIfEmpty();
return getListDelegate().set(index, element);
}
@Override
public void add(int index, @ParametricNullness V element) {
refreshIfEmpty();
boolean wasEmpty = getDelegate().isEmpty();
getListDelegate().add(index, element);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
@Override
@ParametricNullness
public V remove(int index) {
refreshIfEmpty();
V value = getListDelegate().remove(index);
totalSize--;
removeIfEmpty();
return value;
}
@Override
public int indexOf(@CheckForNull Object o) {
refreshIfEmpty();
return getListDelegate().indexOf(o);
}
@Override
public int lastIndexOf(@CheckForNull Object o) {
refreshIfEmpty();
return getListDelegate().lastIndexOf(o);
}
@Override
public ListIterator<V> listIterator() {
refreshIfEmpty();
return new WrappedListIterator();
}
@Override
public ListIterator<V> listIterator(int index) {
refreshIfEmpty();
return new WrappedListIterator(index);
}
@Override
public List<V> subList(int fromIndex, int toIndex) {
refreshIfEmpty();
return wrapList(
getKey(),
getListDelegate().subList(fromIndex, toIndex),
(getAncestor() == null) ? this : getAncestor());
}
/** ListIterator decorator. */
private class WrappedListIterator extends WrappedIterator implements ListIterator<V> {
WrappedListIterator() {}
public WrappedListIterator(int index) {
super(getListDelegate().listIterator(index));
}
private ListIterator<V> getDelegateListIterator() {
return (ListIterator<V>) getDelegateIterator();
}
@Override
public boolean hasPrevious() {
return getDelegateListIterator().hasPrevious();
}
@Override
@ParametricNullness
public V previous() {
return getDelegateListIterator().previous();
}
@Override
public int nextIndex() {
return getDelegateListIterator().nextIndex();
}
@Override
public int previousIndex() {
return getDelegateListIterator().previousIndex();
}
@Override
public void set(@ParametricNullness V value) {
getDelegateListIterator().set(value);
}
@Override
public void add(@ParametricNullness V value) {
boolean wasEmpty = isEmpty();
getDelegateListIterator().add(value);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
}
}
/**
* List decorator that stays in sync with the multimap values for a key and supports rapid random
* access.
*/
private class RandomAccessWrappedList extends WrappedList implements RandomAccess {
RandomAccessWrappedList(
@ParametricNullness K key, List<V> delegate, @CheckForNull WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
}
@Override
Set<K> createKeySet() {
return new KeySet(map);
}
final Set<K> createMaybeNavigableKeySet() {
if (map instanceof NavigableMap) {
return new NavigableKeySet((NavigableMap<K, Collection<V>>) map);
} else if (map instanceof SortedMap) {
return new SortedKeySet((SortedMap<K, Collection<V>>) map);
} else {
return new KeySet(map);
}
}
@WeakOuter
private class KeySet extends Maps.KeySet<K, Collection<V>> {
KeySet(final Map<K, Collection<V>> subMap) {
super(subMap);
}
@Override
public Iterator<K> iterator() {
final Iterator<Entry<K, Collection<V>>> entryIterator = map().entrySet().iterator();
return new Iterator<K>() {
@CheckForNull Entry<K, Collection<V>> entry;
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
@ParametricNullness
public K next() {
entry = entryIterator.next();
return entry.getKey();
}
@Override
public void remove() {
checkState(entry != null, "no calls to next() since the last call to remove()");
Collection<V> collection = entry.getValue();
entryIterator.remove();
totalSize -= collection.size();
collection.clear();
entry = null;
}
};
}
// The following methods are included for better performance.
@Override
public boolean remove(@CheckForNull Object key) {
int count = 0;
Collection<V> collection = map().remove(key);
if (collection != null) {
count = collection.size();
collection.clear();
totalSize -= count;
}
return count > 0;
}
@Override
public void clear() {
Iterators.clear(iterator());
}
@Override
public boolean containsAll(Collection<?> c) {
return map().keySet().containsAll(c);
}
@Override
public boolean equals(@CheckForNull Object object) {
return this == object || this.map().keySet().equals(object);
}
@Override
public int hashCode() {
return map().keySet().hashCode();
}
}
@WeakOuter
private class SortedKeySet extends KeySet implements SortedSet<K> {
SortedKeySet(SortedMap<K, Collection<V>> subMap) {
super(subMap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) super.map();
}
@Override
@CheckForNull
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
@ParametricNullness
public K first() {
return sortedMap().firstKey();
}
@Override
public SortedSet<K> headSet(@ParametricNullness K toElement) {
return new SortedKeySet(sortedMap().headMap(toElement));
}
@Override
@ParametricNullness
public K last() {
return sortedMap().lastKey();
}
@Override
public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) {
return new SortedKeySet(sortedMap().subMap(fromElement, toElement));
}
@Override
public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
return new SortedKeySet(sortedMap().tailMap(fromElement));
}
}
@WeakOuter
class NavigableKeySet extends SortedKeySet implements NavigableSet<K> {
NavigableKeySet(NavigableMap<K, Collection<V>> subMap) {
super(subMap);
}
@Override
NavigableMap<K, Collection<V>> sortedMap() {
return (NavigableMap<K, Collection<V>>) super.sortedMap();
}
@Override
@CheckForNull
public K lower(@ParametricNullness K k) {
return sortedMap().lowerKey(k);
}
@Override
@CheckForNull
public K floor(@ParametricNullness K k) {
return sortedMap().floorKey(k);
}
@Override
@CheckForNull
public K ceiling(@ParametricNullness K k) {
return sortedMap().ceilingKey(k);
}
@Override
@CheckForNull
public K higher(@ParametricNullness K k) {
return sortedMap().higherKey(k);
}
@Override
@CheckForNull
public K pollFirst() {
return Iterators.pollNext(iterator());
}
@Override
@CheckForNull
public K pollLast() {
return Iterators.pollNext(descendingIterator());
}
@Override
public NavigableSet<K> descendingSet() {
return new NavigableKeySet(sortedMap().descendingMap());
}
@Override
public Iterator<K> descendingIterator() {
return descendingSet().iterator();
}
@Override
public NavigableSet<K> headSet(@ParametricNullness K toElement) {
return headSet(toElement, false);
}
@Override
public NavigableSet<K> headSet(@ParametricNullness K toElement, boolean inclusive) {
return new NavigableKeySet(sortedMap().headMap(toElement, inclusive));
}
@Override
public NavigableSet<K> subSet(
@ParametricNullness K fromElement, @ParametricNullness K toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public NavigableSet<K> subSet(
@ParametricNullness K fromElement,
boolean fromInclusive,
@ParametricNullness K toElement,
boolean toInclusive) {
return new NavigableKeySet(
sortedMap().subMap(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<K> tailSet(@ParametricNullness K fromElement) {
return tailSet(fromElement, true);
}
@Override
public NavigableSet<K> tailSet(@ParametricNullness K fromElement, boolean inclusive) {
return new NavigableKeySet(sortedMap().tailMap(fromElement, inclusive));
}
}
/** Removes all values for the provided key. */
private void removeValuesForKey(@CheckForNull Object key) {
Collection<V> collection = Maps.safeRemove(map, key);
if (collection != null) {
int count = collection.size();
collection.clear();
totalSize -= count;
}
}
private abstract class Itr<T extends @Nullable Object> implements Iterator<T> {
final Iterator<Entry<K, Collection<V>>> keyIterator;
@CheckForNull K key;
@CheckForNull Collection<V> collection;
Iterator<V> valueIterator;
Itr() {
keyIterator = map.entrySet().iterator();
key = null;
collection = null;
valueIterator = Iterators.emptyModifiableIterator();
}
abstract T output(@ParametricNullness K key, @ParametricNullness V value);
@Override
public boolean hasNext() {
return keyIterator.hasNext() || valueIterator.hasNext();
}
@Override
public T next() {
if (!valueIterator.hasNext()) {
Entry<K, Collection<V>> mapEntry = keyIterator.next();
key = mapEntry.getKey();
collection = mapEntry.getValue();
valueIterator = collection.iterator();
}
/*
* uncheckedCastNullableTToT is safe: The first call to this method always enters the !hasNext() case and
* populates key, after which it's never cleared.
*/
return output(uncheckedCastNullableTToT(key), valueIterator.next());
}
@Override
public void remove() {
valueIterator.remove();
/*
* requireNonNull is safe because we've already initialized `collection`. If we hadn't, then
* valueIterator.remove() would have failed.
*/
if (requireNonNull(collection).isEmpty()) {
keyIterator.remove();
}
totalSize--;
}
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values for one key, followed
* by the values of a second key, and so on.
*/
@Override
public Collection<V> values() {
return super.values();
}
@Override
Collection<V> createValues() {
return new Values();
}
@Override
Iterator<V> valueIterator() {
return new Itr<V>() {
@Override
@ParametricNullness
V output(@ParametricNullness K key, @ParametricNullness V value) {
return value;
}
};
}
/*
* TODO(kevinb): should we copy this javadoc to each concrete class, so that
* classes like LinkedHashMultimap that need to say something different are
* still able to {@inheritDoc} all the way from Multimap?
*/
@Override
Multiset<K> createKeys() {
return new Multimaps.Keys<K, V>(this);
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values for one key, followed
* by the values of a second key, and so on.
*
* <p>Each entry is an immutable snapshot of a key-value mapping in the multimap, taken at the
* time the entry is returned by a method call to the collection or its iterator.
*/
@Override
public Collection<Entry<K, V>> entries() {
return super.entries();
}
@Override
Collection<Entry<K, V>> createEntries() {
if (this instanceof SetMultimap) {
return new EntrySet();
} else {
return new Entries();
}
}
/**
* Returns an iterator across all key-value map entries, used by {@code entries().iterator()} and
* {@code values().iterator()}. The default behavior, which traverses the values for one key, the
* values for a second key, and so on, suffices for most {@code AbstractMapBasedMultimap}
* implementations.
*
* @return an iterator across map entries
*/
@Override
Iterator<Entry<K, V>> entryIterator() {
return new Itr<Entry<K, V>>() {
@Override
Entry<K, V> output(@ParametricNullness K key, @ParametricNullness V value) {
return Maps.immutableEntry(key, value);
}
};
}
@Override
Map<K, Collection<V>> createAsMap() {
return new AsMap(map);
}
final Map<K, Collection<V>> createMaybeNavigableAsMap() {
if (map instanceof NavigableMap) {
return new NavigableAsMap((NavigableMap<K, Collection<V>>) map);
} else if (map instanceof SortedMap) {
return new SortedAsMap((SortedMap<K, Collection<V>>) map);
} else {
return new AsMap(map);
}
}
@WeakOuter
private class AsMap extends ViewCachingAbstractMap<K, Collection<V>> {
/**
* Usually the same as map, but smaller for the headMap(), tailMap(), or subMap() of a
* SortedAsMap.
*/
final transient Map<K, Collection<V>> submap;
AsMap(Map<K, Collection<V>> submap) {
this.submap = submap;
}
@Override
protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new AsMapEntries();
}
// The following methods are included for performance.
@Override
public boolean containsKey(@CheckForNull Object key) {
return Maps.safeContainsKey(submap, key);
}
@Override
@CheckForNull
public Collection<V> get(@CheckForNull Object key) {
Collection<V> collection = Maps.safeGet(submap, key);
if (collection == null) {
return null;
}
@SuppressWarnings("unchecked")
K k = (K) key;
return wrapCollection(k, collection);
}
@Override
public Set<K> keySet() {
return AbstractMapBasedMultimap.this.keySet();
}
@Override
public int size() {
return submap.size();
}
@Override
@CheckForNull
public Collection<V> remove(@CheckForNull Object key) {
Collection<V> collection = submap.remove(key);
if (collection == null) {
return null;
}
Collection<V> output = createCollection();
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
return output;
}
@Override
public boolean equals(@CheckForNull Object object) {
return this == object || submap.equals(object);
}
@Override
public int hashCode() {
return submap.hashCode();
}
@Override
public String toString() {
return submap.toString();
}
@Override
public void clear() {
if (submap == map) {
AbstractMapBasedMultimap.this.clear();
} else {
Iterators.clear(new AsMapIterator());
}
}
Entry<K, Collection<V>> wrapEntry(Entry<K, Collection<V>> entry) {
K key = entry.getKey();
return Maps.immutableEntry(key, wrapCollection(key, entry.getValue()));
}
@WeakOuter
class AsMapEntries extends Maps.EntrySet<K, Collection<V>> {
@Override
Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override
public Iterator<Entry<K, Collection<V>>> iterator() {
return new AsMapIterator();
}
// The following methods are included for performance.
@Override
public boolean contains(@CheckForNull Object o) {
return Collections2.safeContains(submap.entrySet(), o);
}
@Override
public boolean remove(@CheckForNull Object o) {
if (!contains(o)) {
return false;
}
// requireNonNull is safe because of the contains check.
Entry<?, ?> entry = requireNonNull((Entry<?, ?>) o);
removeValuesForKey(entry.getKey());
return true;
}
}
/** Iterator across all keys and value collections. */
class AsMapIterator implements Iterator<Entry<K, Collection<V>>> {
final Iterator<Entry<K, Collection<V>>> delegateIterator = submap.entrySet().iterator();
@CheckForNull Collection<V> collection;
@Override
public boolean hasNext() {
return delegateIterator.hasNext();
}
@Override
public Entry<K, Collection<V>> next() {
Entry<K, Collection<V>> entry = delegateIterator.next();
collection = entry.getValue();
return wrapEntry(entry);
}
@Override
public void remove() {
checkState(collection != null, "no calls to next() since the last call to remove()");
delegateIterator.remove();
totalSize -= collection.size();
collection.clear();
collection = null;
}
}
}
@WeakOuter
private class SortedAsMap extends AsMap implements SortedMap<K, Collection<V>> {
SortedAsMap(SortedMap<K, Collection<V>> submap) {
super(submap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) submap;
}
@Override
@CheckForNull
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
@ParametricNullness
public K firstKey() {
return sortedMap().firstKey();
}
@Override
@ParametricNullness
public K lastKey() {
return sortedMap().lastKey();
}
@Override
public SortedMap<K, Collection<V>> headMap(@ParametricNullness K toKey) {
return new SortedAsMap(sortedMap().headMap(toKey));
}
@Override
public SortedMap<K, Collection<V>> subMap(
@ParametricNullness K fromKey, @ParametricNullness K toKey) {
return new SortedAsMap(sortedMap().subMap(fromKey, toKey));
}
@Override
public SortedMap<K, Collection<V>> tailMap(@ParametricNullness K fromKey) {
return new SortedAsMap(sortedMap().tailMap(fromKey));
}
@CheckForNull SortedSet<K> sortedKeySet;
// returns a SortedSet, even though returning a Set would be sufficient to
// satisfy the SortedMap.keySet() interface
@Override
public SortedSet<K> keySet() {
SortedSet<K> result = sortedKeySet;
return (result == null) ? sortedKeySet = createKeySet() : result;
}
@Override
SortedSet<K> createKeySet() {
return new SortedKeySet(sortedMap());
}
}
class NavigableAsMap extends SortedAsMap implements NavigableMap<K, Collection<V>> {
NavigableAsMap(NavigableMap<K, Collection<V>> submap) {
super(submap);
}
@Override
NavigableMap<K, Collection<V>> sortedMap() {
return (NavigableMap<K, Collection<V>>) super.sortedMap();
}
@Override
@CheckForNull
public Entry<K, Collection<V>> lowerEntry(@ParametricNullness K key) {
Entry<K, Collection<V>> entry = sortedMap().lowerEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
@CheckForNull
public K lowerKey(@ParametricNullness K key) {
return sortedMap().lowerKey(key);
}
@Override
@CheckForNull
public Entry<K, Collection<V>> floorEntry(@ParametricNullness K key) {
Entry<K, Collection<V>> entry = sortedMap().floorEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
@CheckForNull
public K floorKey(@ParametricNullness K key) {
return sortedMap().floorKey(key);
}
@Override
@CheckForNull
public Entry<K, Collection<V>> ceilingEntry(@ParametricNullness K key) {
Entry<K, Collection<V>> entry = sortedMap().ceilingEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
@CheckForNull
public K ceilingKey(@ParametricNullness K key) {
return sortedMap().ceilingKey(key);
}
@Override
@CheckForNull
public Entry<K, Collection<V>> higherEntry(@ParametricNullness K key) {
Entry<K, Collection<V>> entry = sortedMap().higherEntry(key);
return (entry == null) ? null : wrapEntry(entry);
}
@Override
@CheckForNull
public K higherKey(@ParametricNullness K key) {
return sortedMap().higherKey(key);
}
@Override
@CheckForNull
public Entry<K, Collection<V>> firstEntry() {
Entry<K, Collection<V>> entry = sortedMap().firstEntry();
return (entry == null) ? null : wrapEntry(entry);
}
@Override
@CheckForNull
public Entry<K, Collection<V>> lastEntry() {
Entry<K, Collection<V>> entry = sortedMap().lastEntry();
return (entry == null) ? null : wrapEntry(entry);
}
@Override
@CheckForNull
public Entry<K, Collection<V>> pollFirstEntry() {
return pollAsMapEntry(entrySet().iterator());
}
@Override
@CheckForNull
public Entry<K, Collection<V>> pollLastEntry() {
return pollAsMapEntry(descendingMap().entrySet().iterator());
}
@CheckForNull
Entry<K, Collection<V>> pollAsMapEntry(Iterator<Entry<K, Collection<V>>> entryIterator) {
if (!entryIterator.hasNext()) {
return null;
}
Entry<K, Collection<V>> entry = entryIterator.next();
Collection<V> output = createCollection();
output.addAll(entry.getValue());
entryIterator.remove();
return Maps.immutableEntry(entry.getKey(), unmodifiableCollectionSubclass(output));
}
@Override
public NavigableMap<K, Collection<V>> descendingMap() {
return new NavigableAsMap(sortedMap().descendingMap());
}
@Override
public NavigableSet<K> keySet() {
return (NavigableSet<K>) super.keySet();
}
@Override
NavigableSet<K> createKeySet() {
return new NavigableKeySet(sortedMap());
}
@Override
public NavigableSet<K> navigableKeySet() {
return keySet();
}
@Override
public NavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
@Override
public NavigableMap<K, Collection<V>> subMap(
@ParametricNullness K fromKey, @ParametricNullness K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override
public NavigableMap<K, Collection<V>> subMap(
@ParametricNullness K fromKey,
boolean fromInclusive,
@ParametricNullness K toKey,
boolean toInclusive) {
return new NavigableAsMap(sortedMap().subMap(fromKey, fromInclusive, toKey, toInclusive));
}
@Override
public NavigableMap<K, Collection<V>> headMap(@ParametricNullness K toKey) {
return headMap(toKey, false);
}
@Override
public NavigableMap<K, Collection<V>> headMap(@ParametricNullness K toKey, boolean inclusive) {
return new NavigableAsMap(sortedMap().headMap(toKey, inclusive));
}
@Override
public NavigableMap<K, Collection<V>> tailMap(@ParametricNullness K fromKey) {
return tailMap(fromKey, true);
}
@Override
public NavigableMap<K, Collection<V>> tailMap(
@ParametricNullness K fromKey, boolean inclusive) {
return new NavigableAsMap(sortedMap().tailMap(fromKey, inclusive));
}
}
private static final long serialVersionUID = 2447537837011683357L;
}
| apache-2.0 |
jwren/intellij-community | plugins/coverage-common/src/com/intellij/coverage/view/CoverageViewExtension.java | 3819 | // 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.coverage.view;
import com.intellij.coverage.CoverageDataManager;
import com.intellij.coverage.CoverageSuitesBundle;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.ui.ColumnInfo;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
public abstract class CoverageViewExtension {
protected final Project myProject;
protected final CoverageSuitesBundle mySuitesBundle;
protected final CoverageViewManager.StateBean myStateBean;
protected final CoverageDataManager myCoverageDataManager;
protected final CoverageViewManager myCoverageViewManager;
public CoverageViewExtension(@NotNull Project project, CoverageSuitesBundle suitesBundle, CoverageViewManager.StateBean stateBean) {
assert !project.isDefault() : "Should not run coverage for default project";
myProject = project;
mySuitesBundle = suitesBundle;
myStateBean = stateBean;
myCoverageDataManager = CoverageDataManager.getInstance(myProject);
myCoverageViewManager = CoverageViewManager.getInstance(myProject);
}
/**
* @deprecated This method is not used in CoverageView.
*/
@Nullable
@Deprecated
public abstract @Nls String getSummaryForNode(@NotNull AbstractTreeNode<?> node);
/**
* @deprecated This method is not used in CoverageView.
*/
@Nullable
@Deprecated
public abstract @Nls String getSummaryForRootNode(@NotNull AbstractTreeNode<?> childNode);
@Nullable
public abstract String getPercentage(int columnIdx, @NotNull AbstractTreeNode<?> node);
public abstract List<AbstractTreeNode<?>> getChildrenNodes(AbstractTreeNode<?> node);
public abstract ColumnInfo[] createColumnInfos();
@Nullable
public abstract PsiElement getParentElement(PsiElement element);
@NotNull
public abstract AbstractTreeNode<?> createRootNode();
public boolean canSelectInCoverageView(Object object) {
return object instanceof VirtualFile && PsiManager.getInstance(myProject).findFile((VirtualFile)object) != null;
}
@Nullable
public PsiElement getElementToSelect(Object object) {
if (object instanceof PsiElement) return (PsiElement)object;
return object instanceof VirtualFile ? PsiManager.getInstance(myProject).findFile((VirtualFile)object) : null;
}
@Nullable
public VirtualFile getVirtualFile(Object object) {
if (object instanceof PsiElement) {
if (object instanceof PsiDirectory) return ((PsiDirectory)object).getVirtualFile();
final PsiFile containingFile = ((PsiElement)object).getContainingFile();
if (containingFile != null) {
return containingFile.getVirtualFile();
}
return null;
}
return object instanceof VirtualFile ? (VirtualFile)object : null;
}
@NotNull
public List<AbstractTreeNode<?>> createTopLevelNodes() {
return Collections.emptyList();
}
public boolean supportFlattenPackages() {
return false;
}
/**
* @return extra actions which will be added to {@link CoverageView} toolbar menu
* directly after all еру default actions (Flatten Packages, Generate Coverage Report)
*/
@ApiStatus.Experimental
@NotNull
public List<AnAction> createExtraToolbarActions() {
return Collections.emptyList();
}
} | apache-2.0 |
nknize/elasticsearch | server/src/main/java/org/elasticsearch/search/fetch/subphase/FetchVersionPhase.java | 2199 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.fetch.subphase;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.NumericDocValues;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.index.mapper.VersionFieldMapper;
import org.elasticsearch.search.fetch.FetchContext;
import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.fetch.FetchSubPhaseProcessor;
import java.io.IOException;
public final class FetchVersionPhase implements FetchSubPhase {
@Override
public FetchSubPhaseProcessor getProcessor(FetchContext context) {
if (context.version() == false) {
return null;
}
return new FetchSubPhaseProcessor() {
NumericDocValues versions = null;
@Override
public void setNextReader(LeafReaderContext readerContext) throws IOException {
versions = readerContext.reader().getNumericDocValues(VersionFieldMapper.NAME);
}
@Override
public void process(HitContext hitContext) throws IOException {
long version = Versions.NOT_FOUND;
if (versions != null && versions.advanceExact(hitContext.docId())) {
version = versions.longValue();
}
hitContext.hit().version(version < 0 ? -1 : version);
}
};
}
}
| apache-2.0 |
gpc/searchable | src/java/grails/plugin/searchable/internal/support/DynamicMethodUtils.java | 2871 | /*
* Copyright 2007 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 grails.plugin.searchable.internal.support;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.springframework.beans.BeanUtils;
/**
* @author Maurice Nicholson
*/
public class DynamicMethodUtils {
/**
* Extract the property names from the given method name suffix
*
* @param methodSuffix a method name suffix like 'NameAndAddress'
* @return a Collection of property names like ['name', 'address']
*/
public static Collection extractPropertyNames(String methodSuffix) {
String[] splited = methodSuffix.split("And");
Set propertyNames = new HashSet();
for (int i = 0; i < splited.length; i++) {
if (splited[i].length() > 0) {
propertyNames.add(Introspector.decapitalize(splited[i]));
}
}
return propertyNames;
}
/**
* Extract the property names from the given method name suffix accoring
* to the given Class's properties
*
* @param clazz the Class to resolve property names against
* @param methodSuffix a method name suffix like 'NameAndAddressCity'
* @return a Collection of property names like ['name', 'address']
*/
public static Collection extractPropertyNames(Class clazz, String methodSuffix) {
String joinedNames = methodSuffix;
Set propertyNames = new HashSet();
PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz);
for (int i = 0; i < propertyDescriptors.length; i++) {
String name = propertyDescriptors[i].getName();
String capitalized = name.substring(0, 1).toUpperCase() + name.substring(1);
if (joinedNames.indexOf(capitalized) > -1) { // uses indexOf instead of contains for Java 1.4 compatibility
propertyNames.add(name);
joinedNames = DefaultGroovyMethods.minus(joinedNames, capitalized);
}
}
if (joinedNames.length() > 0) {
propertyNames.addAll(extractPropertyNames(joinedNames));
}
return propertyNames;
}
}
| apache-2.0 |
dvandok/not-yet-commons-ssl-debian | src/java/org/apache/commons/ssl/asn1/ConstructedOctetStream.java | 2236 | package org.apache.commons.ssl.asn1;
import java.io.IOException;
import java.io.InputStream;
class ConstructedOctetStream
extends InputStream {
private final ASN1ObjectParser _parser;
private boolean _first = true;
private InputStream _currentStream;
ConstructedOctetStream(
ASN1ObjectParser parser) {
_parser = parser;
}
public int read(byte[] b, int off, int len) throws IOException {
if (_currentStream == null) {
if (!_first) {
return -1;
}
ASN1OctetStringParser s = (ASN1OctetStringParser) _parser.readObject();
if (s == null) {
return -1;
}
_first = false;
_currentStream = s.getOctetStream();
}
int totalRead = 0;
for (; ;) {
int numRead = _currentStream.read(b, off + totalRead, len - totalRead);
if (numRead >= 0) {
totalRead += numRead;
if (totalRead == len) {
return totalRead;
}
} else {
ASN1OctetStringParser aos = (ASN1OctetStringParser) _parser.readObject();
if (aos == null) {
_currentStream = null;
return totalRead < 1 ? -1 : totalRead;
}
_currentStream = aos.getOctetStream();
}
}
}
public int read()
throws IOException {
if (_currentStream == null) {
if (!_first) {
return -1;
}
ASN1OctetStringParser s = (ASN1OctetStringParser) _parser.readObject();
if (s == null) {
return -1;
}
_first = false;
_currentStream = s.getOctetStream();
}
for (; ;) {
int b = _currentStream.read();
if (b >= 0) {
return b;
}
ASN1OctetStringParser s = (ASN1OctetStringParser) _parser.readObject();
if (s == null) {
_currentStream = null;
return -1;
}
_currentStream = s.getOctetStream();
}
}
}
| apache-2.0 |
saandrews/pulsar | pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ServiceChannelInitializer.java | 2540 | /**
* 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.pulsar.proxy.server;
import org.apache.pulsar.common.api.PulsarDecoder;
import org.apache.pulsar.common.util.SecurityUtility;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.ssl.SslContext;
/**
* Initialize service channel handlers.
*
*/
public class ServiceChannelInitializer extends ChannelInitializer<SocketChannel> {
public static final String TLS_HANDLER = "tls";
private ProxyConfiguration serviceConfig;
private ProxyService proxyService;
private boolean enableTLS;
public ServiceChannelInitializer(ProxyService proxyService, ProxyConfiguration serviceConfig, boolean enableTLS) {
super();
this.serviceConfig = serviceConfig;
this.proxyService = proxyService;
this.enableTLS = enableTLS;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
if (enableTLS) {
SslContext sslCtx = SecurityUtility.createNettySslContextForServer(true /* to allow InsecureConnection */,
serviceConfig.getTlsTrustCertsFilePath(), serviceConfig.getTlsCertificateFilePath(),
serviceConfig.getTlsKeyFilePath(), serviceConfig.getTlsCiphers(), serviceConfig.getTlsProtocols(),
serviceConfig.getTlsRequireTrustedClientCertOnConnect());
ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
}
ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
ch.pipeline().addLast("handler", new ProxyConnection(proxyService));
}
}
| apache-2.0 |
my-popsy/cameraview | demo/src/main/java/com/google/android/cameraview/demo/AspectRatioFragment.java | 4866 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.cameraview.demo;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.google.android.cameraview.AspectRatio;
import java.util.Arrays;
import java.util.Set;
/**
* A simple dialog that allows user to pick an aspect ratio.
*/
public class AspectRatioFragment extends DialogFragment {
private static final String ARG_ASPECT_RATIOS = "aspect_ratios";
private static final String ARG_CURRENT_ASPECT_RATIO = "current_aspect_ratio";
private Listener mListener;
public static AspectRatioFragment newInstance(Set<AspectRatio> ratios,
AspectRatio currentRatio) {
final AspectRatioFragment fragment = new AspectRatioFragment();
final Bundle args = new Bundle();
args.putParcelableArray(ARG_ASPECT_RATIOS,
ratios.toArray(new AspectRatio[ratios.size()]));
args.putParcelable(ARG_CURRENT_ASPECT_RATIO, currentRatio);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mListener = (Listener) context;
}
@Override
public void onDetach() {
mListener = null;
super.onDetach();
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Bundle args = getArguments();
final AspectRatio[] ratios = (AspectRatio[]) args.getParcelableArray(ARG_ASPECT_RATIOS);
if (ratios == null) {
throw new RuntimeException("No ratios");
}
Arrays.sort(ratios);
final AspectRatio current = args.getParcelable(ARG_CURRENT_ASPECT_RATIO);
final AspectRatioAdapter adapter = new AspectRatioAdapter(ratios, current);
return new AlertDialog.Builder(getActivity())
.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
mListener.onAspectRatioSelected(ratios[position]);
}
})
.create();
}
private static class AspectRatioAdapter extends BaseAdapter {
private final AspectRatio[] mRatios;
private final AspectRatio mCurrentRatio;
AspectRatioAdapter(AspectRatio[] ratios, AspectRatio current) {
mRatios = ratios;
mCurrentRatio = current;
}
@Override
public int getCount() {
return mRatios.length;
}
@Override
public AspectRatio getItem(int position) {
return mRatios[position];
}
@Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
@Override
public View getView(int position, View view, ViewGroup parent) {
AspectRatioAdapter.ViewHolder holder;
if (view == null) {
view = LayoutInflater.from(parent.getContext())
.inflate(android.R.layout.simple_list_item_1, parent, false);
holder = new AspectRatioAdapter.ViewHolder();
holder.text = (TextView) view.findViewById(android.R.id.text1);
view.setTag(holder);
} else {
holder = (AspectRatioAdapter.ViewHolder) view.getTag();
}
AspectRatio ratio = getItem(position);
StringBuilder sb = new StringBuilder(ratio.toString());
if (ratio.equals(mCurrentRatio)) {
sb.append(" *");
}
holder.text.setText(sb);
return view;
}
private static class ViewHolder {
TextView text;
}
}
public interface Listener {
void onAspectRatioSelected(@NonNull AspectRatio ratio);
}
}
| apache-2.0 |
raviagarwal7/buck | src/com/facebook/buck/util/DirectoryCleaner.java | 5454 | /*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.util;
import com.facebook.buck.io.MoreFiles;
import com.facebook.buck.log.Logger;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
public class DirectoryCleaner {
private static final Logger LOG = Logger.get(DirectoryCleaner.class);
public interface PathSelector {
Iterable<Path> getCandidatesToDelete(Path rootPath) throws IOException;
/**
* Returns the preferred sorting order to delete paths.
*/
int comparePaths(PathStats path1, PathStats path2);
}
private final DirectoryCleanerArgs args;
public DirectoryCleaner(DirectoryCleanerArgs args) {
this.args = args;
}
public void clean(Path pathToClean) throws IOException {
List<PathStats> pathStats = Lists.newArrayList();
long totalSizeBytes = 0;
for (Path path : args.getPathSelector().getCandidatesToDelete(pathToClean)) {
PathStats stats = computePathStats(path);
totalSizeBytes += stats.getTotalSizeBytes();
pathStats.add(stats);
}
if (shouldDeleteOldestLog(pathStats.size(), totalSizeBytes)) {
Collections.sort(pathStats, new Comparator<PathStats>() {
@Override
public int compare(PathStats stats1, PathStats stats2) {
return args.getPathSelector().comparePaths(stats1, stats2);
}
});
int remainingLogDirectories = pathStats.size();
long finalMaxSizeBytes = args.getMaxTotalSizeBytes();
if (args.getMaxBytesAfterDeletion().isPresent()) {
finalMaxSizeBytes = args.getMaxBytesAfterDeletion().get();
}
for (int i = 0; i < pathStats.size(); ++i) {
if (totalSizeBytes <= finalMaxSizeBytes &&
remainingLogDirectories <= args.getMaxPathCount()) {
break;
}
PathStats currentPath = pathStats.get(i);
LOG.verbose(
"Deleting path [%s] of total size [%d] bytes.",
currentPath.getPath(),
currentPath.getTotalSizeBytes());
MoreFiles.deleteRecursivelyIfExists(currentPath.getPath());
--remainingLogDirectories;
totalSizeBytes -= currentPath.getTotalSizeBytes();
}
}
}
private boolean shouldDeleteOldestLog(int currentNumberOfLogs, long totalSizeBytes) {
if (currentNumberOfLogs <= args.getMinAmountOfEntriesToKeep()) {
return false;
}
return totalSizeBytes > args.getMaxTotalSizeBytes() ||
currentNumberOfLogs > args.getMaxPathCount();
}
private PathStats computePathStats(Path path) throws IOException {
// Note this will change the lastAccessTime of the file.
BasicFileAttributes attributes = Files.readAttributes(
path,
BasicFileAttributes.class);
if (attributes.isDirectory()) {
return new PathStats(
path,
computeDirSizeBytesRecursively(path),
attributes.creationTime().toMillis(),
attributes.lastAccessTime().toMillis());
} else if (attributes.isRegularFile()) {
return new PathStats(
path,
attributes.size(),
attributes.creationTime().toMillis(),
attributes.lastAccessTime().toMillis());
}
throw new IllegalArgumentException(String.format(
"Argument path [%s] is not a valid file or directory.",
path.toString()));
}
private static long computeDirSizeBytesRecursively(Path directoryPath) throws IOException {
final AtomicLong totalSizeBytes = new AtomicLong(0);
Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(
Path file, BasicFileAttributes attrs) throws IOException {
totalSizeBytes.addAndGet(attrs.size());
return FileVisitResult.CONTINUE;
}
});
return totalSizeBytes.get();
}
public static class PathStats {
private final Path path;
private final long totalSizeBytes;
private final long creationMillis;
private final long lastAccessMillis;
public PathStats(
Path path, long totalSizeBytes, long creationMillis, long lastAccessMillis) {
this.path = path;
this.totalSizeBytes = totalSizeBytes;
this.creationMillis = creationMillis;
this.lastAccessMillis = lastAccessMillis;
}
public Path getPath() {
return path;
}
public long getTotalSizeBytes() {
return totalSizeBytes;
}
public long getCreationMillis() {
return creationMillis;
}
public long getLastAccessMillis() {
return lastAccessMillis;
}
}
}
| apache-2.0 |
argv0/cloudstack | server/src/com/cloud/configuration/ZoneConfig.java | 3054 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.configuration;
import java.util.ArrayList;
import java.util.List;
public enum ZoneConfig {
EnableSecStorageVm( Boolean.class, "enable.secstorage.vm", "true", "Enables secondary storage vm service", null),
EnableConsoleProxyVm( Boolean.class, "enable.consoleproxy.vm", "true", "Enables console proxy vm service", null),
MaxHosts( Long.class, "max.hosts", null, "Maximum number of hosts the Zone can have", null),
MaxVirtualMachines( Long.class, "max.vms", null, "Maximum number of VMs the Zone can have", null),
ZoneMode( String.class, "zone.mode", null, "Mode of the Zone", "Free,Basic,Advanced"),
HasNoPublicIp(Boolean.class, "has.no.public.ip", "false", "True if Zone has no public IP", null),
DhcpStrategy(String.class, "zone.dhcp.strategy", "cloudstack-systemvm", "Who controls DHCP", "cloudstack-systemvm,cloudstack-external,external"),
DnsSearchOrder(String.class, "network.guestnetwork.dns.search.order", null, "Domains list to be used for domain search order", null);
private final Class<?> _type;
private final String _name;
private final String _defaultValue;
private final String _description;
private final String _range;
private static final List<String> _zoneConfigKeys = new ArrayList<String>();
static {
// Add keys into List
for (ZoneConfig c : ZoneConfig.values()) {
String key = c.key();
_zoneConfigKeys.add(key);
}
}
private ZoneConfig( Class<?> type, String name, String defaultValue, String description, String range) {
_type = type;
_name = name;
_defaultValue = defaultValue;
_description = description;
_range = range;
}
public Class<?> getType() {
return _type;
}
public String getName() {
return _name;
}
public String getDefaultValue() {
return _defaultValue;
}
public String getDescription() {
return _description;
}
public String getRange() {
return _range;
}
public String key() {
return _name;
}
public static boolean doesKeyExist(String key){
return _zoneConfigKeys.contains(key);
}
}
| apache-2.0 |
aldaris/wicket | wicket-request/src/main/java/org/apache/wicket/request/Url.java | 30113 | /*
* 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.wicket.request;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.wicket.util.encoding.UrlDecoder;
import org.apache.wicket.util.encoding.UrlEncoder;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Generics;
import org.apache.wicket.util.lang.Objects;
import org.apache.wicket.util.string.StringValue;
import org.apache.wicket.util.string.Strings;
/**
* Represents the URL to an external resource or internal resource/component.
* <p>
* A url could be:
* <ul>
* <li>full - consists of an optional protocol/scheme, a host name, an optional port,
* optional segments and and optional query parameters.</li>
* <li>non-full:
* <ul>
* <li>absolute - a url relative to the host name. Such url may escape from the application by using
* different context path and/or different filter path. For example: <code>/foo/bar</code></li>
* <li>relative - a url relative to the current base url. The base url is the url of the currently rendered page.
* For example: <code>foo/bar</code>, <code>../foo/bar</code></li>
* </ul>
* </ul>
*
* </p>
*
* Example URLs:
*
* <ul>
* <li>http://hostname:1234/foo/bar?a=b#baz - protocol: http, host: hostname, port: 1234, segments: ["foo","bar"], fragment: baz </li>
* <li>http://hostname:1234/foo/bar?a=b - protocol: http, host: hostname, port: 1234, segments: ["foo","bar"] </li>
* <li>//hostname:1234/foo/bar?a=b - protocol: null, host: hostname, port: 1234, segments: ["foo","bar"] </li>
* <li>foo/bar/baz?a=1&b=5 - segments: ["foo","bar","baz"], query parameters: ["a"="1", "b"="5"]</li>
* <li>foo/bar//baz?=4&6 - segments: ["foo", "bar", "", "baz"], query parameters: [""="4", "6"=""]</li>
* <li>/foo/bar/ - segments: ["", "foo", "bar", ""]</li>
* <li>foo/bar// - segments: ["foo", "bar", "", ""]</li>
* <li>?a=b - segments: [ ], query parameters: ["a"="b"]</li>
* <li></li>
* </ul>
*
* The Url class takes care of encoding and decoding of the segments and parameters.
*
* @author Matej Knopp
* @author Igor Vaynberg
*/
public class Url implements Serializable
{
private static final long serialVersionUID = 1L;
private static final String DEFAULT_CHARSET_NAME = "UTF-8";
private final List<String> segments;
private final List<QueryParameter> parameters;
private String charsetName;
private transient Charset _charset;
private String protocol;
private Integer port;
private String host;
private String fragment;
/**
* Flags the URL as relative to the application context. It is a special type of URL, used
* internally to hold the client data: protocol + host + port + relative segments
*
* Unlike absolute URLs, a context relative one has no context or filter mapping segments
*/
private boolean contextRelative;
/**
* Modes with which urls can be stringized
*
* @author igor
*/
public static enum StringMode {
/** local urls are rendered without the host name */
LOCAL,
/**
* full urls are written with hostname. if the hostname is not set or one of segments is
* {@literal ..} an {@link IllegalStateException} is thrown.
*/
FULL;
}
/**
* Construct.
*/
public Url()
{
segments = Generics.newArrayList();
parameters = Generics.newArrayList();
}
/**
* Construct.
*
* @param charset
*/
public Url(final Charset charset)
{
this();
setCharset(charset);
}
/**
* copy constructor
*
* @param url
* url being copied
*/
public Url(final Url url)
{
Args.notNull(url, "url");
protocol = url.protocol;
host = url.host;
port = url.port;
segments = new ArrayList<>(url.segments);
parameters = new ArrayList<>(url.parameters);
charsetName = url.charsetName;
_charset = url._charset;
}
/**
* Construct.
*
* @param segments
* @param parameters
*/
public Url(final List<String> segments, final List<QueryParameter> parameters)
{
this(segments, parameters, null);
}
/**
* Construct.
*
* @param segments
* @param charset
*/
public Url(final List<String> segments, final Charset charset)
{
this(segments, Collections.<QueryParameter> emptyList(), charset);
}
/**
* Construct.
*
* @param segments
* @param parameters
* @param charset
*/
public Url(final List<String> segments, final List<QueryParameter> parameters,
final Charset charset)
{
Args.notNull(segments, "segments");
Args.notNull(parameters, "parameters");
this.segments = new ArrayList<>(segments);
this.parameters = new ArrayList<>(parameters);
setCharset(charset);
}
/**
* Parses the given URL string.
*
* @param url
* absolute or relative url with query string
* @return Url object
*/
public static Url parse(final CharSequence url)
{
return parse(url, null);
}
/**
* Parses the given URL string.
*
* @param _url
* absolute or relative url with query string
* @param charset
* @return Url object
*/
public static Url parse(CharSequence _url, Charset charset)
{
return parse(_url, charset, true);
}
/**
* Parses the given URL string.
*
* @param _url
* absolute or relative url with query string
* @param charset
* @param isFullHint
* a hint whether to try to parse the protocol, host and port part of the url
* @return Url object
*/
public static Url parse(CharSequence _url, Charset charset, boolean isFullHint)
{
Args.notNull(_url, "_url");
final Url result = new Url(charset);
// the url object resolved the charset, use that
charset = result.getCharset();
String url = _url.toString();
// extract query string part
final String queryString;
final String absoluteUrl;
final int fragmentAt = url.indexOf('#');
// matches url fragment, but doesn't match optional path parameter (e.g. .../#{optional}/...)
if (fragmentAt > -1 && url.length() > fragmentAt + 1 && url.charAt(fragmentAt + 1) != '{')
{
result.fragment = url.substring(fragmentAt + 1);
url = url.substring(0, fragmentAt);
}
final int queryAt = url.indexOf('?');
if (queryAt == -1)
{
queryString = "";
absoluteUrl = url;
}
else
{
absoluteUrl = url.substring(0, queryAt);
queryString = url.substring(queryAt + 1);
}
// get absolute / relative part of url
String relativeUrl;
final int idxOfFirstSlash = absoluteUrl.indexOf('/');
final int protocolAt = absoluteUrl.indexOf("://");
// full urls start either with a "scheme://" or with "//"
boolean protocolLess = absoluteUrl.startsWith("//");
final boolean isFull = (protocolAt > 1 && (protocolAt < idxOfFirstSlash)) || protocolLess;
if (isFull && isFullHint)
{
if (protocolLess == false)
{
result.protocol = absoluteUrl.substring(0, protocolAt).toLowerCase(Locale.US);
}
final String afterProto = absoluteUrl.substring(protocolAt + 3);
final String hostAndPort;
int relativeAt = afterProto.indexOf('/');
if (relativeAt == -1)
{
relativeAt = afterProto.indexOf(';');
}
if (relativeAt == -1)
{
relativeUrl = "";
hostAndPort = afterProto;
}
else
{
relativeUrl = afterProto.substring(relativeAt);
hostAndPort = afterProto.substring(0, relativeAt);
}
final int credentialsAt = hostAndPort.lastIndexOf('@') + 1;
//square brackets are used for ip6 URLs
final int closeSqrBracketAt = hostAndPort.lastIndexOf(']') + 1;
final int portAt = hostAndPort.substring(credentialsAt)
.substring(closeSqrBracketAt)
.lastIndexOf(':');
if (portAt == -1)
{
result.host = hostAndPort;
result.port = getDefaultPortForProtocol(result.protocol);
}
else
{
final int portOffset = portAt + credentialsAt + closeSqrBracketAt;
result.host = hostAndPort.substring(0, portOffset);
result.port = Integer.parseInt(hostAndPort.substring(portOffset + 1));
}
if (relativeAt < 0)
{
relativeUrl = "/";
}
}
else
{
relativeUrl = absoluteUrl;
}
if (relativeUrl.length() > 0)
{
boolean removeLast = false;
if (relativeUrl.endsWith("/"))
{
// we need to append something and remove it after splitting
// because otherwise the
// trailing slashes will be lost
relativeUrl += "/x";
removeLast = true;
}
String segmentArray[] = Strings.split(relativeUrl, '/');
if (removeLast)
{
segmentArray[segmentArray.length - 1] = null;
}
for (String s : segmentArray)
{
if (s != null)
{
result.segments.add(decodeSegment(s, charset));
}
}
}
if (queryString.length() > 0)
{
String queryArray[] = Strings.split(queryString, '&');
for (String s : queryArray)
{
if (Strings.isEmpty(s) == false)
{
result.parameters.add(parseQueryParameter(s, charset));
}
}
}
return result;
}
/**
*
* @param qp
* @param charset
* @return query parameters
*/
private static QueryParameter parseQueryParameter(final String qp, final Charset charset)
{
int idxOfEquals = qp.indexOf('=');
if (idxOfEquals == -1)
{
// name => empty value
return new QueryParameter(decodeParameter(qp, charset), "");
}
String parameterName = qp.substring(0, idxOfEquals);
String parameterValue = qp.substring(idxOfEquals + 1);
return new QueryParameter(decodeParameter(parameterName, charset), decodeParameter(parameterValue, charset));
}
/**
* get default port number for protocol
*
* @param protocol
* name of protocol
* @return default port for protocol or <code>null</code> if unknown
*/
private static Integer getDefaultPortForProtocol(String protocol)
{
if ("http".equals(protocol))
{
return 80;
}
else if ("https".equals(protocol))
{
return 443;
}
else if ("ftp".equals(protocol))
{
return 21;
}
else
{
return null;
}
}
/**
*
* @return charset
*/
public Charset getCharset()
{
if (Strings.isEmpty(charsetName))
{
charsetName = DEFAULT_CHARSET_NAME;
}
if (_charset == null)
{
_charset = Charset.forName(charsetName);
}
return _charset;
}
/**
*
* @param charset
*/
private void setCharset(final Charset charset)
{
if (charset == null)
{
charsetName = "UTF-8";
_charset = null;
}
else
{
charsetName = charset.name();
_charset = charset;
}
}
/**
* Returns segments of the URL. Segments form the part before query string.
*
* @return mutable list of segments
*/
public List<String> getSegments()
{
return segments;
}
/**
* Returns query parameters of the URL.
*
* @return mutable list of query parameters
*/
public List<QueryParameter> getQueryParameters()
{
return parameters;
}
/**
*
* @return fragment
*/
public String getFragment()
{
return fragment;
}
/**
*
* @param fragment
*/
public void setFragment(String fragment)
{
this.fragment = fragment;
}
/**
* Returns whether the Url is context absolute. Absolute Urls start with a '{@literal /}'.
*
* @return <code>true</code> if Url starts with the context path, <code>false</code> otherwise.
*/
public boolean isContextAbsolute()
{
return !contextRelative && !isFull() && !getSegments().isEmpty() && Strings.isEmpty(getSegments().get(0));
}
/**
* Returns whether the Url is a CSS data uri. Data uris start with '{@literal data:}'.
*
* @return <code>true</code> if Url starts with 'data:', <code>false</code> otherwise.
*/
public boolean isDataUrl()
{
return (getProtocol() != null && getProtocol().equals("data")) || (!getSegments().isEmpty() && getSegments()
.get(0).startsWith("data"));
}
/**
* Returns whether the Url has a <em>host</em> attribute.
* The scheme is optional because the url may be <code>//host/path</code>.
* The port is also optional because there are defaults for the different protocols.
*
* @return <code>true</code> if Url has a <em>host</em> attribute, <code>false</code> otherwise.
*/
public boolean isFull()
{
return !contextRelative && getHost() != null;
}
/**
* Convenience method that removes all query parameters with given name.
*
* @param name
* query parameter name
*/
public void removeQueryParameters(final String name)
{
for (Iterator<QueryParameter> i = getQueryParameters().iterator(); i.hasNext();)
{
QueryParameter param = i.next();
if (Objects.equal(name, param.getName()))
{
i.remove();
}
}
}
/**
* Convenience method that removes <code>count</code> leading segments
*
* @param count
*/
public void removeLeadingSegments(final int count)
{
Args.withinRange(0, segments.size(), count, "count");
for (int i = 0; i < count; i++)
{
segments.remove(0);
}
}
/**
* Convenience method that prepends <code>segments</code> to the segments collection
*
* @param newSegments
*/
public void prependLeadingSegments(final List<String> newSegments)
{
Args.notNull(newSegments, "segments");
segments.addAll(0, newSegments);
}
/**
* Convenience method that removes all query parameters with given name and adds new query
* parameter with specified name and value
*
* @param name
* @param value
*/
public void setQueryParameter(final String name, final Object value)
{
removeQueryParameters(name);
addQueryParameter(name, value);
}
/**
* Convenience method that removes adds a query parameter with given name
*
* @param name
* @param value
*/
public void addQueryParameter(final String name, final Object value)
{
if (value != null)
{
QueryParameter parameter = new QueryParameter(name, value.toString());
getQueryParameters().add(parameter);
}
}
/**
* Returns first query parameter with specified name or null if such query parameter doesn't
* exist.
*
* @param name
* @return query parameter or <code>null</code>
*/
public QueryParameter getQueryParameter(final String name)
{
for (QueryParameter parameter : parameters)
{
if (Objects.equal(name, parameter.getName()))
{
return parameter;
}
}
return null;
}
/**
* Returns the value of first query parameter with specified name. Note that this method never
* returns <code>null</code>. Not even if the parameter does not exist.
*
* @see StringValue#isNull()
*
* @param name
* @return {@link StringValue} instance wrapping the parameter value
*/
public StringValue getQueryParameterValue(final String name)
{
QueryParameter parameter = getQueryParameter(name);
if (parameter == null)
{
return StringValue.valueOf((String)null);
}
else
{
return StringValue.valueOf(parameter.getValue());
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if ((obj instanceof Url) == false)
{
return false;
}
Url rhs = (Url)obj;
return getSegments().equals(rhs.getSegments()) &&
getQueryParameters().equals(rhs.getQueryParameters()) &&
Objects.isEqual(getFragment(), rhs.getFragment());
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
return Objects.hashCode(getSegments(), getQueryParameters(), getFragment());
}
/**
*
* @param string
* @param charset
* @return encoded segment
*/
private static String encodeSegment(final String string, final Charset charset)
{
return UrlEncoder.PATH_INSTANCE.encode(string, charset);
}
/**
*
* @param string
* @param charset
* @return decoded segment
*/
private static String decodeSegment(final String string, final Charset charset)
{
return UrlDecoder.PATH_INSTANCE.decode(string, charset);
}
/**
*
* @param string
* @param charset
* @return encoded parameter
*/
private static String encodeParameter(final String string, final Charset charset)
{
return UrlEncoder.QUERY_INSTANCE.encode(string, charset);
}
/**
*
* @param string
* @param charset
* @return decoded parameter
*/
private static String decodeParameter(final String string, final Charset charset)
{
return UrlDecoder.QUERY_INSTANCE.decode(string, charset);
}
/**
* Renders a url with {@link StringMode#LOCAL} using the url's charset
*/
@Override
public String toString()
{
return toString(getCharset());
}
/**
* Stringizes this url
*
* @param mode
* {@link StringMode} that determins how to stringize the url
* @param charset
* charset
* @return sringized version of this url
*
*/
public String toString(StringMode mode, Charset charset)
{
StringBuilder result = new StringBuilder();
final String path = getPath(charset);
if (StringMode.FULL == mode)
{
if (Strings.isEmpty(host))
{
throw new IllegalStateException("Cannot render this url in " +
StringMode.FULL.name() + " mode because it does not have a host set.");
}
if (Strings.isEmpty(protocol) == false)
{
result.append(protocol);
result.append("://");
}
else if (Strings.isEmpty(protocol) && Strings.isEmpty(host) == false)
{
result.append("//");
}
result.append(host);
if (port != null && port.equals(getDefaultPortForProtocol(protocol)) == false)
{
result.append(':');
result.append(port);
}
if (segments.contains(".."))
{
throw new IllegalStateException("Cannot render this url in " +
StringMode.FULL.name() + " mode because it has a `..` segment: " + toString());
}
if (!path.startsWith("/"))
{
result.append('/');
}
}
result.append(path);
final String queryString = getQueryString(charset);
if (queryString != null)
{
result.append('?').append(queryString);
}
String _fragment = getFragment();
if (Strings.isEmpty(_fragment) == false)
{
result.append('#').append(_fragment);
}
return result.toString();
}
/**
* Stringizes this url using the specific {@link StringMode} and url's charset
*
* @param mode
* {@link StringMode} that determines how to stringize the url
* @return stringized url
*/
public String toString(StringMode mode)
{
return toString(mode, getCharset());
}
/**
* Stringizes this url using {@link StringMode#LOCAL} and the specified charset
*
* @param charset
* @return stringized url
*/
public String toString(final Charset charset)
{
return toString(StringMode.LOCAL, charset);
}
/**
*
* @return true if last segment contains a name and not something like "." or "..".
*/
private boolean isLastSegmentReal()
{
if (segments.isEmpty())
{
return false;
}
String last = segments.get(segments.size() - 1);
return (last.length() > 0) && !".".equals(last) && !"..".equals(last);
}
/**
* @param segments
* @return true if last segment is empty
*/
private boolean isLastSegmentEmpty(final List<String> segments)
{
if (segments.isEmpty())
{
return false;
}
String last = segments.get(segments.size() - 1);
return last.length() == 0;
}
/**
*
* @return true, if last segement is empty
*/
private boolean isLastSegmentEmpty()
{
return isLastSegmentEmpty(segments);
}
/**
*
* @param segments
* @return true if at least one segement is real
*/
private boolean isAtLeastOneSegmentReal(final List<String> segments)
{
for (String s : segments)
{
if ((s.length() > 0) && !".".equals(s) && !"..".equals(s))
{
return true;
}
}
return false;
}
/**
* Concatenate the specified segments; The segments can be relative - begin with "." or "..".
*
* @param segments
*/
public void concatSegments(List<String> segments)
{
boolean checkedLastSegment = false;
if (!isAtLeastOneSegmentReal(segments) && !isLastSegmentEmpty(segments))
{
segments = new ArrayList<>(segments);
segments.add("");
}
for (String s : segments)
{
if (".".equals(s))
{
continue;
}
else if ("..".equals(s) && !this.segments.isEmpty())
{
this.segments.remove(this.segments.size() - 1);
}
else
{
if (!checkedLastSegment)
{
if (isLastSegmentReal() || isLastSegmentEmpty())
{
this.segments.remove(this.segments.size() - 1);
}
checkedLastSegment = true;
}
this.segments.add(s);
}
}
if ((this.segments.size() == 1) && (this.segments.get(0).length() == 0))
{
this.segments.clear();
}
}
/**
* Represents a single query parameter
*
* @author Matej Knopp
*/
public final static class QueryParameter implements Serializable
{
private static final long serialVersionUID = 1L;
private final String name;
private final String value;
/**
* Creates new {@link QueryParameter} instance. The <code>name</code> and <code>value</code>
* parameters must not be <code>null</code>, though they can be empty strings.
*
* @param name
* parameter name
* @param value
* parameter value
*/
public QueryParameter(final String name, final String value)
{
Args.notNull(name, "name");
Args.notNull(value, "value");
this.name = name;
this.value = value;
}
/**
* Returns query parameter name.
*
* @return query parameter name
*/
public String getName()
{
return name;
}
/**
* Returns query parameter value.
*
* @return query parameter value
*/
public String getValue()
{
return value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if ((obj instanceof QueryParameter) == false)
{
return false;
}
QueryParameter rhs = (QueryParameter)obj;
return Objects.equal(getName(), rhs.getName()) &&
Objects.equal(getValue(), rhs.getValue());
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
return Objects.hashCode(getName(), getValue());
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return toString(Charset.forName(DEFAULT_CHARSET_NAME));
}
/**
*
* @param charset
* @return see toString()
*/
public String toString(final Charset charset)
{
StringBuilder result = new StringBuilder();
result.append(encodeParameter(getName(), charset));
if (!Strings.isEmpty(getValue()))
{
result.append('=');
result.append(encodeParameter(getValue(), charset));
}
return result.toString();
}
}
/**
* Makes this url the result of resolving the {@code relative} url against this url.
* <p>
* Segments will be properly resolved, handling any {@code ..} references, while the query
* parameters will be completely replaced with {@code relative}'s query parameters.
* </p>
* <p>
* For example:
*
* <pre>
* wicket/page/render?foo=bar
* </pre>
*
* resolved with
*
* <pre>
* ../component/render?a=b
* </pre>
*
* will become
*
* <pre>
* wicket/component/render?a=b
* </pre>
*
* </p>
*
* @param relative
* relative url
*/
public void resolveRelative(final Url relative)
{
if (getSegments().size() > 0)
{
// strip the first non-folder segment (if it is not empty)
getSegments().remove(getSegments().size() - 1);
}
// remove leading './' (current folder) and empty segments, process any ../ segments from
// the relative url
while (!relative.getSegments().isEmpty())
{
if (".".equals(relative.getSegments().get(0)))
{
relative.getSegments().remove(0);
}
else if ("".equals(relative.getSegments().get(0)))
{
relative.getSegments().remove(0);
}
else if ("..".equals(relative.getSegments().get(0)))
{
relative.getSegments().remove(0);
if (getSegments().isEmpty() == false)
{
getSegments().remove(getSegments().size() - 1);
}
}
else
{
break;
}
}
if (!getSegments().isEmpty() && relative.getSegments().isEmpty())
{
getSegments().add("");
}
// append the remaining relative segments
getSegments().addAll(relative.getSegments());
// replace query params with the ones from relative
parameters.clear();
parameters.addAll(relative.getQueryParameters());
}
/**
* Gets the protocol of this url (http/https/etc)
*
* @return protocol or {@code null} if none has been set
*/
public String getProtocol()
{
return protocol;
}
/**
* Sets the protocol of this url (http/https/etc)
*
* @param protocol
*/
public void setProtocol(final String protocol)
{
this.protocol = protocol;
}
/**
*
* Flags the URL as relative to the application context.
*
* @param contextRelative
*/
public void setContextRelative(boolean contextRelative)
{
this.contextRelative = contextRelative;
}
/**
* Tests if the URL is relative to the application context. If so, it holds all the information
* an absolute URL would have, minus the context and filter mapping segments
*
* @return contextRelative
*/
public boolean isContextRelative()
{
return contextRelative;
}
/**
* Gets the port of this url
*
* @return port or {@code null} if none has been set
*/
public Integer getPort()
{
return port;
}
/**
* Sets the port of this url
*
* @param port
*/
public void setPort(final Integer port)
{
this.port = port;
}
/**
* Gets the host name of this url
*
* @return host name or {@code null} if none is seto
*/
public String getHost()
{
return host;
}
/**
* Sets the host name of this url
*
* @param host
*/
public void setHost(final String host)
{
this.host = host;
}
/**
* return path for current url in given encoding
*
* @param charset
* character set for encoding
*
* @return path string
*/
public String getPath(Charset charset)
{
Args.notNull(charset, "charset");
StringBuilder path = new StringBuilder();
boolean slash = false;
for (String segment : getSegments())
{
if (slash)
{
path.append('/');
}
path.append(encodeSegment(segment, charset));
slash = true;
}
return path.toString();
}
/**
* return path for current url in original encoding
*
* @return path string
*/
public String getPath()
{
return getPath(getCharset());
}
/**
* return query string part of url in given encoding
*
* @param charset
* character set for encoding
* @since Wicket 7
* the return value does not contain any "?" and could be null
* @return query string (null if empty)
*/
public String getQueryString(Charset charset)
{
Args.notNull(charset, "charset");
String queryString = null;
List<QueryParameter> queryParameters = getQueryParameters();
if (queryParameters.size() != 0)
{
StringBuilder query = new StringBuilder();
for (QueryParameter parameter : queryParameters)
{
if (query.length() != 0)
{
query.append('&');
}
query.append(parameter.toString(charset));
}
queryString = query.toString();
}
return queryString;
}
/**
* return query string part of url in original encoding
*
* @since Wicket 7
* the return value does not contain any "?" and could be null
* @return query string (null if empty)
*/
public String getQueryString()
{
return getQueryString(getCharset());
}
/**
* Try to reduce url by eliminating '..' and '.' from the path where appropriate (this is
* somehow similar to {@link java.io.File#getCanonicalPath()}). Either by different / unexpected
* browser behavior or by malicious attacks it can happen that these kind of redundant urls are
* processed by wicket. These urls can cause some trouble when mapping the request.
* <p/>
* <strong>example:</strong>
*
* the url
*
* <pre>
* /example/..;jsessionid=234792?0
* </pre>
*
* will not get normalized by the browser due to the ';jsessionid' string that gets appended by
* the servlet container. After wicket strips the jsessionid part the resulting internal url
* will be
*
* <pre>
* /example/..
* </pre>
*
* instead of
*
* <pre>
* /
* </pre>
*
* <p/>
*
* This code correlates to <a
* href="https://issues.apache.org/jira/browse/WICKET-4303">WICKET-4303</a>
*
* @return canonical url
*/
public Url canonical()
{
Url url = new Url(this);
url.segments.clear();
for (int i = 0; i < segments.size(); i++)
{
final String segment = segments.get(i);
// drop '.' from path
if (".".equals(segment))
{
// skip
}
else if ("..".equals(segment) && url.segments.isEmpty() == false)
{
url.segments.remove(url.segments.size() - 1);
}
// skip segment if following segment is a '..'
else if ((i + 1) < segments.size() && "..".equals(segments.get(i + 1)))
{
i++;
}
else
{
url.segments.add(segment);
}
}
return url;
}
}
| apache-2.0 |
salyh/incubator-tamaya | java8/api/src/main/java/org/apache/tamaya/spi/PropertySourceProvider.java | 1735 | /*
* 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.tamaya.spi;
import java.util.Collection;
/**
* <p>Implement this interfaces to provide a PropertySource provider which
* is able to register multiple PropertySources. This is e.g. needed if
* there are multiple property files of a given config file name.</p>
* <p>
* <p>If a PropertySource like JNDI only exists once, then there is no need
* to implement it via the PropertySourceProvider but should directly
* expose a {@link PropertySource}.</p>
* <p>
* <p>A PropertySourceProvider will get picked up via the
* {@link java.util.ServiceLoader} mechanism and must get registered via
* META-INF/services/org.apache.tamaya.spi.PropertySourceProvider</p>
*/
public interface PropertySourceProvider {
/**
* @return For each e.g. property file, we return a single PropertySource
* or an empty list if no PropertySource exists.
*/
Collection<PropertySource> getPropertySources();
}
| apache-2.0 |
diorcety/intellij-community | java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java | 9435 | /*
* Copyright 2000-2012 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.tree.java;
import com.intellij.icons.AllIcons;
import com.intellij.lang.ASTNode;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
import com.intellij.psi.impl.source.tree.ChildRole;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Map;
public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements PsiLambdaExpression {
private static final ControlFlowPolicy ourPolicy = new ControlFlowPolicy() {
@Nullable
@Override
public PsiVariable getUsedVariable(@NotNull PsiReferenceExpression refExpr) {
return null;
}
@Override
public boolean isParameterAccepted(@NotNull PsiParameter psiParameter) {
return true;
}
@Override
public boolean isLocalVariableAccepted(@NotNull PsiLocalVariable psiVariable) {
return true;
}
};
public PsiLambdaExpressionImpl() {
super(JavaElementType.LAMBDA_EXPRESSION);
}
@NotNull
@Override
public PsiParameterList getParameterList() {
return PsiTreeUtil.getRequiredChildOfType(this, PsiParameterList.class);
}
@Override
public int getChildRole(ASTNode child) {
final IElementType elType = child.getElementType();
if (elType == JavaTokenType.ARROW) {
return ChildRole.ARROW;
} else if (elType == JavaElementType.PARAMETER_LIST) {
return ChildRole.PARAMETER_LIST;
} else if (elType == JavaElementType.CODE_BLOCK) {
return ChildRole.LBRACE;
} else {
return ChildRole.EXPRESSION;
}
}
@Override
public PsiElement getBody() {
final PsiElement element = getLastChild();
return element instanceof PsiExpression || element instanceof PsiCodeBlock ? element : null;
}
@Nullable
@Override
public PsiType getFunctionalInterfaceType() {
return FunctionalInterfaceParameterizationUtil.getGroundTargetType(LambdaUtil.getFunctionalInterfaceType(this, true), this);
}
@Override
public boolean isVoidCompatible() {
final PsiElement body = getBody();
if (body instanceof PsiCodeBlock) {
for (PsiReturnStatement statement : PsiUtil.findReturnStatements((PsiCodeBlock)body)) {
if (statement.getReturnValue() != null) {
return false;
}
}
}
return true;
}
@Override
public boolean isValueCompatible() {
final PsiElement body = getBody();
if (body instanceof PsiCodeBlock) {
try {
ControlFlow controlFlow = ControlFlowFactory.getInstance(getProject()).getControlFlow(body, ourPolicy);
int startOffset = controlFlow.getStartOffset(body);
int endOffset = controlFlow.getEndOffset(body);
if (startOffset != -1 && endOffset != -1 && ControlFlowUtil.canCompleteNormally(controlFlow, startOffset, endOffset)) {
return false;
}
}
catch (AnalysisCanceledException e) {
return false;
}
for (PsiReturnStatement statement : PsiUtil.findReturnStatements((PsiCodeBlock)body)) {
if (statement.getReturnValue() == null) {
return false;
}
}
}
return true;
}
@Override
public PsiType getType() {
return new PsiLambdaExpressionType(this);
}
@Override
public void accept(@NotNull final PsiElementVisitor visitor) {
if (visitor instanceof JavaElementVisitor) {
((JavaElementVisitor)visitor).visitLambdaExpression(this);
}
else {
visitor.visitElement(this);
}
}
@Override
public boolean processDeclarations(@NotNull final PsiScopeProcessor processor,
@NotNull final ResolveState state,
final PsiElement lastParent,
@NotNull final PsiElement place) {
return PsiImplUtil.processDeclarationsInLambda(this, processor, state, lastParent, place);
}
@Override
public String toString() {
return "PsiLambdaExpression:" + getText();
}
@Override
public boolean hasFormalParameterTypes() {
final PsiParameter[] parameters = getParameterList().getParameters();
for (PsiParameter parameter : parameters) {
if (parameter.getTypeElement() == null) return false;
}
return true;
}
@Override
public boolean isAcceptable(PsiType leftType) {
if (leftType instanceof PsiIntersectionType) {
for (PsiType conjunctType : ((PsiIntersectionType)leftType).getConjuncts()) {
if (isAcceptable(conjunctType)) return true;
}
return false;
}
final PsiExpressionList argsList = PsiTreeUtil.getParentOfType(this, PsiExpressionList.class);
if (MethodCandidateInfo.ourOverloadGuard.currentStack().contains(argsList)) {
final MethodCandidateInfo.CurrentCandidateProperties candidateProperties = MethodCandidateInfo.getCurrentMethod(argsList);
if (candidateProperties != null) {
final PsiMethod method = candidateProperties.getMethod();
if (hasFormalParameterTypes() && !InferenceSession.isPertinentToApplicability(this, method)) {
return true;
}
if (LambdaUtil.isPotentiallyCompatibleWithTypeParameter(this, argsList, method)) {
return true;
}
}
}
leftType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(leftType, this);
if (!isPotentiallyCompatible(leftType)) {
return false;
}
if (MethodCandidateInfo.ourOverloadGuard.currentStack().contains(argsList) && !hasFormalParameterTypes()) {
return true;
}
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(leftType);
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult);
if (interfaceMethod == null) return false;
if (interfaceMethod.hasTypeParameters()) return false;
final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, resolveResult);
if (hasFormalParameterTypes()) {
final PsiParameter[] lambdaParameters = getParameterList().getParameters();
final PsiType[] parameterTypes = interfaceMethod.getSignature(substitutor).getParameterTypes();
for (int lambdaParamIdx = 0, length = lambdaParameters.length; lambdaParamIdx < length; lambdaParamIdx++) {
PsiParameter parameter = lambdaParameters[lambdaParamIdx];
final PsiTypeElement typeElement = parameter.getTypeElement();
if (typeElement != null) {
final PsiType lambdaFormalType = toArray(typeElement.getType());
final PsiType methodParameterType = toArray(parameterTypes[lambdaParamIdx]);
if (!lambdaFormalType.equals(methodParameterType)) {
return false;
}
}
}
}
PsiType methodReturnType = interfaceMethod.getReturnType();
if (methodReturnType != null && methodReturnType != PsiType.VOID) {
Map<PsiElement, PsiType> map = LambdaUtil.getFunctionalTypeMap();
try {
if (map.put(this, leftType) != null) {
return false;
}
return LambdaUtil.checkReturnTypeCompatible(this, substitutor.substitute(methodReturnType)) == null;
}
finally {
map.remove(this);
}
}
return true;
}
@Override
public boolean isPotentiallyCompatible(PsiType left) {
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(left);
if (interfaceMethod == null) return false;
if (getParameterList().getParametersCount() != interfaceMethod.getParameterList().getParametersCount()) {
return false;
}
final PsiType methodReturnType = interfaceMethod.getReturnType();
final PsiElement body = getBody();
if (methodReturnType == PsiType.VOID) {
if (body instanceof PsiCodeBlock) {
return isVoidCompatible();
} else {
return LambdaUtil.isExpressionStatementExpression(body);
}
}
else {
return body instanceof PsiCodeBlock && isValueCompatible() || body instanceof PsiExpression;
}
}
private static PsiType toArray(PsiType paramType) {
if (paramType instanceof PsiEllipsisType) {
return ((PsiEllipsisType)paramType).toArrayType();
}
return paramType;
}
@Nullable
@Override
public Icon getIcon(int flags) {
return AllIcons.Nodes.AnonymousClass;
}
}
| apache-2.0 |
pdxrunner/geode | geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/IndexRepositoryFactory.java | 8853 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.lucene.internal;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.geode.cache.CacheClosedException;
import org.apache.geode.cache.EntryDestroyedException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.lucene.LuceneSerializer;
import org.apache.geode.cache.lucene.internal.directory.RegionDirectory;
import org.apache.geode.cache.lucene.internal.partition.BucketTargetingMap;
import org.apache.geode.cache.lucene.internal.repository.IndexRepository;
import org.apache.geode.cache.lucene.internal.repository.IndexRepositoryImpl;
import org.apache.geode.distributed.DistributedLockService;
import org.apache.geode.internal.cache.BucketRegion;
import org.apache.geode.internal.cache.EntrySnapshot;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.PartitionRegionConfig;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.PartitionedRegionHelper;
import org.apache.geode.internal.logging.LogService;
public class IndexRepositoryFactory {
private static final Logger logger = LogService.getLogger();
public static final String FILE_REGION_LOCK_FOR_BUCKET_ID = "FileRegionLockForBucketId:";
public static final String APACHE_GEODE_INDEX_COMPLETE = "APACHE_GEODE_INDEX_COMPLETE";
public IndexRepositoryFactory() {}
public IndexRepository computeIndexRepository(final Integer bucketId, LuceneSerializer serializer,
InternalLuceneIndex index, PartitionedRegion userRegion, final IndexRepository oldRepository,
PartitionedRepositoryManager partitionedRepositoryManager) throws IOException {
LuceneIndexForPartitionedRegion indexForPR = (LuceneIndexForPartitionedRegion) index;
final PartitionedRegion fileRegion = indexForPR.getFileAndChunkRegion();
// We need to ensure that all members have created the fileAndChunk region before continuing
Region prRoot = PartitionedRegionHelper.getPRRoot(fileRegion.getCache());
PartitionRegionConfig prConfig =
(PartitionRegionConfig) prRoot.get(fileRegion.getRegionIdentifier());
LuceneFileRegionColocationListener luceneFileRegionColocationCompleteListener =
new LuceneFileRegionColocationListener(partitionedRepositoryManager, bucketId);
fileRegion.addColocationListener(luceneFileRegionColocationCompleteListener);
IndexRepository repo = null;
if (prConfig.isColocationComplete()) {
repo = finishComputingRepository(bucketId, serializer, userRegion, oldRepository, index);
}
return repo;
}
/*
* NOTE: The method finishComputingRepository must be called through computeIndexRepository.
* Executing finishComputingRepository outside of computeIndexRepository may result in race
* conditions.
* This is a util function just to not let computeIndexRepository be a huge chunk of code.
*/
private IndexRepository finishComputingRepository(Integer bucketId, LuceneSerializer serializer,
PartitionedRegion userRegion, IndexRepository oldRepository, InternalLuceneIndex index)
throws IOException {
LuceneIndexForPartitionedRegion indexForPR = (LuceneIndexForPartitionedRegion) index;
final PartitionedRegion fileRegion = indexForPR.getFileAndChunkRegion();
BucketRegion fileAndChunkBucket = getMatchingBucket(fileRegion, bucketId);
BucketRegion dataBucket = getMatchingBucket(userRegion, bucketId);
boolean success = false;
if (fileAndChunkBucket == null) {
if (oldRepository != null) {
oldRepository.cleanup();
}
return null;
}
if (!fileAndChunkBucket.getBucketAdvisor().isPrimary()) {
if (oldRepository != null) {
oldRepository.cleanup();
}
return null;
}
if (oldRepository != null && !oldRepository.isClosed()) {
return oldRepository;
}
if (oldRepository != null) {
oldRepository.cleanup();
}
DistributedLockService lockService = getLockService();
String lockName = getLockName(fileAndChunkBucket);
while (!lockService.lock(lockName, 100, -1)) {
if (!fileAndChunkBucket.getBucketAdvisor().isPrimary()) {
return null;
}
}
final IndexRepository repo;
InternalCache cache = (InternalCache) userRegion.getRegionService();
boolean initialPdxReadSerializedFlag = cache.getPdxReadSerializedOverride();
cache.setPdxReadSerializedOverride(true);
try {
// bucketTargetingMap handles partition resolver (via bucketId as callbackArg)
Map bucketTargetingMap = getBucketTargetingMap(fileAndChunkBucket, bucketId);
RegionDirectory dir =
new RegionDirectory(bucketTargetingMap, indexForPR.getFileSystemStats());
IndexWriterConfig config = new IndexWriterConfig(indexForPR.getAnalyzer());
IndexWriter writer = new IndexWriter(dir, config);
repo = new IndexRepositoryImpl(fileAndChunkBucket, writer, serializer,
indexForPR.getIndexStats(), dataBucket, lockService, lockName, indexForPR);
success = false;
// fileRegion ops (get/put) need bucketId as a callbackArg for PartitionResolver
if (null != fileRegion.get(APACHE_GEODE_INDEX_COMPLETE, bucketId)) {
success = true;
return repo;
} else {
success = reindexUserDataRegion(bucketId, userRegion, fileRegion, dataBucket, repo);
}
return repo;
} catch (IOException e) {
logger.info("Exception thrown while constructing Lucene Index for bucket:" + bucketId
+ " for file region:" + fileAndChunkBucket.getFullPath());
throw e;
} catch (CacheClosedException e) {
logger.info("CacheClosedException thrown while constructing Lucene Index for bucket:"
+ bucketId + " for file region:" + fileAndChunkBucket.getFullPath());
throw e;
} finally {
if (!success) {
lockService.unlock(lockName);
}
cache.setPdxReadSerializedOverride(initialPdxReadSerializedFlag);
}
}
private boolean reindexUserDataRegion(Integer bucketId, PartitionedRegion userRegion,
PartitionedRegion fileRegion, BucketRegion dataBucket, IndexRepository repo)
throws IOException {
Set<IndexRepository> affectedRepos = new HashSet<IndexRepository>();
for (Object key : dataBucket.keySet()) {
Object value = getValue(userRegion.getEntry(key));
if (value != null) {
repo.update(key, value);
} else {
repo.delete(key);
}
affectedRepos.add(repo);
}
for (IndexRepository affectedRepo : affectedRepos) {
affectedRepo.commit();
}
// fileRegion ops (get/put) need bucketId as a callbackArg for PartitionResolver
fileRegion.put(APACHE_GEODE_INDEX_COMPLETE, APACHE_GEODE_INDEX_COMPLETE, bucketId);
return true;
}
private Object getValue(Region.Entry entry) {
final EntrySnapshot es = (EntrySnapshot) entry;
Object value;
try {
value = es == null ? null : es.getRawValue(true);
} catch (EntryDestroyedException e) {
value = null;
}
return value;
}
private Map getBucketTargetingMap(BucketRegion region, int bucketId) {
return new BucketTargetingMap(region, bucketId);
}
private String getLockName(final BucketRegion fileAndChunkBucket) {
return FILE_REGION_LOCK_FOR_BUCKET_ID + fileAndChunkBucket.getFullPath();
}
private DistributedLockService getLockService() {
return DistributedLockService
.getServiceNamed(PartitionedRegionHelper.PARTITION_LOCK_SERVICE_NAME);
}
/**
* Find the bucket in region2 that matches the bucket id from region1.
*/
protected BucketRegion getMatchingBucket(PartitionedRegion region, Integer bucketId) {
// Force the bucket to be created if it is not already
region.getOrCreateNodeForBucketWrite(bucketId, null);
return region.getDataStore().getLocalBucketById(bucketId);
}
}
| apache-2.0 |
messi49/hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3native/NativeS3FileSystem.java | 26157 | /**
* 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.fs.s3native;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BufferedFSInputStream;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FSExceptionMessages;
import org.apache.hadoop.fs.FSInputStream;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalDirAllocator;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.s3.S3Exception;
import org.apache.hadoop.io.retry.RetryPolicies;
import org.apache.hadoop.io.retry.RetryPolicy;
import org.apache.hadoop.io.retry.RetryProxy;
import org.apache.hadoop.util.Progressable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link FileSystem} for reading and writing files stored on
* <a href="http://aws.amazon.com/s3">Amazon S3</a>.
* Unlike {@link org.apache.hadoop.fs.s3.S3FileSystem} this implementation
* stores files on S3 in their
* native form so they can be read by other S3 tools.
* <p>
* A note about directories. S3 of course has no "native" support for them.
* The idiom we choose then is: for any directory created by this class,
* we use an empty object "#{dirpath}_$folder$" as a marker.
* Further, to interoperate with other S3 tools, we also accept the following:
* <ul>
* <li>an object "#{dirpath}/' denoting a directory marker</li>
* <li>
* if there exists any objects with the prefix "#{dirpath}/", then the
* directory is said to exist
* </li>
* <li>
* if both a file with the name of a directory and a marker for that
* directory exists, then the *file masks the directory*, and the directory
* is never returned.
* </li>
* </ul>
*
* @see org.apache.hadoop.fs.s3.S3FileSystem
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class NativeS3FileSystem extends FileSystem {
public static final Logger LOG =
LoggerFactory.getLogger(NativeS3FileSystem.class);
private static final String FOLDER_SUFFIX = "_$folder$";
static final String PATH_DELIMITER = Path.SEPARATOR;
private static final int S3_MAX_LISTING_LENGTH = 1000;
static class NativeS3FsInputStream extends FSInputStream {
private NativeFileSystemStore store;
private Statistics statistics;
private InputStream in;
private final String key;
private long pos = 0;
public NativeS3FsInputStream(NativeFileSystemStore store, Statistics statistics, InputStream in, String key) {
Preconditions.checkNotNull(in, "Null input stream");
this.store = store;
this.statistics = statistics;
this.in = in;
this.key = key;
}
@Override
public synchronized int read() throws IOException {
int result;
try {
result = in.read();
} catch (IOException e) {
LOG.info("Received IOException while reading '{}', attempting to reopen",
key);
LOG.debug("{}", e, e);
try {
seek(pos);
result = in.read();
} catch (EOFException eof) {
LOG.debug("EOF on input stream read: {}", eof, eof);
result = -1;
}
}
if (result != -1) {
pos++;
}
if (statistics != null && result != -1) {
statistics.incrementBytesRead(1);
}
return result;
}
@Override
public synchronized int read(byte[] b, int off, int len)
throws IOException {
if (in == null) {
throw new EOFException("Cannot read closed stream");
}
int result = -1;
try {
result = in.read(b, off, len);
} catch (EOFException eof) {
throw eof;
} catch (IOException e) {
LOG.info( "Received IOException while reading '{}'," +
" attempting to reopen.", key);
seek(pos);
result = in.read(b, off, len);
}
if (result > 0) {
pos += result;
}
if (statistics != null && result > 0) {
statistics.incrementBytesRead(result);
}
return result;
}
@Override
public synchronized void close() throws IOException {
closeInnerStream();
}
/**
* Close the inner stream if not null. Even if an exception
* is raised during the close, the field is set to null
* @throws IOException if raised by the close() operation.
*/
private void closeInnerStream() throws IOException {
if (in != null) {
try {
in.close();
} finally {
in = null;
}
}
}
/**
* Update inner stream with a new stream and position
* @param newStream new stream -must not be null
* @param newpos new position
* @throws IOException IO exception on a failure to close the existing
* stream.
*/
private synchronized void updateInnerStream(InputStream newStream, long newpos) throws IOException {
Preconditions.checkNotNull(newStream, "Null newstream argument");
closeInnerStream();
in = newStream;
this.pos = newpos;
}
@Override
public synchronized void seek(long newpos) throws IOException {
if (newpos < 0) {
throw new EOFException(
FSExceptionMessages.NEGATIVE_SEEK);
}
if (pos != newpos) {
// the seek is attempting to move the current position
LOG.debug("Opening key '{}' for reading at position '{}", key, newpos);
InputStream newStream = store.retrieve(key, newpos);
updateInnerStream(newStream, newpos);
}
}
@Override
public synchronized long getPos() throws IOException {
return pos;
}
@Override
public boolean seekToNewSource(long targetPos) throws IOException {
return false;
}
}
private class NativeS3FsOutputStream extends OutputStream {
private Configuration conf;
private String key;
private File backupFile;
private OutputStream backupStream;
private MessageDigest digest;
private boolean closed;
private LocalDirAllocator lDirAlloc;
public NativeS3FsOutputStream(Configuration conf,
NativeFileSystemStore store, String key, Progressable progress,
int bufferSize) throws IOException {
this.conf = conf;
this.key = key;
this.backupFile = newBackupFile();
LOG.info("OutputStream for key '" + key + "' writing to tempfile '" + this.backupFile + "'");
try {
this.digest = MessageDigest.getInstance("MD5");
this.backupStream = new BufferedOutputStream(new DigestOutputStream(
new FileOutputStream(backupFile), this.digest));
} catch (NoSuchAlgorithmException e) {
LOG.warn("Cannot load MD5 digest algorithm," +
"skipping message integrity check.", e);
this.backupStream = new BufferedOutputStream(
new FileOutputStream(backupFile));
}
}
private File newBackupFile() throws IOException {
if (lDirAlloc == null) {
lDirAlloc = new LocalDirAllocator("fs.s3.buffer.dir");
}
File result = lDirAlloc.createTmpFileForWrite("output-", LocalDirAllocator.SIZE_UNKNOWN, conf);
result.deleteOnExit();
return result;
}
@Override
public void flush() throws IOException {
backupStream.flush();
}
@Override
public synchronized void close() throws IOException {
if (closed) {
return;
}
backupStream.close();
LOG.info("OutputStream for key '{}' closed. Now beginning upload", key);
try {
byte[] md5Hash = digest == null ? null : digest.digest();
store.storeFile(key, backupFile, md5Hash);
} finally {
if (!backupFile.delete()) {
LOG.warn("Could not delete temporary s3n file: " + backupFile);
}
super.close();
closed = true;
}
LOG.info("OutputStream for key '{}' upload complete", key);
}
@Override
public void write(int b) throws IOException {
backupStream.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
backupStream.write(b, off, len);
}
}
private URI uri;
private NativeFileSystemStore store;
private Path workingDir;
public NativeS3FileSystem() {
// set store in initialize()
}
public NativeS3FileSystem(NativeFileSystemStore store) {
this.store = store;
}
/**
* Return the protocol scheme for the FileSystem.
*
* @return <code>s3n</code>
*/
@Override
public String getScheme() {
return "s3n";
}
@Override
public void initialize(URI uri, Configuration conf) throws IOException {
super.initialize(uri, conf);
if (store == null) {
store = createDefaultStore(conf);
}
store.initialize(uri, conf);
setConf(conf);
this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
this.workingDir =
new Path("/user", System.getProperty("user.name")).makeQualified(this.uri, this.getWorkingDirectory());
}
private static NativeFileSystemStore createDefaultStore(Configuration conf) {
NativeFileSystemStore store = new Jets3tNativeFileSystemStore();
RetryPolicy basePolicy = RetryPolicies.retryUpToMaximumCountWithFixedSleep(
conf.getInt("fs.s3.maxRetries", 4),
conf.getLong("fs.s3.sleepTimeSeconds", 10), TimeUnit.SECONDS);
Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap =
new HashMap<Class<? extends Exception>, RetryPolicy>();
exceptionToPolicyMap.put(IOException.class, basePolicy);
exceptionToPolicyMap.put(S3Exception.class, basePolicy);
RetryPolicy methodPolicy = RetryPolicies.retryByException(
RetryPolicies.TRY_ONCE_THEN_FAIL, exceptionToPolicyMap);
Map<String, RetryPolicy> methodNameToPolicyMap =
new HashMap<String, RetryPolicy>();
methodNameToPolicyMap.put("storeFile", methodPolicy);
methodNameToPolicyMap.put("rename", methodPolicy);
return (NativeFileSystemStore)
RetryProxy.create(NativeFileSystemStore.class, store,
methodNameToPolicyMap);
}
private static String pathToKey(Path path) {
if (path.toUri().getScheme() != null && path.toUri().getPath().isEmpty()) {
// allow uris without trailing slash after bucket to refer to root,
// like s3n://mybucket
return "";
}
if (!path.isAbsolute()) {
throw new IllegalArgumentException("Path must be absolute: " + path);
}
String ret = path.toUri().getPath().substring(1); // remove initial slash
if (ret.endsWith("/") && (ret.indexOf("/") != ret.length() - 1)) {
ret = ret.substring(0, ret.length() -1);
}
return ret;
}
private static Path keyToPath(String key) {
return new Path("/" + key);
}
private Path makeAbsolute(Path path) {
if (path.isAbsolute()) {
return path;
}
return new Path(workingDir, path);
}
/** This optional operation is not yet supported. */
@Override
public FSDataOutputStream append(Path f, int bufferSize,
Progressable progress) throws IOException {
throw new IOException("Not supported");
}
@Override
public FSDataOutputStream create(Path f, FsPermission permission,
boolean overwrite, int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
if (exists(f) && !overwrite) {
throw new FileAlreadyExistsException("File already exists: " + f);
}
if(LOG.isDebugEnabled()) {
LOG.debug("Creating new file '" + f + "' in S3");
}
Path absolutePath = makeAbsolute(f);
String key = pathToKey(absolutePath);
return new FSDataOutputStream(new NativeS3FsOutputStream(getConf(), store,
key, progress, bufferSize), statistics);
}
@Override
public boolean delete(Path f, boolean recurse) throws IOException {
FileStatus status;
try {
status = getFileStatus(f);
} catch (FileNotFoundException e) {
if(LOG.isDebugEnabled()) {
LOG.debug("Delete called for '" + f +
"' but file does not exist, so returning false");
}
return false;
}
Path absolutePath = makeAbsolute(f);
String key = pathToKey(absolutePath);
if (status.isDirectory()) {
if (!recurse && listStatus(f).length > 0) {
throw new IOException("Can not delete " + f + " as is a not empty directory and recurse option is false");
}
createParent(f);
if(LOG.isDebugEnabled()) {
LOG.debug("Deleting directory '" + f + "'");
}
String priorLastKey = null;
do {
PartialListing listing = store.list(key, S3_MAX_LISTING_LENGTH, priorLastKey, true);
for (FileMetadata file : listing.getFiles()) {
store.delete(file.getKey());
}
priorLastKey = listing.getPriorLastKey();
} while (priorLastKey != null);
try {
store.delete(key + FOLDER_SUFFIX);
} catch (FileNotFoundException e) {
//this is fine, we don't require a marker
}
} else {
if(LOG.isDebugEnabled()) {
LOG.debug("Deleting file '" + f + "'");
}
createParent(f);
store.delete(key);
}
return true;
}
@Override
public FileStatus getFileStatus(Path f) throws IOException {
Path absolutePath = makeAbsolute(f);
String key = pathToKey(absolutePath);
if (key.length() == 0) { // root always exists
return newDirectory(absolutePath);
}
if(LOG.isDebugEnabled()) {
LOG.debug("getFileStatus retrieving metadata for key '" + key + "'");
}
FileMetadata meta = store.retrieveMetadata(key);
if (meta != null) {
if(LOG.isDebugEnabled()) {
LOG.debug("getFileStatus returning 'file' for key '" + key + "'");
}
return newFile(meta, absolutePath);
}
if (store.retrieveMetadata(key + FOLDER_SUFFIX) != null) {
if(LOG.isDebugEnabled()) {
LOG.debug("getFileStatus returning 'directory' for key '" + key +
"' as '" + key + FOLDER_SUFFIX + "' exists");
}
return newDirectory(absolutePath);
}
if(LOG.isDebugEnabled()) {
LOG.debug("getFileStatus listing key '" + key + "'");
}
PartialListing listing = store.list(key, 1);
if (listing.getFiles().length > 0 ||
listing.getCommonPrefixes().length > 0) {
if(LOG.isDebugEnabled()) {
LOG.debug("getFileStatus returning 'directory' for key '" + key +
"' as it has contents");
}
return newDirectory(absolutePath);
}
if(LOG.isDebugEnabled()) {
LOG.debug("getFileStatus could not find key '" + key + "'");
}
throw new FileNotFoundException("No such file or directory '" + absolutePath + "'");
}
@Override
public URI getUri() {
return uri;
}
/**
* <p>
* If <code>f</code> is a file, this method will make a single call to S3.
* If <code>f</code> is a directory, this method will make a maximum of
* (<i>n</i> / 1000) + 2 calls to S3, where <i>n</i> is the total number of
* files and directories contained directly in <code>f</code>.
* </p>
*/
@Override
public FileStatus[] listStatus(Path f) throws IOException {
Path absolutePath = makeAbsolute(f);
String key = pathToKey(absolutePath);
if (key.length() > 0) {
FileMetadata meta = store.retrieveMetadata(key);
if (meta != null) {
return new FileStatus[] { newFile(meta, absolutePath) };
}
}
URI pathUri = absolutePath.toUri();
Set<FileStatus> status = new TreeSet<FileStatus>();
String priorLastKey = null;
do {
PartialListing listing = store.list(key, S3_MAX_LISTING_LENGTH, priorLastKey, false);
for (FileMetadata fileMetadata : listing.getFiles()) {
Path subpath = keyToPath(fileMetadata.getKey());
String relativePath = pathUri.relativize(subpath.toUri()).getPath();
if (fileMetadata.getKey().equals(key + "/")) {
// this is just the directory we have been asked to list
}
else if (relativePath.endsWith(FOLDER_SUFFIX)) {
status.add(newDirectory(new Path(
absolutePath,
relativePath.substring(0, relativePath.indexOf(FOLDER_SUFFIX)))));
}
else {
status.add(newFile(fileMetadata, subpath));
}
}
for (String commonPrefix : listing.getCommonPrefixes()) {
Path subpath = keyToPath(commonPrefix);
String relativePath = pathUri.relativize(subpath.toUri()).getPath();
status.add(newDirectory(new Path(absolutePath, relativePath)));
}
priorLastKey = listing.getPriorLastKey();
} while (priorLastKey != null);
if (status.isEmpty() &&
key.length() > 0 &&
store.retrieveMetadata(key + FOLDER_SUFFIX) == null) {
throw new FileNotFoundException("File " + f + " does not exist.");
}
return status.toArray(new FileStatus[status.size()]);
}
private FileStatus newFile(FileMetadata meta, Path path) {
return new FileStatus(meta.getLength(), false, 1, getDefaultBlockSize(),
meta.getLastModified(), path.makeQualified(this.getUri(), this.getWorkingDirectory()));
}
private FileStatus newDirectory(Path path) {
return new FileStatus(0, true, 1, 0, 0, path.makeQualified(this.getUri(), this.getWorkingDirectory()));
}
@Override
public boolean mkdirs(Path f, FsPermission permission) throws IOException {
Path absolutePath = makeAbsolute(f);
List<Path> paths = new ArrayList<Path>();
do {
paths.add(0, absolutePath);
absolutePath = absolutePath.getParent();
} while (absolutePath != null);
boolean result = true;
for (Path path : paths) {
result &= mkdir(path);
}
return result;
}
private boolean mkdir(Path f) throws IOException {
try {
FileStatus fileStatus = getFileStatus(f);
if (fileStatus.isFile()) {
throw new FileAlreadyExistsException(String.format(
"Can't make directory for path '%s' since it is a file.", f));
}
} catch (FileNotFoundException e) {
if(LOG.isDebugEnabled()) {
LOG.debug("Making dir '" + f + "' in S3");
}
String key = pathToKey(f) + FOLDER_SUFFIX;
store.storeEmptyFile(key);
}
return true;
}
@Override
public FSDataInputStream open(Path f, int bufferSize) throws IOException {
FileStatus fs = getFileStatus(f); // will throw if the file doesn't exist
if (fs.isDirectory()) {
throw new FileNotFoundException("'" + f + "' is a directory");
}
LOG.info("Opening '" + f + "' for reading");
Path absolutePath = makeAbsolute(f);
String key = pathToKey(absolutePath);
return new FSDataInputStream(new BufferedFSInputStream(
new NativeS3FsInputStream(store, statistics, store.retrieve(key), key), bufferSize));
}
// rename() and delete() use this method to ensure that the parent directory
// of the source does not vanish.
private void createParent(Path path) throws IOException {
Path parent = path.getParent();
if (parent != null) {
String key = pathToKey(makeAbsolute(parent));
if (key.length() > 0) {
store.storeEmptyFile(key + FOLDER_SUFFIX);
}
}
}
@Override
public boolean rename(Path src, Path dst) throws IOException {
String srcKey = pathToKey(makeAbsolute(src));
final String debugPreamble = "Renaming '" + src + "' to '" + dst + "' - ";
if (srcKey.length() == 0) {
// Cannot rename root of file system
if (LOG.isDebugEnabled()) {
LOG.debug(debugPreamble +
"returning false as cannot rename the root of a filesystem");
}
return false;
}
//get status of source
boolean srcIsFile;
try {
srcIsFile = getFileStatus(src).isFile();
} catch (FileNotFoundException e) {
//bail out fast if the source does not exist
if (LOG.isDebugEnabled()) {
LOG.debug(debugPreamble + "returning false as src does not exist");
}
return false;
}
// Figure out the final destination
String dstKey = pathToKey(makeAbsolute(dst));
try {
boolean dstIsFile = getFileStatus(dst).isFile();
if (dstIsFile) {
//destination is a file.
//you can't copy a file or a directory onto an existing file
//except for the special case of dest==src, which is a no-op
if(LOG.isDebugEnabled()) {
LOG.debug(debugPreamble +
"returning without rename as dst is an already existing file");
}
//exit, returning true iff the rename is onto self
return srcKey.equals(dstKey);
} else {
//destination exists and is a directory
if(LOG.isDebugEnabled()) {
LOG.debug(debugPreamble + "using dst as output directory");
}
//destination goes under the dst path, with the name of the
//source entry
dstKey = pathToKey(makeAbsolute(new Path(dst, src.getName())));
}
} catch (FileNotFoundException e) {
//destination does not exist => the source file or directory
//is copied over with the name of the destination
if(LOG.isDebugEnabled()) {
LOG.debug(debugPreamble + "using dst as output destination");
}
try {
if (getFileStatus(dst.getParent()).isFile()) {
if(LOG.isDebugEnabled()) {
LOG.debug(debugPreamble +
"returning false as dst parent exists and is a file");
}
return false;
}
} catch (FileNotFoundException ex) {
if(LOG.isDebugEnabled()) {
LOG.debug(debugPreamble +
"returning false as dst parent does not exist");
}
return false;
}
}
//rename to self behavior follows Posix rules and is different
//for directories and files -the return code is driven by src type
if (srcKey.equals(dstKey)) {
//fully resolved destination key matches source: fail
if (LOG.isDebugEnabled()) {
LOG.debug(debugPreamble + "renamingToSelf; returning true");
}
return true;
}
if (srcIsFile) {
//source is a file; COPY then DELETE
if(LOG.isDebugEnabled()) {
LOG.debug(debugPreamble +
"src is file, so doing copy then delete in S3");
}
store.copy(srcKey, dstKey);
store.delete(srcKey);
} else {
//src is a directory
if(LOG.isDebugEnabled()) {
LOG.debug(debugPreamble + "src is directory, so copying contents");
}
//Verify dest is not a child of the parent
if (dstKey.startsWith(srcKey + "/")) {
if (LOG.isDebugEnabled()) {
LOG.debug(
debugPreamble + "cannot rename a directory to a subdirectory of self");
}
return false;
}
//create the subdir under the destination
store.storeEmptyFile(dstKey + FOLDER_SUFFIX);
List<String> keysToDelete = new ArrayList<String>();
String priorLastKey = null;
do {
PartialListing listing = store.list(srcKey, S3_MAX_LISTING_LENGTH, priorLastKey, true);
for (FileMetadata file : listing.getFiles()) {
keysToDelete.add(file.getKey());
store.copy(file.getKey(), dstKey + file.getKey().substring(srcKey.length()));
}
priorLastKey = listing.getPriorLastKey();
} while (priorLastKey != null);
if(LOG.isDebugEnabled()) {
LOG.debug(debugPreamble +
"all files in src copied, now removing src files");
}
for (String key: keysToDelete) {
store.delete(key);
}
try {
store.delete(srcKey + FOLDER_SUFFIX);
} catch (FileNotFoundException e) {
//this is fine, we don't require a marker
}
if(LOG.isDebugEnabled()) {
LOG.debug(debugPreamble + "done");
}
}
return true;
}
@Override
public long getDefaultBlockSize() {
return getConf().getLong("fs.s3n.block.size", 64 * 1024 * 1024);
}
/**
* Set the working directory to the given directory.
*/
@Override
public void setWorkingDirectory(Path newDir) {
workingDir = newDir;
}
@Override
public Path getWorkingDirectory() {
return workingDir;
}
@Override
public String getCanonicalServiceName() {
// Does not support Token
return null;
}
}
| apache-2.0 |
flofreud/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/DeleteRouteRequest.java | 6223 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.Request;
import com.amazonaws.services.ec2.model.transform.DeleteRouteRequestMarshaller;
/**
* <p>
* Contains the parameters for DeleteRoute.
* </p>
*/
public class DeleteRouteRequest extends AmazonWebServiceRequest implements
Serializable, Cloneable, DryRunSupportedRequest<DeleteRouteRequest> {
/**
* <p>
* The ID of the route table.
* </p>
*/
private String routeTableId;
/**
* <p>
* The CIDR range for the route. The value you specify must match the CIDR
* for the route exactly.
* </p>
*/
private String destinationCidrBlock;
/**
* <p>
* The ID of the route table.
* </p>
*
* @param routeTableId
* The ID of the route table.
*/
public void setRouteTableId(String routeTableId) {
this.routeTableId = routeTableId;
}
/**
* <p>
* The ID of the route table.
* </p>
*
* @return The ID of the route table.
*/
public String getRouteTableId() {
return this.routeTableId;
}
/**
* <p>
* The ID of the route table.
* </p>
*
* @param routeTableId
* The ID of the route table.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DeleteRouteRequest withRouteTableId(String routeTableId) {
setRouteTableId(routeTableId);
return this;
}
/**
* <p>
* The CIDR range for the route. The value you specify must match the CIDR
* for the route exactly.
* </p>
*
* @param destinationCidrBlock
* The CIDR range for the route. The value you specify must match the
* CIDR for the route exactly.
*/
public void setDestinationCidrBlock(String destinationCidrBlock) {
this.destinationCidrBlock = destinationCidrBlock;
}
/**
* <p>
* The CIDR range for the route. The value you specify must match the CIDR
* for the route exactly.
* </p>
*
* @return The CIDR range for the route. The value you specify must match
* the CIDR for the route exactly.
*/
public String getDestinationCidrBlock() {
return this.destinationCidrBlock;
}
/**
* <p>
* The CIDR range for the route. The value you specify must match the CIDR
* for the route exactly.
* </p>
*
* @param destinationCidrBlock
* The CIDR range for the route. The value you specify must match the
* CIDR for the route exactly.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DeleteRouteRequest withDestinationCidrBlock(
String destinationCidrBlock) {
setDestinationCidrBlock(destinationCidrBlock);
return this;
}
/**
* This method is intended for internal use only. Returns the marshaled
* request configured with additional parameters to enable operation
* dry-run.
*/
@Override
public Request<DeleteRouteRequest> getDryRunRequest() {
Request<DeleteRouteRequest> request = new DeleteRouteRequestMarshaller()
.marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRouteTableId() != null)
sb.append("RouteTableId: " + getRouteTableId() + ",");
if (getDestinationCidrBlock() != null)
sb.append("DestinationCidrBlock: " + getDestinationCidrBlock());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteRouteRequest == false)
return false;
DeleteRouteRequest other = (DeleteRouteRequest) obj;
if (other.getRouteTableId() == null ^ this.getRouteTableId() == null)
return false;
if (other.getRouteTableId() != null
&& other.getRouteTableId().equals(this.getRouteTableId()) == false)
return false;
if (other.getDestinationCidrBlock() == null
^ this.getDestinationCidrBlock() == null)
return false;
if (other.getDestinationCidrBlock() != null
&& other.getDestinationCidrBlock().equals(
this.getDestinationCidrBlock()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getRouteTableId() == null) ? 0 : getRouteTableId()
.hashCode());
hashCode = prime
* hashCode
+ ((getDestinationCidrBlock() == null) ? 0
: getDestinationCidrBlock().hashCode());
return hashCode;
}
@Override
public DeleteRouteRequest clone() {
return (DeleteRouteRequest) super.clone();
}
} | apache-2.0 |
shenyefeng/java-sdk-for-UPYUN | src/main/java/com/upyun/sdk/utils/PropertyUtil.java | 1556 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.upyun.sdk.utils;
import java.util.Properties;
import org.apache.log4j.Logger;
public final class PropertyUtil {
private static Logger logger = Logger.getLogger(PropertyUtil.class);
private final static String CONF_DIR = "settings.properties";
private static Properties pro;
private PropertyUtil() {
}
public static String getProperty(String name) {
if (pro != null)
return pro.getProperty(name);
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = PropertyUtil.class.getClassLoader();
}
pro = new Properties();
pro.load(cl.getResourceAsStream(CONF_DIR));
} catch (Exception e) {
LogUtil.exception(logger, e);
}
return pro.getProperty(name);
}
}
| apache-2.0 |
playframework/playframework | core/play-java/src/test/java/play/mvc/HttpTest.java | 10346 | /*
* Copyright (C) Lightbend Inc. <https://www.lightbend.com>
*/
package play.mvc;
import java.util.Optional;
import java.util.function.Consumer;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.junit.Test;
import play.Application;
import play.Environment;
import play.i18n.Lang;
import play.i18n.MessagesApi;
import play.inject.guice.GuiceApplicationBuilder;
import play.mvc.Http.Cookie;
import play.mvc.Http.Request;
import play.mvc.Http.RequestBuilder;
import static org.fest.assertions.Assertions.assertThat;
import static play.mvc.Http.HeaderNames.ACCEPT_LANGUAGE;
/**
* Tests for the Http class. This test is in the play-java project because we want to use some of
* the play-java classes, e.g. the GuiceApplicationBuilder.
*/
public class HttpTest {
/** Gets the PLAY_LANG cookie, or the last one if there is more than one */
private String resultLangCookie(Result result, MessagesApi messagesApi) {
String value = null;
for (Cookie c : result.cookies()) {
if (c.name().equals(messagesApi.langCookieName())) {
value = c.value();
}
}
return value;
}
private MessagesApi messagesApi(Application app) {
return app.injector().instanceOf(MessagesApi.class);
}
private static Config addLangs(Environment environment) {
Config langOverrides =
ConfigFactory.parseString("play.i18n.langs = [\"en\", \"en-US\", \"fr\" ]");
Config loaded = ConfigFactory.load(environment.classLoader());
return langOverrides.withFallback(loaded);
}
private static void withApplication(Consumer<Application> r) {
Application app = new GuiceApplicationBuilder().withConfigLoader(HttpTest::addLangs).build();
play.api.Play.start(app.asScala());
try {
r.accept(app);
} finally {
play.api.Play.stop(app.asScala());
}
}
@Test
public void testChangeLang() {
withApplication(
(app) -> {
// Start off as 'en' with no cookie set
Request req = new RequestBuilder().build();
Result result = Results.ok();
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en");
assertThat(resultLangCookie(result, messagesApi(app))).isNull();
// Change the language to 'en-US'
Lang lang = Lang.forCode("en-US");
req = new RequestBuilder().langCookie(lang, messagesApi(app)).build();
result = result.withLang(lang, messagesApi(app));
// The language and cookie should now be 'en-US'
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US");
assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("en-US");
// The Messages instance uses the language which is set now into account
assertThat(messagesApi(app).preferred(req).at("hello")).isEqualTo("Aloha");
});
}
@Test
public void testMessagesOrder() {
withApplication(
(app) -> {
RequestBuilder rb = new RequestBuilder().header(ACCEPT_LANGUAGE, "en-US");
Request req = rb.build();
// if no cookie is provided the lang order will have the accept language as the default
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US");
Lang fr = Lang.forCode("fr");
rb = new RequestBuilder().langCookie(fr, messagesApi(app)).header(ACCEPT_LANGUAGE, "en");
req = rb.build();
// if no transient lang is provided the language order will be cookie > accept language
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr");
// if a transient lang is set the order will be transient lang > cookie > accept language
req = rb.build().withTransientLang(Lang.forCode("en-US"));
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US");
});
}
@Test
public void testChangeLangFailure() {
withApplication(
(app) -> {
// Start off as 'en' with no cookie set
Request req = new RequestBuilder().build();
Result result = Results.ok();
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en");
assertThat(resultLangCookie(result, messagesApi(app))).isNull();
Lang lang = Lang.forCode("en-NZ");
req = new RequestBuilder().langCookie(lang, messagesApi(app)).build();
result = result.withLang(lang, messagesApi(app));
// Try to change the language to 'en-NZ' - which fails, the language should still be 'en'
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en");
// The cookie however will get set
assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("en-NZ");
});
}
@Test
public void testClearLang() {
withApplication(
(app) -> {
// Set 'fr' as our initial language
Lang lang = Lang.forCode("fr");
Request req = new RequestBuilder().langCookie(lang, messagesApi(app)).build();
Result result = Results.ok().withLang(lang, messagesApi(app));
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr");
assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("fr");
// Clear language
result = result.withoutLang(messagesApi(app));
// The cookie should be cleared
assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("");
// However the request is not effected by changing the result
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr");
});
}
@Test
public void testSetTransientLang() {
withApplication(
(app) -> {
Request req = new RequestBuilder().build();
Result result = Results.ok();
// Start off as 'en' with no cookie set
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en");
assertThat(resultLangCookie(result, messagesApi(app))).isNull();
// Change the language to 'en-US'
req = req.withTransientLang(Lang.forCode("en-US"));
// The language should now be 'en-US', but the cookie mustn't be set
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US");
assertThat(resultLangCookie(result, messagesApi(app))).isNull();
// The Messages instance uses the language which is set now into account
assertThat(messagesApi(app).preferred(req).at("hello")).isEqualTo("Aloha");
});
}
public void testSetTransientLangFailure() {
withApplication(
(app) -> {
Request req = new RequestBuilder().build();
Result result = Results.ok();
// Start off as 'en' with no cookie set
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en");
assertThat(resultLangCookie(result, messagesApi(app))).isNull();
// Try to change the language to 'en-NZ'
req = req.withTransientLang(Lang.forCode("en-NZ"));
// When trying to get the messages it does not work because en-NZ is not valid
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en");
// However if you access the transient lang directly you will see it was set
assertThat(req.transientLang().map(l -> l.code())).isEqualTo(Optional.of("en-NZ"));
});
}
@Test
public void testClearTransientLang() {
withApplication(
(app) -> {
Lang lang = Lang.forCode("fr");
RequestBuilder rb = new RequestBuilder().langCookie(lang, messagesApi(app));
Result result = Results.ok().withLang(lang, messagesApi(app));
// Start off as 'fr' with cookie set
Request req = rb.build();
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr");
assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("fr");
// Change the language to 'en-US'
lang = Lang.forCode("en-US");
req = req.withTransientLang(lang);
result = result.withLang(lang, messagesApi(app));
// The language should now be 'en-US' and the cookie must be set again
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("en-US");
assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("en-US");
// Clear the language to the default for the current request and result
req = req.withoutTransientLang();
result = result.withoutLang(messagesApi(app));
// The language should now be back to 'fr', and the cookie must be cleared
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr");
assertThat(resultLangCookie(result, messagesApi(app))).isEqualTo("");
});
}
@Test
public void testRequestImplLang() {
withApplication(
(app) -> {
RequestBuilder rb = new RequestBuilder();
Request req = rb.build();
// Lets change the lang to something that is not the default
req = req.withTransientLang(Lang.forCode("fr"));
// Make sure the request did set that lang correctly
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr");
// Now let's copy the request
Request newReq = new Http.RequestImpl(req.asScala());
// Make sure the new request correctly set its internal lang variable
assertThat(messagesApi(app).preferred(newReq).lang().code()).isEqualTo("fr");
// Now change the lang on the new request to something not default
newReq = newReq.withTransientLang(Lang.forCode("en-US"));
// Make sure the new request correctly set its internal lang variable
assertThat(messagesApi(app).preferred(newReq).lang().code()).isEqualTo("en-US");
assertThat(newReq.transientLang().map(l -> l.code())).isEqualTo(Optional.of("en-US"));
// Also make sure the original request didn't change it's language
assertThat(messagesApi(app).preferred(req).lang().code()).isEqualTo("fr");
assertThat(req.transientLang().map(l -> l.code())).isEqualTo(Optional.of("fr"));
});
}
}
| apache-2.0 |
apache/drill | exec/java-exec/src/main/java/org/apache/drill/exec/store/dfs/easy/EvfV1ScanBuilder.java | 5918 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store.dfs.easy;
import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.common.logical.FormatPluginConfig;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.physical.impl.scan.file.FileScanFramework.FileReaderFactory;
import org.apache.drill.exec.physical.impl.scan.file.FileScanFramework.FileScanBuilder;
import org.apache.drill.exec.physical.impl.scan.file.FileScanFramework.FileSchemaNegotiator;
import org.apache.drill.exec.physical.impl.scan.framework.ManagedReader;
import org.apache.drill.exec.record.CloseableRecordBatch;
import org.apache.drill.exec.server.options.OptionManager;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Create the plugin-specific framework that manages the scan. The framework
* creates batch readers one by one for each file or block. It defines semantic
* rules for projection. It handles "early" or "late" schema readers. A typical
* framework builds on standardized frameworks for files in general or text
* files in particular.
* <p>
* This is for "version 1" of EVF. Newer code should use "version 2."
*
* @return the scan framework which orchestrates the scan operation across
* potentially many files
* @throws ExecutionSetupException for all setup failures
*/
class EvfV1ScanBuilder {
private static final Logger logger = LoggerFactory.getLogger(EvfV1ScanBuilder.class);
/**
* Builds the readers for the V1 row-set based scan operator.
*/
private static class EasyReaderFactory extends FileReaderFactory {
private final EasyFormatPlugin<? extends FormatPluginConfig> plugin;
private final EasySubScan scan;
private final FragmentContext context;
public EasyReaderFactory(EasyFormatPlugin<? extends FormatPluginConfig> plugin,
EasySubScan scan, FragmentContext context) {
this.plugin = plugin;
this.scan = scan;
this.context = context;
}
@Override
public ManagedReader<? extends FileSchemaNegotiator> newReader() {
try {
return plugin.newBatchReader(scan, context.getOptions());
} catch (ExecutionSetupException e) {
throw UserException.validationError(e)
.addContext("Reason", "Failed to create a batch reader")
.addContext(errorContext())
.build(logger);
}
}
}
private final FragmentContext context;
private final EasySubScan scan;
private final EasyFormatPlugin<? extends FormatPluginConfig> plugin;
public EvfV1ScanBuilder(FragmentContext context, EasySubScan scan,
EasyFormatPlugin<? extends FormatPluginConfig> plugin) {
this.context = context;
this.scan = scan;
this.plugin = plugin;
}
/**
* Revised scanner based on the revised {@link org.apache.drill.exec.physical.resultSet.ResultSetLoader}
* and {@link org.apache.drill.exec.physical.impl.scan.RowBatchReader} classes.
* Handles most projection tasks automatically. Able to limit
* vector and batch sizes. Use this for new format plugins.
*/
public CloseableRecordBatch build() throws ExecutionSetupException {
final FileScanBuilder builder = plugin.frameworkBuilder(context.getOptions(), scan);
// Add batch reader, if none specified
if (builder.readerFactory() == null) {
builder.setReaderFactory(new EasyReaderFactory(plugin, scan, context));
}
return builder.buildScanOperator(context, scan);
}
/**
* Initialize the scan framework builder with standard options.
* Call this from the plugin-specific
* {@link #frameworkBuilder(OptionManager, EasySubScan)} method.
* The plugin can then customize/revise options as needed.
*
* @param builder the scan framework builder you create in the
* {@link #frameworkBuilder(OptionManager, EasySubScan)} method
* @param scan the physical scan operator definition passed to
* the {@link #frameworkBuilder(OptionManager, EasySubScan)} method
*/
protected static void initScanBuilder(EasyFormatPlugin<? extends FormatPluginConfig> plugin,
FileScanBuilder builder, EasySubScan scan) {
builder.projection(scan.getColumns());
builder.setUserName(scan.getUserName());
// Pass along the output schema, if any
builder.providedSchema(scan.getSchema());
// Pass along file path information
builder.setFileSystemConfig(plugin.getFsConf());
builder.setFiles(scan.getWorkUnits());
final Path selectionRoot = scan.getSelectionRoot();
if (selectionRoot != null) {
builder.implicitColumnOptions().setSelectionRoot(selectionRoot);
builder.implicitColumnOptions().setPartitionDepth(scan.getPartitionDepth());
}
// Additional error context to identify this plugin
builder.errorContext(
currentBuilder -> currentBuilder
.addContext("Format plugin", plugin.easyConfig().getDefaultName())
.addContext("Format plugin", plugin.getClass().getSimpleName())
.addContext("Plugin config name", plugin.getName()));
}
}
| apache-2.0 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/filter/SetActiveListFilter.java | 1272 | /**
*
* Copyright 2015-2021 Florian Schmaus
*
* 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.jivesoftware.smackx.privacy.filter;
import org.jivesoftware.smack.filter.FlexibleStanzaTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smackx.privacy.packet.Privacy;
public final class SetActiveListFilter extends FlexibleStanzaTypeFilter<Privacy> {
public static final SetActiveListFilter INSTANCE = new SetActiveListFilter();
private SetActiveListFilter() {
}
@Override
protected boolean acceptSpecific(Privacy privacy) {
if (privacy.getType() != IQ.Type.set) {
return false;
}
return privacy.getActiveName() != null || privacy.isDeclineActiveList();
}
}
| apache-2.0 |
Netflix/governator | governator-core/src/main/java/com/netflix/governator/internal/scanner/ClasspathUrlDecoder.java | 1996 | package com.netflix.governator.internal.scanner;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URL;
public class ClasspathUrlDecoder {
public static File toFile(URL url)
{
if ( !"file".equals(url.getProtocol()) && !"vfs".equals(url.getProtocol()) )
{
throw new IllegalArgumentException("not a file or vfs url: " + url);
}
String path = url.getFile();
File dir = new File(decode(path));
if (dir.getName().equals("META-INF")) {
dir = dir.getParentFile(); // Scrape "META-INF" off
}
return dir;
}
public static String decode(String fileName)
{
if ( fileName.indexOf('%') == -1 )
{
return fileName;
}
StringBuilder result = new StringBuilder(fileName.length());
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < fileName.length();) {
char c = fileName.charAt(i);
if (c == '%') {
out.reset();
do {
if (i + 2 >= fileName.length()) {
throw new IllegalArgumentException("Incomplete % sequence at: " + i);
}
int d1 = Character.digit(fileName.charAt(i + 1), 16);
int d2 = Character.digit(fileName.charAt(i + 2), 16);
if (d1 == -1 || d2 == -1) {
throw new IllegalArgumentException("Invalid % sequence (" + fileName.substring(i, i + 3) + ") at: " + String.valueOf(i));
}
out.write((byte) ((d1 << 4) + d2));
i += 3;
} while (i < fileName.length() && fileName.charAt(i) == '%');
result.append(out.toString());
continue;
} else {
result.append(c);
}
i++;
}
return result.toString();
}
}
| apache-2.0 |
mike-jumper/incubator-guacamole-client | guacamole/src/main/java/org/apache/guacamole/rest/history/APISortPredicate.java | 4823 | /*
* 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.guacamole.rest.history;
import javax.ws.rs.core.Response;
import org.apache.guacamole.GuacamoleClientException;
import org.apache.guacamole.net.auth.ActivityRecordSet;
import org.apache.guacamole.rest.APIException;
/**
* A sort predicate which species the property to use when sorting activity
* records, along with the sort order.
*/
public class APISortPredicate {
/**
* The prefix which will be included before the name of a sortable property
* to indicate that the sort order is descending, not ascending.
*/
public static final String DESCENDING_PREFIX = "-";
/**
* All possible property name strings and their corresponding
* ActivityRecordSet.SortableProperty values.
*/
public enum SortableProperty {
/**
* The date that the activity associated with the activity record
* began.
*/
startDate(ActivityRecordSet.SortableProperty.START_DATE);
/**
* The ActivityRecordSet.SortableProperty that this property name
* string represents.
*/
public final ActivityRecordSet.SortableProperty recordProperty;
/**
* Creates a new SortableProperty which associates the property name
* string (identical to its own name) with the given
* ActivityRecordSet.SortableProperty value.
*
* @param recordProperty
* The ActivityRecordSet.SortableProperty value to associate with
* the new SortableProperty.
*/
SortableProperty(ActivityRecordSet.SortableProperty recordProperty) {
this.recordProperty = recordProperty;
}
}
/**
* The property to use when sorting ActivityRecords.
*/
private ActivityRecordSet.SortableProperty property;
/**
* Whether the requested sort order is descending (true) or ascending
* (false).
*/
private boolean descending;
/**
* Parses the given string value, determining the requested sort property
* and ordering. Possible values consist of any valid property name, and
* may include an optional prefix to denote descending sort order. Each
* possible property name is enumerated by the SortableValue enum.
*
* @param value
* The sort predicate string to parse, which must consist ONLY of a
* valid property name, possibly preceded by the DESCENDING_PREFIX.
*
* @throws APIException
* If the provided sort predicate string is invalid.
*/
public APISortPredicate(String value)
throws APIException {
// Parse whether sort order is descending
if (value.startsWith(DESCENDING_PREFIX)) {
descending = true;
value = value.substring(DESCENDING_PREFIX.length());
}
// Parse sorting property into ActivityRecordSet.SortableProperty
try {
this.property = SortableProperty.valueOf(value).recordProperty;
}
// Bail out if sort property is not valid
catch (IllegalArgumentException e) {
throw new APIException(
Response.Status.BAD_REQUEST,
new GuacamoleClientException(String.format("Invalid sort property: \"%s\"", value))
);
}
}
/**
* Returns the SortableProperty defined by ActivityRecordSet which
* represents the property requested.
*
* @return
* The ActivityRecordSet.SortableProperty which refers to the same
* property as the string originally provided when this
* APISortPredicate was created.
*/
public ActivityRecordSet.SortableProperty getProperty() {
return property;
}
/**
* Returns whether the requested sort order is descending.
*
* @return
* true if the sort order is descending, false if the sort order is
* ascending.
*/
public boolean isDescending() {
return descending;
}
}
| apache-2.0 |
lucastheisen/apache-directory-server | core-api/src/main/java/org/apache/directory/server/core/api/changelog/RevisionOrder.java | 1412 | /*
* 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.directory.server.core.api.changelog;
/**
* The order, based on revision numbers, in which to return log changes or
* tags.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public enum RevisionOrder
{
AscendingOrder(true),
DescendingOrder(false);
private final boolean ascending;
private RevisionOrder( boolean ascending )
{
this.ascending = ascending;
}
/**
* @return the ascending
*/
public boolean isAscending()
{
return ascending;
}
}
| apache-2.0 |
neo4art/neo4art | neo4art-mobile/src/main/app/plugins/plugin.google.maps/src/android/plugin/google/maps/GoogleMaps.java | 73351 | package plugin.google.maps;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import android.view.*;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginEntry;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import plugin.http.request.HttpRequest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Typeface;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnIndoorStateChangeListener;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLoadedCallback;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.CameraPosition.Builder;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.IndoorBuilding;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.VisibleRegion;
@SuppressWarnings("deprecation")
public class GoogleMaps extends CordovaPlugin implements View.OnClickListener, OnMarkerClickListener,
OnInfoWindowClickListener, OnMapClickListener, OnMapLongClickListener,
OnCameraChangeListener, OnMapLoadedCallback, OnMarkerDragListener,
OnMyLocationButtonClickListener, OnIndoorStateChangeListener, InfoWindowAdapter {
private final String TAG = "GoogleMapsPlugin";
private final HashMap<String, PluginEntry> plugins = new HashMap<String, PluginEntry>();
private float density;
private HashMap<String, Bundle> bufferForLocationDialog = new HashMap<String, Bundle>();
private enum EVENTS {
onScrollChanged
}
private enum TEXT_STYLE_ALIGNMENTS {
left, center, right
}
private final int ACTIVITY_LOCATION_DIALOG = 0x7f999900; // Invite the location dialog using Google Play Services
private final int ACTIVITY_LOCATION_PAGE = 0x7f999901; // Open the location settings page
private JSONObject mapDivLayoutJSON = null;
private MapView mapView = null;
public GoogleMap map = null;
private Activity activity;
private LinearLayout windowLayer = null;
private ViewGroup root;
private final int CLOSE_LINK_ID = 0x7f999990; //random
private final int LICENSE_LINK_ID = 0x7f99991; //random
private final String PLUGIN_VERSION = "1.2.5";
private MyPluginLayout mPluginLayout = null;
public boolean isDebug = false;
private GoogleApiClient googleApiClient = null;
@SuppressLint("NewApi") @Override
public void initialize(final CordovaInterface cordova, final CordovaWebView webView) {
super.initialize(cordova, webView);
activity = cordova.getActivity();
density = Resources.getSystem().getDisplayMetrics().density;
final View view = webView.getView();
root = (ViewGroup) view.getParent();
// Is this release build version?
boolean isRelease = false;
try {
PackageManager manager = activity.getPackageManager();
ApplicationInfo appInfo = manager.getApplicationInfo(activity.getPackageName(), 0);
isRelease = !((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE);
} catch (Exception e) {}
Log.i("CordovaLog", "This app uses phonegap-googlemaps-plugin version " + PLUGIN_VERSION);
if (!isRelease) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
JSONArray params = new JSONArray();
params.put("get");
params.put("http://plugins.cordova.io/api/plugin.google.maps");
HttpRequest httpReq = new HttpRequest();
httpReq.initialize(cordova, null);
httpReq.execute("execute", params, new CallbackContext("version_check", webView) {
@Override
public void sendPluginResult(PluginResult pluginResult) {
if (pluginResult.getStatus() == PluginResult.Status.OK.ordinal()) {
try {
JSONObject result = new JSONObject(pluginResult.getStrMessage());
JSONObject distTags = result.getJSONObject("dist-tags");
String latestVersion = distTags.getString("latest");
if (latestVersion.equals(PLUGIN_VERSION) == false) {
Log.i("CordovaLog", "phonegap-googlemaps-plugin version " + latestVersion + " is available.");
}
} catch (JSONException e) {}
}
}
});
} catch (Exception e) {}
}
});
}
cordova.getActivity().runOnUiThread(new Runnable() {
@SuppressLint("NewApi")
public void run() {
/*
try {
Method method = webView.getClass().getMethod("getSettings");
WebSettings settings = (WebSettings)method.invoke(null);
settings.setRenderPriority(RenderPriority.HIGH);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
} catch (Exception e) {
e.printStackTrace();
}
*/
if (Build.VERSION.SDK_INT >= 11){
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
root.setBackgroundColor(Color.WHITE);
if (VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
if (VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
Log.d(TAG, "Google Maps Plugin reloads the browser to change the background color as transparent.");
view.setBackgroundColor(0);
try {
Method method = webView.getClass().getMethod("reload");
method.invoke(webView);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (isDebug) {
if (args != null && args.length() > 0) {
Log.d(TAG, "(debug)action=" + action + " args[0]=" + args.getString(0));
} else {
Log.d(TAG, "(debug)action=" + action);
}
}
Runnable runnable = new Runnable() {
public void run() {
if (("getMap".equals(action) == false && "isAvailable".equals(action) == false && "getLicenseInfo".equals(action) == false) &&
GoogleMaps.this.map == null) {
Log.w(TAG, "Can not execute '" + action + "' because the map is not created.");
return;
}
if ("exec".equals(action)) {
try {
String classMethod = args.getString(0);
String[] params = classMethod.split("\\.", 0);
if ("Map.setOptions".equals(classMethod)) {
JSONObject jsonParams = args.getJSONObject(1);
if (jsonParams.has("backgroundColor")) {
JSONArray rgba = jsonParams.getJSONArray("backgroundColor");
int backgroundColor = Color.WHITE;
if (rgba != null && rgba.length() == 4) {
try {
backgroundColor = PluginUtil.parsePluginColor(rgba);
mPluginLayout.setBackgroundColor(backgroundColor);
} catch (JSONException e) {}
}
}
}
// Load the class plugin
GoogleMaps.this.loadPlugin(params[0]);
PluginEntry entry = GoogleMaps.this.plugins.get(params[0]);
if (params.length == 2 && entry != null) {
entry.plugin.execute("execute", args, callbackContext);
} else {
callbackContext.error("'" + action + "' parameter is invalid length.");
}
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("Java Error\n" + e.getCause().getMessage());
}
} else {
try {
Method method = GoogleMaps.this.getClass().getDeclaredMethod(action, JSONArray.class, CallbackContext.class);
if (method.isAccessible() == false) {
method.setAccessible(true);
}
method.invoke(GoogleMaps.this, args, callbackContext);
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("'" + action + "' is not defined in GoogleMaps plugin.");
}
}
}
};
cordova.getActivity().runOnUiThread(runnable);
return true;
}
@SuppressWarnings("unused")
private void setDiv(JSONArray args, CallbackContext callbackContext) throws JSONException {
if (args.length() == 0) {
this.mapDivLayoutJSON = null;
mPluginLayout.detachMyView();
this.sendNoResult(callbackContext);
return;
}
if (args.length() == 2) {
mPluginLayout.attachMyView(mapView);
this.resizeMap(args, callbackContext);
}
}
/**
* Set visibility of the map
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean visible = args.getBoolean(0);
if (this.windowLayer == null) {
if (visible) {
mapView.setVisibility(View.VISIBLE);
} else {
mapView.setVisibility(View.INVISIBLE);
}
}
this.sendNoResult(callbackContext);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void getMap(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (map != null) {
callbackContext.success();
return;
}
mPluginLayout = new MyPluginLayout(webView.getView(), activity);
// ------------------------------
// Check of Google Play Services
// ------------------------------
int checkGooglePlayServices = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(activity);
if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
// google play services is missing!!!!
/*
* Returns status code indicating whether there was an error. Can be one
* of following in ConnectionResult: SUCCESS, SERVICE_MISSING,
* SERVICE_VERSION_UPDATE_REQUIRED, SERVICE_DISABLED, SERVICE_INVALID.
*/
Log.e("CordovaLog", "---Google Play Services is not available: " + GooglePlayServicesUtil.getErrorString(checkGooglePlayServices));
Dialog errorDialog = null;
try {
//errorDialog = GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices, activity, 1);
Method getErrorDialogMethod = GooglePlayServicesUtil.class.getMethod("getErrorDialog", int.class, Activity.class, int.class);
errorDialog = (Dialog)getErrorDialogMethod.invoke(null, checkGooglePlayServices, activity, 1);
} catch (Exception e) {};
if (errorDialog != null) {
errorDialog.show();
} else {
boolean isNeedToUpdate = false;
String errorMsg = "Google Maps Android API v2 is not available for some reason on this device. Do you install the latest Google Play Services from Google Play Store?";
switch (checkGooglePlayServices) {
case ConnectionResult.DEVELOPER_ERROR:
errorMsg = "The application is misconfigured. This error is not recoverable and will be treated as fatal. The developer should look at the logs after this to determine more actionable information.";
break;
case ConnectionResult.INTERNAL_ERROR:
errorMsg = "An internal error of Google Play Services occurred. Please retry, and it should resolve the problem.";
break;
case ConnectionResult.INVALID_ACCOUNT:
errorMsg = "You attempted to connect to the service with an invalid account name specified.";
break;
case ConnectionResult.LICENSE_CHECK_FAILED:
errorMsg = "The application is not licensed to the user. This error is not recoverable and will be treated as fatal.";
break;
case ConnectionResult.NETWORK_ERROR:
errorMsg = "A network error occurred. Please retry, and it should resolve the problem.";
break;
case ConnectionResult.SERVICE_DISABLED:
errorMsg = "The installed version of Google Play services has been disabled on this device. Please turn on Google Play Services.";
break;
case ConnectionResult.SERVICE_INVALID:
errorMsg = "The version of the Google Play services installed on this device is not authentic. Please update the Google Play Services from Google Play Store.";
isNeedToUpdate = true;
break;
case ConnectionResult.SERVICE_MISSING:
errorMsg = "Google Play services is missing on this device. Please install the Google Play Services.";
isNeedToUpdate = true;
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
errorMsg = "The installed version of Google Play services is out of date. Please update the Google Play Services from Google Play Store.";
isNeedToUpdate = true;
break;
case ConnectionResult.SIGN_IN_REQUIRED:
errorMsg = "You attempted to connect to the service but you are not signed in. Please check the Google Play Services configuration";
break;
default:
isNeedToUpdate = true;
break;
}
final boolean finalIsNeedToUpdate = isNeedToUpdate;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder
.setMessage(errorMsg)
.setCancelable(false)
.setPositiveButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.dismiss();
if (finalIsNeedToUpdate) {
try {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.gms")));
} catch (android.content.ActivityNotFoundException anfe) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=appPackageName")));
}
}
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
callbackContext.error("Google Play Services is not available.");
return;
}
// Check the API key
ApplicationInfo appliInfo = null;
try {
appliInfo = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA);
} catch (NameNotFoundException e) {}
String API_KEY = appliInfo.metaData.getString("com.google.android.maps.v2.API_KEY");
if ("API_KEY_FOR_ANDROID".equals(API_KEY)) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder
.setMessage("Please replace 'API_KEY_FOR_ANDROID' in the platforms/android/AndroidManifest.xml with your API Key!")
.setCancelable(false)
.setPositiveButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// ------------------------------
// Initialize Google Maps SDK
// ------------------------------
try {
MapsInitializer.initialize(activity);
} catch (Exception e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
return;
}
GoogleMapOptions options = new GoogleMapOptions();
final JSONObject params = args.getJSONObject(0);
//background color
if (params.has("backgroundColor")) {
JSONArray rgba = params.getJSONArray("backgroundColor");
int backgroundColor = Color.WHITE;
if (rgba != null && rgba.length() == 4) {
try {
backgroundColor = PluginUtil.parsePluginColor(rgba);
this.mPluginLayout.setBackgroundColor(backgroundColor);
} catch (JSONException e) {}
}
}
//controls
if (params.has("controls")) {
JSONObject controls = params.getJSONObject("controls");
if (controls.has("compass")) {
options.compassEnabled(controls.getBoolean("compass"));
}
if (controls.has("zoom")) {
options.zoomControlsEnabled(controls.getBoolean("zoom"));
}
}
//gestures
if (params.has("gestures")) {
JSONObject gestures = params.getJSONObject("gestures");
if (gestures.has("tilt")) {
options.tiltGesturesEnabled(gestures.getBoolean("tilt"));
}
if (gestures.has("scroll")) {
options.scrollGesturesEnabled(gestures.getBoolean("scroll"));
}
if (gestures.has("rotate")) {
options.rotateGesturesEnabled(gestures.getBoolean("rotate"));
}
if (gestures.has("zoom")) {
options.zoomGesturesEnabled(gestures.getBoolean("zoom"));
}
}
// map type
if (params.has("mapType")) {
String typeStr = params.getString("mapType");
int mapTypeId = -1;
mapTypeId = typeStr.equals("MAP_TYPE_NORMAL") ? GoogleMap.MAP_TYPE_NORMAL
: mapTypeId;
mapTypeId = typeStr.equals("MAP_TYPE_HYBRID") ? GoogleMap.MAP_TYPE_HYBRID
: mapTypeId;
mapTypeId = typeStr.equals("MAP_TYPE_SATELLITE") ? GoogleMap.MAP_TYPE_SATELLITE
: mapTypeId;
mapTypeId = typeStr.equals("MAP_TYPE_TERRAIN") ? GoogleMap.MAP_TYPE_TERRAIN
: mapTypeId;
mapTypeId = typeStr.equals("MAP_TYPE_NONE") ? GoogleMap.MAP_TYPE_NONE
: mapTypeId;
if (mapTypeId != -1) {
options.mapType(mapTypeId);
}
}
// initial camera position
if (params.has("camera")) {
JSONObject camera = params.getJSONObject("camera");
Builder builder = CameraPosition.builder();
if (camera.has("bearing")) {
builder.bearing((float) camera.getDouble("bearing"));
}
if (camera.has("latLng")) {
JSONObject latLng = camera.getJSONObject("latLng");
builder.target(new LatLng(latLng.getDouble("lat"), latLng.getDouble("lng")));
}
if (camera.has("tilt")) {
builder.tilt((float) camera.getDouble("tilt"));
}
if (camera.has("zoom")) {
builder.zoom((float) camera.getDouble("zoom"));
}
options.camera(builder.build());
}
mapView = new MapView(activity, options);
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
try {
//controls
if (params.has("controls")) {
JSONObject controls = params.getJSONObject("controls");
if (controls.has("myLocationButton")) {
Boolean isEnabled = controls.getBoolean("myLocationButton");
map.setMyLocationEnabled(isEnabled);
map.getUiSettings().setMyLocationButtonEnabled(isEnabled);
}
if (controls.has("indoorPicker")) {
Boolean isEnabled = controls.getBoolean("indoorPicker");
map.setIndoorEnabled(isEnabled);
}
}
// Set event listener
map.setOnCameraChangeListener(GoogleMaps.this);
map.setOnInfoWindowClickListener(GoogleMaps.this);
map.setOnMapClickListener(GoogleMaps.this);
map.setOnMapLoadedCallback(GoogleMaps.this);
map.setOnMapLongClickListener(GoogleMaps.this);
map.setOnMarkerClickListener(GoogleMaps.this);
map.setOnMarkerDragListener(GoogleMaps.this);
map.setOnMyLocationButtonClickListener(GoogleMaps.this);
map.setOnIndoorStateChangeListener(GoogleMaps.this);
// Load PluginMap class
GoogleMaps.this.loadPlugin("Map");
//Custom info window
map.setInfoWindowAdapter(GoogleMaps.this);
// ------------------------------
// Embed the map if a container is specified.
// ------------------------------
if (args.length() == 3) {
GoogleMaps.this.mapDivLayoutJSON = args.getJSONObject(1);
mPluginLayout.attachMyView(mapView);
GoogleMaps.this.resizeMap(args, callbackContext);
}
callbackContext.success();
} catch (Exception e) {
Log.d("GoogleMaps", "------->error");
callbackContext.error(e.getMessage());
}
}
});
}
private float contentToView(long d) {
return d * this.density;
}
//-----------------------------------
// Create the instance of class
//-----------------------------------
@SuppressWarnings("rawtypes")
private void loadPlugin(String serviceName) {
if (plugins.containsKey(serviceName)) {
return;
}
try {
String className = "plugin.google.maps.Plugin" + serviceName;
Class pluginCls = Class.forName(className);
CordovaPlugin plugin = (CordovaPlugin) pluginCls.newInstance();
PluginEntry pluginEntry = new PluginEntry("GoogleMaps", plugin);
this.plugins.put(serviceName, pluginEntry);
plugin.privateInitialize(className, this.cordova, webView, null);
plugin.initialize(this.cordova, webView);
((MyPluginInterface)plugin).setMapCtrl(this);
if (map == null) {
Log.e(TAG, "map is null!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unused")
private Boolean getLicenseInfo(JSONArray args, CallbackContext callbackContext) {
String msg = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(activity);
callbackContext.success(msg);
return true;
}
private void closeWindow() {
try {
Method method = webView.getClass().getMethod("hideCustomView");
method.invoke(webView);
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unused")
private void showDialog(final JSONArray args, final CallbackContext callbackContext) {
if (windowLayer != null) {
return;
}
// window layout
windowLayer = new LinearLayout(activity);
windowLayer.setPadding(0, 0, 0, 0);
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
windowLayer.setLayoutParams(layoutParams);
// dialog window layer
FrameLayout dialogLayer = new FrameLayout(activity);
dialogLayer.setLayoutParams(layoutParams);
//dialogLayer.setPadding(15, 15, 15, 0);
dialogLayer.setBackgroundColor(Color.LTGRAY);
windowLayer.addView(dialogLayer);
// map frame
final FrameLayout mapFrame = new FrameLayout(activity);
mapFrame.setPadding(0, 0, 0, (int)(40 * density));
dialogLayer.addView(mapFrame);
if (this.mPluginLayout != null &&
this.mPluginLayout.getMyView() != null) {
this.mPluginLayout.detachMyView();
}
ViewGroup.LayoutParams lParams = (ViewGroup.LayoutParams) mapView.getLayoutParams();
if (lParams == null) {
lParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
lParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
lParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
if (lParams instanceof AbsoluteLayout.LayoutParams) {
AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams) lParams;
params.x = 0;
params.y = 0;
mapView.setLayoutParams(params);
} else if (lParams instanceof LinearLayout.LayoutParams) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lParams;
params.topMargin = 0;
params.leftMargin = 0;
mapView.setLayoutParams(params);
} else if (lParams instanceof FrameLayout.LayoutParams) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) lParams;
params.topMargin = 0;
params.leftMargin = 0;
mapView.setLayoutParams(params);
}
mapFrame.addView(this.mapView);
// button frame
LinearLayout buttonFrame = new LinearLayout(activity);
buttonFrame.setOrientation(LinearLayout.HORIZONTAL);
buttonFrame.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM);
LinearLayout.LayoutParams buttonFrameParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
buttonFrame.setLayoutParams(buttonFrameParams);
dialogLayer.addView(buttonFrame);
//close button
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1.0f);
TextView closeLink = new TextView(activity);
closeLink.setText("Close");
closeLink.setLayoutParams(buttonParams);
closeLink.setTextColor(Color.BLUE);
closeLink.setTextSize(20);
closeLink.setGravity(Gravity.LEFT);
closeLink.setPadding((int)(10 * density), 0, 0, (int)(10 * density));
closeLink.setOnClickListener(GoogleMaps.this);
closeLink.setId(CLOSE_LINK_ID);
buttonFrame.addView(closeLink);
//license button
TextView licenseLink = new TextView(activity);
licenseLink.setText("Legal Notices");
licenseLink.setTextColor(Color.BLUE);
licenseLink.setLayoutParams(buttonParams);
licenseLink.setTextSize(20);
licenseLink.setGravity(Gravity.RIGHT);
licenseLink.setPadding((int)(10 * density), (int)(20 * density), (int)(10 * density), (int)(10 * density));
licenseLink.setOnClickListener(GoogleMaps.this);
licenseLink.setId(LICENSE_LINK_ID);
buttonFrame.addView(licenseLink);
webView.getView().setVisibility(View.GONE);
root.addView(windowLayer);
/**
* TODO: webView.showCustomView() has been deprecated in Cordova 4.0
* I need to catch the backbutton event
*/
WebChromeClient.CustomViewCallback customCallback = new WebChromeClient.CustomViewCallback() {
@Override
public void onCustomViewHidden() {
mapFrame.removeView(mapView);
if (mPluginLayout != null &&
mapDivLayoutJSON != null) {
mPluginLayout.attachMyView(mapView);
mPluginLayout.updateViewPosition();
}
root.removeView(windowLayer);
webView.getView().setVisibility(View.VISIBLE);
windowLayer = null;
GoogleMaps.this.onMapEvent("map_close");
}
};
//Dummy view for the back-button event
try {
Method method = webView.getClass().getDeclaredMethod("showCustomView", View.class, WebChromeClient.CustomViewCallback.class);
if (method != null) {
FrameLayout dummyLayout = new FrameLayout(activity);
method.invoke(webView, dummyLayout, customCallback);
}
} catch (Exception e) {
e.printStackTrace();
}
callbackContext.success();
}
private void resizeMap(JSONArray args, CallbackContext callbackContext) throws JSONException {
if (mPluginLayout == null) {
callbackContext.success();
return;
}
mapDivLayoutJSON = args.getJSONObject(args.length() - 2);
JSONArray HTMLs = args.getJSONArray(args.length() - 1);
JSONObject elemInfo, elemSize;
String elemId;
float divW, divH, divLeft, divTop;
if (mPluginLayout == null) {
this.sendNoResult(callbackContext);
return;
}
this.mPluginLayout.clearHTMLElement();
for (int i = 0; i < HTMLs.length(); i++) {
elemInfo = HTMLs.getJSONObject(i);
try {
elemId = elemInfo.getString("id");
elemSize = elemInfo.getJSONObject("size");
divW = contentToView(elemSize.getLong("width"));
divH = contentToView(elemSize.getLong("height"));
divLeft = contentToView(elemSize.getLong("left"));
divTop = contentToView(elemSize.getLong("top"));
mPluginLayout.putHTMLElement(elemId, divLeft, divTop, divLeft + divW, divTop + divH);
} catch (Exception e){
e.printStackTrace();
}
}
//mPluginLayout.inValidate();
updateMapViewLayout();
this.sendNoResult(callbackContext);
}
private void updateMapViewLayout() {
if (mPluginLayout == null) {
return;
}
try {
float divW = contentToView(mapDivLayoutJSON.getLong("width"));
float divH = contentToView(mapDivLayoutJSON.getLong("height"));
float divLeft = contentToView(mapDivLayoutJSON.getLong("left"));
float divTop = contentToView(mapDivLayoutJSON.getLong("top"));
// Update the plugin drawing view rect
mPluginLayout.setDrawingRect(
divLeft,
divTop - webView.getView().getScrollY(),
divLeft + divW,
divTop + divH - webView.getView().getScrollY());
mPluginLayout.updateViewPosition();
mapView.requestLayout();
} catch (JSONException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unused")
private void closeDialog(final JSONArray args, final CallbackContext callbackContext) {
this.closeWindow();
this.sendNoResult(callbackContext);
}
@SuppressWarnings("unused")
private void isAvailable(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
// ------------------------------
// Check of Google Play Services
// ------------------------------
int checkGooglePlayServices = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(activity);
if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
// google play services is missing!!!!
callbackContext.error("Google Maps Android API v2 is not available, because this device does not have Google Play Service.");
return;
}
// ------------------------------
// Check of Google Maps Android API v2
// ------------------------------
try {
@SuppressWarnings({ "rawtypes" })
Class GoogleMapsClass = Class.forName("com.google.android.gms.maps.GoogleMap");
} catch (Exception e) {
Log.e("GoogleMaps", "Error", e);
callbackContext.error(e.getMessage());
return;
}
callbackContext.success();
}
@SuppressWarnings("unused")
private void getFocusedBuilding(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
IndoorBuilding focusedBuilding = map.getFocusedBuilding();
if (focusedBuilding != null) {
JSONObject result = PluginUtil.convertIndoorBuildingToJson(focusedBuilding);
callbackContext.success(result);
} else {
callbackContext.success(-1);
}
}
@SuppressWarnings("unused")
private void getMyLocation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
// enableHighAccuracy = true -> PRIORITY_HIGH_ACCURACY
// enableHighAccuracy = false -> PRIORITY_BALANCED_POWER_ACCURACY
JSONObject params = args.getJSONObject(0);
boolean isHigh = false;
if (params.has("enableHighAccuracy")) {
isHigh = params.getBoolean("enableHighAccuracy");
}
final boolean enableHighAccuracy = isHigh;
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this.activity)
.addApi(LocationServices.API)
.addConnectionCallbacks(new com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle connectionHint) {
Log.e("CordovaLog", "===> onConnected");
GoogleMaps.this.sendNoResult(callbackContext);
_checkLocationSettings(enableHighAccuracy, callbackContext);
}
@Override
public void onConnectionSuspended(int cause) {
Log.e("CordovaLog", "===> onConnectionSuspended");
}
})
.addOnConnectionFailedListener(new com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.e("CordovaLog", "===> onConnectionFailed");
PluginResult tmpResult = new PluginResult(PluginResult.Status.ERROR, result.toString());
tmpResult.setKeepCallback(false);
callbackContext.sendPluginResult(tmpResult);
googleApiClient.disconnect();
}
})
.build();
googleApiClient.connect();
} else if (googleApiClient.isConnected()) {
_checkLocationSettings(enableHighAccuracy, callbackContext);
}
}
private void _checkLocationSettings(final boolean enableHighAccuracy, final CallbackContext callbackContext) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
LocationRequest locationRequest;
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
builder.addLocationRequest(locationRequest);
if (enableHighAccuracy) {
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
builder.addLocationRequest(locationRequest);
}
PendingResult<LocationSettingsResult> locationSettingsResult =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
locationSettingsResult.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
_requestLocationUpdate(false, enableHighAccuracy, callbackContext);
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
//Keep the callback id
Bundle bundle = new Bundle();
bundle.putInt("type", ACTIVITY_LOCATION_DIALOG);
bundle.putString("callbackId", callbackContext.getCallbackId());
bundle.putBoolean("enableHighAccuracy", enableHighAccuracy);
int hashCode = bundle.hashCode();
bufferForLocationDialog.put("bundle_" + hashCode, bundle);
GoogleMaps.this.sendNoResult(callbackContext);
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
cordova.setActivityResultCallback(GoogleMaps.this);
status.startResolutionForResult(cordova.getActivity(), hashCode);
} catch (SendIntentException e) {
// Show the dialog that is original version of this plugin.
_showLocationSettingsPage(enableHighAccuracy, callbackContext);
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
JSONObject jsResult = new JSONObject();
try {
jsResult.put("status", false);
jsResult.put("error_code", "service_not_available");
jsResult.put("error_message", "This app has been rejected to use Location Services.");
} catch (JSONException e) {}
callbackContext.error(jsResult);
break;
}
}
});
}
private void _showLocationSettingsPage(final boolean enableHighAccuracy, final CallbackContext callbackContext) {
//Ask the user to turn on the location services.
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.setTitle("Improve location accuracy");
builder.setMessage("To enhance your Maps experience:\n\n" +
" - Enable Google apps location access\n\n" +
" - Turn on GPS and mobile network location");
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Keep the callback id
Bundle bundle = new Bundle();
bundle.putInt("type", ACTIVITY_LOCATION_PAGE);
bundle.putString("callbackId", callbackContext.getCallbackId());
bundle.putBoolean("enableHighAccuracy", enableHighAccuracy);
int hashCode = bundle.hashCode();
bufferForLocationDialog.put("bundle_" + hashCode, bundle);
GoogleMaps.this.sendNoResult(callbackContext);
//Launch settings, allowing user to make a change
cordova.setActivityResultCallback(GoogleMaps.this);
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activity.startActivityForResult(intent, hashCode);
}
});
builder.setNegativeButton("Skip", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//No location service, no Activity
dialog.dismiss();
JSONObject result = new JSONObject();
try {
result.put("status", false);
result.put("error_code", "service_denied");
result.put("error_message", "This app has been rejected to use Location Services.");
} catch (JSONException e) {}
callbackContext.error(result);
}
});
builder.create().show();
return;
}
private void _requestLocationUpdate(final boolean isRetry, final boolean enableHighAccuracy, final CallbackContext callbackContext) {
int priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
if (enableHighAccuracy) {
priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
}
LocationRequest locationRequest= LocationRequest.create()
.setExpirationTime(5000)
.setNumUpdates(2)
.setSmallestDisplacement(0)
.setPriority(priority)
.setInterval(5000);
final PendingResult<Status> result = LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
/*
if (callbackContext.isFinished()) {
return;
}
*/
JSONObject result;
try {
result = PluginUtil.location2Json(location);
result.put("status", true);
callbackContext.success(result);
} catch (JSONException e) {}
googleApiClient.disconnect();
}
});
result.setResultCallback(new ResultCallback<Status>() {
public void onResult(Status status) {
if (!status.isSuccess()) {
String errorMsg = status.getStatusMessage();
PluginResult result = new PluginResult(PluginResult.Status.ERROR, errorMsg);
callbackContext.sendPluginResult(result);
} else {
// no update location
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
try {
JSONObject result = PluginUtil.location2Json(location);
result.put("status", true);
callbackContext.success(result);
} catch (JSONException e) {
e.printStackTrace();
}
return;
} else {
if (isRetry == false) {
Toast.makeText(activity, "Waiting for location...", Toast.LENGTH_SHORT).show();
GoogleMaps.this.sendNoResult(callbackContext);
// Retry
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
_requestLocationUpdate(true, enableHighAccuracy, callbackContext);
}
}, 3000);
} else {
// Send back the error result
JSONObject result = new JSONObject();
try {
result.put("status", false);
result.put("error_code", "cannot_detect");
result.put("error_message", "Can not detect your location. Try again.");
} catch (JSONException e) {}
callbackContext.error(result);
}
}
}
}
});
}
private void showLicenseText() {
AsyncLicenseInfo showLicense = new AsyncLicenseInfo(activity);
showLicense.execute();
}
/********************************************************
* Callbacks
********************************************************/
/**
* Notify marker event to JS
* @param eventName
* @param marker
*/
private void onMarkerEvent(String eventName, Marker marker) {
String markerId = "marker_" + marker.getId();
webView.loadUrl("javascript:plugin.google.maps.Map." +
"_onMarkerEvent('" + eventName + "','" + markerId + "')");
}
private void onOverlayEvent(String eventName, String overlayId, LatLng point) {
webView.loadUrl("javascript:plugin.google.maps.Map." +
"_onOverlayEvent(" +
"'" + eventName + "','" + overlayId + "', " +
"new window.plugin.google.maps.LatLng(" + point.latitude + "," + point.longitude + ")" +
")");
}
private void onPolylineClick(Polyline polyline, LatLng point) {
String overlayId = "polyline_" + polyline.getId();
this.onOverlayEvent("overlay_click", overlayId, point);
}
private void onPolygonClick(Polygon polygon, LatLng point) {
String overlayId = "polygon_" + polygon.getId();
this.onOverlayEvent("overlay_click", overlayId, point);
}
private void onCircleClick(Circle circle, LatLng point) {
String overlayId = "circle_" + circle.getId();
this.onOverlayEvent("overlay_click", overlayId, point);
}
private void onGroundOverlayClick(GroundOverlay groundOverlay, LatLng point) {
String overlayId = "groundOverlay_" + groundOverlay.getId();
this.onOverlayEvent("overlay_click", overlayId, point);
}
@Override
public boolean onMarkerClick(Marker marker) {
this.onMarkerEvent("click", marker);
JSONObject properties = null;
String propertyId = "marker_property_" + marker.getId();
PluginEntry pluginEntry = this.plugins.get("Marker");
PluginMarker pluginMarker = (PluginMarker)pluginEntry.plugin;
if (pluginMarker.objects.containsKey(propertyId)) {
properties = (JSONObject) pluginMarker.objects.get(propertyId);
if (properties.has("disableAutoPan")) {
boolean disableAutoPan = false;
try {
disableAutoPan = properties.getBoolean("disableAutoPan");
} catch (JSONException e) {}
if (disableAutoPan) {
//marker.showInfoWindow();
return true;
}
}
}
//marker.showInfoWindow();
return true;
//return false;
}
@Override
public void onInfoWindowClick(Marker marker) {
this.onMarkerEvent("info_click", marker);
}
@Override
public void onMarkerDrag(Marker marker) {
this.onMarkerEvent("drag", marker);
}
@Override
public void onMarkerDragEnd(Marker marker) {
this.onMarkerEvent("drag_end", marker);
}
@Override
public void onMarkerDragStart(Marker marker) {
this.onMarkerEvent("drag_start", marker);
}
/**
* Notify map event to JS
* @param eventName
* @param point
*/
private void onMapEvent(final String eventName) {
webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('" + eventName + "')");
}
/**
* Notify map event to JS
* @param eventName
* @param point
*/
private void onMapEvent(final String eventName, final LatLng point) {
webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent(" +
"'" + eventName + "', new window.plugin.google.maps.LatLng(" + point.latitude + "," + point.longitude + "))");
}
@Override
public void onMapLongClick(LatLng point) {
this.onMapEvent("long_click", point);
}
private double calculateDistance(LatLng pt1, LatLng pt2){
float[] results = new float[1];
Location.distanceBetween(pt1.latitude, pt1.longitude,
pt2.latitude, pt2.longitude, results);
return results[0];
}
/**
* Notify map click event to JS, also checks for click on a polygon and triggers onPolygonEvent
* @param point
*/
public void onMapClick(LatLng point) {
boolean hitPoly = false;
String key;
LatLngBounds bounds;
// Polyline
PluginEntry polylinePlugin = this.plugins.get("Polyline");
if(polylinePlugin != null) {
PluginPolyline polylineClass = (PluginPolyline) polylinePlugin.plugin;
List<LatLng> points ;
Polyline polyline;
Point origin = new Point();
Point hitArea = new Point();
hitArea.x = 1;
hitArea.y = 1;
Projection projection = map.getProjection();
double threshold = this.calculateDistance(
projection.fromScreenLocation(origin),
projection.fromScreenLocation(hitArea));
for (HashMap.Entry<String, Object> entry : polylineClass.objects.entrySet()) {
key = entry.getKey();
if (key.contains("polyline_bounds_")) {
bounds = (LatLngBounds) entry.getValue();
if (bounds.contains(point)) {
key = key.replace("bounds_", "");
polyline = polylineClass.getPolyline(key);
points = polyline.getPoints();
if (polyline.isGeodesic()) {
if (this.isPointOnTheGeodesicLine(points, point, threshold)) {
hitPoly = true;
this.onPolylineClick(polyline, point);
}
} else {
if (this.isPointOnTheLine(points, point)) {
hitPoly = true;
this.onPolylineClick(polyline, point);
}
}
}
}
}
if (hitPoly) {
return;
}
}
// Loop through all polygons to check if within the touch point
PluginEntry polygonPlugin = this.plugins.get("Polygon");
if (polygonPlugin != null) {
PluginPolygon polygonClass = (PluginPolygon) polygonPlugin.plugin;
for (HashMap.Entry<String, Object> entry : polygonClass.objects.entrySet()) {
key = entry.getKey();
if (key.contains("polygon_bounds_")) {
bounds = (LatLngBounds) entry.getValue();
if (bounds.contains(point)) {
key = key.replace("_bounds", "");
Polygon polygon = polygonClass.getPolygon(key);
if (this.isPolygonContains(polygon.getPoints(), point)) {
hitPoly = true;
this.onPolygonClick(polygon, point);
}
}
}
}
if (hitPoly) {
return;
}
}
// Loop through all circles to check if within the touch point
PluginEntry circlePlugin = this.plugins.get("Circle");
if (circlePlugin != null) {
PluginCircle circleClass = (PluginCircle) circlePlugin.plugin;
for (HashMap.Entry<String, Object> entry : circleClass.objects.entrySet()) {
Circle circle = (Circle) entry.getValue();
if (this.isCircleContains(circle, point)) {
hitPoly = true;
this.onCircleClick(circle, point);
}
}
if (hitPoly) {
return;
}
}
// Loop through ground overlays to check if within the touch point
PluginEntry groundOverlayPlugin = this.plugins.get("GroundOverlay");
if (groundOverlayPlugin != null) {
PluginGroundOverlay groundOverlayClass = (PluginGroundOverlay) groundOverlayPlugin.plugin;
for (HashMap.Entry<String, Object> entry : groundOverlayClass.objects.entrySet()) {
key = entry.getKey();
if (key.contains("groundOverlay_")) {
GroundOverlay groundOverlay = (GroundOverlay) entry.getValue();
if (this.isGroundOverlayContains(groundOverlay, point)) {
hitPoly = true;
this.onGroundOverlayClick(groundOverlay, point);
}
}
}
if (hitPoly) {
return;
}
}
// Only emit click event if no overlays hit
this.onMapEvent("click", point);
}
/**
* Intersection for geodesic line
* @ref http://my-clip-devdiary.blogspot.com/2014/01/html5canvas.html
*
* @param points
* @param point
* @param threshold
* @return
*/
private boolean isPointOnTheGeodesicLine(List<LatLng> points, LatLng point, double threshold) {
double trueDistance, testDistance1, testDistance2;
Point p0, p1, touchPoint;
touchPoint = new Point();
touchPoint.x = (int) (point.latitude * 100000);
touchPoint.y = (int) (point.longitude * 100000);
for (int i = 0; i < points.size() - 1; i++) {
p0 = new Point();
p0.x = (int) (points.get(i).latitude * 100000);
p0.y = (int) (points.get(i).longitude * 100000);
p1 = new Point();
p1.x = (int) (points.get(i + 1).latitude * 100000);
p1.y = (int) (points.get(i + 1).longitude * 100000);
trueDistance = this.calculateDistance(points.get(i), points.get(i + 1));
testDistance1 = this.calculateDistance(points.get(i), point);
testDistance2 = this.calculateDistance(point, points.get(i + 1));
// the distance is exactly same if the point is on the straight line
if (Math.abs(trueDistance - (testDistance1 + testDistance2)) < threshold) {
return true;
}
}
return false;
}
/**
* Intersection for non-geodesic line
* @ref http://movingahead.seesaa.net/article/299962216.html
* @ref http://www.softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm#Line-Plane
*
* @param points
* @param point
* @return
*/
private boolean isPointOnTheLine(List<LatLng> points, LatLng point) {
double Sx, Sy;
Projection projection = map.getProjection();
Point p0, p1, touchPoint;
touchPoint = projection.toScreenLocation(point);
p0 = projection.toScreenLocation(points.get(0));
for (int i = 1; i < points.size(); i++) {
p1 = projection.toScreenLocation(points.get(i));
Sx = ((double)touchPoint.x - (double)p0.x) / ((double)p1.x - (double)p0.x);
Sy = ((double)touchPoint.y - (double)p0.y) / ((double)p1.y - (double)p0.y);
if (Math.abs(Sx - Sy) < 0.05 && Sx < 1 && Sx > 0) {
return true;
}
p0 = p1;
}
return false;
}
/**
* Intersects using the Winding Number Algorithm
* @ref http://www.nttpc.co.jp/company/r_and_d/technology/number_algorithm.html
* @param path
* @param point
* @return
*/
private boolean isPolygonContains(List<LatLng> path, LatLng point) {
int wn = 0;
Projection projection = map.getProjection();
VisibleRegion visibleRegion = projection.getVisibleRegion();
LatLngBounds bounds = visibleRegion.latLngBounds;
Point sw = projection.toScreenLocation(bounds.southwest);
Point touchPoint = projection.toScreenLocation(point);
touchPoint.y = sw.y - touchPoint.y;
double vt;
for (int i = 0; i < path.size() - 1; i++) {
Point a = projection.toScreenLocation(path.get(i));
a.y = sw.y - a.y;
Point b = projection.toScreenLocation(path.get(i + 1));
b.y = sw.y - b.y;
if ((a.y <= touchPoint.y) && (b.y > touchPoint.y)) {
vt = ((double)touchPoint.y - (double)a.y) / ((double)b.y - (double)a.y);
if (touchPoint.x < ((double)a.x + (vt * ((double)b.x - (double)a.x)))) {
wn++;
}
} else if ((a.y > touchPoint.y) && (b.y <= touchPoint.y)) {
vt = ((double)touchPoint.y - (double)a.y) / ((double)b.y - (double)a.y);
if (touchPoint.x < ((double)a.x + (vt * ((double)b.x - (double)a.x)))) {
wn--;
}
}
}
return (wn != 0);
}
/**
* Check if a circle contains a point
* @param circle
* @param point
*/
private boolean isCircleContains(Circle circle, LatLng point) {
double r = circle.getRadius();
LatLng center = circle.getCenter();
double cX = center.latitude;
double cY = center.longitude;
double pX = point.latitude;
double pY = point.longitude;
float[] results = new float[1];
Location.distanceBetween(cX, cY, pX, pY, results);
if(results[0] < r) {
return true;
} else {
return false;
}
}
/**
* Check if a ground overlay contains a point
* @param groundOverlay
* @param point
*/
private boolean isGroundOverlayContains(GroundOverlay groundOverlay, LatLng point) {
LatLngBounds groundOverlayBounds = groundOverlay.getBounds();
return groundOverlayBounds.contains(point);
}
@Override
public boolean onMyLocationButtonClick() {
webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('my_location_button_click')");
return false;
}
@Override
public void onMapLoaded() {
webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('map_loaded')");
}
/**
* Notify the myLocationChange event to JS
*/
@Override
public void onCameraChange(CameraPosition position) {
JSONObject params = new JSONObject();
String jsonStr = "";
try {
JSONObject target = new JSONObject();
target.put("lat", position.target.latitude);
target.put("lng", position.target.longitude);
params.put("target", target);
params.put("hashCode", position.hashCode());
params.put("bearing", position.bearing);
params.put("tilt", position.tilt);
params.put("zoom", position.zoom);
jsonStr = params.toString();
} catch (JSONException e) {
e.printStackTrace();
}
webView.loadUrl("javascript:plugin.google.maps.Map._onCameraEvent('camera_change', " + jsonStr + ")");
}
@Override
public void onIndoorBuildingFocused() {
webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('indoor_building_focused')");
}
@Override
public void onIndoorLevelActivated(IndoorBuilding building) {
String jsonStr = "null";
JSONObject result = PluginUtil.convertIndoorBuildingToJson(building);
if (result != null) {
jsonStr = result.toString();
}
webView.loadUrl("javascript:plugin.google.maps.Map._onMapEvent('indoor_level_activated', " + jsonStr + ")");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (!bufferForLocationDialog.containsKey("bundle_" + requestCode)) {
Log.e("CordovaLog", "no key");
return;
}
Bundle query = bufferForLocationDialog.get("bundle_" + requestCode);
Log.d("CordovaLog", "====> onActivityResult (" + resultCode + ")");
switch (query.getInt("type")) {
case ACTIVITY_LOCATION_DIALOG:
// User was asked to enable the location setting.
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
_inviteLocationUpdateAfterActivityResult(query);
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
_userRefusedToUseLocationAfterActivityResult(query);
break;
default:
break;
}
break;
case ACTIVITY_LOCATION_PAGE:
_onActivityResultLocationPage(query);
break;
}
}
private void _onActivityResultLocationPage(Bundle bundle) {
String callbackId = bundle.getString("callbackId");
CallbackContext callbackContext = new CallbackContext(callbackId, this.webView);
LocationManager locationManager = (LocationManager) this.activity.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = locationManager.getAllProviders();
int availableProviders = 0;
if (isDebug) {
Log.d("CordovaLog", "---debug at getMyLocation(available providers)--");
}
Iterator<String> iterator = providers.iterator();
String provider;
boolean isAvailable = false;
while(iterator.hasNext()) {
provider = iterator.next();
isAvailable = locationManager.isProviderEnabled(provider);
if (isAvailable) {
availableProviders++;
}
if (isDebug) {
Log.d("CordovaLog", " " + provider + " = " + (isAvailable ? "" : "not ") + "available");
}
}
if (availableProviders == 0) {
JSONObject result = new JSONObject();
try {
result.put("status", false);
result.put("error_code", "not_available");
result.put("error_message", "Since this device does not have any location provider, this app can not detect your location.");
} catch (JSONException e) {}
callbackContext.error(result);
return;
}
_inviteLocationUpdateAfterActivityResult(bundle);
}
private void _inviteLocationUpdateAfterActivityResult(Bundle bundle) {
boolean enableHighAccuracy = bundle.getBoolean("enableHighAccuracy");
String callbackId = bundle.getString("callbackId");
CallbackContext callbackContext = new CallbackContext(callbackId, this.webView);
this._requestLocationUpdate(false, enableHighAccuracy, callbackContext);
}
private void _userRefusedToUseLocationAfterActivityResult(Bundle bundle) {
String callbackId = bundle.getString("callbackId");
CallbackContext callbackContext = new CallbackContext(callbackId, this.webView);
JSONObject result = new JSONObject();
try {
result.put("status", false);
result.put("error_code", "service_denied");
result.put("error_message", "This app has been rejected to use Location Services.");
} catch (JSONException e) {}
callbackContext.error(result);
}
@Override
public void onPause(boolean multitasking) {
if (mapView != null) {
mapView.onPause();
}
super.onPause(multitasking);
}
@Override
public void onResume(boolean multitasking) {
if (mapView != null) {
mapView.onResume();
}
super.onResume(multitasking);
}
@Override
public void onDestroy() {
if (mapView != null) {
mapView.onDestroy();
}
super.onDestroy();
}
@Override
public void onClick(View view) {
int viewId = view.getId();
if (viewId == CLOSE_LINK_ID) {
closeWindow();
return;
}
if (viewId == LICENSE_LINK_ID) {
showLicenseText();
return;
}
}
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public View getInfoContents(Marker marker) {
String title = marker.getTitle();
String snippet = marker.getSnippet();
if ((title == null) && (snippet == null)) {
return null;
}
JSONObject properties = null;
JSONObject styles = null;
String propertyId = "marker_property_" + marker.getId();
PluginEntry pluginEntry = this.plugins.get("Marker");
PluginMarker pluginMarker = (PluginMarker)pluginEntry.plugin;
if (pluginMarker.objects.containsKey(propertyId)) {
properties = (JSONObject) pluginMarker.objects.get(propertyId);
if (properties.has("styles")) {
try {
styles = (JSONObject) properties.getJSONObject("styles");
} catch (JSONException e) {}
}
}
// Linear layout
LinearLayout windowLayer = new LinearLayout(activity);
windowLayer.setPadding(3, 3, 3, 3);
windowLayer.setOrientation(LinearLayout.VERTICAL);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER;
int maxWidth = 0;
if (styles != null) {
try {
int width = 0;
String widthString = styles.getString("width");
if (widthString.endsWith("%")) {
double widthDouble = Double.parseDouble(widthString.replace ("%", ""));
width = (int)((double)mapView.getWidth() * (widthDouble / 100));
} else if (isNumeric(widthString)) {
double widthDouble = Double.parseDouble(widthString);
if (widthDouble <= 1.0) { // for percentage values (e.g. 0.5 = 50%).
width = (int)((double)mapView.getWidth() * (widthDouble));
} else {
width = (int)widthDouble;
}
}
if (width > 0) {
layoutParams.width = width;
}
} catch (Exception e) {}
try {
String widthString = styles.getString("maxWidth");
if (widthString.endsWith("%")) {
double widthDouble = Double.parseDouble(widthString.replace ("%", ""));
maxWidth = (int)((double)mapView.getWidth() * (widthDouble / 100));
// make sure to take padding into account.
maxWidth -= (windowLayer.getPaddingLeft() + windowLayer.getPaddingRight());
} else if (isNumeric(widthString)) {
double widthDouble = Double.parseDouble(widthString);
if (widthDouble <= 1.0) { // for percentage values (e.g. 0.5 = 50%).
maxWidth = (int)((double)mapView.getWidth() * (widthDouble));
} else {
maxWidth = (int)widthDouble;
}
}
} catch (Exception e) {}
}
windowLayer.setLayoutParams(layoutParams);
//----------------------------------------
// text-align = left | center | right
//----------------------------------------
int gravity = Gravity.LEFT;
int textAlignment = View.TEXT_ALIGNMENT_GRAVITY;
if (styles != null) {
try {
String textAlignValue = styles.getString("text-align");
switch(TEXT_STYLE_ALIGNMENTS.valueOf(textAlignValue)) {
case left:
gravity = Gravity.LEFT;
textAlignment = View.TEXT_ALIGNMENT_GRAVITY;
break;
case center:
gravity = Gravity.CENTER;
textAlignment = View.TEXT_ALIGNMENT_CENTER;
break;
case right:
gravity = Gravity.RIGHT;
textAlignment = View.TEXT_ALIGNMENT_VIEW_END;
break;
}
} catch (Exception e) {}
}
if (title != null) {
if (title.indexOf("data:image/") > -1 && title.indexOf(";base64,") > -1) {
String[] tmp = title.split(",");
Bitmap image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]);
image = PluginUtil.scaleBitmapForDevice(image);
ImageView imageView = new ImageView(this.cordova.getActivity());
imageView.setImageBitmap(image);
if (maxWidth > 0) {
imageView.setMaxWidth(maxWidth);
}
windowLayer.addView(imageView);
} else {
TextView textView = new TextView(this.cordova.getActivity());
textView.setText(title);
textView.setSingleLine(false);
int titleColor = Color.BLACK;
if (styles != null && styles.has("color")) {
try {
titleColor = PluginUtil.parsePluginColor(styles.getJSONArray("color"));
} catch (JSONException e) {}
}
textView.setTextColor(titleColor);
textView.setGravity(gravity);
if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
textView.setTextAlignment(textAlignment);
}
//----------------------------------------
// font-style = normal | italic
// font-weight = normal | bold
//----------------------------------------
int fontStyle = Typeface.NORMAL;
if (styles != null) {
try {
if ("italic".equals(styles.getString("font-style"))) {
fontStyle = Typeface.ITALIC;
}
} catch (JSONException e) {}
try {
if ("bold".equals(styles.getString("font-weight"))) {
fontStyle = fontStyle | Typeface.BOLD;
}
} catch (JSONException e) {}
}
textView.setTypeface(Typeface.DEFAULT, fontStyle);
if (maxWidth > 0) {
textView.setMaxWidth(maxWidth);
}
windowLayer.addView(textView);
}
}
if (snippet != null) {
//snippet = snippet.replaceAll("\n", "");
TextView textView2 = new TextView(this.cordova.getActivity());
textView2.setText(snippet);
textView2.setTextColor(Color.GRAY);
textView2.setTextSize((textView2.getTextSize() / 6 * 5) / density);
textView2.setGravity(gravity);
if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
textView2.setTextAlignment(textAlignment);
}
if (maxWidth > 0) {
textView2.setMaxWidth(maxWidth);
}
windowLayer.addView(textView2);
}
return windowLayer;
}
@Override
public View getInfoWindow(Marker marker) {
return null;
}
/**
* Clear all markups
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void clear(JSONArray args, CallbackContext callbackContext) throws JSONException {
Set<String> pluginNames = plugins.keySet();
Iterator<String> iterator = pluginNames.iterator();
String pluginName;
PluginEntry pluginEntry;
while(iterator.hasNext()) {
pluginName = iterator.next();
if ("Map".equals(pluginName) == false) {
pluginEntry = plugins.get(pluginName);
((MyPlugin) pluginEntry.plugin).clear();
}
}
this.map.clear();
this.sendNoResult(callbackContext);
}
@SuppressWarnings("unused")
private void pluginLayer_pushHtmlElement(JSONArray args, CallbackContext callbackContext) throws JSONException {
if (mPluginLayout != null) {
String domId = args.getString(0);
JSONObject elemSize = args.getJSONObject(1);
float left = contentToView(elemSize.getLong("left"));
float top = contentToView(elemSize.getLong("top"));
float width = contentToView(elemSize.getLong("width"));
float height = contentToView(elemSize.getLong("height"));
mPluginLayout.putHTMLElement(domId, left, top, (left + width), (top + height));
this.mPluginLayout.inValidate();
}
this.sendNoResult(callbackContext);
}
@SuppressWarnings("unused")
private void pluginLayer_removeHtmlElement(JSONArray args, CallbackContext callbackContext) throws JSONException {
if (mPluginLayout != null) {
String domId = args.getString(0);
mPluginLayout.removeHTMLElement(domId);
this.mPluginLayout.inValidate();
}
this.sendNoResult(callbackContext);
}
/**
* Set click-ability of the map
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void pluginLayer_setClickable(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean clickable = args.getBoolean(0);
if (mapView != null && this.windowLayer == null) {
this.mPluginLayout.setClickable(clickable);
}
this.sendNoResult(callbackContext);
}
/**
* Set the app background
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void pluginLayer_setBackGroundColor(JSONArray args, CallbackContext callbackContext) throws JSONException {
if (mPluginLayout != null) {
JSONArray rgba = args.getJSONArray(0);
int backgroundColor = Color.WHITE;
if (rgba != null && rgba.length() == 4) {
try {
backgroundColor = PluginUtil.parsePluginColor(rgba);
this.mPluginLayout.setBackgroundColor(backgroundColor);
} catch (JSONException e) {}
}
}
this.sendNoResult(callbackContext);
}
/**
* Set the debug flag of myPluginLayer
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void pluginLayer_setDebuggable(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean debuggable = args.getBoolean(0);
if (mapView != null && this.windowLayer == null) {
this.mPluginLayout.setDebug(debuggable);
}
this.isDebug = debuggable;
this.sendNoResult(callbackContext);
}
/**
* Destroy the map completely
* @param args
* @param callbackContext
*/
@SuppressWarnings("unused")
private void remove(JSONArray args, CallbackContext callbackContext) {
if (mPluginLayout != null) {
this.mPluginLayout.setClickable(false);
this.mPluginLayout.detachMyView();
this.mPluginLayout = null;
}
plugins.clear();
if (map != null) {
map.setMyLocationEnabled(false);
map.clear();
}
if (mapView != null) {
mapView.onDestroy();
}
map = null;
mapView = null;
windowLayer = null;
mapDivLayoutJSON = null;
System.gc();
this.sendNoResult(callbackContext);
}
protected void sendNoResult(CallbackContext callbackContext) {
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
}
| apache-2.0 |
adessaigne/camel | core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/StreamComponentBuilderFactory.java | 5231 | /*
* 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.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.stream.StreamComponent;
/**
* Read from system-in and write to system-out and system-err streams.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface StreamComponentBuilderFactory {
/**
* Stream (camel-stream)
* Read from system-in and write to system-out and system-err streams.
*
* Category: file,system
* Since: 1.3
* Maven coordinates: org.apache.camel:camel-stream
*/
static StreamComponentBuilder stream() {
return new StreamComponentBuilderImpl();
}
/**
* Builder for the Stream component.
*/
interface StreamComponentBuilder
extends
ComponentBuilder<StreamComponent> {
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*/
default StreamComponentBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default StreamComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the component should use basic property binding (Camel 2.x)
* or the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
@Deprecated
default StreamComponentBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
}
class StreamComponentBuilderImpl
extends
AbstractComponentBuilder<StreamComponent>
implements
StreamComponentBuilder {
@Override
protected StreamComponent buildConcreteComponent() {
return new StreamComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "bridgeErrorHandler": ((StreamComponent) component).setBridgeErrorHandler((boolean) value); return true;
case "lazyStartProducer": ((StreamComponent) component).setLazyStartProducer((boolean) value); return true;
case "basicPropertyBinding": ((StreamComponent) component).setBasicPropertyBinding((boolean) value); return true;
default: return false;
}
}
}
} | apache-2.0 |
bartoszmajsak/arquillian-core | container/test-impl-base/src/test/java/org/jboss/arquillian/container/test/impl/execution/RemoteTestExecuterTestCase.java | 7427 | /*
* JBoss, Home of Professional Open Source
* Copyright 2009 Red Hat Inc. and/or its affiliates and other contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.arquillian.container.test.impl.execution;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.spi.Container;
import org.jboss.arquillian.container.spi.client.deployment.DeploymentDescription;
import org.jboss.arquillian.container.spi.client.protocol.ProtocolDescription;
import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData;
import org.jboss.arquillian.container.test.impl.domain.ProtocolDefinition;
import org.jboss.arquillian.container.test.impl.domain.ProtocolRegistry;
import org.jboss.arquillian.container.test.impl.execution.event.RemoteExecutionEvent;
import org.jboss.arquillian.container.test.spi.ContainerMethodExecutor;
import org.jboss.arquillian.container.test.spi.client.protocol.Protocol;
import org.jboss.arquillian.container.test.spi.client.protocol.ProtocolConfiguration;
import org.jboss.arquillian.container.test.spi.command.Command;
import org.jboss.arquillian.container.test.spi.command.CommandCallback;
import org.jboss.arquillian.container.test.test.AbstractContainerTestTestBase;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.spi.context.Context;
import org.jboss.arquillian.core.test.context.ManagerTestContext;
import org.jboss.arquillian.core.test.context.ManagerTestContextImpl;
import org.jboss.arquillian.test.spi.TestMethodExecutor;
import org.jboss.arquillian.test.spi.TestResult;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
/**
* TestExecutorHandlerTestCase
*
* @author <a href="mailto:aknutsen@redhat.com">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(MockitoJUnitRunner.class)
public class RemoteTestExecuterTestCase extends AbstractContainerTestTestBase {
@Mock
private ContainerMethodExecutor executor;
@Mock
private Container container;
@Mock
private TestMethodExecutor testExecutor;
@Mock
private DeploymentDescription deploymentDescription;
@Mock
@SuppressWarnings("rawtypes")
private Protocol protocol;
@Mock
private ProtocolDefinition protocolDefinition;
@Mock
private ProtocolRegistry protocolRegistry;
@Mock
private ProtocolMetaData protocolMetaData;
@Override
protected void addContexts(List<Class<? extends Context>> contexts) {
super.addContexts(contexts);
contexts.add(ManagerTestContextImpl.class);
}
@Override
protected void addExtensions(List<Class<?>> extensions) {
extensions.add(RemoteTestExecuter.class);
}
@SuppressWarnings("unchecked")
@Before
public void setup() throws Exception {
bind(ApplicationScoped.class, Container.class, container);
bind(ApplicationScoped.class, DeploymentDescription.class, deploymentDescription);
bind(ApplicationScoped.class, ProtocolMetaData.class, protocolMetaData);
bind(ApplicationScoped.class, ProtocolRegistry.class, protocolRegistry);
Mockito.when(deploymentDescription.getProtocol()).thenReturn(new ProtocolDescription("TEST"));
Mockito.when(protocolRegistry.getProtocol(Mockito.any(ProtocolDescription.class))).thenReturn(protocolDefinition);
Mockito.when(protocolDefinition.getProtocol()).thenReturn(protocol);
Mockito.when(protocol.getExecutor(
Mockito.any(ProtocolConfiguration.class),
Mockito.any(ProtocolMetaData.class),
Mockito.any(CommandCallback.class))).thenAnswer(new Answer<ContainerMethodExecutor>() {
@Override
public ContainerMethodExecutor answer(InvocationOnMock invocation) throws Throwable {
return new TestContainerMethodExecutor((CommandCallback) invocation.getArguments()[2]);
}
});
Mockito.when(testExecutor.getInstance()).thenReturn(this);
Mockito.when(testExecutor.getMethod()).thenReturn(
getTestMethod("shouldReactivePreviousContextsOnRemoteEvents"));
}
@Test
public void shouldReactivePreviousContextsOnRemoteEvents() throws Exception {
getManager().getContext(ManagerTestContext.class).activate();
fire(new RemoteExecutionEvent(testExecutor));
assertEventFiredInContext(TestStringCommand.class, ManagerTestContext.class);
}
private Method getTestMethod(String name) throws Exception {
return this.getClass().getMethod(name);
}
public class TestContainerMethodExecutor implements ContainerMethodExecutor {
private CommandCallback callback;
public TestContainerMethodExecutor(CommandCallback callback) {
this.callback = callback;
}
@Override
public TestResult invoke(TestMethodExecutor testMethodExecutor) {
final CountDownLatch latch = new CountDownLatch(1);
Thread remote = new Thread() {
public void run() {
callback.fired(new TestStringCommand());
latch.countDown();
}
;
};
remote.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
throw new RuntimeException(e);
}
});
remote.start();
try {
if (!latch.await(200, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Latch never reached");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return TestResult.passed();
}
}
public class TestStringCommand implements Command<String>, Serializable {
private static final long serialVersionUID = 1L;
private String result;
private Throwable throwable;
@Override
public String getResult() {
return result;
}
@Override
public void setResult(String result) {
this.result = result;
}
@Override
public Throwable getThrowable() {
return throwable;
}
@Override
public void setThrowable(Throwable throwable) {
this.throwable = throwable;
}
}
} | apache-2.0 |
DataSketches/sketches-core | src/test/java/org/apache/datasketches/quantiles/ItemsUnionTest.java | 17150 | /*
* 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.datasketches.quantiles;
import static org.apache.datasketches.quantiles.PreambleUtil.DEFAULT_K;
import java.util.Comparator;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.ArrayOfItemsSerDe;
import org.apache.datasketches.ArrayOfLongsSerDe;
import org.apache.datasketches.ArrayOfStringsSerDe;
@SuppressWarnings("javadoc")
public class ItemsUnionTest {
@Test
public void nullAndEmpty() {
ItemsUnion<Integer> union = ItemsUnion.getInstance(Comparator.naturalOrder());
// union gadget sketch is null at this point
Assert.assertTrue(union.isEmpty());
Assert.assertFalse(union.isDirect());
Assert.assertEquals(union.getMaxK(), DEFAULT_K);
Assert.assertEquals(union.getEffectiveK(), DEFAULT_K);
Assert.assertTrue(union.toString().length() > 0);
union.update((Integer) null);
ItemsSketch<Integer> result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getN(), 0);
Assert.assertNull(result.getMinValue());
Assert.assertNull(result.getMaxValue());
Assert.assertNull(union.getResultAndReset());
final ItemsSketch<Integer> emptySk = ItemsSketch.getInstance(Comparator.naturalOrder());
final ItemsSketch<Integer> validSk = ItemsSketch.getInstance(Comparator.naturalOrder());
validSk.update(1);
union.update(validSk);
union = ItemsUnion.getInstance(result);
// internal sketch is empty at this point
union.update((ItemsSketch<Integer>) null);
union.update(emptySk);
Assert.assertTrue(union.isEmpty());
Assert.assertFalse(union.isDirect());
Assert.assertEquals(union.getMaxK(), DEFAULT_K);
Assert.assertEquals(union.getEffectiveK(), DEFAULT_K);
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getN(), 0);
Assert.assertNull(result.getMinValue());
Assert.assertNull(result.getMaxValue());
union.update(validSk);
union.reset();
// internal sketch is null again
union.update((ItemsSketch<Integer>) null);
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getN(), 0);
Assert.assertNull(result.getMinValue());
Assert.assertNull(result.getMaxValue());
// internal sketch is not null again because getResult() instantiated it
union.update(ItemsSketch.getInstance(Comparator.naturalOrder()));
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getN(), 0);
Assert.assertNull(result.getMinValue());
Assert.assertNull(result.getMaxValue());
union.reset();
// internal sketch is null again
union.update(ItemsSketch.getInstance(Comparator.naturalOrder()));
result = union.getResult();
Assert.assertTrue(result.isEmpty());
Assert.assertEquals(result.getN(), 0);
Assert.assertNull(result.getMinValue());
Assert.assertNull(result.getMaxValue());
}
@Test
public void nullAndEmptyInputsToNonEmptyUnion() {
final ItemsUnion<Integer> union = ItemsUnion.getInstance(128, Comparator.naturalOrder());
union.update(1);
ItemsSketch<Integer> result = union.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getN(), 1);
Assert.assertEquals(result.getMinValue(), Integer.valueOf(1));
Assert.assertEquals(result.getMaxValue(), Integer.valueOf(1));
union.update((ItemsSketch<Integer>) null);
result = union.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getN(), 1);
Assert.assertEquals(result.getMinValue(), Integer.valueOf(1));
Assert.assertEquals(result.getMaxValue(), Integer.valueOf(1));
union.update(ItemsSketch.getInstance(Comparator.naturalOrder()));
result = union.getResult();
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(result.getN(), 1);
Assert.assertEquals(result.getMinValue(), Integer.valueOf(1));
Assert.assertEquals(result.getMaxValue(), Integer.valueOf(1));
}
@Test
public void basedOnSketch() {
final Comparator<String> comp = Comparator.naturalOrder();
final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe();
final ItemsSketch<String> sketch = ItemsSketch.getInstance(comp);
ItemsUnion<String> union = ItemsUnion.getInstance(sketch);
union.reset();
final byte[] byteArr = sketch.toByteArray(serDe);
final Memory mem = Memory.wrap(byteArr);
union = ItemsUnion.getInstance(mem, comp, serDe);
Assert.assertEquals(byteArr.length, 8);
union.reset();
}
@Test
public void sameK() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(128, Comparator.naturalOrder());
ItemsSketch<Long> result = union.getResult();
Assert.assertEquals(result.getN(), 0);
Assert.assertNull(result.getMinValue());
Assert.assertNull(result.getMaxValue());
for (int i = 1; i <= 1000; i++) { union.update((long) i); }
result = union.getResult();
Assert.assertEquals(result.getN(), 1000);
Assert.assertEquals(result.getMinValue(), Long.valueOf(1));
Assert.assertEquals(result.getMaxValue(), Long.valueOf(1000));
Assert.assertEquals(result.getQuantile(0.5), 500, 17); // ~1.7% normalized rank error
final ItemsSketch<Long> sketch1 = ItemsSketch.getInstance(Comparator.naturalOrder());
for (int i = 1001; i <= 2000; i++) { sketch1.update((long) i); }
union.update(sketch1);
result = union.getResult();
Assert.assertEquals(result.getN(), 2000);
Assert.assertEquals(result.getMinValue(), Long.valueOf(1));
Assert.assertEquals(result.getMaxValue(), Long.valueOf(2000));
Assert.assertEquals(result.getQuantile(0.5), 1000, 34); // ~1.7% normalized rank error
final ItemsSketch<Long> sketch2 = ItemsSketch.getInstance(Comparator.naturalOrder());
for (int i = 2001; i <= 3000; i++) { sketch2.update((long) i); }
final ArrayOfItemsSerDe<Long> serDe = new ArrayOfLongsSerDe();
union.update(Memory.wrap(sketch2.toByteArray(serDe)), serDe);
result = union.getResultAndReset();
Assert.assertNotNull(result);
Assert.assertEquals(result.getN(), 3000);
Assert.assertEquals(result.getMinValue(), Long.valueOf(1));
Assert.assertEquals(result.getMaxValue(), Long.valueOf(3000));
Assert.assertEquals(result.getQuantile(0.5), 1500, 51); // ~1.7% normalized rank error
result = union.getResult();
Assert.assertEquals(result.getN(), 0);
Assert.assertNull(result.getMinValue());
Assert.assertNull(result.getMaxValue());
}
@Test
public void differentK() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(512, Comparator.naturalOrder());
ItemsSketch<Long> result = union.getResult();
Assert.assertEquals(result.getN(), 0);
Assert.assertNull(result.getMinValue());
Assert.assertNull(result.getMaxValue());
for (int i = 1; i <= 10000; i++) { union.update((long) i); }
result = union.getResult();
Assert.assertEquals(result.getK(), 512);
Assert.assertEquals(result.getN(), 10000);
Assert.assertEquals(result.getMinValue(), Long.valueOf(1));
Assert.assertEquals(result.getMaxValue(), Long.valueOf(10000));
Assert.assertEquals(result.getQuantile(0.5), 5000, 50); // ~0.5% normalized rank error
final ItemsSketch<Long> sketch1 = ItemsSketch.getInstance(256, Comparator.naturalOrder());
for (int i = 10001; i <= 20000; i++) { sketch1.update((long) i); }
union.update(sketch1);
result = union.getResult();
Assert.assertEquals(result.getK(), 256);
Assert.assertEquals(result.getN(), 20000);
Assert.assertEquals(result.getMinValue(), Long.valueOf(1));
Assert.assertEquals(result.getMaxValue(), Long.valueOf(20000));
Assert.assertEquals(result.getQuantile(0.5), 10000, 180); // ~0.9% normalized rank error
final ItemsSketch<Long> sketch2 = ItemsSketch.getInstance(128, Comparator.naturalOrder());
for (int i = 20001; i <= 30000; i++) { sketch2.update((long) i); }
final ArrayOfItemsSerDe<Long> serDe = new ArrayOfLongsSerDe();
union.update(Memory.wrap(sketch2.toByteArray(serDe)), serDe);
result = union.getResultAndReset();
Assert.assertNotNull(result);
Assert.assertEquals(result.getK(), 128);
Assert.assertEquals(result.getN(), 30000);
Assert.assertEquals(result.getMinValue(), Long.valueOf(1));
Assert.assertEquals(result.getMaxValue(), Long.valueOf(30000));
Assert.assertEquals(result.getQuantile(0.5), 15000, 510); // ~1.7% normalized rank error
result = union.getResult();
Assert.assertEquals(result.getN(), 0);
Assert.assertNull(result.getMinValue());
Assert.assertNull(result.getMaxValue());
}
@Test
public void differentLargerK() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(128, Comparator.naturalOrder());
final ItemsSketch<Long> sketch1 = ItemsSketch.getInstance(256, Comparator.naturalOrder());
union.update(sketch1);
Assert.assertEquals(union.getResult().getK(), 128);
sketch1.update(1L);
union.update(sketch1);
Assert.assertEquals(union.getResult().getK(), 128);
}
@Test
public void differentSmallerK() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(128, Comparator.naturalOrder());
final ItemsSketch<Long> sketch1 = ItemsSketch.getInstance(64, Comparator.naturalOrder());
union.update(sketch1);
Assert.assertEquals(union.getResult().getK(), 64);
sketch1.update(1L);
union.update(sketch1);
Assert.assertEquals(union.getResult().getK(), 64);
}
@Test
public void toStringCrudeCheck() {
final ItemsUnion<String> union = ItemsUnion.getInstance(128, Comparator.naturalOrder());
union.update("a");
final String brief = union.toString();
final String full = union.toString(true, true);
Assert.assertTrue(brief.length() < full.length());
}
@Test
public void meNullOtherExactBiggerSmaller() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(16, Comparator.naturalOrder()); //me null
ItemsSketch<Long> skExact = buildIS(32, 31); //other is bigger, exact
union.update(skExact);
println(skExact.toString(true, true));
println(union.toString(true, true));
Assert.assertEquals(skExact.getQuantile(0.5), union.getResult().getQuantile(0.5), 0.0);
union.reset();
skExact = buildIS(8, 15); //other is smaller exact,
union.update(skExact);
println(skExact.toString(true, true));
println(union.toString(true, true));
Assert.assertEquals(skExact.getQuantile(0.5), union.getResult().getQuantile(0.5), 0.0);
}
@Test
public void meNullOtherEstBiggerSmaller() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(16, Comparator.naturalOrder()); //me null
ItemsSketch<Long> skEst = buildIS(32, 64); //other is bigger, est
union.update(skEst);
Assert.assertEquals(union.getResult().getMinValue(), skEst.getMinValue(), 0.0);
Assert.assertEquals(union.getResult().getMaxValue(), skEst.getMaxValue(), 0.0);
union.reset();
skEst = buildIS(8, 64); //other is smaller est,
union.update(skEst);
Assert.assertEquals(union.getResult().getMinValue(), skEst.getMinValue(), 0.0);
Assert.assertEquals(union.getResult().getMaxValue(), skEst.getMaxValue(), 0.0);
}
@Test
public void meEmptyOtherExactBiggerSmaller() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(16, Comparator.naturalOrder()); //me null
final ItemsSketch<Long> skEmpty = ItemsSketch.getInstance(64, Comparator.naturalOrder());
union.update(skEmpty); //empty at k = 16
ItemsSketch<Long> skExact = buildIS(32, 63); //bigger, exact
union.update(skExact);
Assert.assertEquals(union.getResult().getMinValue(), skExact.getMinValue(), 0.0);
Assert.assertEquals(union.getResult().getMaxValue(), skExact.getMaxValue(), 0.0);
union.reset();
union.update(skEmpty); //empty at k = 16
skExact = buildIS(8, 15); //smaller, exact
union.update(skExact);
Assert.assertEquals(union.getResult().getMinValue(), skExact.getMinValue(), 0.0);
Assert.assertEquals(union.getResult().getMaxValue(), skExact.getMaxValue(), 0.0);
}
@Test
public void meEmptyOtherEstBiggerSmaller() {
final ItemsUnion<Long> union = ItemsUnion.getInstance(16, Comparator.naturalOrder()); //me null
final ItemsSketch<Long> skEmpty = ItemsSketch.getInstance(64, Comparator.naturalOrder());
union.update(skEmpty); //empty at k = 16
ItemsSketch<Long> skExact = buildIS(32, 64); //bigger, est
union.update(skExact);
Assert.assertEquals(union.getResult().getMinValue(), skExact.getMinValue(), 0.0);
Assert.assertEquals(union.getResult().getMaxValue(), skExact.getMaxValue(), 0.0);
union.reset();
union.update(skEmpty); //empty at k = 16
skExact = buildIS(8, 16); //smaller, est
union.update(skExact);
Assert.assertEquals(union.getResult().getMinValue(), skExact.getMinValue(), 0.0);
Assert.assertEquals(union.getResult().getMaxValue(), skExact.getMaxValue(), 0.0);
}
@Test
public void checkMergeIntoEqualKs() {
final ItemsSketch<Long> skEmpty1 = buildIS(32, 0);
final ItemsSketch<Long> skEmpty2 = buildIS(32, 0);
ItemsMergeImpl.mergeInto(skEmpty1, skEmpty2);
Assert.assertNull(skEmpty2.getMaxValue());
Assert.assertNull(skEmpty2.getMaxValue());
ItemsSketch<Long> skValid1, skValid2;
int n = 64;
skValid1 = buildIS(32, n, 0);
skValid2 = buildIS(32, 0, 0); //empty
ItemsMergeImpl.mergeInto(skValid1, skValid2);
Assert.assertEquals(skValid2.getMinValue(), 0.0, 0.0);
Assert.assertEquals(skValid2.getMaxValue(), n - 1.0, 0.0);
skValid1 = buildIS(32, 0, 0); //empty
skValid2 = buildIS(32, n, 0);
ItemsMergeImpl.mergeInto(skValid1, skValid2);
Assert.assertEquals(skValid2.getMinValue(), 0.0, 0.0);
Assert.assertEquals(skValid2.getMaxValue(), n - 1.0, 0.0);
skValid1 = buildIS(32, n, 0);
skValid2 = buildIS(32, n, n);
ItemsMergeImpl.mergeInto(skValid1, skValid2);
Assert.assertEquals(skValid2.getMinValue(), 0.0, 0.0);
Assert.assertEquals(skValid2.getMaxValue(), (2 * n) - 1.0, 0.0);
n = 512;
skValid1 = buildIS(32, n, 0);
skValid2 = buildIS(32, n, n);
ItemsMergeImpl.mergeInto(skValid1, skValid2);
Assert.assertEquals(skValid2.getMinValue(), 0.0, 0.0);
Assert.assertEquals(skValid2.getMaxValue(), (2 * n) - 1.0, 0.0);
skValid1 = buildIS(32, n, 0);
skValid2 = buildIS(32, n, n);
ItemsMergeImpl.mergeInto(skValid2, skValid1);
Assert.assertEquals(skValid1.getMinValue(), 0.0, 0.0);
Assert.assertEquals(skValid1.getMaxValue(), (2 * n) - 1.0, 0.0);
}
@Test
public void checkDownSamplingMergeIntoUnequalKs() {
ItemsSketch<Long> sk1, sk2;
final int n = 128;
sk1 = buildIS(64, n, 0);
sk2 = buildIS(32, n, 128);
ItemsMergeImpl.downSamplingMergeInto(sk1, sk2);
sk1 = buildIS(64, n, 128);
sk2 = buildIS(32, n, 0);
ItemsMergeImpl.downSamplingMergeInto(sk1, sk2);
}
@Test
public void checkToByteArray() {
final int k = 32;
final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe();
ItemsUnion<Long> union = ItemsUnion.getInstance(k, Comparator.naturalOrder());
byte[] bytesOut = union.toByteArray(serDe);
Assert.assertEquals(bytesOut.length, 8);
Assert.assertTrue(union.isEmpty());
final byte[] byteArr = buildIS(k, (2 * k) + 5).toByteArray(serDe);
final Memory mem = Memory.wrap(byteArr);
union = ItemsUnion.getInstance(mem, Comparator.naturalOrder(), serDe);
bytesOut = union.toByteArray(serDe);
Assert.assertEquals(bytesOut.length, byteArr.length);
Assert.assertEquals(bytesOut, byteArr); // assumes consistent internal use of toByteArray()
}
private static ItemsSketch<Long> buildIS(final int k, final int n) {
return buildIS(k, n, 0);
}
private static ItemsSketch<Long> buildIS(final int k, final int n, final int startV) {
final ItemsSketch<Long> is = ItemsSketch.getInstance(k, Comparator.naturalOrder());
for (long i = 0; i < n; i++) { is.update(i + startV); }
return is;
}
@Test
public void printlnTest() {
println("PRINTING: " + this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s); //disable here
}
}
| apache-2.0 |
vineetgarg02/hive | druid-handler/src/java/org/apache/hadoop/hive/druid/DruidStorageHandlerUtils.java | 51702 | /*
* 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.hive.druid;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import org.apache.calcite.adapter.druid.DruidQuery;
import org.apache.calcite.sql.validate.SqlValidatorUtil;
import org.apache.druid.common.config.NullHandling;
import org.apache.druid.data.input.impl.DimensionSchema;
import org.apache.druid.data.input.impl.StringDimensionSchema;
import org.apache.druid.guice.BloomFilterSerializersModule;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.JodaUtils;
import org.apache.druid.java.util.common.MapUtils;
import org.apache.druid.java.util.common.Pair;
import org.apache.druid.java.util.common.granularity.Granularity;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.emitter.core.NoopEmitter;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.http.client.Request;
import org.apache.druid.java.util.http.client.response.InputStreamResponseHandler;
import org.apache.druid.java.util.http.client.response.StringFullResponseHandler;
import org.apache.druid.java.util.http.client.response.StringFullResponseHolder;
import org.apache.druid.math.expr.ExprMacroTable;
import org.apache.druid.metadata.MetadataStorageTablesConfig;
import org.apache.druid.metadata.SQLMetadataConnector;
import org.apache.druid.metadata.storage.mysql.MySQLConnector;
import org.apache.druid.query.DruidProcessingConfig;
import org.apache.druid.query.Druids;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.DoubleSumAggregatorFactory;
import org.apache.druid.query.aggregation.FloatSumAggregatorFactory;
import org.apache.druid.query.aggregation.LongSumAggregatorFactory;
import org.apache.druid.query.expression.LikeExprMacro;
import org.apache.druid.query.expression.RegexpExtractExprMacro;
import org.apache.druid.query.expression.TimestampCeilExprMacro;
import org.apache.druid.query.expression.TimestampExtractExprMacro;
import org.apache.druid.query.expression.TimestampFloorExprMacro;
import org.apache.druid.query.expression.TimestampFormatExprMacro;
import org.apache.druid.query.expression.TimestampParseExprMacro;
import org.apache.druid.query.expression.TimestampShiftExprMacro;
import org.apache.druid.query.expression.TrimExprMacro;
import org.apache.druid.query.filter.AndDimFilter;
import org.apache.druid.query.filter.BloomDimFilter;
import org.apache.druid.query.filter.BloomKFilter;
import org.apache.druid.query.filter.BloomKFilterHolder;
import org.apache.druid.query.filter.BoundDimFilter;
import org.apache.druid.query.filter.DimFilter;
import org.apache.druid.query.filter.OrDimFilter;
import org.apache.druid.query.groupby.GroupByQuery;
import org.apache.druid.query.ordering.StringComparator;
import org.apache.druid.query.ordering.StringComparators;
import org.apache.druid.query.scan.ScanQuery;
import org.apache.druid.query.spec.MultipleIntervalSegmentSpec;
import org.apache.druid.query.timeseries.TimeseriesQuery;
import org.apache.druid.query.topn.TopNQuery;
import org.apache.druid.query.topn.TopNQueryBuilder;
import org.apache.druid.segment.IndexIO;
import org.apache.druid.segment.IndexMergerV9;
import org.apache.druid.segment.IndexSpec;
import org.apache.druid.segment.VirtualColumn;
import org.apache.druid.segment.VirtualColumns;
import org.apache.druid.segment.column.ValueType;
import org.apache.druid.segment.data.BitmapSerdeFactory;
import org.apache.druid.segment.data.ConciseBitmapSerdeFactory;
import org.apache.druid.segment.data.RoaringBitmapSerdeFactory;
import org.apache.druid.segment.indexing.granularity.GranularitySpec;
import org.apache.druid.segment.indexing.granularity.UniformGranularitySpec;
import org.apache.druid.segment.loading.DataSegmentPusher;
import org.apache.druid.segment.realtime.appenderator.SegmentIdWithShardSpec;
import org.apache.druid.segment.virtual.ExpressionVirtualColumn;
import org.apache.druid.segment.writeout.TmpFileSegmentWriteOutMediumFactory;
import org.apache.druid.storage.hdfs.HdfsDataSegmentPusher;
import org.apache.druid.storage.hdfs.HdfsDataSegmentPusherConfig;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.TimelineObjectHolder;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.LinearShardSpec;
import org.apache.druid.timeline.partition.NoneShardSpec;
import org.apache.druid.timeline.partition.NumberedShardSpec;
import org.apache.druid.timeline.partition.PartitionChunk;
import org.apache.druid.timeline.partition.ShardSpec;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.Constants;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.druid.conf.DruidConstants;
import org.apache.hadoop.hive.druid.json.AvroParseSpec;
import org.apache.hadoop.hive.druid.json.AvroStreamInputRowParser;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.ql.exec.ExprNodeDynamicValueEvaluator;
import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluator;
import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluatorFactory;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.udf.UDFToDouble;
import org.apache.hadoop.hive.ql.udf.UDFToFloat;
import org.apache.hadoop.hive.ql.udf.UDFToLong;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBetween;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBridge;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFInBloomFilter;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFToString;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.retry.RetryPolicies;
import org.apache.hadoop.io.retry.RetryProxy;
import org.apache.hadoop.util.StringUtils;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.Period;
import org.joda.time.chrono.ISOChronology;
import org.skife.jdbi.v2.Folder3;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.PreparedBatch;
import org.skife.jdbi.v2.Query;
import org.skife.jdbi.v2.ResultIterator;
import org.skife.jdbi.v2.exceptions.CallbackFailedException;
import org.skife.jdbi.v2.tweak.HandleCallback;
import org.skife.jdbi.v2.util.ByteArrayMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* Utils class for Druid storage handler.
*/
public final class DruidStorageHandlerUtils {
private DruidStorageHandlerUtils() {
}
private static final Logger LOG = LoggerFactory.getLogger(DruidStorageHandlerUtils.class);
private static final int NUM_RETRIES = 8;
private static final int SECONDS_BETWEEN_RETRIES = 2;
private static final int DEFAULT_FS_BUFFER_SIZE = 1 << 18; // 256KB
private static final int DEFAULT_STREAMING_RESULT_SIZE = 100;
private static final String SMILE_CONTENT_TYPE = "application/x-jackson-smile";
static final String INDEX_ZIP = "index.zip";
private static final String DESCRIPTOR_JSON = "descriptor.json";
private static final Interval
DEFAULT_INTERVAL =
new Interval(new DateTime("1900-01-01", ISOChronology.getInstanceUTC()),
new DateTime("3000-01-01", ISOChronology.getInstanceUTC())).withChronology(ISOChronology.getInstanceUTC());
/**
* Mapper to use to serialize/deserialize Druid objects (JSON).
*/
public static final ObjectMapper JSON_MAPPER = new DefaultObjectMapper();
/**
* Mapper to use to serialize/deserialize Druid objects (SMILE).
*/
public static final ObjectMapper SMILE_MAPPER = new DefaultObjectMapper(new SmileFactory());
private static final int DEFAULT_MAX_TRIES = 10;
static {
// This is needed to initliaze NullHandling for druid without guice.
NullHandling.initializeForTests();
// This is needed for serde of PagingSpec as it uses JacksonInject for injecting SelectQueryConfig
InjectableValues.Std injectableValues = new InjectableValues.Std()
// Expressions macro table used when we deserialize the query from calcite plan
.addValue(ExprMacroTable.class, new ExprMacroTable(ImmutableList
.of(new LikeExprMacro(), new RegexpExtractExprMacro(), new TimestampCeilExprMacro(),
new TimestampExtractExprMacro(), new TimestampFormatExprMacro(), new TimestampParseExprMacro(),
new TimestampShiftExprMacro(), new TimestampFloorExprMacro(), new TrimExprMacro.BothTrimExprMacro(),
new TrimExprMacro.LeftTrimExprMacro(), new TrimExprMacro.RightTrimExprMacro())))
.addValue(ObjectMapper.class, JSON_MAPPER)
.addValue(DataSegment.PruneSpecsHolder.class, DataSegment.PruneSpecsHolder.DEFAULT);
JSON_MAPPER.setInjectableValues(injectableValues);
SMILE_MAPPER.setInjectableValues(injectableValues);
// Register the shard sub type to be used by the mapper
JSON_MAPPER.registerSubtypes(new NamedType(LinearShardSpec.class, "linear"));
JSON_MAPPER.registerSubtypes(new NamedType(NumberedShardSpec.class, "numbered"));
JSON_MAPPER.registerSubtypes(new NamedType(AvroParseSpec.class, "avro"));
SMILE_MAPPER.registerSubtypes(new NamedType(AvroParseSpec.class, "avro"));
JSON_MAPPER.registerSubtypes(new NamedType(AvroStreamInputRowParser.class, "avro_stream"));
SMILE_MAPPER.registerSubtypes(new NamedType(AvroStreamInputRowParser.class, "avro_stream"));
// Register Bloom Filter Serializers
BloomFilterSerializersModule bloomFilterSerializersModule = new BloomFilterSerializersModule();
JSON_MAPPER.registerModule(bloomFilterSerializersModule);
SMILE_MAPPER.registerModule(bloomFilterSerializersModule);
// set the timezone of the object mapper
// THIS IS NOT WORKING workaround is to set it as part of java opts -Duser.timezone="UTC"
JSON_MAPPER.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
// No operation emitter will be used by some internal druid classes.
EmittingLogger.registerEmitter(new ServiceEmitter("druid-hive-indexer",
InetAddress.getLocalHost().getHostName(),
new NoopEmitter()));
} catch (UnknownHostException e) {
throw Throwables.propagate(e);
}
}
/**
* Used by druid to perform IO on indexes.
*/
public static final IndexIO INDEX_IO = new IndexIO(JSON_MAPPER, new DruidProcessingConfig() {
@Override public String getFormatString() {
return "%s-%s";
}
});
/**
* Used by druid to merge indexes.
*/
public static final IndexMergerV9
INDEX_MERGER_V9 =
new IndexMergerV9(JSON_MAPPER, DruidStorageHandlerUtils.INDEX_IO, TmpFileSegmentWriteOutMediumFactory.instance());
/**
* Generic Interner implementation used to read segments object from metadata storage.
*/
private static final Interner<DataSegment> DATA_SEGMENT_INTERNER = Interners.newWeakInterner();
/**
* Method that creates a request for Druid query using SMILE format.
*
* @param address of the host target.
* @param query druid query.
* @return Request object to be submitted.
*/
public static Request createSmileRequest(String address, org.apache.druid.query.Query query) {
try {
return new Request(HttpMethod.POST, new URL(String.format("%s/druid/v2/", "http://" + address))).setContent(
SMILE_MAPPER.writeValueAsBytes(query)).setHeader(HttpHeaders.Names.CONTENT_TYPE, SMILE_CONTENT_TYPE);
} catch (MalformedURLException e) {
LOG.error("URL Malformed address {}", address);
throw new RuntimeException(e);
} catch (JsonProcessingException e) {
LOG.error("can not Serialize the Query [{}]", query.toString());
throw new RuntimeException(e);
}
}
/**
* Method that submits a request to an Http address and retrieves the result.
* The caller is responsible for closing the stream once it finishes consuming it.
*
* @param client Http Client will be used to submit request.
* @param request Http request to be submitted.
* @return response object.
* @throws IOException in case of request IO error.
*/
public static InputStream submitRequest(HttpClient client, Request request) throws IOException {
try {
return client.go(request, new InputStreamResponseHandler()).get();
} catch (ExecutionException | InterruptedException e) {
throw new IOException(e.getCause());
}
}
static StringFullResponseHolder getResponseFromCurrentLeader(HttpClient client, Request request,
StringFullResponseHandler fullResponseHandler) throws ExecutionException, InterruptedException {
StringFullResponseHolder responseHolder = client.go(request, fullResponseHandler).get();
if (HttpResponseStatus.TEMPORARY_REDIRECT.equals(responseHolder.getStatus())) {
String redirectUrlStr = responseHolder.getResponse().headers().get("Location");
LOG.debug("Request[%s] received redirect response to location [%s].", request.getUrl(), redirectUrlStr);
final URL redirectUrl;
try {
redirectUrl = new URL(redirectUrlStr);
} catch (MalformedURLException ex) {
throw new ExecutionException(String
.format("Malformed redirect location is found in response from url[%s], new location[%s].",
request.getUrl(),
redirectUrlStr), ex);
}
responseHolder = client.go(withUrl(request, redirectUrl), fullResponseHandler).get();
}
return responseHolder;
}
private static Request withUrl(Request old, URL url) {
Request req = new Request(old.getMethod(), url);
req.addHeaderValues(old.getHeaders());
if (old.hasContent()) {
req.setContent(old.getContent());
}
return req;
}
/**
* @param taskDir path to the directory containing the segments descriptor info
* the descriptor path will be
* ../workingPath/task_id/{@link DruidStorageHandler#SEGMENTS_DESCRIPTOR_DIR_NAME}/*.json
* @param conf hadoop conf to get the file system
* @return List of DataSegments
* @throws IOException can be for the case we did not produce data.
*/
public static List<DataSegment> getCreatedSegments(Path taskDir, Configuration conf) throws IOException {
ImmutableList.Builder<DataSegment> publishedSegmentsBuilder = ImmutableList.builder();
FileSystem fs = taskDir.getFileSystem(conf);
FileStatus[] fss;
fss = fs.listStatus(taskDir);
for (FileStatus fileStatus : fss) {
final DataSegment segment = JSON_MAPPER.readValue((InputStream) fs.open(fileStatus.getPath()), DataSegment.class);
publishedSegmentsBuilder.add(segment);
}
return publishedSegmentsBuilder.build();
}
/**
* Writes to filesystem serialized form of segment descriptor if an existing file exists it will try to replace it.
*
* @param outputFS filesystem.
* @param segment DataSegment object.
* @param descriptorPath path.
* @throws IOException in case any IO issues occur.
*/
public static void writeSegmentDescriptor(final FileSystem outputFS,
final DataSegment segment,
final Path descriptorPath) throws IOException {
final DataPusher descriptorPusher = (DataPusher) RetryProxy.create(DataPusher.class, () -> {
if (outputFS.exists(descriptorPath)) {
if (!outputFS.delete(descriptorPath, false)) {
throw new IOException(String.format("Failed to delete descriptor at [%s]", descriptorPath));
}
}
try (final OutputStream descriptorOut = outputFS.create(descriptorPath, true, DEFAULT_FS_BUFFER_SIZE)) {
JSON_MAPPER.writeValue(descriptorOut, segment);
descriptorOut.flush();
}
}, RetryPolicies.exponentialBackoffRetry(NUM_RETRIES, SECONDS_BETWEEN_RETRIES, TimeUnit.SECONDS));
descriptorPusher.push();
}
/**
* @param connector SQL metadata connector to the metadata storage
* @param metadataStorageTablesConfig Table config
* @return all the active data sources in the metadata storage
*/
static Collection<String> getAllDataSourceNames(SQLMetadataConnector connector,
final MetadataStorageTablesConfig metadataStorageTablesConfig) {
return connector.getDBI()
.withHandle((HandleCallback<List<String>>) handle -> handle.createQuery(String.format(
"SELECT DISTINCT(datasource) FROM %s WHERE used = true",
metadataStorageTablesConfig.getSegmentsTable()))
.fold(Lists.<String>newArrayList(),
(druidDataSources, stringObjectMap, foldController, statementContext) -> {
druidDataSources.add(MapUtils.getString(stringObjectMap, "datasource"));
return druidDataSources;
}));
}
/**
* @param connector SQL connector to metadata
* @param metadataStorageTablesConfig Tables configuration
* @param dataSource Name of data source
* @return true if the data source was successfully disabled false otherwise
*/
static boolean disableDataSource(SQLMetadataConnector connector,
final MetadataStorageTablesConfig metadataStorageTablesConfig,
final String dataSource) {
try {
if (!getAllDataSourceNames(connector, metadataStorageTablesConfig).contains(dataSource)) {
LOG.warn("Cannot delete data source {}, does not exist", dataSource);
return false;
}
connector.getDBI().withHandle((HandleCallback<Void>) handle -> {
disableDataSourceWithHandle(handle, metadataStorageTablesConfig, dataSource);
return null;
});
} catch (Exception e) {
LOG.error(String.format("Error removing dataSource %s", dataSource), e);
return false;
}
return true;
}
/**
* First computes the segments timeline to accommodate new segments for insert into case.
* Then moves segments to druid deep storage with updated metadata/version.
* ALL IS DONE IN ONE TRANSACTION
*
* @param connector DBI connector to commit
* @param metadataStorageTablesConfig Druid metadata tables definitions
* @param dataSource Druid datasource name
* @param segments List of segments to move and commit to metadata
* @param overwrite if it is an insert overwrite
* @param conf Configuration
* @param dataSegmentPusher segment pusher
* @return List of successfully published Druid segments.
* This list has the updated versions and metadata about segments after move and timeline sorting
* @throws CallbackFailedException in case the connector can not add the segment to the DB.
*/
@SuppressWarnings("unchecked") static List<DataSegment> publishSegmentsAndCommit(final SQLMetadataConnector connector,
final MetadataStorageTablesConfig metadataStorageTablesConfig,
final String dataSource,
final List<DataSegment> segments,
boolean overwrite,
Configuration conf,
DataSegmentPusher dataSegmentPusher) throws CallbackFailedException {
return connector.getDBI().inTransaction((handle, transactionStatus) -> {
// We create the timeline for the existing and new segments
VersionedIntervalTimeline<String, DataSegment> timeline;
if (overwrite) {
// If we are overwriting, we disable existing sources
disableDataSourceWithHandle(handle, metadataStorageTablesConfig, dataSource);
// When overwriting, we just start with empty timeline,
// as we are overwriting segments with new versions
timeline = new VersionedIntervalTimeline<>(Ordering.natural());
} else {
// Append Mode
if (segments.isEmpty()) {
// If there are no new segments, we can just bail out
return Collections.EMPTY_LIST;
}
// Otherwise, build a timeline of existing segments in metadata storage
Interval
indexedInterval =
JodaUtils.umbrellaInterval(segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()));
LOG.info("Building timeline for umbrella Interval [{}]", indexedInterval);
timeline = getTimelineForIntervalWithHandle(handle, dataSource, indexedInterval, metadataStorageTablesConfig);
}
final List<DataSegment> finalSegmentsToPublish = Lists.newArrayList();
for (DataSegment segment : segments) {
List<TimelineObjectHolder<String, DataSegment>> existingChunks = timeline.lookup(segment.getInterval());
if (existingChunks.size() > 1) {
// Not possible to expand since we have more than one chunk with a single segment.
// This is the case when user wants to append a segment with coarser granularity.
// case metadata storage has segments with granularity HOUR and segments to append have DAY granularity.
// Druid shard specs does not support multiple partitions for same interval with different granularity.
throw new IllegalStateException(String.format(
"Cannot allocate new segment for dataSource[%s], interval[%s], already have [%,d] chunks. "
+ "Not possible to append new segment.",
dataSource,
segment.getInterval(),
existingChunks.size()));
}
// Find out the segment with latest version and maximum partition number
SegmentIdWithShardSpec max = null;
final ShardSpec newShardSpec;
final String newVersion;
if (!existingChunks.isEmpty()) {
// Some existing chunk, Find max
TimelineObjectHolder<String, DataSegment> existingHolder = Iterables.getOnlyElement(existingChunks);
for (PartitionChunk<DataSegment> existing : existingHolder.getObject()) {
if (max == null || max.getShardSpec().getPartitionNum() < existing.getObject()
.getShardSpec()
.getPartitionNum()) {
max = SegmentIdWithShardSpec.fromDataSegment(existing.getObject());
}
}
}
if (max == null) {
// No existing shard present in the database, use the current version.
newShardSpec = segment.getShardSpec();
newVersion = segment.getVersion();
} else {
// use version of existing max segment to generate new shard spec
newShardSpec = getNextPartitionShardSpec(max.getShardSpec());
newVersion = max.getVersion();
}
DataSegment
publishedSegment =
publishSegmentWithShardSpec(segment,
newShardSpec,
newVersion,
getPath(segment).getFileSystem(conf),
dataSegmentPusher);
finalSegmentsToPublish.add(publishedSegment);
timeline.add(publishedSegment.getInterval(),
publishedSegment.getVersion(),
publishedSegment.getShardSpec().createChunk(publishedSegment));
}
// Publish new segments to metadata storage
final PreparedBatch
batch =
handle.prepareBatch(String.format(
"INSERT INTO %1$s (id, dataSource, created_date, start, \"end\", partitioned, version, used, payload) "
+ "VALUES (:id, :dataSource, :created_date, :start, :end, :partitioned, :version, :used, :payload)",
metadataStorageTablesConfig.getSegmentsTable())
);
for (final DataSegment segment : finalSegmentsToPublish) {
batch.add(new ImmutableMap.Builder<String, Object>().put("id", segment.getId().toString())
.put("dataSource", segment.getDataSource())
.put("created_date", new DateTime().toString())
.put("start", segment.getInterval().getStart().toString())
.put("end", segment.getInterval().getEnd().toString())
.put("partitioned", !(segment.getShardSpec() instanceof NoneShardSpec))
.put("version", segment.getVersion())
.put("used", true)
.put("payload", JSON_MAPPER.writeValueAsBytes(segment))
.build());
LOG.info("Published {}", segment.getId().toString());
}
batch.execute();
return finalSegmentsToPublish;
});
}
private static void disableDataSourceWithHandle(Handle handle,
MetadataStorageTablesConfig metadataStorageTablesConfig,
String dataSource) {
handle.createStatement(String.format("UPDATE %s SET used=false WHERE dataSource = :dataSource",
metadataStorageTablesConfig.getSegmentsTable())).bind("dataSource", dataSource).execute();
}
/**
* @param connector SQL connector to metadata
* @param metadataStorageTablesConfig Tables configuration
* @param dataSource Name of data source
* @return List of all data segments part of the given data source
*/
static List<DataSegment> getDataSegmentList(final SQLMetadataConnector connector,
final MetadataStorageTablesConfig metadataStorageTablesConfig,
final String dataSource) {
return connector.retryTransaction((handle, status) -> handle.createQuery(String.format(
"SELECT payload FROM %s WHERE dataSource = :dataSource",
metadataStorageTablesConfig.getSegmentsTable()))
.setFetchSize(getStreamingFetchSize(connector))
.bind("dataSource", dataSource)
.map(ByteArrayMapper.FIRST)
.fold(new ArrayList<>(), (Folder3<List<DataSegment>, byte[]>) (accumulator, payload, control, ctx) -> {
try {
final DataSegment segment = DATA_SEGMENT_INTERNER.intern(JSON_MAPPER.readValue(payload, DataSegment.class));
accumulator.add(segment);
return accumulator;
} catch (Exception e) {
throw new SQLException(e.toString());
}
}), 3, DEFAULT_MAX_TRIES);
}
/**
* @param connector SQL DBI connector.
* @return streaming fetch size.
*/
private static int getStreamingFetchSize(SQLMetadataConnector connector) {
if (connector instanceof MySQLConnector) {
return Integer.MIN_VALUE;
}
return DEFAULT_STREAMING_RESULT_SIZE;
}
/**
* @param pushedSegment the pushed data segment object
* @param segmentsDescriptorDir actual directory path for descriptors.
* @return a sanitize file name
*/
public static Path makeSegmentDescriptorOutputPath(DataSegment pushedSegment, Path segmentsDescriptorDir) {
return new Path(segmentsDescriptorDir, String.format("%s.json", pushedSegment.getId().toString().replace(":", "")));
}
public static String createScanAllQuery(String dataSourceName, List<String> columns) throws JsonProcessingException {
final Druids.ScanQueryBuilder scanQueryBuilder = Druids.newScanQueryBuilder();
final List<Interval> intervals = Collections.singletonList(DEFAULT_INTERVAL);
ScanQuery
scanQuery =
scanQueryBuilder.dataSource(dataSourceName).resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
.intervals(new MultipleIntervalSegmentSpec(intervals))
.columns(columns)
.build();
return JSON_MAPPER.writeValueAsString(scanQuery);
}
@Nullable static Boolean getBooleanProperty(Table table, String propertyName) {
String val = getTableProperty(table, propertyName);
if (val == null) {
return null;
}
return Boolean.parseBoolean(val);
}
static boolean getBooleanProperty(Table table, String propertyName, boolean defaultVal) {
Boolean val = getBooleanProperty(table, propertyName);
return val == null ? defaultVal : val;
}
@Nullable static Integer getIntegerProperty(Table table, String propertyName) {
String val = getTableProperty(table, propertyName);
if (val == null) {
return null;
}
try {
return Integer.parseInt(val);
} catch (NumberFormatException e) {
throw new NumberFormatException(String.format("Exception while parsing property[%s] with Value [%s] as Integer",
propertyName,
val));
}
}
static int getIntegerProperty(Table table, String propertyName, int defaultVal) {
Integer val = getIntegerProperty(table, propertyName);
return val == null ? defaultVal : val;
}
@Nullable static Long getLongProperty(Table table, String propertyName) {
String val = getTableProperty(table, propertyName);
if (val == null) {
return null;
}
try {
return Long.parseLong(val);
} catch (NumberFormatException e) {
throw new NumberFormatException(String.format("Exception while parsing property[%s] with Value [%s] as Long",
propertyName,
val));
}
}
@Nullable static Period getPeriodProperty(Table table, String propertyName) {
String val = getTableProperty(table, propertyName);
if (val == null) {
return null;
}
try {
return Period.parse(val);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(String.format("Exception while parsing property[%s] with Value [%s] as Period",
propertyName,
val));
}
}
@Nullable public static List<String> getListProperty(Table table, String propertyName) {
List<String> rv = new ArrayList<>();
String values = getTableProperty(table, propertyName);
if (values == null) {
return null;
}
String[] vals = values.trim().split(",");
for (String val : vals) {
if (org.apache.commons.lang3.StringUtils.isNotBlank(val)) {
rv.add(val);
}
}
return rv;
}
static String getTableProperty(Table table, String propertyName) {
return table.getParameters().get(propertyName);
}
/**
* Simple interface for retry operations.
*/
public interface DataPusher {
void push() throws IOException;
}
// Thanks, HBase Storage handler
@SuppressWarnings("SameParameterValue") static void addDependencyJars(Configuration conf, Class<?>... classes)
throws IOException {
FileSystem localFs = FileSystem.getLocal(conf);
Set<String> jars = new HashSet<>(conf.getStringCollection("tmpjars"));
for (Class<?> clazz : classes) {
if (clazz == null) {
continue;
}
final String path = Utilities.jarFinderGetJar(clazz);
if (path == null) {
throw new RuntimeException("Could not find jar for class " + clazz + " in order to ship it to the cluster.");
}
if (!localFs.exists(new Path(path))) {
throw new RuntimeException("Could not validate jar file " + path + " for class " + clazz);
}
jars.add(path);
}
if (jars.isEmpty()) {
return;
}
//noinspection ToArrayCallWithZeroLengthArrayArgument
conf.set("tmpjars", StringUtils.arrayToString(jars.toArray(new String[jars.size()])));
}
private static VersionedIntervalTimeline<String, DataSegment> getTimelineForIntervalWithHandle(final Handle handle,
final String dataSource,
final Interval interval,
final MetadataStorageTablesConfig dbTables) throws IOException {
Query<Map<String, Object>>
sql =
handle.createQuery(String.format(
"SELECT payload FROM %s WHERE used = true AND dataSource = ? AND start <= ? AND \"end\" >= ?",
dbTables.getSegmentsTable()))
.bind(0, dataSource)
.bind(1, interval.getEnd().toString())
.bind(2, interval.getStart().toString());
final VersionedIntervalTimeline<String, DataSegment> timeline = new VersionedIntervalTimeline<>(Ordering.natural());
try (ResultIterator<byte[]> dbSegments = sql.map(ByteArrayMapper.FIRST).iterator()) {
while (dbSegments.hasNext()) {
final byte[] payload = dbSegments.next();
DataSegment segment = JSON_MAPPER.readValue(payload, DataSegment.class);
timeline.add(segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(segment));
}
}
return timeline;
}
public static DataSegmentPusher createSegmentPusherForDirectory(String segmentDirectory, Configuration configuration)
throws IOException {
final HdfsDataSegmentPusherConfig hdfsDataSegmentPusherConfig = new HdfsDataSegmentPusherConfig();
hdfsDataSegmentPusherConfig.setStorageDirectory(segmentDirectory);
return new HdfsDataSegmentPusher(hdfsDataSegmentPusherConfig, configuration, JSON_MAPPER);
}
private static DataSegment publishSegmentWithShardSpec(DataSegment segment,
ShardSpec shardSpec,
String version,
FileSystem fs,
DataSegmentPusher dataSegmentPusher) throws IOException {
boolean retry = true;
DataSegment.Builder dataSegmentBuilder = new DataSegment.Builder(segment).version(version);
Path finalPath = null;
while (retry) {
retry = false;
dataSegmentBuilder.shardSpec(shardSpec);
final Path intermediatePath = getPath(segment);
finalPath =
new Path(dataSegmentPusher.getPathForHadoop(),
dataSegmentPusher.makeIndexPathName(dataSegmentBuilder.build(), DruidStorageHandlerUtils.INDEX_ZIP));
// Create parent if it does not exist, recreation is not an error
fs.mkdirs(finalPath.getParent());
if (!fs.rename(intermediatePath, finalPath)) {
if (fs.exists(finalPath)) {
// Someone else is also trying to append
shardSpec = getNextPartitionShardSpec(shardSpec);
retry = true;
} else {
throw new IOException(String.format(
"Failed to rename intermediate segment[%s] to final segment[%s] is not present.",
intermediatePath,
finalPath));
}
}
}
DataSegment dataSegment = dataSegmentBuilder.loadSpec(dataSegmentPusher.makeLoadSpec(finalPath.toUri())).build();
writeSegmentDescriptor(fs, dataSegment, new Path(finalPath.getParent(), DruidStorageHandlerUtils.DESCRIPTOR_JSON));
return dataSegment;
}
private static ShardSpec getNextPartitionShardSpec(ShardSpec shardSpec) {
if (shardSpec instanceof LinearShardSpec) {
return new LinearShardSpec(shardSpec.getPartitionNum() + 1);
} else if (shardSpec instanceof NumberedShardSpec) {
return new NumberedShardSpec(shardSpec.getPartitionNum(), ((NumberedShardSpec) shardSpec).getPartitions());
} else {
// Druid only support appending more partitions to Linear and Numbered ShardSpecs.
throw new IllegalStateException(String.format("Cannot expand shard spec [%s]", shardSpec));
}
}
static Path getPath(DataSegment dataSegment) {
return new Path(String.valueOf(Objects.requireNonNull(dataSegment.getLoadSpec()).get("path")));
}
public static GranularitySpec getGranularitySpec(Configuration configuration, Properties tableProperties) {
final String
segmentGranularity =
tableProperties.getProperty(Constants.DRUID_SEGMENT_GRANULARITY) != null ?
tableProperties.getProperty(Constants.DRUID_SEGMENT_GRANULARITY) :
HiveConf.getVar(configuration, HiveConf.ConfVars.HIVE_DRUID_INDEXING_GRANULARITY);
final boolean
rollup =
tableProperties.getProperty(DruidConstants.DRUID_ROLLUP) != null ?
Boolean.parseBoolean(tableProperties.getProperty(Constants.DRUID_SEGMENT_GRANULARITY)) :
HiveConf.getBoolVar(configuration, HiveConf.ConfVars.HIVE_DRUID_ROLLUP);
return new UniformGranularitySpec(Granularity.fromString(segmentGranularity),
Granularity.fromString(tableProperties.getProperty(DruidConstants.DRUID_QUERY_GRANULARITY) == null ?
"NONE" :
tableProperties.getProperty(DruidConstants.DRUID_QUERY_GRANULARITY)),
rollup,
null);
}
public static IndexSpec getIndexSpec(Configuration jc) {
final BitmapSerdeFactory bitmapSerdeFactory;
if ("concise".equals(HiveConf.getVar(jc, HiveConf.ConfVars.HIVE_DRUID_BITMAP_FACTORY_TYPE))) {
bitmapSerdeFactory = new ConciseBitmapSerdeFactory();
} else {
bitmapSerdeFactory = new RoaringBitmapSerdeFactory(true);
}
return new IndexSpec(bitmapSerdeFactory,
IndexSpec.DEFAULT_DIMENSION_COMPRESSION,
IndexSpec.DEFAULT_METRIC_COMPRESSION,
IndexSpec.DEFAULT_LONG_ENCODING);
}
public static Pair<List<DimensionSchema>, AggregatorFactory[]> getDimensionsAndAggregates(List<String> columnNames,
List<TypeInfo> columnTypes) {
// Default, all columns that are not metrics or timestamp, are treated as dimensions
final List<DimensionSchema> dimensions = new ArrayList<>();
ImmutableList.Builder<AggregatorFactory> aggregatorFactoryBuilder = ImmutableList.builder();
for (int i = 0; i < columnTypes.size(); i++) {
final PrimitiveObjectInspector.PrimitiveCategory
primitiveCategory =
((PrimitiveTypeInfo) columnTypes.get(i)).getPrimitiveCategory();
AggregatorFactory af;
switch (primitiveCategory) {
case BYTE:
case SHORT:
case INT:
case LONG:
af = new LongSumAggregatorFactory(columnNames.get(i), columnNames.get(i));
break;
case FLOAT:
af = new FloatSumAggregatorFactory(columnNames.get(i), columnNames.get(i));
break;
case DOUBLE:
af = new DoubleSumAggregatorFactory(columnNames.get(i), columnNames.get(i));
break;
case DECIMAL:
throw new UnsupportedOperationException(String.format("Druid does not support decimal column type cast column "
+ "[%s] to double", columnNames.get(i)));
case TIMESTAMP:
// Granularity column
String tColumnName = columnNames.get(i);
if (!tColumnName.equals(Constants.DRUID_TIMESTAMP_GRANULARITY_COL_NAME)
&& !tColumnName.equals(DruidConstants.DEFAULT_TIMESTAMP_COLUMN)) {
throw new IllegalArgumentException("Dimension "
+ tColumnName
+ " does not have STRING type: "
+ primitiveCategory);
}
continue;
case TIMESTAMPLOCALTZ:
// Druid timestamp column
String tLocalTZColumnName = columnNames.get(i);
if (!tLocalTZColumnName.equals(DruidConstants.DEFAULT_TIMESTAMP_COLUMN)) {
throw new IllegalArgumentException("Dimension "
+ tLocalTZColumnName
+ " does not have STRING type: "
+ primitiveCategory);
}
continue;
default:
// Dimension
String dColumnName = columnNames.get(i);
if (PrimitiveObjectInspectorUtils.getPrimitiveGrouping(primitiveCategory)
!= PrimitiveObjectInspectorUtils.PrimitiveGrouping.STRING_GROUP
&& primitiveCategory != PrimitiveObjectInspector.PrimitiveCategory.BOOLEAN) {
throw new IllegalArgumentException("Dimension "
+ dColumnName
+ " does not have STRING type: "
+ primitiveCategory);
}
dimensions.add(new StringDimensionSchema(dColumnName));
continue;
}
aggregatorFactoryBuilder.add(af);
}
ImmutableList<AggregatorFactory> aggregatorFactories = aggregatorFactoryBuilder.build();
return Pair.of(dimensions, aggregatorFactories.toArray(new AggregatorFactory[0]));
}
// Druid only supports String,Long,Float,Double selectors
private static Set<TypeInfo> druidSupportedTypeInfos =
ImmutableSet.<TypeInfo>of(TypeInfoFactory.stringTypeInfo, TypeInfoFactory.charTypeInfo,
TypeInfoFactory.varcharTypeInfo, TypeInfoFactory.byteTypeInfo, TypeInfoFactory.intTypeInfo,
TypeInfoFactory.longTypeInfo, TypeInfoFactory.shortTypeInfo, TypeInfoFactory.doubleTypeInfo);
private static Set<TypeInfo> stringTypeInfos =
ImmutableSet.<TypeInfo>of(TypeInfoFactory.stringTypeInfo, TypeInfoFactory.charTypeInfo,
TypeInfoFactory.varcharTypeInfo);
public static org.apache.druid.query.Query addDynamicFilters(org.apache.druid.query.Query query,
ExprNodeGenericFuncDesc filterExpr, Configuration conf, boolean resolveDynamicValues) {
List<VirtualColumn> virtualColumns = Arrays.asList(getVirtualColumns(query).getVirtualColumns());
org.apache.druid.query.Query rv = query;
DimFilter joinReductionFilter = toDruidFilter(filterExpr, conf, virtualColumns, resolveDynamicValues);
if (joinReductionFilter != null) {
String type = query.getType();
DimFilter filter = new AndDimFilter(joinReductionFilter, query.getFilter());
switch (type) {
case org.apache.druid.query.Query.TIMESERIES:
rv = Druids.TimeseriesQueryBuilder.copy((TimeseriesQuery) query).filters(filter)
.virtualColumns(VirtualColumns.create(virtualColumns)).build();
break;
case org.apache.druid.query.Query.TOPN:
rv = new TopNQueryBuilder((TopNQuery) query).filters(filter)
.virtualColumns(VirtualColumns.create(virtualColumns)).build();
break;
case org.apache.druid.query.Query.GROUP_BY:
rv = new GroupByQuery.Builder((GroupByQuery) query).setDimFilter(filter)
.setVirtualColumns(VirtualColumns.create(virtualColumns)).build();
break;
case org.apache.druid.query.Query.SCAN:
rv = Druids.ScanQueryBuilder.copy((ScanQuery) query).filters(filter)
.virtualColumns(VirtualColumns.create(virtualColumns)).build();
break;
default:
throw new UnsupportedOperationException("Unsupported Query type " + type);
}
}
return rv;
}
@Nullable private static DimFilter toDruidFilter(ExprNodeDesc filterExpr, Configuration configuration,
List<VirtualColumn> virtualColumns, boolean resolveDynamicValues) {
if (filterExpr == null) {
return null;
}
Class<? extends GenericUDF> genericUDFClass = getGenericUDFClassFromExprDesc(filterExpr);
if (FunctionRegistry.isOpAnd(filterExpr)) {
Iterator<ExprNodeDesc> iterator = filterExpr.getChildren().iterator();
List<DimFilter> delegates = Lists.newArrayList();
while (iterator.hasNext()) {
DimFilter filter = toDruidFilter(iterator.next(), configuration, virtualColumns, resolveDynamicValues);
if (filter != null) {
delegates.add(filter);
}
}
if (!delegates.isEmpty()) {
return new AndDimFilter(delegates);
}
}
if (FunctionRegistry.isOpOr(filterExpr)) {
Iterator<ExprNodeDesc> iterator = filterExpr.getChildren().iterator();
List<DimFilter> delegates = Lists.newArrayList();
while (iterator.hasNext()) {
DimFilter filter = toDruidFilter(iterator.next(), configuration, virtualColumns, resolveDynamicValues);
if (filter != null) {
delegates.add(filter);
}
}
if (!delegates.isEmpty()) {
return new OrDimFilter(delegates);
}
} else if (GenericUDFBetween.class == genericUDFClass) {
List<ExprNodeDesc> child = filterExpr.getChildren();
String col = extractColName(child.get(1), virtualColumns);
if (col != null) {
try {
StringComparator comparator = stringTypeInfos
.contains(child.get(1).getTypeInfo()) ? StringComparators.LEXICOGRAPHIC : StringComparators.NUMERIC;
String lower = evaluate(child.get(2), configuration, resolveDynamicValues);
String upper = evaluate(child.get(3), configuration, resolveDynamicValues);
return new BoundDimFilter(col, lower, upper, false, false, null, null, comparator);
} catch (HiveException e) {
throw new RuntimeException(e);
}
}
} else if (GenericUDFInBloomFilter.class == genericUDFClass) {
List<ExprNodeDesc> child = filterExpr.getChildren();
String col = extractColName(child.get(0), virtualColumns);
if (col != null) {
try {
BloomKFilter bloomFilter = evaluateBloomFilter(child.get(1), configuration, resolveDynamicValues);
return new BloomDimFilter(col, BloomKFilterHolder.fromBloomKFilter(bloomFilter), null);
} catch (HiveException | IOException e) {
throw new RuntimeException(e);
}
}
}
return null;
}
private static String evaluate(ExprNodeDesc desc, Configuration configuration, boolean resolveDynamicValue)
throws HiveException {
ExprNodeEvaluator exprNodeEvaluator = ExprNodeEvaluatorFactory.get(desc, configuration);
if (exprNodeEvaluator instanceof ExprNodeDynamicValueEvaluator && !resolveDynamicValue) {
return desc.getExprStringForExplain();
} else {
return exprNodeEvaluator.evaluate(null).toString();
}
}
private static BloomKFilter evaluateBloomFilter(ExprNodeDesc desc, Configuration configuration,
boolean resolveDynamicValue) throws HiveException, IOException {
if (!resolveDynamicValue) {
// return a dummy bloom filter for explain
return new BloomKFilter(1);
} else {
BytesWritable bw = (BytesWritable) ExprNodeEvaluatorFactory.get(desc, configuration).evaluate(null);
return BloomKFilter.deserialize(ByteBuffer.wrap(bw.getBytes()));
}
}
@Nullable public static String extractColName(ExprNodeDesc expr, List<VirtualColumn> virtualColumns) {
if (!druidSupportedTypeInfos.contains(expr.getTypeInfo())) {
// This column type is currently not supported in druid.(e.g boolean)
// We cannot pass the bloom filter to druid since bloom filter tests for exact object bytes.
return null;
}
if (expr instanceof ExprNodeColumnDesc) {
return ((ExprNodeColumnDesc) expr).getColumn();
}
ExprNodeGenericFuncDesc funcDesc = null;
if (expr instanceof ExprNodeGenericFuncDesc) {
funcDesc = (ExprNodeGenericFuncDesc) expr;
}
if (null == funcDesc) {
return null;
}
GenericUDF udf = funcDesc.getGenericUDF();
// bail out if its not a simple cast expression.
if (funcDesc.getChildren().size() == 1 && funcDesc.getChildren().get(0) instanceof ExprNodeColumnDesc) {
return null;
}
String columnName = ((ExprNodeColumnDesc) (funcDesc.getChildren().get(0))).getColumn();
ValueType targetType = null;
if (udf instanceof GenericUDFBridge) {
Class<? extends UDF> udfClass = ((GenericUDFBridge) udf).getUdfClass();
if (udfClass.equals(UDFToDouble.class)) {
targetType = ValueType.DOUBLE;
} else if (udfClass.equals(UDFToFloat.class)) {
targetType = ValueType.FLOAT;
} else if (udfClass.equals(UDFToLong.class)) {
targetType = ValueType.LONG;
}
} else if (udf instanceof GenericUDFToString) {
targetType = ValueType.STRING;
}
if (targetType == null) {
return null;
}
String virtualColumnExpr = DruidQuery.format("CAST(%s, '%s')", columnName, targetType.toString());
for (VirtualColumn column : virtualColumns) {
if (column instanceof ExpressionVirtualColumn && ((ExpressionVirtualColumn) column).getExpression()
.equals(virtualColumnExpr)) {
// Found an existing virtual column with same expression, no need to add another virtual column
return column.getOutputName();
}
}
Set<String> usedColumnNames = virtualColumns.stream().map(col -> col.getOutputName()).collect(Collectors.toSet());
final String name = SqlValidatorUtil.uniquify("vc", usedColumnNames, SqlValidatorUtil.EXPR_SUGGESTER);
ExpressionVirtualColumn expressionVirtualColumn =
new ExpressionVirtualColumn(name, virtualColumnExpr, targetType, ExprMacroTable.nil());
virtualColumns.add(expressionVirtualColumn);
return name;
}
public static VirtualColumns getVirtualColumns(org.apache.druid.query.Query query) {
String type = query.getType();
switch (type) {
case org.apache.druid.query.Query.TIMESERIES:
return ((TimeseriesQuery) query).getVirtualColumns();
case org.apache.druid.query.Query.TOPN:
return ((TopNQuery) query).getVirtualColumns();
case org.apache.druid.query.Query.GROUP_BY:
return ((GroupByQuery) query).getVirtualColumns();
case org.apache.druid.query.Query.SCAN:
return ((ScanQuery) query).getVirtualColumns();
default:
throw new UnsupportedOperationException("Unsupported Query type " + query);
}
}
@Nullable private static Class<? extends GenericUDF> getGenericUDFClassFromExprDesc(ExprNodeDesc desc) {
if (!(desc instanceof ExprNodeGenericFuncDesc)) {
return null;
}
ExprNodeGenericFuncDesc genericFuncDesc = (ExprNodeGenericFuncDesc) desc;
return genericFuncDesc.getGenericUDF().getClass();
}
}
| apache-2.0 |
rgoldberg/guava | guava/src/com/google/common/collect/ForwardingCollection.java | 8096 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
import java.util.Iterator;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A collection which forwards all its method calls to another collection. Subclasses should
* override one or more methods to modify the behavior of the backing collection as desired per the
* <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p><b>Warning:</b> The methods of {@code ForwardingCollection} forward <b>indiscriminately</b> to
* the methods of the delegate. For example, overriding {@link #add} alone <b>will not</b> change
* the behavior of {@link #addAll}, which can lead to unexpected behavior. In this case, you should
* override {@code addAll} as well, either providing your own implementation, or delegating to the
* provided {@code standardAddAll} method.
*
* <p><b>{@code default} method warning:</b> This class does <i>not</i> forward calls to {@code
* default} methods. Instead, it inherits their default implementations. When those implementations
* invoke methods, they invoke methods on the {@code ForwardingCollection}.
*
* <p>The {@code standard} methods are not guaranteed to be thread-safe, even when all of the
* methods that they depend on are thread-safe.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
* @since 2.0
*/
@GwtCompatible
public abstract class ForwardingCollection<E> extends ForwardingObject implements Collection<E> {
// TODO(lowasser): identify places where thread safety is actually lost
/** Constructor for use by subclasses. */
protected ForwardingCollection() {}
@Override
protected abstract Collection<E> delegate();
@Override
public Iterator<E> iterator() {
return delegate().iterator();
}
@Override
public int size() {
return delegate().size();
}
@CanIgnoreReturnValue
@Override
public boolean removeAll(Collection<?> collection) {
return delegate().removeAll(collection);
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public boolean contains(Object object) {
return delegate().contains(object);
}
@CanIgnoreReturnValue
@Override
public boolean add(E element) {
return delegate().add(element);
}
@CanIgnoreReturnValue
@Override
public boolean remove(Object object) {
return delegate().remove(object);
}
@Override
public boolean containsAll(Collection<?> collection) {
return delegate().containsAll(collection);
}
@CanIgnoreReturnValue
@Override
public boolean addAll(Collection<? extends E> collection) {
return delegate().addAll(collection);
}
@CanIgnoreReturnValue
@Override
public boolean retainAll(Collection<?> collection) {
return delegate().retainAll(collection);
}
@Override
public void clear() {
delegate().clear();
}
@Override
public Object[] toArray() {
return delegate().toArray();
}
@CanIgnoreReturnValue
@Override
public <T> T[] toArray(T[] array) {
return delegate().toArray(array);
}
/**
* A sensible definition of {@link #contains} in terms of {@link #iterator}. If you override
* {@link #iterator}, you may wish to override {@link #contains} to forward to this
* implementation.
*
* @since 7.0
*/
protected boolean standardContains(@Nullable Object object) {
return Iterators.contains(iterator(), object);
}
/**
* A sensible definition of {@link #containsAll} in terms of {@link #contains} . If you override
* {@link #contains}, you may wish to override {@link #containsAll} to forward to this
* implementation.
*
* @since 7.0
*/
protected boolean standardContainsAll(Collection<?> collection) {
return Collections2.containsAllImpl(this, collection);
}
/**
* A sensible definition of {@link #addAll} in terms of {@link #add}. If you override {@link
* #add}, you may wish to override {@link #addAll} to forward to this implementation.
*
* @since 7.0
*/
protected boolean standardAddAll(Collection<? extends E> collection) {
return Iterators.addAll(this, collection.iterator());
}
/**
* A sensible definition of {@link #remove} in terms of {@link #iterator}, using the iterator's
* {@code remove} method. If you override {@link #iterator}, you may wish to override {@link
* #remove} to forward to this implementation.
*
* @since 7.0
*/
protected boolean standardRemove(@Nullable Object object) {
Iterator<E> iterator = iterator();
while (iterator.hasNext()) {
if (Objects.equal(iterator.next(), object)) {
iterator.remove();
return true;
}
}
return false;
}
/**
* A sensible definition of {@link #removeAll} in terms of {@link #iterator}, using the iterator's
* {@code remove} method. If you override {@link #iterator}, you may wish to override {@link
* #removeAll} to forward to this implementation.
*
* @since 7.0
*/
protected boolean standardRemoveAll(Collection<?> collection) {
return Iterators.removeAll(iterator(), collection);
}
/**
* A sensible definition of {@link #retainAll} in terms of {@link #iterator}, using the iterator's
* {@code remove} method. If you override {@link #iterator}, you may wish to override {@link
* #retainAll} to forward to this implementation.
*
* @since 7.0
*/
protected boolean standardRetainAll(Collection<?> collection) {
return Iterators.retainAll(iterator(), collection);
}
/**
* A sensible definition of {@link #clear} in terms of {@link #iterator}, using the iterator's
* {@code remove} method. If you override {@link #iterator}, you may wish to override {@link
* #clear} to forward to this implementation.
*
* @since 7.0
*/
protected void standardClear() {
Iterators.clear(iterator());
}
/**
* A sensible definition of {@link #isEmpty} as {@code !iterator().hasNext}. If you override
* {@link #isEmpty}, you may wish to override {@link #isEmpty} to forward to this implementation.
* Alternately, it may be more efficient to implement {@code isEmpty} as {@code size() == 0}.
*
* @since 7.0
*/
protected boolean standardIsEmpty() {
return !iterator().hasNext();
}
/**
* A sensible definition of {@link #toString} in terms of {@link #iterator}. If you override
* {@link #iterator}, you may wish to override {@link #toString} to forward to this
* implementation.
*
* @since 7.0
*/
protected String standardToString() {
return Collections2.toStringImpl(this);
}
/**
* A sensible definition of {@link #toArray()} in terms of {@link #toArray(Object[])}. If you
* override {@link #toArray(Object[])}, you may wish to override {@link #toArray} to forward to
* this implementation.
*
* @since 7.0
*/
protected Object[] standardToArray() {
Object[] newArray = new Object[size()];
return toArray(newArray);
}
/**
* A sensible definition of {@link #toArray(Object[])} in terms of {@link #size} and {@link
* #iterator}. If you override either of these methods, you may wish to override {@link #toArray}
* to forward to this implementation.
*
* @since 7.0
*/
protected <T> T[] standardToArray(T[] array) {
return ObjectArrays.toArrayImpl(this, array);
}
}
| apache-2.0 |
techkrish/org.ops4j.pax.cdi | pax-cdi-samples/pax-cdi-sample7-service-impl100/src/main/java/org/ops4j/pax/cdi/sample7/impl/RankedServiceImpl100.java | 1073 | /*
* 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.ops4j.pax.cdi.sample7.impl;
import org.ops4j.pax.cdi.api.OsgiServiceProvider;
import org.ops4j.pax.cdi.sample7.api.RankedService;
/**
* Implementation of a RankedService with rank 100
*
* @author Martin Schäfer.
*
*/
@OsgiServiceProvider(ranking = RankedServiceImpl100.RANKING)
public class RankedServiceImpl100 implements RankedService {
static final int RANKING = 100;
@Override
public int getRanking() {
return RANKING;
}
}
| apache-2.0 |
Nimco/sling | bundles/jcr/oak-server/src/test/java/org/apache/sling/jcr/oak/server/it/OakServerTestSupport.java | 7773 | /*
* 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.sling.jcr.oak.server.it;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;
import javax.jcr.observation.ObservationManager;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.testing.paxexam.SlingOptions;
import org.apache.sling.testing.paxexam.TestSupport;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.BundleContext;
import static org.apache.sling.testing.paxexam.SlingOptions.jackrabbitSling;
import static org.apache.sling.testing.paxexam.SlingOptions.scr;
import static org.apache.sling.testing.paxexam.SlingOptions.slingJcr;
import static org.apache.sling.testing.paxexam.SlingOptions.tikaSling;
import static org.apache.sling.testing.paxexam.SlingVersionResolver.SLING_GROUP_ID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.newConfiguration;
public abstract class OakServerTestSupport extends TestSupport {
@Inject
protected SlingRepository slingRepository;
@Inject
protected BundleContext bundleContext;
@Inject
protected SlingRepository repository;
@Inject
protected ResourceResolverFactory resourceResolverFactory;
protected final List<String> toDelete = new LinkedList<String>();
private final AtomicInteger uniqueNameCounter = new AtomicInteger();
protected static final Integer TEST_SCALE = Integer.getInteger("test.scale", 1);
protected class JcrEventsCounter implements EventListener {
private final Session s;
private int jcrEventsCounter;
public JcrEventsCounter() throws RepositoryException {
s = repository.loginAdministrative(null);
final ObservationManager om = s.getWorkspace().getObservationManager();
final int eventTypes = 255; // not sure if that's a recommended value, but common
final boolean deep = true;
final String[] uuid = null;
final String[] nodeTypeNames = new String[]{"mix:language", "sling:Message"};
final boolean noLocal = true;
final String root = "/";
om.addEventListener(this, eventTypes, root, deep, uuid, nodeTypeNames, noLocal);
}
void close() {
s.logout();
}
@Override
public void onEvent(EventIterator it) {
while (it.hasNext()) {
it.nextEvent();
jcrEventsCounter++;
}
}
int get() {
return jcrEventsCounter;
}
}
protected <ItemType extends Item> ItemType deleteAfterTests(ItemType it) throws RepositoryException {
toDelete.add(it.getPath());
return it;
}
/**
* Verify that admin can create and retrieve a node of the specified type.
*
* @return the path of the test node that was created.
*/
protected String assertCreateRetrieveNode(String nodeType) throws RepositoryException {
Session s = repository.loginAdministrative(null);
try {
final Node root = s.getRootNode();
final String name = uniqueName("assertCreateRetrieveNode");
final String propName = "PN_" + name;
final String propValue = "PV_" + name;
final Node child = nodeType == null ? root.addNode(name) : root.addNode(name, nodeType);
child.setProperty(propName, propValue);
child.setProperty("foo", child.getPath());
s.save();
s.logout();
s = repository.loginAdministrative(null);
final Node n = s.getNode("/" + name);
assertNotNull(n);
assertEquals(propValue, n.getProperty(propName).getString());
return n.getPath();
} finally {
s.logout();
}
}
protected String uniqueName(String hint) {
return hint + "_" + uniqueNameCounter.incrementAndGet() + "_" + System.currentTimeMillis();
}
@Configuration
public Option[] configuration() {
return new Option[]{
baseConfiguration(),
launchpad(),
// Sling JCR Oak Server
testBundle("bundle.filename"),
// testing
junitBundles()
};
}
protected Option launchpad() {
SlingOptions.versionResolver.setVersionFromProject(SLING_GROUP_ID, "org.apache.sling.jcr.base");
final String slingHome = String.format("%s/sling", workingDirectory());
final String repositoryHome = String.format("%s/repository", slingHome);
final String localIndexDir = String.format("%s/index", repositoryHome);
return composite(
scr(),
slingJcr(),
jackrabbitSling(),
tikaSling(),
mavenBundle().groupId("org.apache.jackrabbit").artifactId("oak-core").version(SlingOptions.versionResolver),
mavenBundle().groupId("org.apache.jackrabbit").artifactId("oak-commons").version(SlingOptions.versionResolver),
mavenBundle().groupId("org.apache.jackrabbit").artifactId("oak-blob").version(SlingOptions.versionResolver),
mavenBundle().groupId("org.apache.jackrabbit").artifactId("oak-jcr").version(SlingOptions.versionResolver),
mavenBundle().groupId("com.google.guava").artifactId("guava").version(SlingOptions.versionResolver),
mavenBundle().groupId("org.apache.felix").artifactId("org.apache.felix.jaas").version(SlingOptions.versionResolver),
mavenBundle().groupId("org.apache.jackrabbit").artifactId("oak-lucene").version(SlingOptions.versionResolver), // TODO make Oak Lucene optional
mavenBundle().groupId("org.apache.jackrabbit").artifactId("oak-segment").version(SlingOptions.versionResolver),
newConfiguration("org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStoreService")
.put("repository.home", repositoryHome)
.put("name", "Default NodeStore")
.asOption(),
newConfiguration("org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexProviderService")
.put("localIndexDir", localIndexDir)
.asOption(),
newConfiguration("org.apache.sling.resourceresolver.impl.observation.OsgiObservationBridge")
.put("enabled", true)
.asOption()
);
}
}
| apache-2.0 |
djechelon/spring-security | messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java | 9123 | /*
* Copyright 2002-2016 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.security.messaging.context;
import java.security.Principal;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@ExtendWith(MockitoExtension.class)
public class SecurityContextChannelInterceptorTests {
@Mock
MessageChannel channel;
@Mock
MessageHandler handler;
@Mock
Principal principal;
MessageBuilder<String> messageBuilder;
Authentication authentication;
SecurityContextChannelInterceptor interceptor;
AnonymousAuthenticationToken expectedAnonymous;
@BeforeEach
public void setup() {
this.authentication = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
this.messageBuilder = MessageBuilder.withPayload("payload");
this.expectedAnonymous = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
this.interceptor = new SecurityContextChannelInterceptor();
}
@AfterEach
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void constructorNullHeader() {
assertThatIllegalArgumentException().isThrownBy(() -> new SecurityContextChannelInterceptor(null));
}
@Test
public void preSendCustomHeader() {
String headerName = "header";
this.interceptor = new SecurityContextChannelInterceptor(headerName);
this.messageBuilder.setHeader(headerName, this.authentication);
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
}
@Test
public void preSendUserSet() {
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
}
@Test
public void setAnonymousAuthenticationNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.setAnonymousAuthentication(null));
}
@Test
public void preSendUsesCustomAnonymous() {
this.expectedAnonymous = new AnonymousAuthenticationToken("customKey", "customAnonymous",
AuthorityUtils.createAuthorityList("ROLE_CUSTOM"));
this.interceptor.setAnonymousAuthentication(this.expectedAnonymous);
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertAnonymous();
}
// SEC-2845
@Test
public void preSendUserNotAuthentication() {
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.principal);
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertAnonymous();
}
// SEC-2845
@Test
public void preSendUserNotSet() {
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertAnonymous();
}
// SEC-2845
@Test
public void preSendUserNotSetCustomAnonymous() {
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertAnonymous();
}
@Test
public void afterSendCompletion() {
SecurityContextHolder.getContext().setAuthentication(this.authentication);
this.interceptor.afterSendCompletion(this.messageBuilder.build(), this.channel, true, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterSendCompletionNullAuthentication() {
this.interceptor.afterSendCompletion(this.messageBuilder.build(), this.channel, true, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void beforeHandleUserSet() {
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
}
// SEC-2845
@Test
public void beforeHandleUserNotAuthentication() {
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.principal);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertAnonymous();
}
// SEC-2845
@Test
public void beforeHandleUserNotSet() {
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertAnonymous();
}
@Test
public void afterMessageHandledUserNotSet() {
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterMessageHandled() {
SecurityContextHolder.getContext().setAuthentication(this.authentication);
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
// SEC-2829
@Test
public void restoresOriginalContext() {
TestingAuthenticationToken original = new TestingAuthenticationToken("original", "original", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(original);
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(original);
}
/**
* If a user sends a websocket when processing another websocket
*
*/
@Test
public void restoresOriginalContextNestedThreeDeep() {
AnonymousAuthenticationToken anonymous = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_USER"));
TestingAuthenticationToken origional = new TestingAuthenticationToken("original", "origional", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(origional);
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
// start send websocket
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, null);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo(anonymous.getName());
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
// end send websocket
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(origional);
}
private void assertAnonymous() {
Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
assertThat(currentAuthentication).isInstanceOf(AnonymousAuthenticationToken.class);
AnonymousAuthenticationToken anonymous = (AnonymousAuthenticationToken) currentAuthentication;
assertThat(anonymous.getName()).isEqualTo(this.expectedAnonymous.getName());
assertThat(anonymous.getAuthorities()).containsOnlyElementsOf(this.expectedAnonymous.getAuthorities());
assertThat(anonymous.getKeyHash()).isEqualTo(this.expectedAnonymous.getKeyHash());
}
}
| apache-2.0 |
DariusX/camel | core/camel-core/src/test/java/org/apache/camel/component/rest/FromRestConfigurationTest.java | 2881 | /*
* 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.rest;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.FooBar;
import org.apache.camel.spi.Registry;
import org.junit.Test;
public class FromRestConfigurationTest extends FromRestGetTest {
@Override
protected Registry createRegistry() throws Exception {
Registry jndi = super.createRegistry();
jndi.bind("myDummy", new FooBar());
return jndi;
}
@Override
@Test
public void testFromRestModel() throws Exception {
assertEquals("dummy-rest", context.getRestConfiguration().getComponent());
assertEquals("localhost", context.getRestConfiguration().getHost());
assertEquals(9090, context.getRestConfiguration().getPort());
assertEquals("bar", context.getRestConfiguration().getComponentProperties().get("foo"));
assertEquals("stuff", context.getRestConfiguration().getComponentProperties().get("other"));
assertEquals("200", context.getRestConfiguration().getEndpointProperties().get("size"));
assertEquals("1000", context.getRestConfiguration().getConsumerProperties().get("pollTimeout"));
assertEquals("#myDummy", context.getRestConfiguration().getConsumerProperties().get("dummy"));
DummyRestConsumerFactory factory = (DummyRestConsumerFactory)context.getRegistry().lookupByName("dummy-rest");
Object dummy = context.getRegistry().lookupByName("myDummy");
assertSame(dummy, factory.getDummy());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
restConfiguration().component("dummy-rest").host("localhost").port(9090).componentProperty("foo", "bar").componentProperty("other", "stuff")
.endpointProperty("size", "200").consumerProperty("pollTimeout", "1000").consumerProperty("dummy", "#myDummy");
rest("/say/hello").get().to("log:hello");
}
};
}
}
| apache-2.0 |
FasterXML/jackson-core | src/main/java/com/fasterxml/jackson/core/json/async/package-info.java | 126 | /**
* Non-blocking ("async") JSON parser implementation.
*
* @since 2.9
*/
package com.fasterxml.jackson.core.json.async;
| apache-2.0 |
gshlsh17/jredis | core/bench/src/main/java/org/jredis/bench/JRedisJProfileSubject.java | 2083 | /*
* Copyright 2009 Joubin Mohammad Houshyar
*
* 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.jredis.bench;
import org.jredis.JRedis;
import org.jredis.RedisException;
import org.jredis.ri.alphazero.support.Log;
/**
* [TODO: document me!]
*
* @author Joubin Houshyar (alphazero@sensesay.net)
* @version alpha.0, Apr 11, 2009
* @since alpha.0
*
*/
public class JRedisJProfileSubject {
private final JRedis jredis;
public JRedisJProfileSubject (JRedis jredis){
this.jredis = jredis;
}
protected JRedisJProfileSubject () {
jredis = null;
}
/**
* In a tight loop, we execute a few select
* commands that touch the various permutations of
* request complexity, and response type, so that
* we can pinpoint the bottlenecks and the general
* runtime characteristics of the JRedic provider.
* @throws RedisException
*/
public void run () throws RedisException {
Log.log("***** JProfileTestCase ****");
// jredis.auth("jredis").ping().flushall();
int iter = 100000;
String key = "foostring";
String cntrkey = "foocntr";
String listkey = "foolist";
String setkey = "fooset";
byte[] data = "meow".getBytes();
long start = System.currentTimeMillis();
for(Long j=0L; j<iter; j++) {
jredis.incr(cntrkey);
jredis.set(key, data);
jredis.sadd(setkey, data);
jredis.rpush(listkey, data);
}
long delta = System.currentTimeMillis() - start;
float rate = ((float)iter * 1000) / delta;
System.out.format("%d iterations | %d msec | %8.2f /sec \n", iter, delta, rate);
}
}
| apache-2.0 |
amitsela/incubator-beam | runners/google-cloud-dataflow-java/src/main/java/org/apache/beam/runners/dataflow/BatchStatefulParDoOverrides.java | 11297 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.runners.dataflow;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.Iterables;
import java.util.List;
import java.util.Map;
import org.apache.beam.runners.core.construction.ReplacementOutputs;
import org.apache.beam.runners.dataflow.BatchViewOverrides.GroupByKeyAndSortValuesOnly;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.InstantCoder;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.runners.PTransformOverrideFactory;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.GroupByKey;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature;
import org.apache.beam.sdk.transforms.reflect.DoFnSignatures;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.util.WindowingStrategy;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionTuple;
import org.apache.beam.sdk.values.PValue;
import org.apache.beam.sdk.values.TaggedPValue;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.joda.time.Instant;
/**
* {@link PTransformOverrideFactory PTransformOverrideFactories} that expands to correctly implement
* stateful {@link ParDo} using window-unaware {@link GroupByKeyAndSortValuesOnly} to linearize
* processing per key.
*
* <p>This implementation relies on implementation details of the Dataflow runner, specifically
* standard fusion behavior of {@link ParDo} tranforms following a {@link GroupByKey}.
*/
public class BatchStatefulParDoOverrides {
/**
* Returns a {@link PTransformOverrideFactory} that replaces a single-output {@link ParDo} with a
* composite transform specialized for the {@link DataflowRunner}.
*/
public static <K, InputT, OutputT>
PTransformOverrideFactory<
PCollection<KV<K, InputT>>, PCollection<OutputT>,
ParDo.SingleOutput<KV<K, InputT>, OutputT>>
singleOutputOverrideFactory() {
return new SingleOutputOverrideFactory<>();
}
/**
* Returns a {@link PTransformOverrideFactory} that replaces a multi-output
* {@link ParDo} with a composite transform specialized for the {@link DataflowRunner}.
*/
public static <K, InputT, OutputT>
PTransformOverrideFactory<
PCollection<KV<K, InputT>>, PCollectionTuple,
ParDo.MultiOutput<KV<K, InputT>, OutputT>>
multiOutputOverrideFactory() {
return new MultiOutputOverrideFactory<>();
}
private static class SingleOutputOverrideFactory<K, InputT, OutputT>
implements PTransformOverrideFactory<
PCollection<KV<K, InputT>>, PCollection<OutputT>,
ParDo.SingleOutput<KV<K, InputT>, OutputT>> {
@Override
@SuppressWarnings("unchecked")
public PTransform<PCollection<KV<K, InputT>>, PCollection<OutputT>> getReplacementTransform(
ParDo.SingleOutput<KV<K, InputT>, OutputT> originalParDo) {
return new StatefulSingleOutputParDo<>(originalParDo);
}
@Override
public PCollection<KV<K, InputT>> getInput(List<TaggedPValue> inputs, Pipeline p) {
return (PCollection<KV<K, InputT>>) Iterables.getOnlyElement(inputs).getValue();
}
@Override
public Map<PValue, ReplacementOutput> mapOutputs(
List<TaggedPValue> outputs, PCollection<OutputT> newOutput) {
return ReplacementOutputs.singleton(outputs, newOutput);
}
}
private static class MultiOutputOverrideFactory<K, InputT, OutputT>
implements PTransformOverrideFactory<
PCollection<KV<K, InputT>>, PCollectionTuple, ParDo.MultiOutput<KV<K, InputT>, OutputT>> {
@Override
@SuppressWarnings("unchecked")
public PTransform<PCollection<KV<K, InputT>>, PCollectionTuple> getReplacementTransform(
ParDo.MultiOutput<KV<K, InputT>, OutputT> originalParDo) {
return new StatefulMultiOutputParDo<>(originalParDo);
}
@Override
public PCollection<KV<K, InputT>> getInput(List<TaggedPValue> inputs, Pipeline p) {
return (PCollection<KV<K, InputT>>) Iterables.getOnlyElement(inputs).getValue();
}
@Override
public Map<PValue, ReplacementOutput> mapOutputs(
List<TaggedPValue> outputs, PCollectionTuple newOutput) {
return ReplacementOutputs.tagged(outputs, newOutput);
}
}
static class StatefulSingleOutputParDo<K, InputT, OutputT>
extends PTransform<PCollection<KV<K, InputT>>, PCollection<OutputT>> {
private final ParDo.SingleOutput<KV<K, InputT>, OutputT> originalParDo;
StatefulSingleOutputParDo(ParDo.SingleOutput<KV<K, InputT>, OutputT> originalParDo) {
this.originalParDo = originalParDo;
}
ParDo.SingleOutput<KV<K, InputT>, OutputT> getOriginalParDo() {
return originalParDo;
}
@Override
public PCollection<OutputT> expand(PCollection<KV<K, InputT>> input) {
DoFn<KV<K, InputT>, OutputT> fn = originalParDo.getFn();
verifyFnIsStateful(fn);
PTransform<
PCollection<? extends KV<K, Iterable<KV<Instant, WindowedValue<KV<K, InputT>>>>>>,
PCollection<OutputT>>
statefulParDo =
ParDo.of(new BatchStatefulDoFn<>(fn)).withSideInputs(originalParDo.getSideInputs());
return input.apply(new GbkBeforeStatefulParDo<K, InputT>()).apply(statefulParDo);
}
}
static class StatefulMultiOutputParDo<K, InputT, OutputT>
extends PTransform<PCollection<KV<K, InputT>>, PCollectionTuple> {
private final ParDo.MultiOutput<KV<K, InputT>, OutputT> originalParDo;
StatefulMultiOutputParDo(ParDo.MultiOutput<KV<K, InputT>, OutputT> originalParDo) {
this.originalParDo = originalParDo;
}
@Override
public PCollectionTuple expand(PCollection<KV<K, InputT>> input) {
DoFn<KV<K, InputT>, OutputT> fn = originalParDo.getFn();
verifyFnIsStateful(fn);
PTransform<
PCollection<? extends KV<K, Iterable<KV<Instant, WindowedValue<KV<K, InputT>>>>>>,
PCollectionTuple>
statefulParDo =
ParDo.of(new BatchStatefulDoFn<K, InputT, OutputT>(fn))
.withSideInputs(originalParDo.getSideInputs())
.withOutputTags(
originalParDo.getMainOutputTag(), originalParDo.getSideOutputTags());
return input.apply(new GbkBeforeStatefulParDo<K, InputT>()).apply(statefulParDo);
}
public ParDo.MultiOutput<KV<K, InputT>, OutputT> getOriginalParDo() {
return originalParDo;
}
}
static class GbkBeforeStatefulParDo<K, V>
extends PTransform<
PCollection<KV<K, V>>,
PCollection<KV<K, Iterable<KV<Instant, WindowedValue<KV<K, V>>>>>>> {
@Override
public PCollection<KV<K, Iterable<KV<Instant, WindowedValue<KV<K, V>>>>>> expand(
PCollection<KV<K, V>> input) {
WindowingStrategy<?, ?> inputWindowingStrategy = input.getWindowingStrategy();
// A KvCoder is required since this goes through GBK. Further, WindowedValueCoder
// is not registered by default, so we explicitly set the relevant coders.
checkState(
input.getCoder() instanceof KvCoder,
"Input to a %s using state requires a %s, but the coder was %s",
ParDo.class.getSimpleName(),
KvCoder.class.getSimpleName(),
input.getCoder());
KvCoder<K, V> kvCoder = (KvCoder<K, V>) input.getCoder();
Coder<K> keyCoder = kvCoder.getKeyCoder();
Coder<? extends BoundedWindow> windowCoder =
inputWindowingStrategy.getWindowFn().windowCoder();
return input
// Stash the original timestamps, etc, for when it is fed to the user's DoFn
.apply("ReifyWindows", ParDo.of(new ReifyWindowedValueFn<K, V>()))
.setCoder(
KvCoder.of(
keyCoder,
KvCoder.of(InstantCoder.of(), WindowedValue.getFullCoder(kvCoder, windowCoder))))
// Group by key and sort by timestamp, dropping windows as they are reified
.apply(
"PartitionKeys",
new GroupByKeyAndSortValuesOnly<K, Instant, WindowedValue<KV<K, V>>>())
// The GBKO sets the windowing strategy to the global default
.setWindowingStrategyInternal(inputWindowingStrategy);
}
}
/** A key-preserving {@link DoFn} that reifies a windowed value. */
static class ReifyWindowedValueFn<K, V>
extends DoFn<KV<K, V>, KV<K, KV<Instant, WindowedValue<KV<K, V>>>>> {
@ProcessElement
public void processElement(final ProcessContext c, final BoundedWindow window) {
c.output(
KV.of(
c.element().getKey(),
KV.of(
c.timestamp(), WindowedValue.of(c.element(), c.timestamp(), window, c.pane()))));
}
}
/**
* A key-preserving {@link DoFn} that explodes an iterable that has been grouped by key and
* window.
*/
public static class BatchStatefulDoFn<K, V, OutputT>
extends DoFn<KV<K, Iterable<KV<Instant, WindowedValue<KV<K, V>>>>>, OutputT> {
private final DoFn<KV<K, V>, OutputT> underlyingDoFn;
BatchStatefulDoFn(DoFn<KV<K, V>, OutputT> underlyingDoFn) {
this.underlyingDoFn = underlyingDoFn;
}
public DoFn<KV<K, V>, OutputT> getUnderlyingDoFn() {
return underlyingDoFn;
}
@ProcessElement
public void processElement(final ProcessContext c, final BoundedWindow window) {
throw new UnsupportedOperationException(
"BatchStatefulDoFn.ProcessElement should never be invoked");
}
@Override
public TypeDescriptor<OutputT> getOutputTypeDescriptor() {
return underlyingDoFn.getOutputTypeDescriptor();
}
}
private static <InputT, OutputT> void verifyFnIsStateful(DoFn<InputT, OutputT> fn) {
DoFnSignature signature = DoFnSignatures.getSignature(fn.getClass());
// It is still correct to use this without state or timers, but a bad idea.
// Since it is internal it should never be used wrong, so it is OK to crash.
checkState(
signature.usesState() || signature.usesTimers(),
"%s used for %s that does not use state or timers.",
BatchStatefulParDoOverrides.class.getSimpleName(),
ParDo.class.getSimpleName());
}
}
| apache-2.0 |
maropu/spark | common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/protocol/FinalizeShuffleMerge.java | 2575 | /*
* 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.spark.network.shuffle.protocol;
import com.google.common.base.Objects;
import io.netty.buffer.ByteBuf;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.spark.network.protocol.Encoders;
/**
* Request to finalize merge for a given shuffle.
* Returns {@link MergeStatuses}
*
* @since 3.1.0
*/
public class FinalizeShuffleMerge extends BlockTransferMessage {
public final String appId;
public final int shuffleId;
public FinalizeShuffleMerge(
String appId,
int shuffleId) {
this.appId = appId;
this.shuffleId = shuffleId;
}
@Override
protected BlockTransferMessage.Type type() {
return Type.FINALIZE_SHUFFLE_MERGE;
}
@Override
public int hashCode() {
return Objects.hashCode(appId, shuffleId);
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("appId", appId)
.append("shuffleId", shuffleId)
.toString();
}
@Override
public boolean equals(Object other) {
if (other != null && other instanceof FinalizeShuffleMerge) {
FinalizeShuffleMerge o = (FinalizeShuffleMerge) other;
return Objects.equal(appId, o.appId)
&& shuffleId == o.shuffleId;
}
return false;
}
@Override
public int encodedLength() {
return Encoders.Strings.encodedLength(appId) + 4;
}
@Override
public void encode(ByteBuf buf) {
Encoders.Strings.encode(buf, appId);
buf.writeInt(shuffleId);
}
public static FinalizeShuffleMerge decode(ByteBuf buf) {
String appId = Encoders.Strings.decode(buf);
int shuffleId = buf.readInt();
return new FinalizeShuffleMerge(appId, shuffleId);
}
}
| apache-2.0 |
Collaborne/elasticsearch | core/src/main/java/org/elasticsearch/index/indexing/ShardIndexingService.java | 10923 | /*
* 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.indexing;
import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.metrics.CounterMetric;
import org.elasticsearch.common.metrics.MeanMetric;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.shard.AbstractIndexShardComponent;
import org.elasticsearch.index.shard.ShardId;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import static java.util.Collections.emptyMap;
/**
*/
public class ShardIndexingService extends AbstractIndexShardComponent {
private final IndexingSlowLog slowLog;
private final StatsHolder totalStats = new StatsHolder();
private final CopyOnWriteArrayList<IndexingOperationListener> listeners = new CopyOnWriteArrayList<>();
private volatile Map<String, StatsHolder> typesStats = emptyMap();
public ShardIndexingService(ShardId shardId, Settings indexSettings) {
super(shardId, indexSettings);
this.slowLog = new IndexingSlowLog(indexSettings);
}
/**
* Returns the stats, including type specific stats. If the types are null/0 length, then nothing
* is returned for them. If they are set, then only types provided will be returned, or
* <tt>_all</tt> for all types.
*/
public IndexingStats stats(String... types) {
IndexingStats.Stats total = totalStats.stats();
Map<String, IndexingStats.Stats> typesSt = null;
if (types != null && types.length > 0) {
typesSt = new HashMap<>(typesStats.size());
if (types.length == 1 && types[0].equals("_all")) {
for (Map.Entry<String, StatsHolder> entry : typesStats.entrySet()) {
typesSt.put(entry.getKey(), entry.getValue().stats());
}
} else {
for (Map.Entry<String, StatsHolder> entry : typesStats.entrySet()) {
if (Regex.simpleMatch(types, entry.getKey())) {
typesSt.put(entry.getKey(), entry.getValue().stats());
}
}
}
}
return new IndexingStats(total, typesSt);
}
public void addListener(IndexingOperationListener listener) {
listeners.add(listener);
}
public void removeListener(IndexingOperationListener listener) {
listeners.remove(listener);
}
public void throttlingActivated() {
totalStats.setThrottled(true);
}
public void throttlingDeactivated() {
totalStats.setThrottled(false);
}
public Engine.Index preIndex(Engine.Index operation) {
totalStats.indexCurrent.inc();
typeStats(operation.type()).indexCurrent.inc();
for (IndexingOperationListener listener : listeners) {
operation = listener.preIndex(operation);
}
return operation;
}
public void postIndexUnderLock(Engine.Index index) {
for (IndexingOperationListener listener : listeners) {
try {
listener.postIndexUnderLock(index);
} catch (Exception e) {
logger.warn("postIndexUnderLock listener [{}] failed", e, listener);
}
}
}
public void postIndex(Engine.Index index) {
long took = index.endTime() - index.startTime();
totalStats.indexMetric.inc(took);
totalStats.indexCurrent.dec();
StatsHolder typeStats = typeStats(index.type());
typeStats.indexMetric.inc(took);
typeStats.indexCurrent.dec();
slowLog.postIndex(index, took);
for (IndexingOperationListener listener : listeners) {
try {
listener.postIndex(index);
} catch (Exception e) {
logger.warn("postIndex listener [{}] failed", e, listener);
}
}
}
public void postIndex(Engine.Index index, Throwable ex) {
totalStats.indexCurrent.dec();
typeStats(index.type()).indexCurrent.dec();
totalStats.indexFailed.inc();
typeStats(index.type()).indexFailed.inc();
for (IndexingOperationListener listener : listeners) {
try {
listener.postIndex(index, ex);
} catch (Throwable t) {
logger.warn("postIndex listener [{}] failed", t, listener);
}
}
}
public Engine.Delete preDelete(Engine.Delete delete) {
totalStats.deleteCurrent.inc();
typeStats(delete.type()).deleteCurrent.inc();
for (IndexingOperationListener listener : listeners) {
delete = listener.preDelete(delete);
}
return delete;
}
public void postDeleteUnderLock(Engine.Delete delete) {
for (IndexingOperationListener listener : listeners) {
try {
listener.postDeleteUnderLock(delete);
} catch (Exception e) {
logger.warn("postDeleteUnderLock listener [{}] failed", e, listener);
}
}
}
public void postDelete(Engine.Delete delete) {
long took = delete.endTime() - delete.startTime();
totalStats.deleteMetric.inc(took);
totalStats.deleteCurrent.dec();
StatsHolder typeStats = typeStats(delete.type());
typeStats.deleteMetric.inc(took);
typeStats.deleteCurrent.dec();
for (IndexingOperationListener listener : listeners) {
try {
listener.postDelete(delete);
} catch (Exception e) {
logger.warn("postDelete listener [{}] failed", e, listener);
}
}
}
public void postDelete(Engine.Delete delete, Throwable ex) {
totalStats.deleteCurrent.dec();
typeStats(delete.type()).deleteCurrent.dec();
for (IndexingOperationListener listener : listeners) {
try {
listener. postDelete(delete, ex);
} catch (Throwable t) {
logger.warn("postDelete listener [{}] failed", t, listener);
}
}
}
public void noopUpdate(String type) {
totalStats.noopUpdates.inc();
typeStats(type).noopUpdates.inc();
}
public void clear() {
totalStats.clear();
synchronized (this) {
if (!typesStats.isEmpty()) {
MapBuilder<String, StatsHolder> typesStatsBuilder = MapBuilder.newMapBuilder();
for (Map.Entry<String, StatsHolder> typeStats : typesStats.entrySet()) {
if (typeStats.getValue().totalCurrent() > 0) {
typeStats.getValue().clear();
typesStatsBuilder.put(typeStats.getKey(), typeStats.getValue());
}
}
typesStats = typesStatsBuilder.immutableMap();
}
}
}
private StatsHolder typeStats(String type) {
StatsHolder stats = typesStats.get(type);
if (stats == null) {
synchronized (this) {
stats = typesStats.get(type);
if (stats == null) {
stats = new StatsHolder();
typesStats = MapBuilder.newMapBuilder(typesStats).put(type, stats).immutableMap();
}
}
}
return stats;
}
public void onRefreshSettings(Settings settings) {
slowLog.onRefreshSettings(settings);
}
static class StatsHolder {
public final MeanMetric indexMetric = new MeanMetric();
public final MeanMetric deleteMetric = new MeanMetric();
public final CounterMetric indexCurrent = new CounterMetric();
public final CounterMetric indexFailed = new CounterMetric();
public final CounterMetric deleteCurrent = new CounterMetric();
public final CounterMetric noopUpdates = new CounterMetric();
public final CounterMetric throttleTimeMillisMetric = new CounterMetric();
volatile boolean isThrottled = false;
volatile long startOfThrottleNS;
public IndexingStats.Stats stats() {
long currentThrottleNS = 0;
if (isThrottled && startOfThrottleNS != 0) {
currentThrottleNS += System.nanoTime() - startOfThrottleNS;
if (currentThrottleNS < 0) {
// Paranoia (System.nanoTime() is supposed to be monotonic): time slip must have happened, have to ignore this value
currentThrottleNS = 0;
}
}
return new IndexingStats.Stats(
indexMetric.count(), TimeUnit.NANOSECONDS.toMillis(indexMetric.sum()), indexCurrent.count(), indexFailed.count(),
deleteMetric.count(), TimeUnit.NANOSECONDS.toMillis(deleteMetric.sum()), deleteCurrent.count(),
noopUpdates.count(), isThrottled, TimeUnit.MILLISECONDS.toMillis(throttleTimeMillisMetric.count() + TimeValue.nsecToMSec(currentThrottleNS)));
}
void setThrottled(boolean isThrottled) {
if (!this.isThrottled && isThrottled) {
startOfThrottleNS = System.nanoTime();
} else if (this.isThrottled && !isThrottled) {
assert startOfThrottleNS > 0 : "Bad state of startOfThrottleNS";
long throttleTimeNS = System.nanoTime() - startOfThrottleNS;
if (throttleTimeNS >= 0) {
// Paranoia (System.nanoTime() is supposed to be monotonic): time slip may have occurred but never want to add a negative number
throttleTimeMillisMetric.inc(TimeValue.nsecToMSec(throttleTimeNS));
}
}
this.isThrottled = isThrottled;
}
public long totalCurrent() {
return indexCurrent.count() + deleteMetric.count();
}
public void clear() {
indexMetric.clear();
deleteMetric.clear();
}
}
}
| apache-2.0 |
andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/sun/swing/SwingLazyValue.java | 5055 | /*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.swing;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.AccessibleObject;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.swing.UIDefaults;
/**
* SwingLazyValue is a copy of ProxyLazyValue that does not snapshot the
* AccessControlContext or use a doPrivileged to resolve the class name.
* It's intented for use in places in Swing where we need ProxyLazyValue, this
* should never be used in a place where the developer could supply the
* arguments.
*
*/
public class SwingLazyValue implements UIDefaults.LazyValue {
private String className;
private String methodName;
private Object[] args;
public SwingLazyValue(String c) {
this(c, (String)null);
}
public SwingLazyValue(String c, String m) {
this(c, m, null);
}
public SwingLazyValue(String c, Object[] o) {
this(c, null, o);
}
public SwingLazyValue(String c, String m, Object[] o) {
className = c;
methodName = m;
if (o != null) {
args = (Object[])o.clone();
}
}
public Object createValue(final UIDefaults table) {
try {
Class c;
Object cl;
c = Class.forName(className, true, null);
if (methodName != null) {
Class[] types = getClassArray(args);
Method m = c.getMethod(methodName, types);
makeAccessible(m);
return m.invoke(c, args);
} else {
Class[] types = getClassArray(args);
Constructor constructor = c.getConstructor(types);
makeAccessible(constructor);
return constructor.newInstance(args);
}
} catch (Exception e) {
// Ideally we would throw an exception, unfortunately
// often times there are errors as an initial look and
// feel is loaded before one can be switched. Perhaps a
// flag should be added for debugging, so that if true
// the exception would be thrown.
}
return null;
}
private void makeAccessible(final AccessibleObject object) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
object.setAccessible(true);
return null;
}
});
}
private Class[] getClassArray(Object[] args) {
Class[] types = null;
if (args!=null) {
types = new Class[args.length];
for (int i = 0; i< args.length; i++) {
/* PENDING(ges): At present only the primitive types
used are handled correctly; this should eventually
handle all primitive types */
if (args[i] instanceof java.lang.Integer) {
types[i]=Integer.TYPE;
} else if (args[i] instanceof java.lang.Boolean) {
types[i]=Boolean.TYPE;
} else if (args[i] instanceof javax.swing.plaf.ColorUIResource) {
/* PENDING(ges) Currently the Reflection APIs do not
search superclasses of parameters supplied for
constructor/method lookup. Since we only have
one case where this is needed, we substitute
directly instead of adding a massive amount
of mechanism for this. Eventually this will
probably need to handle the general case as well.
*/
types[i]=java.awt.Color.class;
} else {
types[i]=args[i].getClass();
}
}
}
return types;
}
}
| apache-2.0 |
RyanSkraba/beam | sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/CastValidatorTest.java | 4841 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.schemas.transforms;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.schemas.Schema.TypeName;
import org.apache.beam.sdk.testing.UsesSchema;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link Cast.Widening}, {@link Cast.Narrowing}. */
@Category(UsesSchema.class)
@RunWith(JUnit4.class)
public class CastValidatorTest {
public static final Map<TypeName, Number> NUMERICS =
ImmutableMap.<TypeName, Number>builder()
.put(TypeName.BYTE, Byte.valueOf((byte) 42))
.put(TypeName.INT16, Short.valueOf((short) 42))
.put(TypeName.INT32, Integer.valueOf(42))
.put(TypeName.INT64, Long.valueOf(42))
.put(TypeName.FLOAT, Float.valueOf(42))
.put(TypeName.DOUBLE, Double.valueOf(42))
.put(TypeName.DECIMAL, BigDecimal.valueOf(42))
.build();
public static final List<TypeName> NUMERIC_ORDER =
ImmutableList.of(
TypeName.BYTE,
TypeName.INT16,
TypeName.INT32,
TypeName.INT64,
TypeName.FLOAT,
TypeName.DOUBLE,
TypeName.DECIMAL);
@Test
public void testWideningOrder() {
NUMERICS
.keySet()
.forEach(input -> NUMERICS.keySet().forEach(output -> testWideningOrder(input, output)));
}
@Test
public void testCasting() {
NUMERICS
.keySet()
.forEach(input -> NUMERICS.keySet().forEach(output -> testCasting(input, output)));
}
private void testCasting(TypeName inputType, TypeName outputType) {
Object output =
Cast.castValue(NUMERICS.get(inputType), FieldType.of(inputType), FieldType.of(outputType));
assertEquals(NUMERICS.get(outputType), output);
}
@Test
public void testCastingCompleteness() {
boolean all =
NUMERIC_ORDER.stream().filter(TypeName::isNumericType).allMatch(NUMERIC_ORDER::contains);
assertTrue(all);
}
private void testWideningOrder(TypeName input, TypeName output) {
Schema inputSchema = Schema.of(Schema.Field.of("f0", FieldType.of(input)));
Schema outputSchema = Schema.of(Schema.Field.of("f0", FieldType.of(output)));
List<Cast.CompatibilityError> errors = Cast.Widening.of().apply(inputSchema, outputSchema);
if (NUMERIC_ORDER.indexOf(input) <= NUMERIC_ORDER.indexOf(output)) {
assertThat(input + " is before " + output, errors, empty());
} else {
assertThat(input + " is after " + output, errors, not(empty()));
}
}
@Test
public void testWideningNullableToNotNullable() {
Schema input = Schema.of(Schema.Field.nullable("f0", FieldType.INT32));
Schema output = Schema.of(Schema.Field.of("f0", FieldType.INT32));
List<Cast.CompatibilityError> errors = Cast.Widening.of().apply(input, output);
Cast.CompatibilityError expected =
Cast.CompatibilityError.create(
Arrays.asList("f0"), "Can't cast nullable field to non-nullable field");
assertThat(errors, containsInAnyOrder(expected));
}
@Test
public void testNarrowingNullableToNotNullable() {
Schema input = Schema.of(Schema.Field.nullable("f0", FieldType.INT32));
Schema output = Schema.of(Schema.Field.of("f0", FieldType.INT32));
List<Cast.CompatibilityError> errors = Cast.Narrowing.of().apply(input, output);
assertThat(errors, empty());
}
}
| apache-2.0 |
boonproject/boon | boon/src/main/java/org/boon/validation/ValidationException.java | 1961 | /*
* Copyright 2013-2014 Richard M. Hightower
* 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.
*
* __________ _____ __ .__
* \______ \ ____ ____ ____ /\ / \ _____ | | _|__| ____ ____
* | | _// _ \ / _ \ / \ \/ / \ / \\__ \ | |/ / |/ \ / ___\
* | | ( <_> | <_> ) | \ /\ / Y \/ __ \| <| | | \/ /_/ >
* |______ /\____/ \____/|___| / \/ \____|__ (____ /__|_ \__|___| /\___ /
* \/ \/ \/ \/ \/ \//_____/
* ____. ___________ _____ ______________.___.
* | |____ ___ _______ \_ _____/ / _ \ / _____/\__ | |
* | \__ \\ \/ /\__ \ | __)_ / /_\ \ \_____ \ / | |
* /\__| |/ __ \\ / / __ \_ | \/ | \/ \ \____ |
* \________(____ /\_/ (____ / /_______ /\____|__ /_______ / / ______|
* \/ \/ \/ \/ \/ \/
*/
package org.boon.validation;
public class ValidationException extends Exception {
private String field;
public ValidationException( String message, String field ) {
super( message );
this.field = field;
}
public String getField() {
return field;
}
public void setField( String field ) {
this.field = field;
}
} | apache-2.0 |
AndroidX/androidx | wear/wear/src/androidTest/java/androidx/wear/ambient/AmbientModeTestActivity.java | 2031 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.ambient;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
public class AmbientModeTestActivity extends FragmentActivity
implements AmbientMode.AmbientCallbackProvider {
AmbientMode.AmbientController mAmbientController;
boolean mEnterAmbientCalled;
boolean mUpdateAmbientCalled;
boolean mExitAmbientCalled;
boolean mAmbientOffloadInvalidatedCalled;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAmbientController = AmbientMode.attachAmbientSupport(this);
}
@Override
public AmbientMode.AmbientCallback getAmbientCallback() {
return new MyAmbientCallback();
}
private class MyAmbientCallback extends AmbientMode.AmbientCallback {
@Override
public void onEnterAmbient(Bundle ambientDetails) {
mEnterAmbientCalled = true;
}
@Override
public void onUpdateAmbient() {
mUpdateAmbientCalled = true;
}
@Override
public void onExitAmbient() {
mExitAmbientCalled = true;
}
@Override
public void onAmbientOffloadInvalidated() {
mAmbientOffloadInvalidatedCalled = true;
}
}
public AmbientMode.AmbientController getAmbientController() {
return mAmbientController;
}
}
| apache-2.0 |
noobyang/AndroidStudy | opencv/src/main/java/org/opencv/core/Algorithm.java | 2284 | //
// This file is auto-generated. Please don't modify it!
//
package org.opencv.core;
import java.lang.String;
// C++: class Algorithm
//javadoc: Algorithm
public class Algorithm {
protected final long nativeObj;
protected Algorithm(long addr) { nativeObj = addr; }
public long getNativeObjAddr() { return nativeObj; }
// internal usage only
public static Algorithm __fromPtr__(long addr) { return new Algorithm(addr); }
//
// C++: String cv::Algorithm::getDefaultName()
//
//javadoc: Algorithm::getDefaultName()
public String getDefaultName()
{
String retVal = getDefaultName_0(nativeObj);
return retVal;
}
//
// C++: bool cv::Algorithm::empty()
//
//javadoc: Algorithm::empty()
public boolean empty()
{
boolean retVal = empty_0(nativeObj);
return retVal;
}
//
// C++: void cv::Algorithm::clear()
//
//javadoc: Algorithm::clear()
public void clear()
{
clear_0(nativeObj);
return;
}
//
// C++: void cv::Algorithm::read(FileNode fn)
//
// Unknown type 'FileNode' (I), skipping the function
//
// C++: void cv::Algorithm::save(String filename)
//
//javadoc: Algorithm::save(filename)
public void save(String filename)
{
save_0(nativeObj, filename);
return;
}
//
// C++: void cv::Algorithm::write(Ptr_FileStorage fs, String name = String())
//
// Unknown type 'Ptr_FileStorage' (I), skipping the function
@Override
protected void finalize() throws Throwable {
delete(nativeObj);
}
// C++: String cv::Algorithm::getDefaultName()
private static native String getDefaultName_0(long nativeObj);
// C++: bool cv::Algorithm::empty()
private static native boolean empty_0(long nativeObj);
// C++: void cv::Algorithm::clear()
private static native void clear_0(long nativeObj);
// C++: void cv::Algorithm::save(String filename)
private static native void save_0(long nativeObj, String filename);
// native support for java finalize()
private static native void delete(long nativeObj);
}
| apache-2.0 |
karreiro/uberfire | uberfire-organizationalunit-manager/src/main/java/org/guvnor/organizationalunit/manager/client/OrganizationalUnitManagerEntryPoint.java | 1120 | /*
* Copyright 2013 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.guvnor.organizationalunit.manager.client;
import javax.annotation.PostConstruct;
import org.guvnor.organizationalunit.manager.client.resources.OrganizationalUnitManagerResources;
import org.jboss.errai.ioc.client.api.EntryPoint;
/**
* Entry Point for Organizational Manager editor
*/
@EntryPoint
public class OrganizationalUnitManagerEntryPoint {
@PostConstruct
public void startApp() {
OrganizationalUnitManagerResources.INSTANCE.CSS().ensureInjected();
}
}
| apache-2.0 |
rhuss/kubernetes-client | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/DefaultOperationInfo.java | 1538 | /**
* Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.client.dsl.internal;
import io.fabric8.kubernetes.client.OperationInfo;
public class DefaultOperationInfo implements OperationInfo {
private final String kind;
private final String operationType;
private final String name;
private final String namespace;
public DefaultOperationInfo(String kind, String operationType, String name, String namespace) {
this.kind = kind;
this.name = name;
this.namespace = namespace;
this.operationType = operationType;
}
@Override
public String getKind() {
return kind;
}
@Override
public String getName() {
return name;
}
@Override
public String getNamespace() {
return namespace;
}
@Override
public String getOperationType() {
return operationType;
}
@Override
public OperationInfo forOperationType(String type) {
return new DefaultOperationInfo(kind, type, name, namespace);
}
}
| apache-2.0 |
kalaspuffar/pdfbox | pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationSound.java | 2416 | /*
* Copyright 2018 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.interactive.annotation;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.annotation.handlers.PDAppearanceHandler;
import org.apache.pdfbox.pdmodel.interactive.annotation.handlers.PDSoundAppearanceHandler;
/**
*
* @author Paul King
*/
public class PDAnnotationSound extends PDAnnotationMarkup
{
/**
* The type of annotation.
*/
public static final String SUB_TYPE = "Sound";
private PDAppearanceHandler customAppearanceHandler;
public PDAnnotationSound()
{
getCOSObject().setName(COSName.SUBTYPE, SUB_TYPE);
}
/**
* Creates a sound annotation from a COSDictionary, expected to be a correct object definition.
*
* @param field the PDF object to represent as a field.
*/
public PDAnnotationSound(COSDictionary field)
{
super(field);
}
/**
* Set a custom appearance handler for generating the annotations appearance streams.
*
* @param appearanceHandler
*/
public void setCustomAppearanceHandler(PDAppearanceHandler appearanceHandler)
{
customAppearanceHandler = appearanceHandler;
}
@Override
public void constructAppearances()
{
this.constructAppearances(null);
}
@Override
public void constructAppearances(PDDocument document)
{
if (customAppearanceHandler == null)
{
PDSoundAppearanceHandler appearanceHandler = new PDSoundAppearanceHandler(this, document);
appearanceHandler.generateAppearanceStreams();
}
else
{
customAppearanceHandler.generateAppearanceStreams();
}
}
}
| apache-2.0 |
Deepnekroz/kaa | server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/package-info.java | 715 | /**
* Copyright 2014-2016 CyberVision, 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.
*/
/**
* Provides SDK generator service
*/
package org.kaaproject.kaa.server.control.service.sdk; | apache-2.0 |
ThiagoGarciaAlves/intellij-community | platform/lang-impl/src/com/intellij/codeInspection/actions/SilentCodeCleanupAction.java | 3181 | /*
* 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.codeInspection.actions;
import com.intellij.analysis.AnalysisActionUtils;
import com.intellij.analysis.AnalysisScope;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.ex.GlobalInspectionContextBase;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SilentCodeCleanupAction extends AnAction {
public void update(AnActionEvent e) {
Project project = e.getProject();
e.getPresentation().setEnabled(project != null && !DumbService.isDumb(project) && getInspectionScope(e.getDataContext(), project) != null);
}
public void actionPerformed(AnActionEvent e) {
Project project = e.getProject();
if (project == null) return;
AnalysisScope analysisScope = getInspectionScope(e.getDataContext(), project);
if (analysisScope == null)
return;
FileDocumentManager.getInstance().saveAllDocuments();
FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassist.inspect.batch");
runInspections(project, analysisScope);
}
@SuppressWarnings("WeakerAccess")
protected void runInspections(@NotNull Project project, @NotNull AnalysisScope scope) {
InspectionProfile profile = getProfileForSilentCleanup(project);
if (profile == null) {
return;
}
InspectionManager managerEx = InspectionManager.getInstance(project);
GlobalInspectionContextBase globalContext = (GlobalInspectionContextBase) managerEx.createNewGlobalContext(false);
globalContext.codeCleanup(scope, profile, getTemplatePresentation().getText(), null, false);
}
@SuppressWarnings("WeakerAccess")
@Nullable
protected InspectionProfile getProfileForSilentCleanup(@NotNull Project project) {
return InspectionProjectProfileManager.getInstance(project).getCurrentProfile();
}
@Nullable
@SuppressWarnings("WeakerAccess")
protected AnalysisScope getInspectionScope(@NotNull DataContext dataContext, @NotNull Project project) {
return AnalysisActionUtils.getInspectionScope(dataContext, project, false);
}
}
| apache-2.0 |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/ApplicationTest.java | 4044 | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* 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 edu.jhuapl.dorset;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.agents.AgentRequest;
import edu.jhuapl.dorset.agents.AgentResponse;
import edu.jhuapl.dorset.filters.RequestFilter;
import edu.jhuapl.dorset.filters.WakeupRequestFilter;
import edu.jhuapl.dorset.routing.Router;
import edu.jhuapl.dorset.routing.SingleAgentRouter;
public class ApplicationTest {
@Test
public void testProcessWithNoAgents() {
Request request = new Request("test");
Router router = mock(Router.class);
when(router.route(request)).thenReturn(new Agent[0]);
Application app = new Application(router);
Response response = app.process(request);
assertFalse(response.isSuccess());
assertEquals(ResponseStatus.Code.NO_AVAILABLE_AGENT, response.getStatus().getCode());
}
@Test
public void testProcessWithAgentWithResponse() {
Request request = new Request("test");
Agent agent = mock(Agent.class);
when(agent.process((AgentRequest)anyObject())).thenReturn(new AgentResponse("the answer"));
Agent rtn[] = new Agent[1];
rtn[0] = agent;
Router router = mock(Router.class);
when(router.route(request)).thenReturn(rtn);
Application app = new Application(router);
Response response = app.process(request);
assertEquals("the answer", response.getText());
}
@Test
public void testProcessWithAgentWithNoResponse() {
Request request = new Request("test");
Agent agent = mock(Agent.class);
when(agent.process((AgentRequest)anyObject())).thenReturn(null);
Agent rtn[] = new Agent[1];
rtn[0] = agent;
Router router = mock(Router.class);
when(router.route(request)).thenReturn(rtn);
Application app = new Application(router);
Response response = app.process(request);
assertFalse(response.isSuccess());
assertEquals(ResponseStatus.Code.NO_RESPONSE_FROM_AGENT, response.getStatus().getCode());
}
@Test
public void testAddingRequestFilter() {
RequestFilter filter = new WakeupRequestFilter("Dorset");
Agent agent = mock(Agent.class);
when(agent.process((AgentRequest)anyObject())).thenAnswer(new Answer<AgentResponse>() {
@Override
public AgentResponse answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return new AgentResponse(((AgentRequest)args[0]).getText());
}
});
Router router = new SingleAgentRouter(agent);
Application app = new Application(router);
app.addRequestFilter(filter);
Request request = new Request("Dorset test");
Response response = app.process(request);
assertEquals("test", response.getText());
}
@Test
public void testShutdown() {
Router router = mock(Router.class);
Application app = new Application(router);
ShutdownListener listener = mock(ShutdownListener.class);
app.addShutdownListener(listener);
app.shutdown();
verify(listener, times(1)).shutdown();
}
}
| apache-2.0 |
neonbjb/MavInterfaceLib | src/com/MAVLink/Messages/ardupilotmega/msg_roll_pitch_yaw_thrust_setpoint.java | 2911 | // MESSAGE ROLL_PITCH_YAW_THRUST_SETPOINT PACKING
package com.MAVLink.Messages.ardupilotmega;
import com.MAVLink.Messages.MAVLinkMessage;
import com.MAVLink.Messages.MAVLinkPayload;
import com.MAVLink.Messages.MAVLinkPacket;
//import android.util.Log;
/**
* Setpoint in roll, pitch, yaw currently active on the system.
*/
public class msg_roll_pitch_yaw_thrust_setpoint extends MAVLinkMessage{
public static final int MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT = 58;
public static final int MAVLINK_MSG_LENGTH = 20;
private static final long serialVersionUID = MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT;
/**
* Timestamp in milliseconds since system boot
*/
public int time_boot_ms;
/**
* Desired roll angle in radians
*/
public float roll;
/**
* Desired pitch angle in radians
*/
public float pitch;
/**
* Desired yaw angle in radians
*/
public float yaw;
/**
* Collective thrust, normalized to 0 .. 1
*/
public float thrust;
/**
* Generates the payload for a mavlink message for a message of this type
* @return
*/
public MAVLinkPacket pack(){
MAVLinkPacket packet = new MAVLinkPacket();
packet.len = MAVLINK_MSG_LENGTH;
packet.sysid = 255;
packet.compid = 190;
packet.msgid = MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT;
packet.payload.putInt(time_boot_ms);
packet.payload.putFloat(roll);
packet.payload.putFloat(pitch);
packet.payload.putFloat(yaw);
packet.payload.putFloat(thrust);
return packet;
}
/**
* Decode a roll_pitch_yaw_thrust_setpoint message into this class fields
*
* @param payload The message to decode
*/
public void unpack(MAVLinkPayload payload) {
payload.resetIndex();
time_boot_ms = payload.getInt();
roll = payload.getFloat();
pitch = payload.getFloat();
yaw = payload.getFloat();
thrust = payload.getFloat();
}
/**
* Constructor for a new message, just initializes the msgid
*/
public msg_roll_pitch_yaw_thrust_setpoint(){
msgid = MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT;
}
/**
* Constructor for a new message, initializes the message with the payload
* from a mavlink packet
*
*/
public msg_roll_pitch_yaw_thrust_setpoint(MAVLinkPacket mavLinkPacket){
this.sysid = mavLinkPacket.sysid;
this.compid = mavLinkPacket.compid;
this.msgid = MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT;
unpack(mavLinkPacket.payload);
//Log.d("MAVLink", "ROLL_PITCH_YAW_THRUST_SETPOINT");
//Log.d("MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT", toString());
}
/**
* Returns a string with the MSG name and data
*/
public String toString(){
return "MAVLINK_MSG_ID_ROLL_PITCH_YAW_THRUST_SETPOINT -"+" time_boot_ms:"+time_boot_ms+" roll:"+roll+" pitch:"+pitch+" yaw:"+yaw+" thrust:"+thrust+"";
}
}
| apache-2.0 |
zstackorg/zstack | header/src/main/java/org/zstack/header/vm/APISetVmClockTrackMsg.java | 1310 | package org.zstack.header.vm;
import org.springframework.http.HttpMethod;
import org.zstack.header.identity.Action;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
import org.zstack.header.rest.RestRequest;
@Action(category = VmInstanceConstant.ACTION_CATEGORY)
@RestRequest(
path = "/vm-instances/{uuid}/actions",
isAction = true,
method = HttpMethod.PUT,
responseClass = APISetVmClockTrackEvent.class
)
public class APISetVmClockTrackMsg extends APIMessage implements VmInstanceMessage {
@APIParam(resourceType = VmInstanceVO.class, checkAccount = true, operationTarget = true)
private String uuid;
@APIParam(validValues = {"guest", "host"})
private String track;
@Override
public String getVmInstanceUuid() {
return uuid;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getTrack() {
return track;
}
public void setTrack(String track) {
this.track = track;
}
public static APISetVmClockTrackMsg __example__() {
APISetVmClockTrackMsg msg = new APISetVmClockTrackMsg();
msg.uuid = uuid();
msg.track = "guest";
return msg;
}
}
| apache-2.0 |
jprante/elasticsearch-server | server/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSourceParserHelper.java | 4889 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.support;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.AbstractObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.Script;
import org.joda.time.DateTimeZone;
public final class ValuesSourceParserHelper {
static final ParseField TIME_ZONE = new ParseField("time_zone");
private ValuesSourceParserHelper() {} // utility class, no instantiation
public static <T> void declareAnyFields(
AbstractObjectParser<? extends ValuesSourceAggregationBuilder<ValuesSource, ?>, T> objectParser,
boolean scriptable, boolean formattable) {
declareFields(objectParser, scriptable, formattable, false, null);
}
public static <T> void declareNumericFields(
AbstractObjectParser<? extends ValuesSourceAggregationBuilder<ValuesSource.Numeric, ?>, T> objectParser,
boolean scriptable, boolean formattable, boolean timezoneAware) {
declareFields(objectParser, scriptable, formattable, timezoneAware, ValueType.NUMERIC);
}
public static <T> void declareBytesFields(
AbstractObjectParser<? extends ValuesSourceAggregationBuilder<ValuesSource.Bytes, ?>, T> objectParser,
boolean scriptable, boolean formattable) {
declareFields(objectParser, scriptable, formattable, false, ValueType.STRING);
}
public static <T> void declareGeoFields(
AbstractObjectParser<? extends ValuesSourceAggregationBuilder<ValuesSource.GeoPoint, ?>, T> objectParser,
boolean scriptable, boolean formattable) {
declareFields(objectParser, scriptable, formattable, false, ValueType.GEOPOINT);
}
private static <VS extends ValuesSource, T> void declareFields(
AbstractObjectParser<? extends ValuesSourceAggregationBuilder<VS, ?>, T> objectParser,
boolean scriptable, boolean formattable, boolean timezoneAware, ValueType targetValueType) {
objectParser.declareField(ValuesSourceAggregationBuilder::field, XContentParser::text,
new ParseField("field"), ObjectParser.ValueType.STRING);
objectParser.declareField(ValuesSourceAggregationBuilder::missing, XContentParser::objectText,
new ParseField("missing"), ObjectParser.ValueType.VALUE);
objectParser.declareField(ValuesSourceAggregationBuilder::valueType, p -> {
ValueType valueType = ValueType.resolveForScript(p.text());
if (targetValueType != null && valueType.isNotA(targetValueType)) {
throw new ParsingException(p.getTokenLocation(),
"Aggregation [" + objectParser.getName() + "] was configured with an incompatible value type ["
+ valueType + "]. It can only work on value of type ["
+ targetValueType + "]");
}
return valueType;
}, new ParseField("value_type", "valueType"), ObjectParser.ValueType.STRING);
if (formattable) {
objectParser.declareField(ValuesSourceAggregationBuilder::format, XContentParser::text,
new ParseField("format"), ObjectParser.ValueType.STRING);
}
if (scriptable) {
objectParser.declareField(ValuesSourceAggregationBuilder::script,
(parser, context) -> Script.parse(parser),
Script.SCRIPT_PARSE_FIELD, ObjectParser.ValueType.OBJECT_OR_STRING);
}
if (timezoneAware) {
objectParser.declareField(ValuesSourceAggregationBuilder::timeZone, p -> {
if (p.currentToken() == XContentParser.Token.VALUE_STRING) {
return DateTimeZone.forID(p.text());
} else {
return DateTimeZone.forOffsetHours(p.intValue());
}
}, TIME_ZONE, ObjectParser.ValueType.LONG);
}
}
}
| apache-2.0 |
gradle/gradle | subprojects/execution/src/main/java/org/gradle/internal/execution/history/OverlappingOutputs.java | 1269 | /*
* Copyright 2017 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.gradle.internal.execution.history;
public class OverlappingOutputs {
private final String propertyName;
private final String overlappedFilePath;
public OverlappingOutputs(String propertyName, String overlappedFilePath) {
this.propertyName = propertyName;
this.overlappedFilePath = overlappedFilePath;
}
public String getPropertyName() {
return propertyName;
}
public String getOverlappedFilePath() {
return overlappedFilePath;
}
public String toString() {
return String.format("output property '%s' with path '%s'", propertyName, overlappedFilePath);
}
}
| apache-2.0 |
marfer/spring-social-google | spring-social-google/src/main/java/org/springframework/social/google/api/calendar/EventStatus.java | 1403 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.social.google.api.calendar;
import org.springframework.social.google.api.calendar.impl.EventStatusDeserializer;
import org.springframework.social.google.api.impl.ApiEnumSerializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**
* Enumeration representing an event's status.
*
* @author Martin Wink
*/
@JsonSerialize(using=ApiEnumSerializer.class)
@JsonDeserialize(using=EventStatusDeserializer.class)
public enum EventStatus {
/**
* "confirmed" - The event is confirmed. This is the default status.
*/
CONFIRMED,
/**
* "tentative" - The event is tentatively confirmed.
*/
TENTATIVE,
/**
* "cancelled" - The event is cancelled.
*/
CANCELLED
}
| apache-2.0 |
titusfortner/selenium | java/src/org/openqa/selenium/grid/sessionqueue/local/LocalNewSessionQueue.java | 14756 | package org.openqa.selenium.grid.sessionqueue.local;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.openqa.selenium.concurrent.ExecutorServices.shutdownGracefully;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.SessionNotCreatedException;
import org.openqa.selenium.concurrent.GuardedRunnable;
import org.openqa.selenium.events.EventBus;
import org.openqa.selenium.grid.config.Config;
import org.openqa.selenium.grid.data.CreateSessionResponse;
import org.openqa.selenium.grid.data.NewSessionErrorResponse;
import org.openqa.selenium.grid.data.NewSessionRejectedEvent;
import org.openqa.selenium.grid.data.NewSessionRequestEvent;
import org.openqa.selenium.grid.data.RequestId;
import org.openqa.selenium.grid.data.SessionRequest;
import org.openqa.selenium.grid.data.SessionRequestCapability;
import org.openqa.selenium.grid.data.SlotMatcher;
import org.openqa.selenium.grid.data.TraceSessionRequest;
import org.openqa.selenium.grid.distributor.config.DistributorOptions;
import org.openqa.selenium.grid.jmx.JMXHelper;
import org.openqa.selenium.grid.jmx.ManagedAttribute;
import org.openqa.selenium.grid.jmx.ManagedService;
import org.openqa.selenium.grid.log.LoggingOptions;
import org.openqa.selenium.grid.security.Secret;
import org.openqa.selenium.grid.security.SecretOptions;
import org.openqa.selenium.grid.server.EventBusOptions;
import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;
import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;
import org.openqa.selenium.internal.Either;
import org.openqa.selenium.internal.Require;
import org.openqa.selenium.remote.http.Contents;
import org.openqa.selenium.remote.http.HttpResponse;
import org.openqa.selenium.remote.tracing.Span;
import org.openqa.selenium.remote.tracing.TraceContext;
import org.openqa.selenium.remote.tracing.Tracer;
import java.io.Closeable;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* An in-memory implementation of the list of new session requests.
* <p>
* The lifecycle of a request can be described as:
* <ol>
* <li>User adds an item on to the queue using {@link #addToQueue(SessionRequest)}. This
* will block until the request completes in some way.
* <li>After being added, a {@link NewSessionRequestEvent} is fired. Listeners should use
* this as an indication to call {@link #remove(RequestId)} to get the session request.
* <li>If the session request is completed, then {@link #complete(RequestId, Either)} must
* be called. This will not only ensure that {@link #addToQueue(SessionRequest)}
* returns, but will also fire a {@link NewSessionRejectedEvent} if the session was
* rejected. Positive completions of events are assumed to be notified on the event bus
* by other listeners.
* <li>If the request cannot be handled right now, call
* {@link #retryAddToQueue(SessionRequest)} to return the session request to the front
* of the queue.
* </ol>
* <p>
* There is a background thread that will reap {@link SessionRequest}s that have timed out.
* This means that a request can either complete by a listener calling
* {@link #complete(RequestId, Either)} directly, or by being reaped by the thread.
*/
@ManagedService(objectName = "org.seleniumhq.grid:type=SessionQueue,name=LocalSessionQueue",
description = "New session queue")
public class LocalNewSessionQueue extends NewSessionQueue implements Closeable {
private static final String NAME = "Local New Session Queue";
private final EventBus bus;
private final SlotMatcher slotMatcher;
private final Duration requestTimeout;
private final Map<RequestId, Data> requests;
private final Map<RequestId, TraceContext> contexts;
private final Deque<SessionRequest> queue;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName(NAME);
return thread;
});
public LocalNewSessionQueue(
Tracer tracer,
EventBus bus,
SlotMatcher slotMatcher,
Duration retryPeriod,
Duration requestTimeout,
Secret registrationSecret) {
super(tracer, registrationSecret);
this.slotMatcher = Require.nonNull("Slot matcher", slotMatcher);
this.bus = Require.nonNull("Event bus", bus);
Require.nonNegative("Retry period", retryPeriod);
this.requestTimeout = Require.positive("Request timeout", requestTimeout);
this.requests = new ConcurrentHashMap<>();
this.queue = new ConcurrentLinkedDeque<>();
this.contexts = new ConcurrentHashMap<>();
// if retryPeriod is 0, we will schedule timeout checks every 15 seconds
// there is no need to run this more often
long period = retryPeriod.isZero() ? 15000 : retryPeriod.toMillis();
service.scheduleAtFixedRate(
GuardedRunnable.guard(this::timeoutSessions),
retryPeriod.toMillis(),
period, MILLISECONDS);
new JMXHelper().register(this);
}
public static NewSessionQueue create(Config config) {
LoggingOptions loggingOptions = new LoggingOptions(config);
Tracer tracer = loggingOptions.getTracer();
EventBusOptions eventBusOptions = new EventBusOptions(config);
NewSessionQueueOptions newSessionQueueOptions = new NewSessionQueueOptions(config);
SecretOptions secretOptions = new SecretOptions(config);
SlotMatcher slotMatcher = new DistributorOptions(config).getSlotMatcher();
return new LocalNewSessionQueue(
tracer,
eventBusOptions.getEventBus(),
slotMatcher,
newSessionQueueOptions.getSessionRequestRetryInterval(),
newSessionQueueOptions.getSessionRequestTimeout(),
secretOptions.getRegistrationSecret());
}
private void timeoutSessions() {
Instant now = Instant.now();
Lock readLock = lock.readLock();
readLock.lock();
Set<RequestId> ids;
try {
ids = requests.entrySet().stream()
.filter(entry -> isTimedOut(now, entry.getValue()))
.map(Map.Entry::getKey)
.collect(ImmutableSet.toImmutableSet());
} finally {
readLock.unlock();
}
ids.forEach(this::failDueToTimeout);
}
private boolean isTimedOut(Instant now, Data data) {
return data.endTime.isBefore(now);
}
@Override
public HttpResponse addToQueue(SessionRequest request) {
Require.nonNull("New session request", request);
Require.nonNull("Request id", request.getRequestId());
TraceContext context = TraceSessionRequest.extract(tracer, request);
try (Span ignored = context.createSpan("sessionqueue.add_to_queue")) {
contexts.put(request.getRequestId(), context);
Data data = injectIntoQueue(request);
if (isTimedOut(Instant.now(), data)) {
failDueToTimeout(request.getRequestId());
}
Either<SessionNotCreatedException, CreateSessionResponse> result;
try {
if (data.latch.await(requestTimeout.toMillis(), MILLISECONDS)) {
result = data.result;
} else {
result = Either.left(new SessionNotCreatedException("New session request timed out"));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
result = Either.left(new SessionNotCreatedException("Interrupted when creating the session", e));
} catch (RuntimeException e) {
result = Either.left(new SessionNotCreatedException("An error occurred creating the session", e));
}
Lock writeLock = this.lock.writeLock();
writeLock.lock();
try {
requests.remove(request.getRequestId());
queue.remove(request);
} finally {
writeLock.unlock();
}
HttpResponse res = new HttpResponse();
if (result.isRight()) {
res.setContent(Contents.bytes(result.right().getDownstreamEncodedResponse()));
} else {
res.setStatus(HTTP_INTERNAL_ERROR)
.setContent(Contents.asJson(ImmutableMap.of(
"value", ImmutableMap.of("error", "session not created",
"message", result.left().getMessage(),
"stacktrace", result.left().getStackTrace()))));
}
return res;
}
}
@VisibleForTesting
Data injectIntoQueue(SessionRequest request) {
Require.nonNull("Session request", request);
Data data = new Data(request.getEnqueued());
Lock writeLock = lock.writeLock();
writeLock.lock();
try {
requests.put(request.getRequestId(), data);
queue.addLast(request);
} finally {
writeLock.unlock();
}
bus.fire(new NewSessionRequestEvent(request.getRequestId()));
return data;
}
@Override
public boolean retryAddToQueue(SessionRequest request) {
Require.nonNull("New session request", request);
boolean added;
TraceContext context = contexts.getOrDefault(request.getRequestId(), tracer.getCurrentContext());
try (Span ignored = context.createSpan("sessionqueue.retry")) {
Lock writeLock = lock.writeLock();
writeLock.lock();
try {
if (!requests.containsKey(request.getRequestId())) {
return false;
}
if (queue.contains(request)) {
// No need to re-add this
return true;
} else {
added = queue.offerFirst(request);
}
} finally {
writeLock.unlock();
}
if (added) {
bus.fire(new NewSessionRequestEvent(request.getRequestId()));
}
return added;
}
}
@Override
public Optional<SessionRequest> remove(RequestId reqId) {
Require.nonNull("Request ID", reqId);
Lock writeLock = lock.writeLock();
writeLock.lock();
try {
Iterator<SessionRequest> iterator = queue.iterator();
while (iterator.hasNext()) {
SessionRequest req = iterator.next();
if (reqId.equals(req.getRequestId())) {
iterator.remove();
return Optional.of(req);
}
}
return Optional.empty();
} finally {
writeLock.unlock();
}
}
@Override
public Optional<SessionRequest> getNextAvailable(Set<Capabilities> stereotypes) {
Require.nonNull("Stereotypes", stereotypes);
Predicate<Capabilities> matchesStereotype =
caps -> stereotypes.stream().anyMatch(stereotype -> slotMatcher.matches(stereotype, caps));
Lock writeLock = lock.writeLock();
writeLock.lock();
try {
Optional<SessionRequest> maybeRequest =
queue.stream()
.filter(req -> req.getDesiredCapabilities().stream().anyMatch(matchesStereotype))
.findFirst();
maybeRequest.ifPresent(req -> this.remove(req.getRequestId()));
return maybeRequest;
} finally {
writeLock.unlock();
}
}
@Override
public void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result) {
Require.nonNull("New session request", reqId);
Require.nonNull("Result", result);
TraceContext context = contexts.getOrDefault(reqId, tracer.getCurrentContext());
try (Span ignored = context.createSpan("sessionqueue.completed")) {
Lock readLock = lock.readLock();
readLock.lock();
Data data;
try {
data = requests.get(reqId);
} finally {
readLock.unlock();
}
if (data == null) {
return;
}
Lock writeLock = lock.writeLock();
writeLock.lock();
try {
requests.remove(reqId);
queue.removeIf(req -> reqId.equals(req.getRequestId()));
contexts.remove(reqId);
} finally {
writeLock.unlock();
}
if (result.isLeft()) {
bus.fire(new NewSessionRejectedEvent(new NewSessionErrorResponse(reqId, result.left().getMessage())));
}
data.setResult(result);
}
}
@Override
public int clearQueue() {
Lock writeLock = lock.writeLock();
writeLock.lock();
try {
int size = queue.size();
queue.clear();
requests.forEach((reqId, data) -> {
data.setResult(Either.left(new SessionNotCreatedException("Request queue was cleared")));
bus.fire(new NewSessionRejectedEvent(
new NewSessionErrorResponse(reqId, "New session queue was forcibly cleared")));
});
requests.clear();
return size;
} finally {
writeLock.unlock();
}
}
@Override
public List<SessionRequestCapability> getQueueContents() {
Lock readLock = lock.readLock();
readLock.lock();
try {
return queue.stream()
.map(req ->
new SessionRequestCapability(req.getRequestId(), req.getDesiredCapabilities()))
.collect(Collectors.toList());
} finally {
readLock.unlock();
}
}
@ManagedAttribute(name = "NewSessionQueueSize")
public int getQueueSize() {
return queue.size();
}
@Override
public boolean isReady() {
return true;
}
@Override
public void close() throws IOException {
shutdownGracefully(NAME, service);
}
private void failDueToTimeout(RequestId reqId) {
complete(reqId, Either.left(new SessionNotCreatedException("Timed out creating session")));
}
private class Data {
public final Instant endTime;
private final CountDownLatch latch = new CountDownLatch(1);
public Either<SessionNotCreatedException, CreateSessionResponse> result;
private boolean complete;
public Data(Instant enqueued) {
this.endTime = enqueued.plus(requestTimeout);
this.result = Either.left(new SessionNotCreatedException("Session not created"));
}
public synchronized void setResult(Either<SessionNotCreatedException, CreateSessionResponse> result) {
if (complete) {
return;
}
this.result = result;
complete = true;
latch.countDown();
}
}
}
| apache-2.0 |
apache/portals-pluto | pluto-taglib/src/main/java/org/apache/pluto/tags/BasicURLTag.java | 1469 | /*
* 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.pluto.tags;
/**
* Backwards compatibility Pluto 1.0.1 BasicURLTag providing support for old
* Pluto 1.0.x portlet.tld usages.
* <p>
* Although a portlet.tld should not be provided by Portlet Applications
* themselves but "injected" by the target portlet container, fact is many
* have them embedded in the application anyway. This class ensures those
* applications still can use their old portlet.tld.
* </p>
*
* @version $Id$
* @deprecated
*/
public abstract class BasicURLTag extends PortletURLTag168
{
private static final long serialVersionUID = 286L;
public static class TEI extends PortletURLTag168.TEI
{
}
}
| apache-2.0 |
srikalyc/Sql4D | Sql4DCompiler/src/main/java/com/yahoo/sql4d/insert/nodes/RollupSpec.java | 2139 | /**
* Copyright 2014 Yahoo! 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.
* See accompanying LICENSE file.
*/
package com.yahoo.sql4d.insert.nodes;
import com.yahoo.sql4d.query.nodes.AggItem;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Ex: Used in data ingestion.
*"rollupSpec" : {
"aggs": [{
"type" : "count",
"name" : "count"
}, {
"type" : "doubleSum",
"name" : "added",
"fieldName" : "added"
}],
"rowFlushBoundary": 100000,// THIS IS OPTIONAL
"rollupGranularity" : "none"// can also be hour etc. NOTE this is different from segment granularity.
}
*
* @author srikalyan
*/
public class RollupSpec {
public String rollupGranularity = "none";//TODO: Can be hour etc. Validate for other types.
public long rowFlushBoundary = 100000;//TODO:
public List<AggItem> aggs = new ArrayList<>();
@Override
public String toString() {
return String.format(getJson().toString(2));
}
public JSONObject getJson() {
return new JSONObject(getDataMap());
}
public Map<String, Object> getDataMap() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("rowFlushBoundary", rowFlushBoundary);
map.put("rollupGranularity", rollupGranularity);
JSONArray aggsArray = new JSONArray();
for (AggItem aggItem:aggs) {
aggsArray.put(aggItem.getJson());
}
map.put("aggs", aggsArray);
return map;
}
}
| apache-2.0 |
Salaboy/dashbuilder | dashbuilder-client/dashbuilder-common-client/src/main/java/org/dashbuilder/common/client/widgets/slider/view/SliderBarVertical.java | 4123 | package org.dashbuilder.common.client.widgets.slider.view;
import com.google.gwt.event.dom.client.MouseEvent;
import com.google.gwt.user.client.ui.Widget;
import org.dashbuilder.common.client.widgets.slider.presenter.Presenter;
import java.util.ArrayList;
/**
*
* @author kiouri
*
*/
public class SliderBarVertical extends SliderBar{
protected int barWidth, barHeight, dragLeftPosition, scaleHeight;
public SliderBarVertical(Presenter presenter){
super(presenter);
}
public SliderBarVertical(){
super();
}
public int getBarWidth(){
barWidth = getW(drag.getElement());
for (int i = 0; i < orderedWidgets.size(); i++){
if (orderedWidgets.get(i) == scale){
barWidth = Math.max(barWidth, scaleSize);
} else {
barWidth = Math.max(barWidth, getW(orderedWidgets.get(i).getElement()));
}
}
barWidth = Math.max(barWidth, scaleSize);
return barWidth;
}
public void ajustScaleSize(int widgetHeight){
scaleHeight = widgetHeight;
if (less != null) {
for (int i = 0; i < less.size(); i++) {
scaleHeight -= getH(less.get(i).getElement());
}
}
if (more != null) {
for (int i = 0; i < more.size(); i++) {
scaleHeight -= getH(more.get(i).getElement());
}
}
scale.setPixelSize(scaleSize, scaleHeight);
}
public int getAbsMaxLength() {
return scaleHeight - getH(drag.getElement());
}
public void drawScrollBar(int barHeight) {
absPanel.clear();
putWidgetsToAbsPanel();
initVariables(barHeight);
ajustScaleSize(barHeight);
this.setWidth(getBarWidth() + "px");
absPanel.setPixelSize(getBarWidth(), barHeight);
placeWidgets(orderedWidgets);
absPanel.setWidgetPosition(drag, dragLeftPosition, getScaleTop(orderedWidgets));
}
protected void initVariables(int barHeight){
this.barHeight = barHeight;
startPosition = getScaleTop(orderedWidgets);
dragLeftPosition = (getBarWidth() - getW(drag.getElement()))/2;
}
protected int getScaleTop(ArrayList<Widget> widgets){
int sPosition = 0;
for (int i = 0; i < widgets.size(); i++){
if (widgets.get(i) != scale){
sPosition += getH(widgets.get(i).getElement());
} else {
return sPosition;
}
}
return sPosition;
}
protected void placeWidgets(ArrayList<Widget> widgets){
int tmpPosition = 0;
int barWidth = getBarWidth();
for (int i = 0; i < widgets.size(); i++){
if (widgets.get(i) == scale){
absPanel.setWidgetPosition(widgets.get(i), (barWidth - scaleSize)/2, tmpPosition);
} else {
absPanel.setWidgetPosition(widgets.get(i), (barWidth - getW(widgets.get(i).getElement()))/2, tmpPosition);
}
tmpPosition += getH(widgets.get(i).getElement());
}
}
public void setDragPosition(int position){
position = startPosition + position;
absPanel.setWidgetPosition(drag, dragLeftPosition, position);
}
public int getScaleTouchPosition(MouseEvent event) {
return event.getRelativeY(this.getElement()) - startPosition - getH(drag.getElement())/2;
}
public int getDragPosition() {
return absPanel.getWidgetTop(drag) - startPosition;
}
public void putMark(Mark mark, int markPosition) {
int markX = (this.barWidth - mark.getMarkWidth()) / 2;
this.absPanel.add(mark, markX, startPosition + markPosition + getH(drag.getElement())/2);
}
public Presenter.Orientation getOrientation(){
return Presenter.Orientation.VERTICAL;
}
@Override
public void setHeight(String height) {
super.setHeight(height);
if ( this.isAttached()) {
presenter.setBarPixelSize(getH(getElement()));
presenter.processParams();
reDrawMarks();
setValue(getValue());
}
}
/**
* It is not possible to adjust width of vertical sliderbar with help of this method.
* Width of horizontal sliderbar is automatically calculated on base of height of components which are included in widget
*/
@Override
public void setWidth(String width) {
super.setWidth(getBarWidth() + "px");
}
public void setScaleWidget(Widget scaleWidget, int scaleWidth){
super.setScaleWidget(scaleWidget, scaleWidth);
}
}
| apache-2.0 |
hello2009chen/spring-boot | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/DataSourceClosingSpringLiquibase.java | 2026 | /*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.liquibase;
import java.lang.reflect.Method;
import javax.sql.DataSource;
import liquibase.exception.LiquibaseException;
import liquibase.integration.spring.SpringLiquibase;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.util.ReflectionUtils;
/**
* A custom {@link SpringLiquibase} extension that closes the underlying
* {@link DataSource} once the database has been migrated.
*
* @author Andy Wilkinson
* @since 2.0.6
*/
public class DataSourceClosingSpringLiquibase extends SpringLiquibase
implements DisposableBean {
private volatile boolean closeDataSourceOnceMigrated = true;
public void setCloseDataSourceOnceMigrated(boolean closeDataSourceOnceMigrated) {
this.closeDataSourceOnceMigrated = closeDataSourceOnceMigrated;
}
@Override
public void afterPropertiesSet() throws LiquibaseException {
super.afterPropertiesSet();
if (this.closeDataSourceOnceMigrated) {
closeDataSource();
}
}
private void closeDataSource() {
Class<?> dataSourceClass = getDataSource().getClass();
Method closeMethod = ReflectionUtils.findMethod(dataSourceClass, "close");
if (closeMethod != null) {
ReflectionUtils.invokeMethod(closeMethod, getDataSource());
}
}
@Override
public void destroy() throws Exception {
if (!this.closeDataSourceOnceMigrated) {
closeDataSource();
}
}
}
| apache-2.0 |
apache/archiva | archiva-modules/archiva-base/archiva-configuration/archiva-configuration-model/src/main/java/org/apache/archiva/configuration/model/ProxyConnectorRuleConfiguration.java | 3933 | package org.apache.archiva.configuration.model;
/*
* 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.
*/
/**
* Class ProxyConnectorRuleConfiguration.
*
* @version $Revision$ $Date$
*/
@SuppressWarnings( "all" )
public class ProxyConnectorRuleConfiguration
implements java.io.Serializable
{
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
*
* The type if this rule: whiteList, blackList
* etc..
*
*/
private String ruleType;
/**
*
* The pattern for this rule: whiteList, blackList
* etc..
*
*/
private String pattern;
/**
* Field proxyConnectors.
*/
private java.util.List<ProxyConnectorConfiguration> proxyConnectors;
//-----------/
//- Methods -/
//-----------/
/**
* Method addProxyConnector.
*
* @param proxyConnectorConfiguration
*/
public void addProxyConnector( ProxyConnectorConfiguration proxyConnectorConfiguration )
{
getProxyConnectors().add( proxyConnectorConfiguration );
} //-- void addProxyConnector( ProxyConnectorConfiguration )
/**
* Get the pattern for this rule: whiteList, blackList etc..
*
* @return String
*/
public String getPattern()
{
return this.pattern;
} //-- String getPattern()
/**
* Method getProxyConnectors.
*
* @return List
*/
public java.util.List<ProxyConnectorConfiguration> getProxyConnectors()
{
if ( this.proxyConnectors == null )
{
this.proxyConnectors = new java.util.ArrayList<ProxyConnectorConfiguration>();
}
return this.proxyConnectors;
} //-- java.util.List<ProxyConnectorConfiguration> getProxyConnectors()
/**
* Get the type if this rule: whiteList, blackList etc..
*
* @return String
*/
public String getRuleType()
{
return this.ruleType;
} //-- String getRuleType()
/**
* Method removeProxyConnector.
*
* @param proxyConnectorConfiguration
*/
public void removeProxyConnector( ProxyConnectorConfiguration proxyConnectorConfiguration )
{
getProxyConnectors().remove( proxyConnectorConfiguration );
} //-- void removeProxyConnector( ProxyConnectorConfiguration )
/**
* Set the pattern for this rule: whiteList, blackList etc..
*
* @param pattern
*/
public void setPattern( String pattern )
{
this.pattern = pattern;
} //-- void setPattern( String )
/**
* Set associated proxyConnectors configuration.
*
* @param proxyConnectors
*/
public void setProxyConnectors( java.util.List<ProxyConnectorConfiguration> proxyConnectors )
{
this.proxyConnectors = proxyConnectors;
} //-- void setProxyConnectors( java.util.List )
/**
* Set the type if this rule: whiteList, blackList etc..
*
* @param ruleType
*/
public void setRuleType( String ruleType )
{
this.ruleType = ruleType;
} //-- void setRuleType( String )
}
| apache-2.0 |
dkhwangbo/druid | processing/src/test/java/org/apache/druid/query/aggregation/DoubleMinAggregationTest.java | 3980 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.query.aggregation;
import org.apache.druid.segment.ColumnSelectorFactory;
import org.apache.druid.segment.TestHelper;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.nio.ByteBuffer;
/**
*/
public class DoubleMinAggregationTest
{
private DoubleMinAggregatorFactory doubleMinAggFactory;
private ColumnSelectorFactory colSelectorFactory;
private TestDoubleColumnSelectorImpl selector;
private double[] values = {3.5d, 2.7d, 1.1d, 1.3d};
public DoubleMinAggregationTest() throws Exception
{
String aggSpecJson = "{\"type\": \"doubleMin\", \"name\": \"billy\", \"fieldName\": \"nilly\"}";
doubleMinAggFactory = TestHelper.makeJsonMapper().readValue(aggSpecJson, DoubleMinAggregatorFactory.class);
}
@Before
public void setup()
{
selector = new TestDoubleColumnSelectorImpl(values);
colSelectorFactory = EasyMock.createMock(ColumnSelectorFactory.class);
EasyMock.expect(colSelectorFactory.makeColumnValueSelector("nilly")).andReturn(selector);
EasyMock.replay(colSelectorFactory);
}
@Test
public void testDoubleMinAggregator()
{
Aggregator agg = doubleMinAggFactory.factorize(colSelectorFactory);
aggregate(selector, agg);
aggregate(selector, agg);
aggregate(selector, agg);
aggregate(selector, agg);
Assert.assertEquals(values[2], ((Double) agg.get()).doubleValue(), 0.0001);
Assert.assertEquals((long) values[2], agg.getLong());
Assert.assertEquals(values[2], agg.getFloat(), 0.0001);
}
@Test
public void testDoubleMinBufferAggregator()
{
BufferAggregator agg = doubleMinAggFactory.factorizeBuffered(colSelectorFactory);
ByteBuffer buffer = ByteBuffer.wrap(new byte[Double.BYTES + Byte.BYTES]);
agg.init(buffer, 0);
aggregate(selector, agg, buffer, 0);
aggregate(selector, agg, buffer, 0);
aggregate(selector, agg, buffer, 0);
aggregate(selector, agg, buffer, 0);
Assert.assertEquals(values[2], ((Double) agg.get(buffer, 0)).doubleValue(), 0.0001);
Assert.assertEquals((long) values[2], agg.getLong(buffer, 0));
Assert.assertEquals(values[2], agg.getFloat(buffer, 0), 0.0001);
}
@Test
public void testCombine()
{
Assert.assertEquals(1.2d, ((Double) doubleMinAggFactory.combine(1.2, 3.4)).doubleValue(), 0.0001);
}
@Test
public void testEqualsAndHashCode()
{
DoubleMinAggregatorFactory one = new DoubleMinAggregatorFactory("name1", "fieldName1");
DoubleMinAggregatorFactory oneMore = new DoubleMinAggregatorFactory("name1", "fieldName1");
DoubleMinAggregatorFactory two = new DoubleMinAggregatorFactory("name2", "fieldName2");
Assert.assertEquals(one.hashCode(), oneMore.hashCode());
Assert.assertTrue(one.equals(oneMore));
Assert.assertFalse(one.equals(two));
}
private void aggregate(TestDoubleColumnSelectorImpl selector, Aggregator agg)
{
agg.aggregate();
selector.increment();
}
private void aggregate(TestDoubleColumnSelectorImpl selector, BufferAggregator agg, ByteBuffer buff, int position)
{
agg.aggregate(buff, position);
selector.increment();
}
}
| apache-2.0 |
chtyim/cdap | cdap-app-templates/cdap-etl/cdap-etl-batch/src/main/java/co/cask/cdap/etl/batch/ETLBatchApplication.java | 2017 | /*
* Copyright © 2015 Cask Data, 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 co.cask.cdap.etl.batch;
import co.cask.cdap.api.app.AbstractApplication;
import co.cask.cdap.api.schedule.Schedules;
import co.cask.cdap.etl.batch.config.ETLBatchConfig;
import co.cask.cdap.etl.batch.mapreduce.ETLMapReduce;
import co.cask.cdap.etl.batch.spark.ETLSpark;
import com.google.common.base.Joiner;
/**
* ETL Batch Application.
*/
public class ETLBatchApplication extends AbstractApplication<ETLBatchConfig> {
public static final String SCHEDULE_NAME = "etlWorkflow";
public static final String DEFAULT_DESCRIPTION = "Extract-Transform-Load (ETL) Batch Application";
@Override
public void configure() {
ETLBatchConfig config = getConfig();
setDescription(DEFAULT_DESCRIPTION);
switch (config.getEngine()) {
case MAPREDUCE:
addMapReduce(new ETLMapReduce(config));
break;
case SPARK:
addSpark(new ETLSpark(config));
break;
default:
throw new IllegalArgumentException(
String.format("Invalid execution engine '%s'. Must be one of %s.",
config.getEngine(), Joiner.on(',').join(ETLBatchConfig.Engine.values())));
}
addWorkflow(new ETLWorkflow(config));
scheduleWorkflow(Schedules.builder(SCHEDULE_NAME)
.setDescription("ETL Batch schedule")
.createTimeSchedule(config.getSchedule()),
ETLWorkflow.NAME);
}
}
| apache-2.0 |
signed/intellij-community | python/src/com/jetbrains/python/psi/PyUtil.java | 75764 | /*
* 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.jetbrains.python.psi;
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.completion.PrioritizedLookupElement;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.scratch.ScratchFileService;
import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.lang.ASTFactory;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.ApplicationImpl;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.util.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSet;
import com.jetbrains.NotNullPredicate;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.codeInsight.completion.OverwriteEqualsInsertHandler;
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner;
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil;
import com.jetbrains.python.formatter.PyCodeStyleSettings;
import com.jetbrains.python.magicLiteral.PyMagicLiteralTools;
import com.jetbrains.python.psi.impl.PyBuiltinCache;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl;
import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.resolve.QualifiedNameFinder;
import com.jetbrains.python.psi.resolve.RatedResolveResult;
import com.jetbrains.python.psi.stubs.PySetuptoolsNamespaceIndex;
import com.jetbrains.python.psi.types.*;
import com.jetbrains.python.refactoring.classes.PyDependenciesComparator;
import com.jetbrains.python.refactoring.classes.extractSuperclass.PyExtractSuperclassHelper;
import com.jetbrains.python.refactoring.classes.membersManager.PyMemberInfo;
import com.jetbrains.python.sdk.PythonSdkType;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.*;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
import static com.jetbrains.python.psi.PyFunction.Modifier.CLASSMETHOD;
import static com.jetbrains.python.psi.PyFunction.Modifier.STATICMETHOD;
public class PyUtil {
private PyUtil() {
}
@NotNull
public static <T extends PyElement> T[] getAllChildrenOfType(@NotNull PsiElement element, @NotNull Class<T> aClass) {
List<T> result = new SmartList<>();
for (PsiElement child : element.getChildren()) {
if (instanceOf(child, aClass)) {
//noinspection unchecked
result.add((T)child);
}
else {
ContainerUtil.addAll(result, getAllChildrenOfType(child, aClass));
}
}
return ArrayUtil.toObjectArray(result, aClass);
}
/**
* @see PyUtil#flattenedParensAndTuples
*/
protected static List<PyExpression> unfoldParentheses(PyExpression[] targets, List<PyExpression> receiver,
boolean unfoldListLiterals, boolean unfoldStarExpressions) {
// NOTE: this proliferation of instanceofs is not very beautiful. Maybe rewrite using a visitor.
for (PyExpression exp : targets) {
if (exp instanceof PyParenthesizedExpression) {
final PyParenthesizedExpression parenExpr = (PyParenthesizedExpression)exp;
unfoldParentheses(new PyExpression[]{parenExpr.getContainedExpression()}, receiver, unfoldListLiterals, unfoldStarExpressions);
}
else if (exp instanceof PyTupleExpression) {
final PyTupleExpression tupleExpr = (PyTupleExpression)exp;
unfoldParentheses(tupleExpr.getElements(), receiver, unfoldListLiterals, unfoldStarExpressions);
}
else if (exp instanceof PyListLiteralExpression && unfoldListLiterals) {
final PyListLiteralExpression listLiteral = (PyListLiteralExpression)exp;
unfoldParentheses(listLiteral.getElements(), receiver, true, unfoldStarExpressions);
}
else if (exp instanceof PyStarExpression && unfoldStarExpressions) {
unfoldParentheses(new PyExpression[]{((PyStarExpression)exp).getExpression()}, receiver, unfoldListLiterals, true);
}
else if (exp != null) {
receiver.add(exp);
}
}
return receiver;
}
/**
* Flattens the representation of every element in targets, and puts all results together.
* Elements of every tuple nested in target item are brought to the top level: (a, (b, (c, d))) -> (a, b, c, d)
* Typical usage: {@code flattenedParensAndTuples(some_tuple.getExpressions())}.
*
* @param targets target elements.
* @return the list of flattened expressions.
*/
@NotNull
public static List<PyExpression> flattenedParensAndTuples(PyExpression... targets) {
return unfoldParentheses(targets, new ArrayList<>(targets.length), false, false);
}
@NotNull
public static List<PyExpression> flattenedParensAndLists(PyExpression... targets) {
return unfoldParentheses(targets, new ArrayList<>(targets.length), true, true);
}
@NotNull
public static List<PyExpression> flattenedParensAndStars(PyExpression... targets) {
return unfoldParentheses(targets, new ArrayList<>(targets.length), false, true);
}
// Poor man's filter
// TODO: move to a saner place
public static boolean instanceOf(Object obj, Class... possibleClasses) {
if (obj == null || possibleClasses == null) return false;
for (Class cls : possibleClasses) {
if (cls.isInstance(obj)) return true;
}
return false;
}
/**
* Produce a reasonable representation of a PSI element, good for debugging.
*
* @param elt element to represent; nulls and invalid nodes are ok.
* @param cutAtEOL if true, representation stops at nearest EOL inside the element.
* @return the representation.
*/
@NotNull
@NonNls
public static String getReadableRepr(PsiElement elt, final boolean cutAtEOL) {
if (elt == null) return "null!";
ASTNode node = elt.getNode();
if (node == null) {
return "null";
}
else {
String s = node.getText();
int cut_pos;
if (cutAtEOL) {
cut_pos = s.indexOf('\n');
}
else {
cut_pos = -1;
}
if (cut_pos < 0) cut_pos = s.length();
return s.substring(0, Math.min(cut_pos, s.length()));
}
}
@Nullable
public static PyClass getContainingClassOrSelf(final PsiElement element) {
PsiElement current = element;
while (current != null && !(current instanceof PyClass)) {
current = current.getParent();
}
return (PyClass)current;
}
/**
* @param element for which to obtain the file
* @return PyFile, or null, if there's no containing file, or it is not a PyFile.
*/
@Nullable
public static PyFile getContainingPyFile(PyElement element) {
final PsiFile containingFile = element.getContainingFile();
return containingFile instanceof PyFile ? (PyFile)containingFile : null;
}
/**
* Shows an information balloon in a reasonable place at the top right of the window.
*
* @param project our project
* @param message the text, HTML markup allowed
* @param messageType message type, changes the icon and the background.
*/
// TODO: move to a better place
public static void showBalloon(Project project, String message, MessageType messageType) {
// ripped from com.intellij.openapi.vcs.changes.ui.ChangesViewBalloonProblemNotifier
final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
if (frame == null) return;
final JComponent component = frame.getRootPane();
if (component == null) return;
final Rectangle rect = component.getVisibleRect();
final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
final RelativePoint point = new RelativePoint(component, p);
JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(), messageType.getPopupBackground(), null)
.setShowCallout(false).setCloseButtonEnabled(true)
.createBalloon().show(point, Balloon.Position.atLeft);
}
@NonNls
/**
* Returns a quoted string representation, or "null".
*/
public static String nvl(Object s) {
if (s != null) {
return "'" + s.toString() + "'";
}
else {
return "null";
}
}
/**
* Adds an item into a comma-separated list in a PSI tree. E.g. can turn "foo, bar" into "foo, bar, baz", adding commas as needed.
*
* @param parent the element to represent the list; we're adding a child to it.
* @param newItem the element we're inserting (the "baz" in the example).
* @param beforeThis node to mark the insertion point inside the list; must belong to a child of target. Set to null to add first element.
* @param isFirst true if we don't need a comma before the element we're adding.
* @param isLast true if we don't need a comma after the element we're adding.
*/
public static void addListNode(PsiElement parent, PsiElement newItem, ASTNode beforeThis,
boolean isFirst, boolean isLast, boolean addWhitespace) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(parent)) {
return;
}
ASTNode node = parent.getNode();
assert node != null;
ASTNode itemNode = newItem.getNode();
assert itemNode != null;
Project project = parent.getProject();
PyElementGenerator gen = PyElementGenerator.getInstance(project);
if (!isFirst) node.addChild(gen.createComma(), beforeThis);
node.addChild(itemNode, beforeThis);
if (!isLast) node.addChild(gen.createComma(), beforeThis);
if (addWhitespace) node.addChild(ASTFactory.whitespace(" "), beforeThis);
}
/**
* Collects superclasses of a class all the way up the inheritance chain. The order is <i>not</i> necessarily the MRO.
*/
@NotNull
public static List<PyClass> getAllSuperClasses(@NotNull PyClass pyClass) {
List<PyClass> superClasses = new ArrayList<>();
for (PyClass ancestor : pyClass.getAncestorClasses(null)) {
if (!PyNames.TYPES_INSTANCE_TYPE.equals(ancestor.getQualifiedName())) {
superClasses.add(ancestor);
}
}
return superClasses;
}
// TODO: move to a more proper place?
/**
* Determine the type of a special attribute. Currently supported: {@code __class__} and {@code __dict__}.
*
* @param ref reference to a possible attribute; only qualified references make sense.
* @return type, or null (if type cannot be determined, reference is not to a known attribute, etc.)
*/
@Nullable
public static PyType getSpecialAttributeType(@Nullable PyReferenceExpression ref, TypeEvalContext context) {
if (ref != null) {
PyExpression qualifier = ref.getQualifier();
if (qualifier != null) {
String attr_name = ref.getReferencedName();
if (PyNames.__CLASS__.equals(attr_name)) {
PyType qualifierType = context.getType(qualifier);
if (qualifierType instanceof PyClassType) {
return new PyClassTypeImpl(((PyClassType)qualifierType).getPyClass(), true); // always as class, never instance
}
}
else if (PyNames.DICT.equals(attr_name)) {
PyType qualifierType = context.getType(qualifier);
if (qualifierType instanceof PyClassType && ((PyClassType)qualifierType).isDefinition()) {
return PyBuiltinCache.getInstance(ref).getDictType();
}
}
}
}
return null;
}
/**
* Makes sure that 'thing' is not null; else throws an {@link IncorrectOperationException}.
*
* @param thing what we check.
* @return thing, if not null.
*/
@NotNull
public static <T> T sure(T thing) {
if (thing == null) throw new IncorrectOperationException();
return thing;
}
/**
* Makes sure that the 'thing' is true; else throws an {@link IncorrectOperationException}.
*
* @param thing what we check.
*/
public static void sure(boolean thing) {
if (!thing) throw new IncorrectOperationException();
}
public static boolean isAttribute(PyTargetExpression ex) {
return isInstanceAttribute(ex) || isClassAttribute(ex);
}
public static boolean isInstanceAttribute(PyExpression target) {
if (!(target instanceof PyTargetExpression)) {
return false;
}
final ScopeOwner owner = ScopeUtil.getScopeOwner(target);
if (owner instanceof PyFunction) {
final PyFunction method = (PyFunction)owner;
if (method.getContainingClass() != null) {
if (method.getStub() != null) {
return true;
}
final PyParameter[] params = method.getParameterList().getParameters();
if (params.length > 0) {
final PyTargetExpression targetExpr = (PyTargetExpression)target;
final PyExpression qualifier = targetExpr.getQualifier();
return qualifier != null && qualifier.getText().equals(params[0].getName());
}
}
}
return false;
}
public static boolean isClassAttribute(PsiElement element) {
return element instanceof PyTargetExpression && ScopeUtil.getScopeOwner(element) instanceof PyClass;
}
public static boolean isIfNameEqualsMain(PyIfStatement ifStatement) {
final PyExpression condition = ifStatement.getIfPart().getCondition();
return isNameEqualsMain(condition);
}
private static boolean isNameEqualsMain(PyExpression condition) {
if (condition instanceof PyParenthesizedExpression) {
return isNameEqualsMain(((PyParenthesizedExpression)condition).getContainedExpression());
}
if (condition instanceof PyBinaryExpression) {
PyBinaryExpression binaryExpression = (PyBinaryExpression)condition;
if (binaryExpression.getOperator() == PyTokenTypes.OR_KEYWORD) {
return isNameEqualsMain(binaryExpression.getLeftExpression()) || isNameEqualsMain(binaryExpression.getRightExpression());
}
final PyExpression rhs = binaryExpression.getRightExpression();
return binaryExpression.getOperator() == PyTokenTypes.EQEQ &&
binaryExpression.getLeftExpression().getText().equals(PyNames.NAME) &&
rhs != null && rhs.getText().contains("__main__");
}
return false;
}
/**
* Searches for a method wrapping given element.
*
* @param start element presumably inside a method
* @param deep if true, allow 'start' to be inside functions nested in a method; else, 'start' must be directly inside a method.
* @return if not 'deep', [0] is the method and [1] is the class; if 'deep', first several elements may be the nested functions,
* the last but one is the method, and the last is the class.
*/
@Nullable
public static List<PsiElement> searchForWrappingMethod(PsiElement start, boolean deep) {
PsiElement seeker = start;
List<PsiElement> ret = new ArrayList<>(2);
while (seeker != null) {
PyFunction func = PsiTreeUtil.getParentOfType(seeker, PyFunction.class, true, PyClass.class);
if (func != null) {
PyClass cls = func.getContainingClass();
if (cls != null) {
ret.add(func);
ret.add(cls);
return ret;
}
else if (deep) {
ret.add(func);
seeker = func;
}
else {
return null; // no immediate class
}
}
else {
return null; // no function
}
}
return null;
}
public static boolean inSameFile(@NotNull PsiElement e1, @NotNull PsiElement e2) {
final PsiFile f1 = e1.getContainingFile();
final PsiFile f2 = e2.getContainingFile();
if (f1 == null || f2 == null) {
return false;
}
return f1 == f2;
}
public static boolean onSameLine(@NotNull PsiElement e1, @NotNull PsiElement e2) {
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(e1.getProject());
final Document document = documentManager.getDocument(e1.getContainingFile());
if (document == null || document != documentManager.getDocument(e2.getContainingFile())) {
return false;
}
return document.getLineNumber(e1.getTextOffset()) == document.getLineNumber(e2.getTextOffset());
}
public static boolean isTopLevel(@NotNull PsiElement element) {
if (element instanceof StubBasedPsiElement) {
final StubElement stub = ((StubBasedPsiElement)element).getStub();
if (stub != null) {
final StubElement parentStub = stub.getParentStub();
if (parentStub != null) {
return parentStub.getPsi() instanceof PsiFile;
}
}
}
return ScopeUtil.getScopeOwner(element) instanceof PsiFile;
}
public static void deletePycFiles(String pyFilePath) {
if (pyFilePath.endsWith(PyNames.DOT_PY)) {
List<File> filesToDelete = new ArrayList<>();
File pyc = new File(pyFilePath + "c");
if (pyc.exists()) {
filesToDelete.add(pyc);
}
File pyo = new File(pyFilePath + "o");
if (pyo.exists()) {
filesToDelete.add(pyo);
}
final File file = new File(pyFilePath);
File pycache = new File(file.getParentFile(), PyNames.PYCACHE);
if (pycache.isDirectory()) {
final String shortName = FileUtil.getNameWithoutExtension(file);
Collections.addAll(filesToDelete, pycache.listFiles(pathname -> {
if (!FileUtilRt.extensionEquals(pathname.getName(), "pyc")) return false;
String nameWithMagic = FileUtil.getNameWithoutExtension(pathname);
return FileUtil.getNameWithoutExtension(nameWithMagic).equals(shortName);
}));
}
FileUtil.asyncDelete(filesToDelete);
}
}
public static String getElementNameWithoutExtension(PsiNamedElement psiNamedElement) {
return psiNamedElement instanceof PyFile
? FileUtil.getNameWithoutExtension(((PyFile)psiNamedElement).getName())
: psiNamedElement.getName();
}
public static boolean hasUnresolvedAncestors(@NotNull PyClass cls, @NotNull TypeEvalContext context) {
for (PyClassLikeType type : cls.getAncestorTypes(context)) {
if (type == null) {
return true;
}
}
return false;
}
@NotNull
public static AccessDirection getPropertyAccessDirection(@NotNull PyFunction function) {
final Property property = function.getProperty();
if (property != null) {
if (property.getGetter().valueOrNull() == function) {
return AccessDirection.READ;
}
if (property.getSetter().valueOrNull() == function) {
return AccessDirection.WRITE;
}
else if (property.getDeleter().valueOrNull() == function) {
return AccessDirection.DELETE;
}
}
return AccessDirection.READ;
}
public static void removeQualifier(@NotNull final PyReferenceExpression element) {
final PyExpression qualifier = element.getQualifier();
if (qualifier == null) return;
if (qualifier instanceof PyCallExpression) {
final PyExpression callee = ((PyCallExpression)qualifier).getCallee();
if (callee instanceof PyReferenceExpression) {
final PyExpression calleeQualifier = ((PyReferenceExpression)callee).getQualifier();
if (calleeQualifier != null) {
qualifier.replace(calleeQualifier);
return;
}
}
}
final PsiElement dot = PyPsiUtils.getNextNonWhitespaceSibling(qualifier);
if (dot != null) dot.delete();
qualifier.delete();
}
/**
* Returns string that represents element in string search.
*
* @param element element to search
* @return string that represents element
*/
@NotNull
public static String computeElementNameForStringSearch(@NotNull final PsiElement element) {
if (element instanceof PyFile) {
return FileUtil.getNameWithoutExtension(((PyFile)element).getName());
}
if (element instanceof PsiDirectory) {
return ((PsiDirectory)element).getName();
}
// Magic literals are always represented by their string values
if ((element instanceof PyStringLiteralExpression) && PyMagicLiteralTools.isMagicLiteral(element)) {
final String name = ((StringLiteralExpression)element).getStringValue();
if (name != null) {
return name;
}
}
if (element instanceof PyElement) {
final String name = ((PyElement)element).getName();
if (name != null) {
return name;
}
}
return element.getNode().getText();
}
public static boolean isOwnScopeComprehension(@NotNull PyComprehensionElement comprehension) {
final boolean isAtLeast30 = LanguageLevel.forElement(comprehension).isAtLeast(LanguageLevel.PYTHON30);
final boolean isListComprehension = comprehension instanceof PyListCompExpression;
return !isListComprehension || isAtLeast30;
}
public static boolean hasCustomDecorators(@NotNull PyDecoratable decoratable) {
return PyKnownDecoratorUtil.hasNonBuiltinDecorator(decoratable, TypeEvalContext.codeInsightFallback(null));
}
public static boolean isDecoratedAsAbstract(@NotNull final PyDecoratable decoratable) {
return PyKnownDecoratorUtil.hasAbstractDecorator(decoratable, TypeEvalContext.codeInsightFallback(null));
}
public static ASTNode createNewName(PyElement element, String name) {
return PyElementGenerator.getInstance(element.getProject()).createNameIdentifier(name, LanguageLevel.forElement(element));
}
/**
* Finds element declaration by resolving its references top the top but not further than file (to prevent un-stubbing)
*
* @param elementToResolve element to resolve
* @return its declaration
*/
@NotNull
public static PsiElement resolveToTheTop(@NotNull final PsiElement elementToResolve) {
PsiElement currentElement = elementToResolve;
final Set<PsiElement> checkedElements = new HashSet<>(); // To prevent PY-20553
while (true) {
final PsiReference reference = currentElement.getReference();
if (reference == null) {
break;
}
final PsiElement resolve = reference.resolve();
if ((resolve == null) || checkedElements.contains(resolve) || resolve.equals(currentElement) || !inSameFile(resolve, currentElement)) {
break;
}
currentElement = resolve;
checkedElements.add(resolve);
}
return currentElement;
}
/**
* Note that returned list may contain {@code null} items, e.g. for unresolved import elements, originally wrapped
* in {@link com.jetbrains.python.psi.resolve.ImportedResolveResult}.
*/
@NotNull
public static List<PsiElement> multiResolveTopPriority(@NotNull PsiElement element, @NotNull PyResolveContext resolveContext) {
if (element instanceof PyReferenceOwner) {
final PsiPolyVariantReference ref = ((PyReferenceOwner)element).getReference(resolveContext);
return filterTopPriorityResults(ref.multiResolve(false));
}
else {
final PsiReference reference = element.getReference();
return reference != null ? Collections.singletonList(reference.resolve()) : Collections.emptyList();
}
}
@NotNull
public static List<PsiElement> multiResolveTopPriority(@NotNull PsiPolyVariantReference reference) {
return filterTopPriorityResults(reference.multiResolve(false));
}
@NotNull
public static List<PsiElement> filterTopPriorityResults(@NotNull ResolveResult[] resolveResults) {
if (resolveResults.length == 0) return Collections.emptyList();
final int maxRate = getMaxRate(Arrays.asList(resolveResults));
return StreamEx
.of(resolveResults)
.filter(resolveResult -> getRate(resolveResult) >= maxRate)
.map(ResolveResult::getElement)
.nonNull()
.toList();
}
@NotNull
public static <E extends ResolveResult> List<E> filterTopPriorityResults(@NotNull List<E> resolveResults) {
if (resolveResults.isEmpty()) return Collections.emptyList();
final int maxRate = getMaxRate(resolveResults);
return ContainerUtil.filter(resolveResults, resolveResult -> getRate(resolveResult) >= maxRate);
}
private static int getMaxRate(@NotNull List<? extends ResolveResult> resolveResults) {
return resolveResults
.stream()
.mapToInt(PyUtil::getRate)
.max()
.orElse(Integer.MIN_VALUE);
}
private static int getRate(@NotNull ResolveResult resolveResult) {
return resolveResult instanceof RatedResolveResult ? ((RatedResolveResult)resolveResult).getRate() : 0;
}
/**
* Gets class init method
*
* @param pyClass class where to find init
* @return class init method if any
*/
@Nullable
public static PyFunction getInitMethod(@NotNull final PyClass pyClass) {
return pyClass.findMethodByName(PyNames.INIT, false, null);
}
/**
* Returns Python language level for a virtual file.
*
* @see {@link LanguageLevel#forElement}
*/
@NotNull
public static LanguageLevel getLanguageLevelForVirtualFile(@NotNull Project project,
@NotNull VirtualFile virtualFile) {
if (virtualFile instanceof VirtualFileWindow) {
virtualFile = ((VirtualFileWindow)virtualFile).getDelegate();
}
// Most of the cases should be handled by this one, PyLanguageLevelPusher pushes folders only
final VirtualFile folder = virtualFile.getParent();
if (folder != null) {
final LanguageLevel folderLevel = folder.getUserData(LanguageLevel.KEY);
if (folderLevel != null) {
return folderLevel;
}
final LanguageLevel fileLevel = PythonLanguageLevelPusher.getFileLanguageLevel(project, virtualFile);
if (fileLevel != null) {
return fileLevel;
}
}
else {
// However this allows us to setup language level per file manually
// in case when it is LightVirtualFile
final LanguageLevel level = virtualFile.getUserData(LanguageLevel.KEY);
if (level != null) return level;
if (ApplicationManager.getApplication().isUnitTestMode()) {
final LanguageLevel languageLevel = LanguageLevel.FORCE_LANGUAGE_LEVEL;
if (languageLevel != null) {
return languageLevel;
}
}
}
return guessLanguageLevelWithCaching(project);
}
public static void invalidateLanguageLevelCache(@NotNull Project project) {
project.putUserData(PythonLanguageLevelPusher.PYTHON_LANGUAGE_LEVEL, null);
}
@NotNull
public static LanguageLevel guessLanguageLevelWithCaching(@NotNull Project project) {
LanguageLevel languageLevel = project.getUserData(PythonLanguageLevelPusher.PYTHON_LANGUAGE_LEVEL);
if (languageLevel == null) {
languageLevel = guessLanguageLevel(project);
project.putUserData(PythonLanguageLevelPusher.PYTHON_LANGUAGE_LEVEL, languageLevel);
}
return languageLevel;
}
@NotNull
public static LanguageLevel guessLanguageLevel(@NotNull Project project) {
final ModuleManager moduleManager = ModuleManager.getInstance(project);
if (moduleManager != null) {
LanguageLevel maxLevel = null;
for (Module projectModule : moduleManager.getModules()) {
final Sdk sdk = PythonSdkType.findPythonSdk(projectModule);
if (sdk != null) {
final LanguageLevel level = PythonSdkType.getLanguageLevelForSdk(sdk);
if (maxLevel == null || maxLevel.isOlderThan(level)) {
maxLevel = level;
}
}
}
if (maxLevel != null) {
return maxLevel;
}
}
return LanguageLevel.getDefault();
}
/**
* Clone of C# "as" operator.
* Checks if expression has correct type and casts it if it has. Returns null otherwise.
* It saves coder from "instanceof / cast" chains.
*
* @param expression expression to check
* @param clazz class to cast
* @param <T> class to cast
* @return expression casted to appropriate type (if could be casted). Null otherwise.
*/
@Nullable
@SuppressWarnings("unchecked")
public static <T> T as(@Nullable final Object expression, @NotNull final Class<T> clazz) {
return ObjectUtils.tryCast(expression, clazz);
}
// TODO: Move to PsiElement?
/**
* Searches for references injected to element with certain type
*
* @param element element to search injected references for
* @param expectedClass expected type of element reference resolved to
* @param <T> expected type of element reference resolved to
* @return resolved element if found or null if not found
*/
@Nullable
public static <T extends PsiElement> T findReference(@NotNull final PsiElement element, @NotNull final Class<T> expectedClass) {
for (final PsiReference reference : element.getReferences()) {
final T result = as(reference.resolve(), expectedClass);
if (result != null) {
return result;
}
}
return null;
}
/**
* Converts collection to list of certain type
*
* @param expression expression of collection type
* @param elementClass expected element type
* @param <T> expected element type
* @return list of elements of expected element type
*/
@NotNull
public static <T> List<T> asList(@Nullable final Collection<?> expression, @NotNull final Class<T> elementClass) {
if ((expression == null) || expression.isEmpty()) {
return Collections.emptyList();
}
final List<T> result = new ArrayList<>();
for (final Object element : expression) {
final T toAdd = as(element, elementClass);
if (toAdd != null) {
result.add(toAdd);
}
}
return result;
}
/**
* Force re-highlighting in all open editors that belong to specified project.
*/
public static void rehighlightOpenEditors(final @NotNull Project project) {
ApplicationManager.getApplication().runWriteAction(() -> {
for (Editor editor : EditorFactory.getInstance().getAllEditors()) {
if (editor instanceof EditorEx && editor.getProject() == project) {
final VirtualFile vFile = ((EditorEx)editor).getVirtualFile();
if (vFile != null) {
final EditorHighlighter highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, vFile);
((EditorEx)editor).setHighlighter(highlighter);
}
}
}
});
}
public static <T, P> T getParameterizedCachedValue(@NotNull PsiElement element, @Nullable P param, @NotNull NullableFunction<P, T> f) {
final CachedValuesManager manager = CachedValuesManager.getManager(element.getProject());
final Map<Optional<P>, Optional<T>> cache = CachedValuesManager.getCachedValue(element, manager.getKeyForClass(f.getClass()), () -> {
// concurrent hash map is a null-hostile collection
return CachedValueProvider.Result.create(Maps.newConcurrentMap(), PsiModificationTracker.MODIFICATION_COUNT);
});
// Don't use ConcurrentHashMap#computeIfAbsent(), it blocks if the function tries to update the cache recursively for the same key
// during computation. We can accept here that some values will be computed several times due to non-atomic updates.
final Optional<P> wrappedParam = Optional.ofNullable(param);
Optional<T> value = cache.get(wrappedParam);
if (value == null) {
value = Optional.ofNullable(f.fun(param));
cache.put(wrappedParam, value);
}
return value.orElse(null);
}
/**
* This method is allowed to be called from any thread, but in general you should not set {@code modal=true} if you're calling it
* from the write action, because in this case {@code function} will be executed right in the current thread (presumably EDT)
* without any progress whatsoever to avoid possible deadlock.
*
* @see ApplicationImpl#runProcessWithProgressSynchronously(Runnable, String, boolean, Project, JComponent, String)
*/
public static void runWithProgress(@Nullable Project project, @Nls(capitalization = Nls.Capitalization.Title) @NotNull String title,
boolean modal, boolean canBeCancelled, @NotNull final Consumer<ProgressIndicator> function) {
if (modal) {
ProgressManager.getInstance().run(new Task.Modal(project, title, canBeCancelled) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
function.consume(indicator);
}
});
}
else {
ProgressManager.getInstance().run(new Task.Backgroundable(project, title, canBeCancelled) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
function.consume(indicator);
}
});
}
}
/**
* Executes code only if <pre>_PYCHARM_VERBOSE_MODE</pre> is set in env (which should be done for debug purposes only)
* @param runnable code to call
*/
public static void verboseOnly(@NotNull final Runnable runnable) {
if (System.getenv().get("_PYCHARM_VERBOSE_MODE") != null) {
runnable.run();
}
}
/**
* Returns the line comment that immediately precedes statement list of the given compound statement. Python parser ensures
* that it follows the statement header, i.e. it's directly after the colon, not on its own line.
*/
@Nullable
public static PsiComment getCommentOnHeaderLine(@NotNull PyStatementListContainer container) {
final PyStatementList statementList = container.getStatementList();
return as(PyPsiUtils.getPrevNonWhitespaceSibling(statementList), PsiComment.class);
}
public static boolean isPy2ReservedWord(@NotNull PyReferenceExpression node) {
if (LanguageLevel.forElement(node).isOlderThan(LanguageLevel.PYTHON30)) {
if (!node.isQualified()) {
final String name = node.getName();
if (PyNames.NONE.equals(name) || PyNames.FALSE.equals(name) || PyNames.TRUE.equals(name)) {
return true;
}
}
}
return false;
}
/**
* Retrieve the document from {@link PsiDocumentManager} using the anchor PSI element and pass it to the consumer function
* first releasing it from pending PSI modifications it with {@link PsiDocumentManager#doPostponedOperationsAndUnblockDocument(Document)}
* and then committing in try/finally block, so that subsequent operations over the PSI can be performed.
*/
public static void updateDocumentUnblockedAndCommitted(@NotNull PsiElement anchor, @NotNull Consumer<Document> consumer) {
final PsiDocumentManager manager = PsiDocumentManager.getInstance(anchor.getProject());
final Document document = manager.getDocument(anchor.getContainingFile());
if (document != null) {
manager.doPostponedOperationsAndUnblockDocument(document);
try {
consumer.consume(document);
}
finally {
manager.commitDocument(document);
}
}
}
public static class KnownDecoratorProviderHolder {
public static PyKnownDecoratorProvider[] KNOWN_DECORATOR_PROVIDERS = Extensions.getExtensions(PyKnownDecoratorProvider.EP_NAME);
private KnownDecoratorProviderHolder() {
}
}
/**
* If argument is a PsiDirectory, turn it into a PsiFile that points to __init__.py in that directory.
* If there's no __init__.py there, null is returned, there's no point to resolve to a dir which is not a package.
* Alas, resolve() and multiResolve() can't return anything but a PyFile or PsiFileImpl.isPsiUpToDate() would fail.
* This is because isPsiUpToDate() relies on identity of objects returned by FileViewProvider.getPsi().
* If we ever need to exactly tell a dir from __init__.py, that logic has to change.
*
* @param target a resolve candidate.
* @return a PsiFile if target was a PsiDirectory, or null, or target unchanged.
*/
@Nullable
public static PsiElement turnDirIntoInit(@Nullable PsiElement target) {
if (target instanceof PsiDirectory) {
final PsiDirectory dir = (PsiDirectory)target;
final PsiFile initStub = dir.findFile(PyNames.INIT_DOT_PYI);
if (initStub != null) {
return initStub;
}
final PsiFile initFile = dir.findFile(PyNames.INIT_DOT_PY);
if (initFile != null) {
return initFile; // ResolveImportUtil will extract directory part as needed, everyone else are better off with a file.
}
else {
return null;
} // dir without __init__.py does not resolve
}
else {
return target;
} // don't touch non-dirs
}
/**
* If directory is a PsiDirectory, that is also a valid Python package, return PsiFile that points to __init__.py,
* if such file exists, or directory itself (i.e. namespace package). Otherwise, return {@code null}.
* Unlike {@link #turnDirIntoInit(PsiElement)} this function handles namespace packages and
* accepts only PsiDirectories as target.
*
* @param directory directory to check
* @param anchor optional PSI element to determine language level as for {@link #isPackage(PsiDirectory, PsiElement)}
* @return PsiFile or PsiDirectory, if target is a Python package and {@code null} null otherwise
*/
@Nullable
public static PsiElement getPackageElement(@NotNull PsiDirectory directory, @Nullable PsiElement anchor) {
if (isPackage(directory, anchor)) {
final PsiElement init = turnDirIntoInit(directory);
if (init != null) {
return init;
}
return directory;
}
return null;
}
/**
* If target is a Python module named __init__.py file, return its directory. Otherwise return target unchanged.
* @param target PSI element to check
* @return PsiDirectory or target unchanged
*/
@Contract("null -> null; !null -> !null")
@Nullable
public static PsiElement turnInitIntoDir(@Nullable PsiElement target) {
if (target instanceof PyFile && isPackage((PsiFile)target)) {
return ((PsiFile)target).getContainingDirectory();
}
return target;
}
/**
* @see #isPackage(PsiDirectory, boolean, PsiElement)
*/
public static boolean isPackage(@NotNull PsiDirectory directory, @Nullable PsiElement anchor) {
return isPackage(directory, true, anchor);
}
/**
* Checks that given PsiDirectory can be treated as Python package, i.e. it's either contains __init__.py or it's a namespace package
* (effectively any directory in Python 3.3 and above). Setuptools namespace packages can be checked as well, but it requires access to
* {@link PySetuptoolsNamespaceIndex} and may slow things down during update of project indexes.
* Also note that this method does not check that directory itself and its parents have valid importable names,
* use {@link PyNames#isIdentifier(String)} for this purpose.
*
* @param directory PSI directory to check
* @param checkSetupToolsPackages whether setuptools namespace packages should be considered as well
* @param anchor optional anchor element to determine language level
* @return whether given directory is Python package
*
* @see PyNames#isIdentifier(String)
*/
public static boolean isPackage(@NotNull PsiDirectory directory, boolean checkSetupToolsPackages, @Nullable PsiElement anchor) {
for (PyCustomPackageIdentifier customPackageIdentifier : PyCustomPackageIdentifier.EP_NAME.getExtensions()) {
if (customPackageIdentifier.isPackage(directory)) {
return true;
}
}
if (directory.findFile(PyNames.INIT_DOT_PY) != null) {
return true;
}
final LanguageLevel level = anchor != null ?
LanguageLevel.forElement(anchor) :
getLanguageLevelForVirtualFile(directory.getProject(), directory.getVirtualFile());
if (level.isAtLeast(LanguageLevel.PYTHON33)) {
return true;
}
return checkSetupToolsPackages && isSetuptoolsNamespacePackage(directory);
}
public static boolean isPackage(@NotNull PsiFile file) {
for (PyCustomPackageIdentifier customPackageIdentifier : PyCustomPackageIdentifier.EP_NAME.getExtensions()) {
if (customPackageIdentifier.isPackageFile(file)) {
return true;
}
}
return PyNames.INIT_DOT_PY.equals(file.getName());
}
private static boolean isSetuptoolsNamespacePackage(@NotNull PsiDirectory directory) {
final String packagePath = getPackagePath(directory);
return packagePath != null && !PySetuptoolsNamespaceIndex.find(packagePath, directory.getProject()).isEmpty();
}
@Nullable
private static String getPackagePath(@NotNull PsiDirectory directory) {
final QualifiedName name = QualifiedNameFinder.findShortestImportableQName(directory);
return name != null ? name.toString() : null;
}
/**
* Counts initial underscores of an identifier.
*
* @param name identifier
* @return 0 if no initial underscores found, 1 if there's only one underscore, 2 if there's two or more initial underscores.
*/
public static int getInitialUnderscores(String name) {
if (name == null) {
return 0;
}
int underscores = 0;
if (name.startsWith("__")) {
underscores = 2;
}
else if (name.startsWith("_")) underscores = 1;
return underscores;
}
/**
* @param name
* @return true iff the name looks like a class-private one, starting with two underscores but not ending with two underscores.
*/
public static boolean isClassPrivateName(@NotNull String name) {
return name.startsWith("__") && !name.endsWith("__");
}
public static boolean isSpecialName(@NotNull String name) {
return name.length() > 4 && name.startsWith("__") && name.endsWith("__");
}
/**
* Constructs new lookup element for completion of keyword argument with equals sign appended.
*
* @param name name of the parameter
* @param project project instance to check code style settings and surround equals sign with spaces if necessary
* @return lookup element
*/
@NotNull
public static LookupElement createNamedParameterLookup(@NotNull String name, @Nullable Project project) {
final String suffix;
if (CodeStyleSettingsManager.getSettings(project).getCustomSettings(PyCodeStyleSettings.class).SPACE_AROUND_EQ_IN_KEYWORD_ARGUMENT) {
suffix = " = ";
}
else {
suffix = "=";
}
LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(name + suffix).withIcon(PlatformIcons.PARAMETER_ICON);
lookupElementBuilder = lookupElementBuilder.withInsertHandler(OverwriteEqualsInsertHandler.INSTANCE);
return PrioritizedLookupElement.withGrouping(lookupElementBuilder, 1);
}
/**
* Peels argument expression of parentheses and of keyword argument wrapper
*
* @param expr an item of getArguments() array
* @return expression actually passed as argument
*/
@Nullable
public static PyExpression peelArgument(PyExpression expr) {
while (expr instanceof PyParenthesizedExpression) expr = ((PyParenthesizedExpression)expr).getContainedExpression();
if (expr instanceof PyKeywordArgument) expr = ((PyKeywordArgument)expr).getValueExpression();
return expr;
}
public static String getFirstParameterName(PyFunction container) {
String selfName = PyNames.CANONICAL_SELF;
if (container != null) {
final PyParameter[] params = container.getParameterList().getParameters();
if (params.length > 0) {
final PyNamedParameter named = params[0].getAsNamed();
if (named != null) {
selfName = named.getName();
}
}
}
return selfName;
}
/**
* @return Source roots <strong>and</strong> content roots for element's project
*/
@NotNull
public static Collection<VirtualFile> getSourceRoots(@NotNull PsiElement foothold) {
final Module module = ModuleUtilCore.findModuleForPsiElement(foothold);
if (module != null) {
return getSourceRoots(module);
}
return Collections.emptyList();
}
/**
* @return Source roots <strong>and</strong> content roots for module
*/
@NotNull
public static Collection<VirtualFile> getSourceRoots(@NotNull Module module) {
final Set<VirtualFile> result = new LinkedHashSet<>();
final ModuleRootManager manager = ModuleRootManager.getInstance(module);
Collections.addAll(result, manager.getSourceRoots());
Collections.addAll(result, manager.getContentRoots());
return result;
}
@Nullable
public static VirtualFile findInRoots(Module module, String path) {
if (module != null) {
for (VirtualFile root : getSourceRoots(module)) {
VirtualFile file = root.findFileByRelativePath(path);
if (file != null) {
return file;
}
}
}
return null;
}
@Nullable
public static List<String> getStringListFromTargetExpression(PyTargetExpression attr) {
return strListValue(attr.findAssignedValue());
}
@Nullable
public static List<String> strListValue(PyExpression value) {
while (value instanceof PyParenthesizedExpression) {
value = ((PyParenthesizedExpression)value).getContainedExpression();
}
if (value instanceof PySequenceExpression) {
final PyExpression[] elements = ((PySequenceExpression)value).getElements();
List<String> result = new ArrayList<>(elements.length);
for (PyExpression element : elements) {
if (!(element instanceof PyStringLiteralExpression)) {
return null;
}
result.add(((PyStringLiteralExpression)element).getStringValue());
}
return result;
}
return null;
}
@NotNull
public static Map<String, PyExpression> dictValue(@NotNull PyDictLiteralExpression dict) {
Map<String, PyExpression> result = Maps.newLinkedHashMap();
for (PyKeyValueExpression keyValue : dict.getElements()) {
PyExpression key = keyValue.getKey();
PyExpression value = keyValue.getValue();
if (key instanceof PyStringLiteralExpression) {
result.put(((PyStringLiteralExpression)key).getStringValue(), value);
}
}
return result;
}
/**
* @param what thing to search for
* @param variants things to search among
* @return true iff what.equals() one of the variants.
*/
public static <T> boolean among(@NotNull T what, T... variants) {
for (T s : variants) {
if (what.equals(s)) return true;
}
return false;
}
@Nullable
public static String getKeywordArgumentString(PyCallExpression expr, String keyword) {
return PyPsiUtils.strValue(expr.getKeywordArgument(keyword));
}
public static boolean isExceptionClass(PyClass pyClass) {
if (isBaseException(pyClass.getQualifiedName())) {
return true;
}
for (PyClassLikeType type : pyClass.getAncestorTypes(TypeEvalContext.codeInsightFallback(pyClass.getProject()))) {
if (type != null && isBaseException(type.getClassQName())) {
return true;
}
}
return false;
}
private static boolean isBaseException(String name) {
return name != null && (name.contains("BaseException") || name.startsWith("exceptions."));
}
public static class MethodFlags {
private final boolean myIsStaticMethod;
private final boolean myIsMetaclassMethod;
private final boolean myIsSpecialMetaclassMethod;
private final boolean myIsClassMethod;
/**
* @return true iff the method belongs to a metaclass (an ancestor of 'type').
*/
public boolean isMetaclassMethod() {
return myIsMetaclassMethod;
}
/**
* @return iff isMetaclassMethod and the method is either __init__ or __call__.
*/
public boolean isSpecialMetaclassMethod() {
return myIsSpecialMetaclassMethod;
}
public boolean isStaticMethod() {
return myIsStaticMethod;
}
public boolean isClassMethod() {
return myIsClassMethod;
}
private MethodFlags(boolean isClassMethod, boolean isStaticMethod, boolean isMetaclassMethod, boolean isSpecialMetaclassMethod) {
myIsClassMethod = isClassMethod;
myIsStaticMethod = isStaticMethod;
myIsMetaclassMethod = isMetaclassMethod;
myIsSpecialMetaclassMethod = isSpecialMetaclassMethod;
}
/**
* @param node a function
* @return a new flags object, or null if the function is not a method
*/
@Nullable
public static MethodFlags of(@NotNull PyFunction node) {
PyClass cls = node.getContainingClass();
if (cls != null) {
PyFunction.Modifier modifier = node.getModifier();
boolean isMetaclassMethod = false;
PyClass type_cls = PyBuiltinCache.getInstance(node).getClass("type");
for (PyClass ancestor_cls : cls.getAncestorClasses(null)) {
if (ancestor_cls == type_cls) {
isMetaclassMethod = true;
break;
}
}
final String method_name = node.getName();
boolean isSpecialMetaclassMethod = isMetaclassMethod && method_name != null && among(method_name, PyNames.INIT, "__call__");
return new MethodFlags(modifier == CLASSMETHOD, modifier == STATICMETHOD, isMetaclassMethod, isSpecialMetaclassMethod);
}
return null;
}
//TODO: Doc
public boolean isInstanceMethod() {
return !(myIsClassMethod || myIsStaticMethod);
}
}
public static boolean isSuperCall(@NotNull PyCallExpression node) {
PyClass klass = PsiTreeUtil.getParentOfType(node, PyClass.class);
if (klass == null) return false;
PyExpression callee = node.getCallee();
if (callee == null) return false;
String name = callee.getName();
if (PyNames.SUPER.equals(name)) {
PsiReference reference = callee.getReference();
if (reference == null) return false;
PsiElement resolved = reference.resolve();
PyBuiltinCache cache = PyBuiltinCache.getInstance(node);
if (resolved != null && cache.isBuiltin(resolved)) {
PyExpression[] args = node.getArguments();
if (args.length > 0) {
String firstArg = args[0].getText();
if (firstArg.equals(klass.getName()) || firstArg.equals(PyNames.CANONICAL_SELF + "." + PyNames.__CLASS__)) {
return true;
}
for (PyClass s : klass.getAncestorClasses(null)) {
if (firstArg.equals(s.getName())) {
return true;
}
}
}
else {
return true;
}
}
}
return false;
}
@NotNull
public static PyFile getOrCreateFile(String path, Project project) {
final VirtualFile vfile = LocalFileSystem.getInstance().findFileByIoFile(new File(path));
final PsiFile psi;
if (vfile == null) {
final File file = new File(path);
try {
final VirtualFile baseDir = project.getBaseDir();
final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance(project);
final FileTemplate template = fileTemplateManager.getInternalTemplate("Python Script");
final Properties properties = fileTemplateManager.getDefaultProperties();
properties.setProperty("NAME", FileUtil.getNameWithoutExtension(file.getName()));
final String content = (template != null) ? template.getText(properties) : null;
psi = PyExtractSuperclassHelper.placeFile(project,
StringUtil.notNullize(
file.getParent(),
baseDir != null ? baseDir
.getPath() : "."
),
file.getName(),
content
);
}
catch (IOException e) {
throw new IncorrectOperationException(String.format("Cannot create file '%s'", path), (Throwable)e);
}
}
else {
psi = PsiManager.getInstance(project).findFile(vfile);
}
if (!(psi instanceof PyFile)) {
throw new IncorrectOperationException(PyBundle.message(
"refactoring.move.module.members.error.cannot.place.elements.into.nonpython.file"));
}
return (PyFile)psi;
}
@Nullable
public static PsiElement findPrevAtOffset(PsiFile psiFile, int caretOffset, Class... toSkip) {
PsiElement element;
if (caretOffset < 0) {
return null;
}
int lineStartOffset = 0;
final Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(psiFile);
if (document != null) {
int lineNumber = document.getLineNumber(caretOffset);
lineStartOffset = document.getLineStartOffset(lineNumber);
}
do {
caretOffset--;
element = psiFile.findElementAt(caretOffset);
}
while (caretOffset >= lineStartOffset && instanceOf(element, toSkip));
return instanceOf(element, toSkip) ? null : element;
}
@Nullable
public static PsiElement findNonWhitespaceAtOffset(PsiFile psiFile, int caretOffset) {
PsiElement element = findNextAtOffset(psiFile, caretOffset, PsiWhiteSpace.class);
if (element == null) {
element = findPrevAtOffset(psiFile, caretOffset - 1, PsiWhiteSpace.class);
}
return element;
}
@Nullable
public static PsiElement findElementAtOffset(PsiFile psiFile, int caretOffset) {
PsiElement element = findPrevAtOffset(psiFile, caretOffset);
if (element == null) {
element = findNextAtOffset(psiFile, caretOffset);
}
return element;
}
@Nullable
public static PsiElement findNextAtOffset(@NotNull final PsiFile psiFile, int caretOffset, Class... toSkip) {
PsiElement element = psiFile.findElementAt(caretOffset);
if (element == null) {
return null;
}
final Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(psiFile);
int lineEndOffset = 0;
if (document != null) {
int lineNumber = document.getLineNumber(caretOffset);
lineEndOffset = document.getLineEndOffset(lineNumber);
}
while (caretOffset < lineEndOffset && instanceOf(element, toSkip)) {
caretOffset++;
element = psiFile.findElementAt(caretOffset);
}
return instanceOf(element, toSkip) ? null : element;
}
/**
* Adds element to statement list to the correct place according to its dependencies.
*
* @param element to insert
* @param statementList where element should be inserted
* @return inserted element
*/
public static <T extends PyElement> T addElementToStatementList(@NotNull final T element,
@NotNull final PyStatementList statementList) {
PsiElement before = null;
PsiElement after = null;
for (final PyStatement statement : statementList.getStatements()) {
if (PyDependenciesComparator.depends(element, statement)) {
after = statement;
}
else if (PyDependenciesComparator.depends(statement, element)) {
before = statement;
}
}
final PsiElement result;
if (after != null) {
result = statementList.addAfter(element, after);
}
else if (before != null) {
result = statementList.addBefore(element, before);
}
else {
result = addElementToStatementList(element, statementList, true);
}
@SuppressWarnings("unchecked") // Inserted element can't have different type
final T resultCasted = (T)result;
return resultCasted;
}
/**
* Inserts specified element into the statement list either at the beginning or at its end. If new element is going to be
* inserted at the beginning, any preceding docstrings and/or calls to super methods will be skipped.
* Moreover if statement list previously didn't contain any statements, explicit new line and indentation will be inserted in
* front of it.
*
* @param element element to insert
* @param statementList statement list
* @param toTheBeginning whether to insert element at the beginning or at the end of the statement list
* @return actually inserted element as for {@link PsiElement#add(PsiElement)}
*/
@NotNull
public static PsiElement addElementToStatementList(@NotNull PsiElement element,
@NotNull PyStatementList statementList,
boolean toTheBeginning) {
final PsiElement prevElem = PyPsiUtils.getPrevNonWhitespaceSibling(statementList);
// If statement list is on the same line as previous element (supposedly colon), move its only statement on the next line
if (prevElem != null && onSameLine(statementList, prevElem)) {
final PsiDocumentManager manager = PsiDocumentManager.getInstance(statementList.getProject());
final Document document = manager.getDocument(statementList.getContainingFile());
if (document != null) {
final PyStatementListContainer container = (PyStatementListContainer)statementList.getParent();
manager.doPostponedOperationsAndUnblockDocument(document);
final String indentation = "\n" + PyIndentUtil.getElementIndent(statementList);
// If statement list was empty initially, we need to add some anchor statement ("pass"), so that preceding new line was not
// parsed as following entire StatementListContainer (e.g. function). It's going to be replaced anyway.
final String text = statementList.getStatements().length == 0 ? indentation + PyNames.PASS : indentation;
document.insertString(statementList.getTextRange().getStartOffset(), text);
manager.commitDocument(document);
statementList = container.getStatementList();
}
}
final PsiElement firstChild = statementList.getFirstChild();
if (firstChild == statementList.getLastChild() && firstChild instanceof PyPassStatement) {
element = firstChild.replace(element);
}
else {
final PyStatement[] statements = statementList.getStatements();
if (toTheBeginning && statements.length > 0) {
final PyDocStringOwner docStringOwner = PsiTreeUtil.getParentOfType(statementList, PyDocStringOwner.class);
PyStatement anchor = statements[0];
if (docStringOwner != null && anchor instanceof PyExpressionStatement &&
((PyExpressionStatement)anchor).getExpression() == docStringOwner.getDocStringExpression()) {
final PyStatement next = PsiTreeUtil.getNextSiblingOfType(anchor, PyStatement.class);
if (next == null) {
return statementList.addAfter(element, anchor);
}
anchor = next;
}
while (anchor instanceof PyExpressionStatement) {
final PyExpression expression = ((PyExpressionStatement)anchor).getExpression();
if (expression instanceof PyCallExpression) {
final PyExpression callee = ((PyCallExpression)expression).getCallee();
if ((isSuperCall((PyCallExpression)expression) || (callee != null && PyNames.INIT.equals(callee.getName())))) {
final PyStatement next = PsiTreeUtil.getNextSiblingOfType(anchor, PyStatement.class);
if (next == null) {
return statementList.addAfter(element, anchor);
}
anchor = next;
continue;
}
}
break;
}
element = statementList.addBefore(element, anchor);
}
else {
element = statementList.add(element);
}
}
return element;
}
@NotNull
public static List<PyParameter> getParameters(@NotNull PyCallable callable, @NotNull TypeEvalContext context) {
return Optional
.ofNullable(as(context.getType(callable), PyCallableType.class))
.map(callableType -> callableType.getParameters(context))
.map(callableParameters -> ContainerUtil.map(callableParameters, PyCallableParameter::getParameter))
.orElse(Arrays.asList(callable.getParameterList().getParameters()));
}
public static boolean isSignatureCompatibleTo(@NotNull PyCallable callable, @NotNull PyCallable otherCallable,
@NotNull TypeEvalContext context) {
final List<PyParameter> parameters = getParameters(callable, context);
final List<PyParameter> otherParameters = getParameters(otherCallable, context);
final int optionalCount = optionalParametersCount(parameters);
final int otherOptionalCount = optionalParametersCount(otherParameters);
final int requiredCount = requiredParametersCount(callable, parameters);
final int otherRequiredCount = requiredParametersCount(otherCallable, otherParameters);
if (hasPositionalContainer(otherParameters) || hasKeywordContainer(otherParameters)) {
if (otherParameters.size() == specialParametersCount(otherCallable, otherParameters)) {
return true;
}
}
if (hasPositionalContainer(parameters) || hasKeywordContainer(parameters)) {
return requiredCount <= otherRequiredCount;
}
return requiredCount <= otherRequiredCount && parameters.size() >= otherParameters.size() && optionalCount >= otherOptionalCount;
}
private static int optionalParametersCount(@NotNull List<PyParameter> parameters) {
int n = 0;
for (PyParameter parameter : parameters) {
if (parameter.hasDefaultValue()) {
n++;
}
}
return n;
}
private static int requiredParametersCount(@NotNull PyCallable callable, @NotNull List<PyParameter> parameters) {
return parameters.size() - optionalParametersCount(parameters) - specialParametersCount(callable, parameters);
}
private static int specialParametersCount(@NotNull PyCallable callable, @NotNull List<PyParameter> parameters) {
int n = 0;
if (hasPositionalContainer(parameters)) {
n++;
}
if (hasKeywordContainer(parameters)) {
n++;
}
if (callable.asMethod() != null) {
n++;
}
else {
if (parameters.size() > 0) {
final PyParameter first = parameters.get(0);
if (PyNames.CANONICAL_SELF.equals(first.getName())) {
n++;
}
}
}
return n;
}
private static boolean hasPositionalContainer(@NotNull List<PyParameter> parameters) {
for (PyParameter parameter : parameters) {
if (parameter instanceof PyNamedParameter && ((PyNamedParameter)parameter).isPositionalContainer()) {
return true;
}
}
return false;
}
private static boolean hasKeywordContainer(@NotNull List<PyParameter> parameters) {
for (PyParameter parameter : parameters) {
if (parameter instanceof PyNamedParameter && ((PyNamedParameter)parameter).isKeywordContainer()) {
return true;
}
}
return false;
}
public static boolean isInit(@NotNull final PyFunction function) {
return PyNames.INIT.equals(function.getName());
}
/**
* Filters out {@link PyMemberInfo}
* that should not be displayed in this refactoring (like object)
*
* @param pyMemberInfos collection to sort
* @return sorted collection
*/
@NotNull
public static Collection<PyMemberInfo<PyElement>> filterOutObject(@NotNull final Collection<PyMemberInfo<PyElement>> pyMemberInfos) {
return Collections2.filter(pyMemberInfos, new ObjectPredicate(false));
}
public static boolean isStarImportableFrom(@NotNull String name, @NotNull PyFile file) {
final List<String> dunderAll = file.getDunderAll();
return dunderAll != null ? dunderAll.contains(name) : !name.startsWith("_");
}
/**
* Filters only PyClass object (new class)
*/
public static class ObjectPredicate extends NotNullPredicate<PyMemberInfo<PyElement>> {
private final boolean myAllowObjects;
/**
* @param allowObjects allows only objects if true. Allows all but objects otherwise.
*/
public ObjectPredicate(final boolean allowObjects) {
myAllowObjects = allowObjects;
}
@Override
public boolean applyNotNull(@NotNull final PyMemberInfo<PyElement> input) {
return myAllowObjects == isObject(input);
}
private static boolean isObject(@NotNull final PyMemberInfo<PyElement> classMemberInfo) {
final PyElement element = classMemberInfo.getMember();
return (element instanceof PyClass) && PyNames.OBJECT.equals(element.getName());
}
}
/**
* Sometimes you do not know real FQN of some class, but you know class name and its package.
* I.e. {@code django.apps.conf.AppConfig} is not documented, but you know
* {@code AppConfig} and {@code django} package.
*
* @param symbol element to check (class or function)
* @param expectedPackage package like "django"
* @param expectedName expected name (i.e. AppConfig)
* @return true if element in package
*/
public static boolean isSymbolInPackage(@NotNull final PyQualifiedNameOwner symbol,
@NotNull final String expectedPackage,
@NotNull final String expectedName) {
final String qualifiedNameString = symbol.getQualifiedName();
if (qualifiedNameString == null) {
return false;
}
final QualifiedName qualifiedName = QualifiedName.fromDottedString(qualifiedNameString);
final String aPackage = qualifiedName.getFirstComponent();
if (!(expectedPackage.equals(aPackage))) {
return false;
}
final String symbolName = qualifiedName.getLastComponent();
return expectedName.equals(symbolName);
}
public static boolean isObjectClass(@NotNull PyClass cls) {
final String name = cls.getQualifiedName();
return PyNames.OBJECT.equals(name) || PyNames.TYPES_INSTANCE_TYPE.equals(name);
}
public static boolean isInScratchFile(@NotNull PsiElement element) {
return ScratchFileService.isInScratchRoot(PsiUtilCore.getVirtualFile(element));
}
@Nullable
public static PyType getReturnTypeOfMember(@NotNull PyType type,
@NotNull String memberName,
@Nullable PyExpression location,
@NotNull TypeEvalContext context) {
final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context);
final List<? extends RatedResolveResult> resolveResults = type.resolveMember(memberName, location, AccessDirection.READ,
resolveContext);
if (resolveResults != null) {
final List<PyType> types = new ArrayList<>();
for (RatedResolveResult resolveResult : resolveResults) {
final PyType returnType = getReturnType(resolveResult.getElement(), context);
if (returnType != null) {
types.add(returnType);
}
}
return PyUnionType.union(types);
}
return null;
}
@Nullable
private static PyType getReturnType(@Nullable PsiElement element, @NotNull TypeEvalContext context) {
if (element instanceof PyTypedElement) {
final PyType type = context.getType((PyTypedElement)element);
return getReturnType(type, context);
}
return null;
}
@Nullable
private static PyType getReturnType(@Nullable PyType type, @NotNull TypeEvalContext context) {
if (type instanceof PyCallableType) {
return ((PyCallableType)type).getReturnType(context);
}
if (type instanceof PyUnionType) {
final List<PyType> types = new ArrayList<>();
for (PyType pyType : ((PyUnionType)type).getMembers()) {
final PyType returnType = getReturnType(pyType, context);
if (returnType != null) {
types.add(returnType);
}
}
return PyUnionType.union(types);
}
return null;
}
public static boolean isEmptyFunction(@NotNull PyFunction function) {
final PyStatementList statementList = function.getStatementList();
final PyStatement[] statements = statementList.getStatements();
if (statements.length == 0) {
return true;
}
else if (statements.length == 1) {
if (isStringLiteral(statements[0]) || isPassOrRaiseOrEmptyReturn(statements[0])) {
return true;
}
}
else if (statements.length == 2) {
if (isStringLiteral(statements[0]) && (isPassOrRaiseOrEmptyReturn(statements[1]))) {
return true;
}
}
return false;
}
private static boolean isPassOrRaiseOrEmptyReturn(PyStatement stmt) {
if (stmt instanceof PyPassStatement || stmt instanceof PyRaiseStatement) {
return true;
}
if (stmt instanceof PyReturnStatement && ((PyReturnStatement)stmt).getExpression() == null) {
return true;
}
return false;
}
private static boolean isStringLiteral(PyStatement stmt) {
if (stmt instanceof PyExpressionStatement) {
final PyExpression expr = ((PyExpressionStatement)stmt).getExpression();
if (expr instanceof PyStringLiteralExpression) {
return true;
}
}
return false;
}
/**
* This helper class allows to collect various information about AST nodes composing {@link PyStringLiteralExpression}.
*/
public static final class StringNodeInfo {
private final ASTNode myNode;
private final String myPrefix;
private final String myQuote;
private final TextRange myContentRange;
public StringNodeInfo(@NotNull ASTNode node) {
if (!PyTokenTypes.STRING_NODES.contains(node.getElementType())) {
throw new IllegalArgumentException("Node must be valid Python string literal token, but " + node.getElementType() + " was given");
}
myNode = node;
final String nodeText = node.getText();
final int prefixLength = PyStringLiteralExpressionImpl.getPrefixLength(nodeText);
myPrefix = nodeText.substring(0, prefixLength);
myContentRange = PyStringLiteralExpressionImpl.getNodeTextRange(nodeText);
myQuote = nodeText.substring(prefixLength, myContentRange.getStartOffset());
}
public StringNodeInfo(@NotNull PsiElement element) {
this(element.getNode());
}
@NotNull
public ASTNode getNode() {
return myNode;
}
/**
* @return string prefix, e.g. "UR", "b" etc.
*/
@NotNull
public String getPrefix() {
return myPrefix;
}
/**
* @return content of the string node between quotes
*/
@NotNull
public String getContent() {
return myContentRange.substring(myNode.getText());
}
/**
* @return <em>relative</em> range of the content (excluding prefix and quotes)
* @see #getAbsoluteContentRange()
*/
@NotNull
public TextRange getContentRange() {
return myContentRange;
}
/**
* @return <em>absolute</em> content range that accounts offset of the {@link #getNode() node} in the document
*/
@NotNull
public TextRange getAbsoluteContentRange() {
return getContentRange().shiftRight(myNode.getStartOffset());
}
/**
* @return the first character of {@link #getQuote()}
*/
public char getSingleQuote() {
return myQuote.charAt(0);
}
@NotNull
public String getQuote() {
return myQuote;
}
public boolean isTripleQuoted() {
return myQuote.length() == 3;
}
/**
* @return true if string literal ends with starting quote
*/
public boolean isTerminated() {
final String text = myNode.getText();
return text.length() - myPrefix.length() >= myQuote.length() * 2 && text.endsWith(myQuote);
}
/**
* @return true if given string node contains "u" or "U" prefix
*/
public boolean isUnicode() {
return PyStringLiteralUtil.isUnicodePrefix(myPrefix);
}
/**
* @return true if given string node contains "r" or "R" prefix
*/
public boolean isRaw() {
return PyStringLiteralUtil.isRawPrefix(myPrefix);
}
/**
* @return true if given string node contains "b" or "B" prefix
*/
public boolean isBytes() {
return PyStringLiteralUtil.isBytesPrefix(myPrefix);
}
/**
* @return true if given string node contains "f" or "F" prefix
*/
public boolean isFormatted() {
return PyStringLiteralUtil.isFormattedPrefix(myPrefix);
}
/**
* @return true if other string node has the same decorations, i.e. quotes and prefix
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StringNodeInfo info = (StringNodeInfo)o;
return getQuote().equals(info.getQuote()) &&
isRaw() == info.isRaw() &&
isUnicode() == info.isUnicode() &&
isBytes() == info.isBytes();
}
}
public static class IterHelper { // TODO: rename sanely
private IterHelper() {}
@Nullable
public static PsiNamedElement findName(Iterable<PsiNamedElement> it, String name) {
PsiNamedElement ret = null;
for (PsiNamedElement elt : it) {
if (elt != null) {
// qualified refs don't match by last name, and we're not checking FQNs here
if (elt instanceof PyQualifiedExpression && ((PyQualifiedExpression)elt).isQualified()) continue;
if (name.equals(elt.getName())) { // plain name matches
ret = elt;
break;
}
}
}
return ret;
}
}
}
| apache-2.0 |
HonzaKral/elasticsearch | x-pack/plugin/identity-provider/qa/idp-rest-tests/src/test/java/org/elasticsearch/xpack/idp/IdentityProviderAuthenticationIT.java | 11146 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.idp;
import org.apache.http.HttpHost;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.ObjectPath;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.xpack.core.security.action.saml.SamlPrepareAuthenticationResponse;
import org.elasticsearch.xpack.idp.saml.sp.SamlServiceProviderIndex;
import org.junit.Before;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
public class IdentityProviderAuthenticationIT extends IdpRestTestCase {
// From build.gradle
private final String SP_ENTITY_ID = "ec:123456:abcdefg";
private final String SP_ACS = "https://sp1.test.es.elasticsearch.org/saml/acs";
private final String REALM_NAME = "cloud-saml";
@Before
public void setupSecurityData() throws IOException {
setUserPassword("kibana", new SecureString("kibana".toCharArray()));
createApplicationPrivileges("elastic-cloud", Map.ofEntries(
Map.entry("deployment_admin", Set.of("sso:admin")),
Map.entry("deployment_viewer", Set.of("sso:viewer"))
));
}
public void testRegistrationAndIdpInitiatedSso() throws Exception {
final Map<String, Object> request = Map.ofEntries(
Map.entry("name", "Test SP"),
Map.entry("acs", SP_ACS),
Map.entry("privileges", Map.ofEntries(
Map.entry("resource", SP_ENTITY_ID),
Map.entry("roles", List.of("sso:(\\w+)"))
)),
Map.entry("attributes", Map.ofEntries(
Map.entry("principal", "https://idp.test.es.elasticsearch.org/attribute/principal"),
Map.entry("name", "https://idp.test.es.elasticsearch.org/attribute/name"),
Map.entry("email", "https://idp.test.es.elasticsearch.org/attribute/email"),
Map.entry("roles", "https://idp.test.es.elasticsearch.org/attribute/roles")
)));
final SamlServiceProviderIndex.DocumentVersion docVersion = createServiceProvider(SP_ENTITY_ID, request);
checkIndexDoc(docVersion);
ensureGreen(SamlServiceProviderIndex.INDEX_NAME);
final String samlResponse = generateSamlResponse(SP_ENTITY_ID, SP_ACS, null);
authenticateWithSamlResponse(samlResponse, null);
}
public void testRegistrationAndSpInitiatedSso() throws Exception {
final Map<String, Object> request = Map.ofEntries(
Map.entry("name", "Test SP"),
Map.entry("acs", SP_ACS),
Map.entry("privileges", Map.ofEntries(
Map.entry("resource", SP_ENTITY_ID),
Map.entry("roles", List.of("sso:(\\w+)"))
)),
Map.entry("attributes", Map.ofEntries(
Map.entry("principal", "https://idp.test.es.elasticsearch.org/attribute/principal"),
Map.entry("name", "https://idp.test.es.elasticsearch.org/attribute/name"),
Map.entry("email", "https://idp.test.es.elasticsearch.org/attribute/email"),
Map.entry("roles", "https://idp.test.es.elasticsearch.org/attribute/roles")
)));
final SamlServiceProviderIndex.DocumentVersion docVersion = createServiceProvider(SP_ENTITY_ID, request);
checkIndexDoc(docVersion);
ensureGreen(SamlServiceProviderIndex.INDEX_NAME);
SamlPrepareAuthenticationResponse samlPrepareAuthenticationResponse = generateSamlAuthnRequest(REALM_NAME);
final String requestId = samlPrepareAuthenticationResponse.getRequestId();
final String query = samlPrepareAuthenticationResponse.getRedirectUrl().split("\\?")[1];
Map<String, Object> authnState = validateAuthnRequest(SP_ENTITY_ID, query);
final String samlResponse = generateSamlResponse(SP_ENTITY_ID, SP_ACS, authnState);
assertThat(samlResponse, containsString("InResponseTo=\"" + requestId + "\""));
authenticateWithSamlResponse(samlResponse, requestId);
}
private Map<String, Object> validateAuthnRequest(String entityId, String authnRequestQuery) throws Exception {
final Request request = new Request("POST", "/_idp/saml/validate");
request.setJsonEntity("{\"authn_request_query\":\"" + authnRequestQuery + "\"}");
final Response response = client().performRequest(request);
final Map<String, Object> map = entityAsMap(response);
assertThat(ObjectPath.eval("service_provider.entity_id", map), instanceOf(String.class));
assertThat(ObjectPath.eval("service_provider.entity_id", map), equalTo(entityId));
assertThat(ObjectPath.eval("authn_state", map), instanceOf(Map.class));
return ObjectPath.eval("authn_state", map);
}
private SamlPrepareAuthenticationResponse generateSamlAuthnRequest(String realmName) throws Exception {
final Request request = new Request("POST", "/_security/saml/prepare");
request.setJsonEntity("{\"realm\":\"" + realmName + "\"}");
try (RestClient kibanaClient = restClientAsKibana()) {
final Response response = kibanaClient.performRequest(request);
final Map<String, Object> map = entityAsMap(response);
assertThat(ObjectPath.eval("realm", map), equalTo(realmName));
assertThat(ObjectPath.eval("id", map), instanceOf(String.class));
assertThat(ObjectPath.eval("redirect", map), instanceOf(String.class));
return new SamlPrepareAuthenticationResponse(realmName, ObjectPath.eval("id", map), ObjectPath.eval("redirect", map));
}
}
private String generateSamlResponse(String entityId, String acs, @Nullable Map<String, Object> authnState) throws Exception {
final Request request = new Request("POST", "/_idp/saml/init");
if (authnState != null && authnState.isEmpty() == false) {
request.setJsonEntity("{\"entity_id\":\"" + entityId + "\", \"acs\":\"" + acs + "\"," +
"\"authn_state\":" + Strings.toString(JsonXContent.contentBuilder().map(authnState)) + "}");
} else {
request.setJsonEntity("{\"entity_id\":\"" + entityId + "\", \"acs\":\"" + acs + "\"}");
}
request.setOptions(RequestOptions.DEFAULT.toBuilder()
.addHeader("es-secondary-authorization", basicAuthHeaderValue("idp_user",
new SecureString("idp-password".toCharArray())))
.build());
final Response response = client().performRequest(request);
final Map<String, Object> map = entityAsMap(response);
assertThat(ObjectPath.eval("service_provider.entity_id", map), equalTo(entityId));
assertThat(ObjectPath.eval("post_url", map), equalTo(acs));
assertThat(ObjectPath.eval("saml_response", map), instanceOf(String.class));
return (String) ObjectPath.eval("saml_response", map);
}
private void authenticateWithSamlResponse(String samlResponse, @Nullable String id) throws Exception {
final String encodedResponse = Base64.getEncoder().encodeToString(samlResponse.getBytes(StandardCharsets.UTF_8));
final Request request = new Request("POST", "/_security/saml/authenticate");
if (Strings.hasText(id)) {
request.setJsonEntity("{\"content\":\"" + encodedResponse + "\", \"realm\":\"" + REALM_NAME + "\", \"ids\":[\"" + id + "\"]}");
} else {
request.setJsonEntity("{\"content\":\"" + encodedResponse + "\", \"realm\":\"" + REALM_NAME + "\"}");
}
final String accessToken;
try (RestClient kibanaClient = restClientAsKibana()) {
final Response response = kibanaClient.performRequest(request);
final Map<String, Object> map = entityAsMap(response);
assertThat(ObjectPath.eval("username", map), instanceOf(String.class));
assertThat(ObjectPath.eval("username", map), equalTo("idp_user"));
assertThat(ObjectPath.eval("realm", map), instanceOf(String.class));
assertThat(ObjectPath.eval("realm", map), equalTo(REALM_NAME));
assertThat(ObjectPath.eval("access_token", map), instanceOf(String.class));
accessToken = ObjectPath.eval("access_token", map);
assertThat(ObjectPath.eval("refresh_token", map), instanceOf(String.class));
}
try (RestClient accessTokenClient = restClientWithToken(accessToken)) {
final Request authenticateRequest = new Request("GET", "/_security/_authenticate");
final Response authenticateResponse = accessTokenClient.performRequest(authenticateRequest);
final Map<String, Object> authMap = entityAsMap(authenticateResponse);
assertThat(ObjectPath.eval("username", authMap), instanceOf(String.class));
assertThat(ObjectPath.eval("username", authMap), equalTo("idp_user"));
assertThat(ObjectPath.eval("metadata.saml_nameid_format", authMap), instanceOf(String.class));
assertThat(ObjectPath.eval("metadata.saml_nameid_format", authMap),
equalTo("urn:oasis:names:tc:SAML:2.0:nameid-format:transient"));
assertThat(ObjectPath.eval("metadata.saml_roles", authMap), instanceOf(List.class));
assertThat(ObjectPath.eval("metadata.saml_roles", authMap), hasSize(1));
assertThat(ObjectPath.eval("metadata.saml_roles", authMap), contains("viewer"));
}
}
private RestClient restClientWithToken(String accessToken) throws IOException {
return buildClient(
Settings.builder().put(ThreadContext.PREFIX + ".Authorization", "Bearer " + accessToken).build(),
getClusterHosts().toArray(new HttpHost[getClusterHosts().size()]));
}
private RestClient restClientAsKibana() throws IOException {
return buildClient(
Settings.builder().put(ThreadContext.PREFIX + ".Authorization", basicAuthHeaderValue("kibana",
new SecureString("kibana".toCharArray()))).build(),
getClusterHosts().toArray(new HttpHost[getClusterHosts().size()]));
}
}
| apache-2.0 |
kbachl/brix-cms | brix-core/src/main/java/org/brixcms/plugin/site/resource/admin/UploadResourcesPanel.java | 4385 | /**
* 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.brixcms.plugin.site.resource.admin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.MultiFileUploadField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.io.Streams;
import org.brixcms.Brix;
import org.brixcms.jcr.wrapper.BrixFileNode;
import org.brixcms.jcr.wrapper.BrixNode;
import org.brixcms.plugin.site.SimpleCallback;
import org.brixcms.plugin.site.SitePlugin;
import org.brixcms.plugin.site.admin.NodeManagerPanel;
import org.brixcms.web.ContainerFeedbackPanel;
public class UploadResourcesPanel extends NodeManagerPanel {
private Collection<FileUpload> uploads = new ArrayList<FileUpload>();
private boolean overwrite = false;
public UploadResourcesPanel(String id, IModel<BrixNode> model, final SimpleCallback goBack) {
super(id, model);
Form<?> form = new Form<UploadResourcesPanel>("form", new CompoundPropertyModel<UploadResourcesPanel>(this));
add(form);
form.add(new ContainerFeedbackPanel("feedback", this));
form.add(new SubmitLink("upload") {
@Override
public void onSubmit() {
processUploads();
}
});
form.add(new Link<Void>("cancel") {
@Override
public void onClick() {
goBack.execute();
}
});
form.add(new MultiFileUploadField("uploads"));
form.add(new CheckBox("overwrite"));
}
private void processUploads() {
final BrixNode parentNode = getModelObject();
for (final FileUpload upload : uploads) {
final String fileName = upload.getClientFileName();
if (parentNode.hasNode(fileName)) {
if (overwrite) {
parentNode.getNode(fileName).remove();
} else {
class ModelObject implements Serializable {
@SuppressWarnings("unused")
private String fileName = upload.getClientFileName();
}
getSession().error(getString("fileExists", new Model<ModelObject>(new ModelObject())));
continue;
}
}
BrixNode newNode = (BrixNode) parentNode.addNode(fileName, "nt:file");
try {
// copy the upload into a temp file and assign that
// output stream to the node
File temp = File.createTempFile(
Brix.NS + "-upload-" + UUID.randomUUID().toString(), null);
Streams.copy(upload.getInputStream(), new FileOutputStream(temp));
upload.closeStreams();
String mime = upload.getContentType();
BrixFileNode file = BrixFileNode.initialize(newNode, mime);
file.setData(file.getSession().getValueFactory().createBinary(new FileInputStream(temp)));
file.getParent().save();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
SitePlugin.get().selectNode(this, parentNode, true);
}
@Override
protected void onDetach() {
uploads.clear();
super.onDetach();
}
}
| apache-2.0 |
HonzaKral/elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/ingest/InferenceProcessor.java | 15721 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.ml.inference.ingest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.ingest.AbstractProcessor;
import org.elasticsearch.ingest.ConfigurationUtils;
import org.elasticsearch.ingest.IngestDocument;
import org.elasticsearch.ingest.IngestMetadata;
import org.elasticsearch.ingest.IngestService;
import org.elasticsearch.ingest.Pipeline;
import org.elasticsearch.ingest.PipelineConfiguration;
import org.elasticsearch.ingest.Processor;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.xpack.core.ml.action.InternalInferModelAction;
import org.elasticsearch.xpack.core.ml.inference.results.WarningInferenceResults;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.ClassificationConfig;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.ClassificationConfigUpdate;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceConfig;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceConfigUpdate;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.RegressionConfig;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.RegressionConfigUpdate;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.ml.inference.loadingservice.Model;
import org.elasticsearch.xpack.ml.notifications.InferenceAuditor;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import static org.elasticsearch.xpack.core.ClientHelper.ML_ORIGIN;
import static org.elasticsearch.xpack.core.ClientHelper.executeAsyncWithOrigin;
public class InferenceProcessor extends AbstractProcessor {
// How many total inference processors are allowed to be used in the cluster.
public static final Setting<Integer> MAX_INFERENCE_PROCESSORS = Setting.intSetting("xpack.ml.max_inference_processors",
50,
1,
Setting.Property.Dynamic,
Setting.Property.NodeScope);
public static final String TYPE = "inference";
public static final String MODEL_ID = "model_id";
public static final String INFERENCE_CONFIG = "inference_config";
public static final String TARGET_FIELD = "target_field";
public static final String FIELD_MAPPINGS = "field_mappings";
public static final String FIELD_MAP = "field_map";
private static final String DEFAULT_TARGET_FIELD = "ml.inference";
private final Client client;
private final String modelId;
private final String targetField;
private final InferenceConfigUpdate<? extends InferenceConfig> inferenceConfig;
private final Map<String, String> fieldMap;
private final InferenceAuditor auditor;
private volatile boolean previouslyLicensed;
private final AtomicBoolean shouldAudit = new AtomicBoolean(true);
public InferenceProcessor(Client client,
InferenceAuditor auditor,
String tag,
String targetField,
String modelId,
InferenceConfigUpdate<? extends InferenceConfig> inferenceConfig,
Map<String, String> fieldMap) {
super(tag);
this.client = ExceptionsHelper.requireNonNull(client, "client");
this.targetField = ExceptionsHelper.requireNonNull(targetField, TARGET_FIELD);
this.auditor = ExceptionsHelper.requireNonNull(auditor, "auditor");
this.modelId = ExceptionsHelper.requireNonNull(modelId, MODEL_ID);
this.inferenceConfig = ExceptionsHelper.requireNonNull(inferenceConfig, INFERENCE_CONFIG);
this.fieldMap = ExceptionsHelper.requireNonNull(fieldMap, FIELD_MAP);
}
public String getModelId() {
return modelId;
}
@Override
public void execute(IngestDocument ingestDocument, BiConsumer<IngestDocument, Exception> handler) {
executeAsyncWithOrigin(client,
ML_ORIGIN,
InternalInferModelAction.INSTANCE,
this.buildRequest(ingestDocument),
ActionListener.wrap(
r -> handleResponse(r, ingestDocument, handler),
e -> handler.accept(ingestDocument, e)
));
}
void handleResponse(InternalInferModelAction.Response response,
IngestDocument ingestDocument,
BiConsumer<IngestDocument, Exception> handler) {
if (previouslyLicensed == false) {
previouslyLicensed = true;
}
if (response.isLicensed() == false) {
auditWarningAboutLicenseIfNecessary();
}
try {
mutateDocument(response, ingestDocument);
handler.accept(ingestDocument, null);
} catch(ElasticsearchException ex) {
handler.accept(ingestDocument, ex);
}
}
InternalInferModelAction.Request buildRequest(IngestDocument ingestDocument) {
Map<String, Object> fields = new HashMap<>(ingestDocument.getSourceAndMetadata());
Model.mapFieldsIfNecessary(fields, fieldMap);
return new InternalInferModelAction.Request(modelId, fields, inferenceConfig, previouslyLicensed);
}
void auditWarningAboutLicenseIfNecessary() {
if (shouldAudit.compareAndSet(true, false)) {
auditor.warning(
modelId,
"This cluster is no longer licensed to use this model in the inference ingest processor. " +
"Please update your license information.");
}
}
void mutateDocument(InternalInferModelAction.Response response, IngestDocument ingestDocument) {
if (response.getInferenceResults().isEmpty()) {
throw new ElasticsearchStatusException("Unexpected empty inference response", RestStatus.INTERNAL_SERVER_ERROR);
}
assert response.getInferenceResults().size() == 1;
response.getInferenceResults().get(0).writeResult(ingestDocument, this.targetField);
ingestDocument.setFieldValue(targetField + "." + MODEL_ID, modelId);
}
@Override
public IngestDocument execute(IngestDocument ingestDocument) {
throw new UnsupportedOperationException("should never be called");
}
@Override
public String getType() {
return TYPE;
}
public static final class Factory implements Processor.Factory, Consumer<ClusterState> {
private static final Logger logger = LogManager.getLogger(Factory.class);
private static final Set<String> RESERVED_ML_FIELD_NAMES = new HashSet<>(Arrays.asList(
WarningInferenceResults.WARNING.getPreferredName(),
MODEL_ID));
private final Client client;
private final IngestService ingestService;
private final InferenceAuditor auditor;
private volatile int currentInferenceProcessors;
private volatile int maxIngestProcessors;
private volatile Version minNodeVersion = Version.CURRENT;
public Factory(Client client,
ClusterService clusterService,
Settings settings,
IngestService ingestService) {
this.client = client;
this.maxIngestProcessors = MAX_INFERENCE_PROCESSORS.get(settings);
this.ingestService = ingestService;
this.auditor = new InferenceAuditor(client, clusterService.getNodeName());
clusterService.getClusterSettings().addSettingsUpdateConsumer(MAX_INFERENCE_PROCESSORS, this::setMaxIngestProcessors);
}
@Override
public void accept(ClusterState state) {
minNodeVersion = state.nodes().getMinNodeVersion();
Metadata metadata = state.getMetadata();
if (metadata == null) {
currentInferenceProcessors = 0;
return;
}
IngestMetadata ingestMetadata = metadata.custom(IngestMetadata.TYPE);
if (ingestMetadata == null) {
currentInferenceProcessors = 0;
return;
}
int count = 0;
for (PipelineConfiguration configuration : ingestMetadata.getPipelines().values()) {
try {
Pipeline pipeline = Pipeline.create(configuration.getId(),
configuration.getConfigAsMap(),
ingestService.getProcessorFactories(),
ingestService.getScriptService());
count += pipeline.getProcessors().stream().filter(processor -> processor instanceof InferenceProcessor).count();
} catch (Exception ex) {
logger.warn(new ParameterizedMessage("failure parsing pipeline config [{}]", configuration.getId()), ex);
}
}
currentInferenceProcessors = count;
}
// Used for testing
int numInferenceProcessors() {
return currentInferenceProcessors;
}
@Override
public InferenceProcessor create(Map<String, Processor.Factory> processorFactories, String tag, Map<String, Object> config) {
if (this.maxIngestProcessors <= currentInferenceProcessors) {
throw new ElasticsearchStatusException("Max number of inference processors reached, total inference processors [{}]. " +
"Adjust the setting [{}]: [{}] if a greater number is desired.",
RestStatus.CONFLICT,
currentInferenceProcessors,
MAX_INFERENCE_PROCESSORS.getKey(),
maxIngestProcessors);
}
String modelId = ConfigurationUtils.readStringProperty(TYPE, tag, config, MODEL_ID);
String defaultTargetField = tag == null ? DEFAULT_TARGET_FIELD : DEFAULT_TARGET_FIELD + "." + tag;
// If multiple inference processors are in the same pipeline, it is wise to tag them
// The tag will keep default value entries from stepping on each other
String targetField = ConfigurationUtils.readStringProperty(TYPE, tag, config, TARGET_FIELD, defaultTargetField);
Map<String, String> fieldMap = ConfigurationUtils.readOptionalMap(TYPE, tag, config, FIELD_MAP);
if (fieldMap == null) {
fieldMap = ConfigurationUtils.readOptionalMap(TYPE, tag, config, FIELD_MAPPINGS);
//TODO Remove in 8.x
if (fieldMap != null) {
LoggingDeprecationHandler.INSTANCE.usedDeprecatedName(null, () -> null, FIELD_MAPPINGS, FIELD_MAP);
}
}
InferenceConfigUpdate<? extends InferenceConfig> inferenceConfig =
inferenceConfigFromMap(ConfigurationUtils.readMap(TYPE, tag, config, INFERENCE_CONFIG));
return new InferenceProcessor(client,
auditor,
tag,
targetField,
modelId,
inferenceConfig,
fieldMap);
}
// Package private for testing
void setMaxIngestProcessors(int maxIngestProcessors) {
logger.trace("updating setting maxIngestProcessors from [{}] to [{}]", this.maxIngestProcessors, maxIngestProcessors);
this.maxIngestProcessors = maxIngestProcessors;
}
InferenceConfigUpdate<? extends InferenceConfig> inferenceConfigFromMap(Map<String, Object> inferenceConfig) {
ExceptionsHelper.requireNonNull(inferenceConfig, INFERENCE_CONFIG);
if (inferenceConfig.size() != 1) {
throw ExceptionsHelper.badRequestException("{} must be an object with one inference type mapped to an object.",
INFERENCE_CONFIG);
}
Object value = inferenceConfig.values().iterator().next();
if ((value instanceof Map<?, ?>) == false) {
throw ExceptionsHelper.badRequestException("{} must be an object with one inference type mapped to an object.",
INFERENCE_CONFIG);
}
@SuppressWarnings("unchecked")
Map<String, Object> valueMap = (Map<String, Object>)value;
if (inferenceConfig.containsKey(ClassificationConfig.NAME.getPreferredName())) {
checkSupportedVersion(ClassificationConfig.EMPTY_PARAMS);
ClassificationConfigUpdate config = ClassificationConfigUpdate.fromMap(valueMap);
checkFieldUniqueness(config.getResultsField(), config.getTopClassesResultsField());
return config;
} else if (inferenceConfig.containsKey(RegressionConfig.NAME.getPreferredName())) {
checkSupportedVersion(RegressionConfig.EMPTY_PARAMS);
RegressionConfigUpdate config = RegressionConfigUpdate.fromMap(valueMap);
checkFieldUniqueness(config.getResultsField());
return config;
} else {
throw ExceptionsHelper.badRequestException("unrecognized inference configuration type {}. Supported types {}",
inferenceConfig.keySet(),
Arrays.asList(ClassificationConfig.NAME.getPreferredName(), RegressionConfig.NAME.getPreferredName()));
}
}
private static void checkFieldUniqueness(String... fieldNames) {
Set<String> duplicatedFieldNames = new HashSet<>();
Set<String> currentFieldNames = new HashSet<>(RESERVED_ML_FIELD_NAMES);
for(String fieldName : fieldNames) {
if (fieldName == null) {
continue;
}
if (currentFieldNames.contains(fieldName)) {
duplicatedFieldNames.add(fieldName);
} else {
currentFieldNames.add(fieldName);
}
}
if (duplicatedFieldNames.isEmpty() == false) {
throw ExceptionsHelper.badRequestException("Cannot create processor as configured." +
" More than one field is configured as {}",
duplicatedFieldNames);
}
}
void checkSupportedVersion(InferenceConfig config) {
if (config.getMinimalSupportedVersion().after(minNodeVersion)) {
throw ExceptionsHelper.badRequestException(Messages.getMessage(Messages.INFERENCE_CONFIG_NOT_SUPPORTED_ON_VERSION,
config.getName(),
config.getMinimalSupportedVersion(),
minNodeVersion));
}
}
}
}
| apache-2.0 |
robojukie/myrobotlab | src/org/myrobotlab/serial/SoftwarePort.java | 72 | package org.myrobotlab.serial;
public abstract class SoftwarePort {
}
| apache-2.0 |
sujianping/Office-365-SDK-for-Android | sdk/office365-mail-calendar-contact-sdk/odata/engine/src/test/java/com/msopentech/odatajclient/engine/it/PropertyValueTestITCase.java | 9081 | /**
* Copyright © Microsoft Open Technologies, Inc.
*
* All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
* ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
* PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache License, Version 2.0 for the specific language
* governing permissions and limitations under the License.
*/
package com.msopentech.odatajclient.engine.it;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
import com.msopentech.odatajclient.engine.communication.ODataClientErrorException;
import com.msopentech.odatajclient.engine.communication.request.retrieve.ODataEntityRequest;
import com.msopentech.odatajclient.engine.communication.request.retrieve.RetrieveRequestFactory;
import com.msopentech.odatajclient.engine.communication.request.retrieve.ODataValueRequest;
import com.msopentech.odatajclient.engine.communication.response.ODataRetrieveResponse;
import com.msopentech.odatajclient.engine.data.ODataEntity;
import com.msopentech.odatajclient.engine.uri.URIBuilder;
import com.msopentech.odatajclient.engine.data.ODataValue;
import com.msopentech.odatajclient.engine.format.ODataValueFormat;
public class PropertyValueTestITCase extends AbstractTest {
//retrieves Edm.Int32
@Test
public void retrieveIntPropertyValueTest() {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendEntityTypeSegment("Product").appendKeySegment(-10).appendStructuralSegment("ProductId").
appendValueSegment();
final ODataValueRequest req = client.getRetrieveRequestFactory().getValueRequest(uriBuilder.build());
req.setFormat(ODataValueFormat.TEXT);
final ODataValue value = req.execute().getBody();
assertNotNull(value);
assertEquals(-10, Integer.parseInt(value.toString()));
}
//retrieves boolean
@Test
public void retrieveBooleanPropertyValueTest() {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendEntityTypeSegment("Product").appendKeySegment(-10).appendStructuralSegment("ProductId").
appendValueSegment();
final ODataValueRequest req = client.getRetrieveRequestFactory().getValueRequest(uriBuilder.build());
req.setFormat(ODataValueFormat.TEXT);
final ODataValue value = req.execute().getBody();
assertNotNull(value);
assertEquals(-10, Integer.parseInt(value.toString()));
}
//retrieves Edm.String
@Test
public void retrieveStringPropertyValueTest() {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendEntityTypeSegment("Product").appendKeySegment(-6).appendStructuralSegment("Description").
appendValueSegment();
final ODataValueRequest req = client.getRetrieveRequestFactory().getValueRequest(uriBuilder.build());
req.setFormat(ODataValueFormat.TEXT);
final ODataValue value = req.execute().getBody();
assertNotNull(value);
assertEquals("expdybhclurfobuyvzmhkgrnrajhamqmkhqpmiypittnp", value.toString());
}
// date from a complex structure.
@Test
public void retrieveDatePropertyValueTest() {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendEntityTypeSegment("Product").appendKeySegment(-7).appendStructuralSegment(
"NestedComplexConcurrency/ModifiedDate").appendValueSegment();
final ODataValueRequest req = client.getRetrieveRequestFactory().getValueRequest(uriBuilder.build());
req.setFormat(ODataValueFormat.TEXT);
final ODataValue value = req.execute().getBody();
assertNotNull(value);
assertEquals("7866-11-16T22:25:52.747755+01:00", value.toString());
}
//decimal type test
@Test
public void retrieveDecimalPropertyValueTest() {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendEntityTypeSegment("Product").appendKeySegment(-6).appendStructuralSegment("Dimensions/Height").
appendValueSegment();
final ODataValueRequest req = client.getRetrieveRequestFactory().getValueRequest(uriBuilder.build());
req.setFormat(ODataValueFormat.TEXT);
final ODataValue value = req.execute().getBody();
assertNotNull(value);
assertEquals("-79228162514264337593543950335", value.toString());
}
//binary test with json format
@Test
public void retrieveBinaryPropertyValueTest() throws IOException {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendNavigationLinkSegment("ProductPhoto(PhotoId=-3,ProductId=-3)").appendStructuralSegment("Photo");
ODataEntityRequest req = client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build());
req.setAccept("application/json");
ODataRetrieveResponse<ODataEntity> res = req.execute();
assertEquals(200, res.getStatusCode());
ODataEntity entitySet = res.getBody();
assertNotNull(entitySet);
assertEquals(
"fi653p3+MklA/LdoBlhWgnMTUUEo8tEgtbMXnF0a3CUNL9BZxXpSRiD9ebTnmNR0zWPjJVIDx4tdmCnq55XrJh+RW9aI/b34wAogK3kcORw=",
entitySet.getProperties().get(0).getValue().toString());
}
//binary test with atom format.
@Test(expected = ODataClientErrorException.class)
public void retrieveBinaryPropertyValueTestWithAtom() throws IOException {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendNavigationLinkSegment("ProductPhoto(PhotoId=-3,ProductId=-3)").appendStructuralSegment("Photo");
ODataEntityRequest req = client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build());
req.setAccept("application/atom+xml");
ODataRetrieveResponse<ODataEntity> res = req.execute();
assertEquals(200, res.getStatusCode());
ODataEntity entitySet = res.getBody();
assertNotNull(entitySet);
assertEquals(
"fi653p3+MklA/LdoBlhWgnMTUUEo8tEgtbMXnF0a3CUNL9BZxXpSRiD9ebTnmNR0zWPjJVIDx4tdmCnq55XrJh+RW9aI/b34wAogK3kcORw=",
entitySet.getProperties().get(0).getValue().toString());
}
// binary data with xml. Unable to deserialize JSON
@Test(expected = IllegalArgumentException.class)
public void retrieveBinaryPropertyValueTestWithXML() throws IOException {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendNavigationLinkSegment("ProductPhoto(PhotoId=-3,ProductId=-3)").appendStructuralSegment("Photo");
ODataEntityRequest req = client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build());
req.setAccept("application/xml");
ODataRetrieveResponse<ODataEntity> res = req.execute();
assertEquals(200, res.getStatusCode());
ODataEntity entitySet = res.getBody();
assertNotNull(entitySet);
assertEquals(
"fi653p3+MklA/LdoBlhWgnMTUUEo8tEgtbMXnF0a3CUNL9BZxXpSRiD9ebTnmNR0zWPjJVIDx4tdmCnq55XrJh+RW9aI/b34wAogK3kcORw=",
entitySet.getProperties().get(0).getValue().toString());
}
//collection of primitives
@Test
public void retrieveCollectionPropertyValueTest() {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendEntityTypeSegment("Product").appendKeySegment(-7).appendStructuralSegment(
"ComplexConcurrency/QueriedDateTime").appendValueSegment();
final ODataValueRequest req = client.getRetrieveRequestFactory().getValueRequest(uriBuilder.build());
req.setFormat(ODataValueFormat.TEXT);
final ODataValue value = req.execute().getBody();
if (value.isPrimitive()) {
assertNotNull(value);
assertEquals("2013-09-18T00:44:43.6196168", value.toString());
}
}
// No resource found error. Token is not available under ComplexConcurrency
@Test
public void retrieveNullPropertyValueTest() {
URIBuilder uriBuilder = client.getURIBuilder(testDefaultServiceRootURL).
appendEntityTypeSegment("Product").appendKeySegment(-10).appendStructuralSegment(
"ComplexConcurrency/Token").appendValueSegment();
final ODataValueRequest req = client.getRetrieveRequestFactory().getValueRequest(uriBuilder.build());
try {
final ODataValue value = req.execute().getBody();
} catch (ODataClientErrorException e) {
assertEquals(404, e.getStatusLine().getStatusCode());
}
}
}
| apache-2.0 |
runnerfish/ssh2_code_learn | SSH2 Code Kit/04/4.5/simpleInterceptor/WEB-INF/src/org/crazyit/app/interceptor/SimpleInterceptor.java | 1487 | package org.crazyit.app.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import java.util.*;
import org.crazyit.app.action.*;
/**
* Description:
* <br/>ÍøÕ¾: <a href="http://www.crazyit.org">·è¿ñJavaÁªÃË</a>
* <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
public class SimpleInterceptor
extends AbstractInterceptor
{
//¼òµ¥À¹½ØÆ÷µÄÃû×Ö
private String name;
//Ϊ¸Ã¼òµ¥À¹½ØÆ÷ÉèÖÃÃû×ÖµÄsetter·½·¨
public void setName(String name)
{
this.name = name;
}
public String intercept(ActionInvocation invocation)
throws Exception
{
//È¡µÃ±»À¹½ØµÄActionʵÀý
LoginAction action = (LoginAction)invocation.getAction();
//´òÓ¡Ö´ÐпªÊ¼µÄʵÏÖ
System.out.println(name + " À¹½ØÆ÷µÄ¶¯×÷---------" +
"¿ªÊ¼Ö´ÐеǼActionµÄʱ¼äΪ£º" + new Date());
//È¡µÃ¿ªÊ¼Ö´ÐÐActionµÄʱ¼ä
long start = System.currentTimeMillis();
//Ö´ÐиÃÀ¹½ØÆ÷µÄºóÒ»¸öÀ¹½ØÆ÷
//Èç¹û¸ÃÀ¹½ØÆ÷ºóûÓÐÆäËûÀ¹½ØÆ÷£¬ÔòÖ±½ÓÖ´ÐÐActionµÄexecute·½·¨
String result = invocation.invoke();
//´òÓ¡Ö´ÐнáÊøµÄʱ¼ä
System.out.println(name + " À¹½ØÆ÷µÄ¶¯×÷---------" +
"Ö´ÐÐÍêµÇ¼ActionµÄʱ¼äΪ£º" + new Date());
long end = System.currentTimeMillis();
System.out.println(name + " À¹½ØÆ÷µÄ¶¯×÷---------" +
"Ö´ÐÐÍê¸ÃActionµÄʼþΪ" + (end - start) + "ºÁÃë");
return result;
}
}
| apache-2.0 |
kensipe/hdfs | mesos-commons/src/main/java/org/apache/mesos/protobuf/AttributeUtil.java | 1544 | package org.apache.mesos.protobuf;
import org.apache.mesos.Protos;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Utility class for creating attributes. This class reduces the overhead of protobuf and makes code
* easier to read.
*/
public class AttributeUtil {
public static Protos.Attribute createScalarAttribute(String name, double value) {
return Protos.Attribute.newBuilder()
.setName(name)
.setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(value).build())
.build();
}
public static Protos.Attribute createRangeAttribute(String name, long begin, long end) {
Protos.Value.Range range = Protos.Value.Range.newBuilder().setBegin(begin).setEnd(end).build();
return Protos.Attribute.newBuilder()
.setName(name)
.setType(Protos.Value.Type.RANGES)
.setRanges(Protos.Value.Ranges.newBuilder().addRange(range))
.build();
}
public static Protos.Attribute createTextAttribute(String name, String value) {
return Protos.Attribute.newBuilder()
.setName(name)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(value).build())
.build();
}
public static Protos.Attribute createTextAttributeSet(String name, String values) {
return Protos.Attribute.newBuilder()
.setName(name)
.setType(Protos.Value.Type.SET)
.setSet(Protos.Value.Set.newBuilder().addAllItem(new ArrayList<String>(Arrays.asList(values.split(",")))))
.build();
}
}
| apache-2.0 |
007slm/nutz | src/org/nutz/el/Parse.java | 703 | package org.nutz.el;
import org.nutz.el.parse.CharQueue;
/**
* 转换器接口.<br>
* 负责对字符队列进行转意,将其零散的字符转换成有具体意义的对象.
* @author juqkai(juqkai@gmail.com)
*
*/
public interface Parse {
/**
* 空对象, 这样更好判断空值
*/
static final Object nullobj = new Object();
/**
* 提取队列顶部元素<br>
* 特别注意,实现本方法的子程序只应该读取自己要转换的数据,不是自己要使用的数据一律不做取操作.<br>
* 一句话,只读取自己能转换的,自己不能转换的一律不操作.
* @param exp 表达式
*/
Object fetchItem(CharQueue exp);
}
| apache-2.0 |
nmldiegues/stibt | infinispan/core/src/main/java/org/infinispan/dataplacement/c50/tree/node/Type3Node.java | 4790 | /*
* INESC-ID, Instituto de Engenharia de Sistemas e Computadores Investigação e Desevolvimento em Lisboa
* Copyright 2013 INESC-ID and/or its affiliates and other
* contributors as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This 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.0 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.infinispan.dataplacement.c50.tree.node;
import org.infinispan.dataplacement.c50.keyfeature.Feature;
import org.infinispan.dataplacement.c50.keyfeature.FeatureValue;
import org.infinispan.dataplacement.c50.tree.ParseTreeNode;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
/**
* Type 3 decision tree node: discrete attributes when possible values are in describe in the rules
*
* @author Pedro Ruivo
* @since 5.2
*/
public class Type3Node implements DecisionTreeNode {
private static final Log log = LogFactory.getLog(Type3Node.class);
private final int value;
private final Feature feature;
private final DecisionTreeNode[] forks;
private final InternalEltsValues[] values;
public Type3Node(int value, Feature feature, DecisionTreeNode[] forks, ParseTreeNode.EltsValues[] eltsValues) {
this.value = value;
this.feature = feature;
if (forks == null || forks.length == 0) {
throw new IllegalArgumentException("Expected a non-null with at least one fork");
}
if (forks.length != eltsValues.length) {
throw new IllegalArgumentException("Expected same number of forks as options");
}
this.forks = forks;
values = new InternalEltsValues[eltsValues.length - 1];
//the first value is the N/A that it is always in the forks[0]
for (int i = 0; i < values.length; ++i) {
values[i] = new InternalEltsValues(eltsValues[i + 1].getValues(), feature);
}
}
@Override
public DecisionTreeNode find(Map<Feature, FeatureValue> keyFeatures) {
if (log.isTraceEnabled()) {
log.tracef("Try to find key [%s] with feature %s", keyFeatures, feature);
}
FeatureValue keyValue = keyFeatures.get(feature);
if (keyValue == null) { //N/A
if (log.isTraceEnabled()) {
log.tracef("Feature Not Available...");
}
return forks[0];
}
if (log.isTraceEnabled()) {
log.tracef("Comparing key value [%s] with possible values %s", keyValue, values);
}
for (int i = 0; i < values.length; ++i) {
if (values[i].match(keyValue)) {
if (log.isTraceEnabled()) {
log.tracef("Next decision tree found. The value in %s matched", i);
}
return forks[i + 1];
}
}
throw new IllegalStateException("Expected one value match");
}
@Override
public int getValue() {
return value;
}
@Override
public int getDeep() {
int maxDeep = 0;
for (DecisionTreeNode decisionTreeNode : forks) {
maxDeep = Math.max(maxDeep, decisionTreeNode.getDeep());
}
return maxDeep + 1;
}
public static class InternalEltsValues implements Serializable {
private final FeatureValue[] values;
public InternalEltsValues(Collection<String> eltsValues, Feature feature) {
values = new FeatureValue[eltsValues.size()];
int index = 0;
for (String value : eltsValues) {
values[index++] = feature.featureValueFromParser(value);
}
}
@Override
public String toString() {
return "InternalEltsValues{" +
"values=" + (values == null ? null : Arrays.asList(values)) +
'}';
}
private boolean match(FeatureValue keyValue) {
for (FeatureValue value : values) {
if (value.isEquals(keyValue)) {
return true;
}
}
return false;
}
}
} | apache-2.0 |
dumitru-petrusca/gosu-lang | idea-gosu-plugin/src/main/java/gw/plugin/ij/debugger/GosuEditorTextProvider.java | 4534 | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.plugin.ij.debugger;
import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.impl.EditorTextProvider;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiCallExpression;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiEnumConstant;
import com.intellij.psi.PsiIdentifier;
import com.intellij.psi.PsiKeyword;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.PsiStatement;
import com.intellij.psi.PsiThisExpression;
import com.intellij.psi.PsiVariable;
import com.intellij.util.IncorrectOperationException;
import gw.plugin.ij.lang.psi.impl.expressions.GosuReferenceExpressionImpl;
import gw.plugin.ij.lang.psi.util.GosuPsiParseUtil;
import org.jetbrains.annotations.Nullable;
/**
*/
public class GosuEditorTextProvider implements EditorTextProvider {
private static final Logger LOG = Logger.getInstance( GosuEditorTextProvider.class );
@Override
public TextWithImports getEditorText( PsiElement elementAtCaret ) {
String result = null;
PsiElement element = findExpression( elementAtCaret );
if( element != null ) {
if( element instanceof GosuReferenceExpressionImpl ) {
final GosuReferenceExpressionImpl reference = (GosuReferenceExpressionImpl)element;
if( reference.getQualifier() == null ) {
final PsiElement resolved = reference.resolve();
if( resolved instanceof PsiEnumConstant ) {
final PsiEnumConstant enumConstant = (PsiEnumConstant)resolved;
final PsiClass enumClass = enumConstant.getContainingClass();
if( enumClass != null ) {
result = enumClass.getName() + "." + enumConstant.getName();
}
}
}
}
if( result == null ) {
result = element.getText();
}
}
return result != null ? new TextWithImportsImpl( CodeFragmentKind.EXPRESSION, result ) : null;
}
@Nullable
private static PsiElement findExpression( PsiElement element ) {
if( !(element instanceof PsiIdentifier || element instanceof PsiKeyword) ) {
return null;
}
PsiElement parent = element.getParent();
if( parent instanceof PsiVariable ) {
return element;
}
if( parent instanceof GosuReferenceExpressionImpl ) {
if( parent.getParent() instanceof PsiCallExpression ) {
return parent.getParent();
}
return parent;
}
if( parent instanceof PsiThisExpression ) {
return parent;
}
return null;
}
@Nullable
public Pair<PsiElement, TextRange> findExpression( PsiElement element, boolean allowMethodCalls ) {
if( !(element instanceof PsiIdentifier || element instanceof PsiKeyword) ) {
return null;
}
PsiElement expression = null;
PsiElement parent = element.getParent();
if( parent instanceof PsiVariable ) {
expression = element;
}
else if( parent instanceof GosuReferenceExpressionImpl ) {
final PsiElement pparent = parent.getParent();
if( pparent instanceof PsiCallExpression ) {
parent = pparent;
}
if( allowMethodCalls || !DebuggerUtils.hasSideEffects( parent ) ) {
expression = parent;
}
}
else if( parent instanceof PsiThisExpression ) {
expression = parent;
}
if( expression != null ) {
try {
PsiElement context = element;
if( parent instanceof PsiParameter ) {
try {
context = ((PsiMethod)((PsiParameter)parent).getDeclarationScope()).getBody();
}
catch( Throwable ignored ) {
}
}
else {
while( context != null && !(context instanceof PsiStatement) && !(context instanceof PsiClass) ) {
context = context.getParent();
}
}
TextRange textRange = expression.getTextRange();
PsiElement psiExpression = GosuPsiParseUtil.parseExpression( expression.getText(), element.getManager() );
return Pair.create( psiExpression, textRange );
}
catch( IncorrectOperationException e ) {
LOG.debug( e );
}
}
return null;
}
}
| apache-2.0 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/bytestreams/socks5/Socks5BytestreamSession.java | 3149 | /**
*
* Copyright 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.jivesoftware.smackx.bytestreams.socks5;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import org.jivesoftware.smackx.bytestreams.BytestreamSession;
/**
* Socks5BytestreamSession class represents a SOCKS5 Bytestream session.
*
* @author Henning Staib
*/
public class Socks5BytestreamSession implements BytestreamSession {
/* the underlying socket of the SOCKS5 Bytestream */
private final Socket socket;
/* flag to indicate if this session is a direct or mediated connection */
private final boolean isDirect;
public Socks5BytestreamSession(Socket socket, boolean isDirect) {
this.socket = socket;
this.isDirect = isDirect;
}
/**
* Returns <code>true</code> if the session is established through a direct connection between
* the initiator and target, <code>false</code> if the session is mediated over a SOCKS proxy.
*
* @return <code>true</code> if session is a direct connection, <code>false</code> if session is
* mediated over a SOCKS5 proxy
*/
public boolean isDirect() {
return this.isDirect;
}
/**
* Returns <code>true</code> if the session is mediated over a SOCKS proxy, <code>false</code>
* if this session is established through a direct connection between the initiator and target.
*
* @return <code>true</code> if session is mediated over a SOCKS5 proxy, <code>false</code> if
* session is a direct connection
*/
public boolean isMediated() {
return !this.isDirect;
}
@Override
public InputStream getInputStream() throws IOException {
return this.socket.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return this.socket.getOutputStream();
}
@Override
public int getReadTimeout() throws IOException {
try {
return this.socket.getSoTimeout();
}
catch (SocketException e) {
throw new IOException("Error on underlying Socket");
}
}
@Override
public void setReadTimeout(int timeout) throws IOException {
try {
this.socket.setSoTimeout(timeout);
}
catch (SocketException e) {
throw new IOException("Error on underlying Socket");
}
}
@Override
public void close() throws IOException {
this.socket.close();
}
}
| apache-2.0 |
stackforge/monasca-common | java/monasca-common-hibernate/src/main/java/monasca/common/hibernate/db/MetricDefinitionDb.java | 2099 | /*
* Copyright 2015 FUJITSU LIMITED
*
* 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 monasca.common.hibernate.db;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import monasca.common.hibernate.type.BinaryId;
@Entity
@Table(name = "metric_definition")
public class MetricDefinitionDb
extends AbstractUUIDPersistable {
private static final long serialVersionUID = 292896181025585969L;
@Column(name = "name", length = 255, nullable = false)
private String name;
@Column(name = "tenant_id", length = 36, nullable = false)
private String tenantId;
@Column(name = "region", length = 255, nullable = false)
private String region;
public MetricDefinitionDb() {
super();
}
public MetricDefinitionDb(BinaryId id, String name, String tenantId, String region) {
super(id);
this.name = name;
this.tenantId = tenantId;
this.region = region;
}
public MetricDefinitionDb(byte[] id, String name, String tenantId, String region) {
this(new BinaryId(id), name, tenantId, region);
}
public MetricDefinitionDb setRegion(final String region) {
this.region = region;
return this;
}
public MetricDefinitionDb setTenantId(final String tenantId) {
this.tenantId = tenantId;
return this;
}
public MetricDefinitionDb setName(final String name) {
this.name = name;
return this;
}
public String getName() {
return this.name;
}
public String getTenantId() {
return this.tenantId;
}
public String getRegion() {
return this.region;
}
}
| apache-2.0 |