lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | error: pathspec 'src/GeeksforGeeksPractice/_0098EditDistance.java' did not match any file(s) known to git
| a3e21dc3edb60c34dd488e49733ffca102af39f0 | 1 | darshanhs90/Java-Coding,darshanhs90/Java-InterviewPrep | package GeeksforGeeksPractice;
/*
* Link : http://www.geeksforgeeks.org/dynamic-programming-set-5-edit-distance/
*/
public class _0098EditDistance {
public static void main(String[] args) {
String x = "sunday";
String y = "saturday";
findEditDistance(x,y);
}
private static void findEditDistance(String x, String y) {
int m=x.length();
int n=y.length();
int[][] dp=new int[m+1][n+1];
for (int i = 0; i <=m; i++) {
for (int j = 0; j <=n; j++) {
if(i==0)
dp[i][j]=j;
else if(j==0)
dp[i][j]=i;
else if(x.charAt(i-1)==y.charAt(j-1))
dp[i][j]=dp[i-1][j-1];
else
dp[i][j]=1+Math.min(dp[i-1][j],Math.min(dp[i][j-1], dp[i-1][j-1]));
}
}
System.out.println(dp[m][n]);
}
}
| src/GeeksforGeeksPractice/_0098EditDistance.java | edit distance completed | src/GeeksforGeeksPractice/_0098EditDistance.java | edit distance completed |
|
Java | mit | error: pathspec 'src/main/java/exceptions/engine/ObjectInfoException.java' did not match any file(s) known to git
| e4ec54400488c18c22b8b9c6376990deabe11261 | 1 | dianwen/oogasalad_TowerDefense,sdh31/tower_defense,jordanly/oogasalad_OOGALoompas,dennis-park/OOGALoompas,codylieu/oogasalad_OOGALoompas,garysheng/tower-defense-game-engine,kevinkdo/oogasalad_OOGALoompas | package main.java.exceptions.engine;
public class ObjectInfoException extends Exception {
public ObjectInfoException(String s) {
super(s);
}
}
| src/main/java/exceptions/engine/ObjectInfoException.java | Added exception for info grabbing
| src/main/java/exceptions/engine/ObjectInfoException.java | Added exception for info grabbing |
|
Java | mit | error: pathspec 'codeplay-base/src/main/java/com/tazine/base/NumberUtils.java' did not match any file(s) known to git
| c6976baec7b4f3d662944508b9eea86e398eb6a1 | 1 | BookFrank/CodePlay,BookFrank/CodePlay,BookFrank/CodePlay | package com.tazine.base;
import java.math.BigDecimal;
import java.text.DecimalFormat;
/**
* NumberUtils
*
* @author frank
* @date 2019/06/26
*/
public class NumberUtils {
public static void main(String[] args) {
double d1 = 3.1415926;
//double d2 = 300.7;
double d2 = 300.7595926;
// 1. DecimalFormat
// 位数不足,会补0
DecimalFormat df = new DecimalFormat("#.00");
// 会四舍五入
System.out.println(df.format(d1));
System.out.println(df.format(d2));
// 2. BigDecimal
// 位数不足,不会补0
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
double f2 = b2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f2);
//
System.out.println(getDoubleWithLen(d2, 3));
}
public static double getDoubleWithLen(double d, int len){
StringBuilder sb = new StringBuilder();
sb.append("#0.");
while (len-- >0){
sb.append("0");
}
DecimalFormat df = new DecimalFormat();
df.applyPattern(sb.toString());
return Double.parseDouble(df.format(d));
}
}
| codeplay-base/src/main/java/com/tazine/base/NumberUtils.java | style (base)
| codeplay-base/src/main/java/com/tazine/base/NumberUtils.java | style (base) |
|
Java | mit | error: pathspec 'src/com/sleepycoders/jlib/algorithm/search/BinarySearch.java' did not match any file(s) known to git
| 4ff36cc78954762f23beec71955e6e82769028c3 | 1 | joshimoo/JLib | package com.sleepycoders.jlib.algorithm.search;
import java.util.Comparator;
/**
* @author Joshua Moody ([email protected])
*/
public final class BinarySearch {
public static final int NOT_FOUND = -1;
private BinarySearch() {}
public static <T extends Comparable<? super T>> int Search(T[] data, T elem) {
int low = 0;
int high = data.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
int c = elem.compareTo(data[mid]);
if (c < 0) { high = mid - 1; }
else if (c > 0) { low = mid + 1; }
else { return mid; }
}
return NOT_FOUND;
}
public static <T> int Search(T[] data, T elem, Comparator<? super T> cmp) {
int low = 0;
int high = data.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
int c = cmp.compare(elem, data[mid]);
if (c < 0) { high = mid - 1; }
else if (c > 0) { low = mid + 1; }
else { return mid; }
}
return NOT_FOUND;
}
}
| src/com/sleepycoders/jlib/algorithm/search/BinarySearch.java | Implemented BinarySearch for Generic Arrays
| src/com/sleepycoders/jlib/algorithm/search/BinarySearch.java | Implemented BinarySearch for Generic Arrays |
|
Java | mit | error: pathspec 'basics/src/main/java/com/stulsoft/pjava/basics/io/FileTreeWalk.java' did not match any file(s) known to git
| 89d27a3aadd16818a6394f15314cd0df2c05113e | 1 | ysden123/ys-pjava,ysden123/ys-pjava,ysden123/ys-pjava | /*
* Copyright (c) 2015, Yuriy Stul. All rights reserved
*/
package com.stulsoft.pjava.basics.io;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
/**
* Usage Files walkFileTree
*
* @author Yuriy Stul
*/
public class FileTreeWalk {
private static void test01() {
System.out.println("==>test01");
String startFolder = "d:/work";
try {
StringBuilder buffer = new StringBuilder();
Files.walkFileTree(Paths.get(startFolder), new SimpleFileVisitor<Path>() {
/*
* (non-Javadoc)
*
* @see java.nio.file.SimpleFileVisitor#visitFile(java.lang.Object, java.nio.file.attribute.BasicFileAttributes)
*/
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String message = String.format("file: %s, parent: %s", file.getFileName(), file.getParent());
System.out.println(message);
buffer.append(message);
buffer.append("\n");
return super.visitFile(file, attrs);
}
/*
* (non-Javadoc)
*
* @see java.nio.file.SimpleFileVisitor#postVisitDirectory(java.lang.Object, java.io.IOException)
*/
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
String message = String.format("directory: %s, parent: %s", dir.getFileName(), dir.getParent());
System.out.println(message);
buffer.append(message);
buffer.append("\n");
return super.postVisitDirectory(dir, exc);
}
});
System.out.println("buffer:\n" + buffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("<==test01");
}
public static void main(String[] args) {
System.out.println("==>main");
test01();
System.out.println("<==main");
}
}
| basics/src/main/java/com/stulsoft/pjava/basics/io/FileTreeWalk.java | walk file tree
| basics/src/main/java/com/stulsoft/pjava/basics/io/FileTreeWalk.java | walk file tree |
|
Java | mit | error: pathspec 'src/main/java/com/gmail/DrZoddiak/BetterBlacklisting/Commands/Set.java' did not match any file(s) known to git
| 7a9327f026677e5ce6a90183875d3cfc28ffb54a | 1 | DrZoddiak/BetterBlacklisting | package io.drzoddiak.betterblacklisting.Commands;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColors;
#Idealy the command structure should resemble /bbl set (itemID) true
#and/or resemble /bbl set true | This of course detecting the item in hand.
| src/main/java/com/gmail/DrZoddiak/BetterBlacklisting/Commands/Set.java | Create Set.java | src/main/java/com/gmail/DrZoddiak/BetterBlacklisting/Commands/Set.java | Create Set.java |
|
Java | mit | error: pathspec 'test/com/chip8java/emulator/com/chip8java/emulator/listeners/PauseMenuItemListenerTest.java' did not match any file(s) known to git
| 14dde82aeb64c8edbf4a6a341c9ec4f072883461 | 1 | craigthomas/Chip8Java | /*
* Copyright (C) 2013-2015 Craig Thomas
* This project uses an MIT style license - see LICENSE for details.
*/
package com.chip8java.emulator.com.chip8java.emulator.listeners;
import com.chip8java.emulator.CentralProcessingUnit;
import com.chip8java.emulator.Keyboard;
import com.chip8java.emulator.Memory;
import com.chip8java.emulator.Screen;
import com.chip8java.emulator.listeners.PauseMenuItemListener;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import javax.swing.*;
import java.awt.event.ItemEvent;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
/**
* Tests for the PauseMenuItemListener.
*/
public class PauseMenuItemListenerTest {
private Memory mMemoryMock;
private Keyboard mKeyboardMock;
private Screen mScreenMock;
private CentralProcessingUnit mCPU;
private PauseMenuItemListener mPauseMenuItemListener;
private ItemEvent mMockItemEvent;
@Before
public void setUp() {
mMemoryMock = mock(Memory.class);
mKeyboardMock = mock(Keyboard.class);
mScreenMock = mock(Screen.class);
mCPU = new CentralProcessingUnit(mMemoryMock, mKeyboardMock);
mCPU.setScreen(mScreenMock);
mPauseMenuItemListener = new PauseMenuItemListener(mCPU);
}
@Test
public void testCPUPausedWhenItemListenerTriggered() {
ButtonModel buttonModel = mock(ButtonModel.class);
Mockito.when(buttonModel.isSelected()).thenReturn(true);
AbstractButton button = mock(AbstractButton.class);
Mockito.when(button.getModel()).thenReturn(buttonModel);
mMockItemEvent = mock(ItemEvent.class);
Mockito.when(mMockItemEvent.getSource()).thenReturn(button);
mPauseMenuItemListener.itemStateChanged(mMockItemEvent);
assertTrue(mCPU.getPaused());
}
@Test
public void testCPUNotPausedWhenItemListenerTriggeredTwice() {
ButtonModel buttonModel = mock(ButtonModel.class);
Mockito.when(buttonModel.isSelected()).thenReturn(true).thenReturn(false);
AbstractButton button = mock(AbstractButton.class);
Mockito.when(button.getModel()).thenReturn(buttonModel);
mMockItemEvent = mock(ItemEvent.class);
Mockito.when(mMockItemEvent.getSource()).thenReturn(button);
mPauseMenuItemListener.itemStateChanged(mMockItemEvent);
mPauseMenuItemListener.itemStateChanged(mMockItemEvent);
assertFalse(mCPU.getPaused());
}
}
| test/com/chip8java/emulator/com/chip8java/emulator/listeners/PauseMenuItemListenerTest.java | Added test for PauseMenuItemListener.
| test/com/chip8java/emulator/com/chip8java/emulator/listeners/PauseMenuItemListenerTest.java | Added test for PauseMenuItemListener. |
|
Java | epl-1.0 | e7fdf2c80c69320cf07857edfeecc77b6aa33f53 | 0 | Techjar/ForgeEssentials,ForgeEssentials/ForgeEssentialsMain,planetguy32/ForgeEssentials,liachmodded/ForgeEssentials,CityOfLearning/ForgeEssentials,aschmois/ForgeEssentialsMain | package com.ForgeEssentials.economy;
import java.util.HashMap;
import net.minecraft.entity.player.EntityPlayer;
import com.ForgeEssentials.api.data.ClassContainer;
import com.ForgeEssentials.api.data.DataStorageManager;
import com.ForgeEssentials.api.economy.IEconManager;
import cpw.mods.fml.common.IPlayerTracker;
/**
* Call these methods to modify a target's Wallet.
*/
public class WalletHandler implements IPlayerTracker, IEconManager
{
private static ClassContainer con = new ClassContainer(Wallet.class);
private static HashMap<String, Wallet> wallets = new HashMap<String, Wallet>();
@Override
public void addToWallet(int amountToAdd, String player)
{
wallets.get(player).amount = wallets.get(player).amount + amountToAdd;
}
@Override
public int getWallet(String player)
{
return wallets.get(player).amount;
}
@Override
public void removeFromWallet(int amountToSubtract, String player)
{
wallets.get(player).amount = wallets.get(player).amount - amountToSubtract;
}
@Override
public void setWallet(int setAmount, EntityPlayer player)
{
wallets.get(player.username).amount = setAmount;
}
@Override
public String currency(int amount)
{
if (amount == 1)
return ConfigEconomy.currencySingular;
else
return ConfigEconomy.currencyPlural;
}
@Override
public String getMoneyString(String username)
{
int am = getWallet(username);
return am + " " + currency(am);
}
/*
* Player tracker stuff
*/
@Override
public void onPlayerLogin(EntityPlayer player)
{
Wallet wallet = (Wallet) DataStorageManager.getReccomendedDriver().loadObject(con, player.username);
if (wallet == null)
{
wallet = new Wallet(player, ModuleEconomy.startbuget);
}
wallets.put(player.username, wallet);
}
@Override
public void onPlayerLogout(EntityPlayer player)
{
if (wallets.containsKey(player.username))
{
DataStorageManager.getReccomendedDriver().saveObject(con, wallets.remove(player.username));
}
}
@Override
public void onPlayerChangedDimension(EntityPlayer player)
{
}
@Override
public void onPlayerRespawn(EntityPlayer player)
{
}
}
| src/FE_SRC_COMMON/com/ForgeEssentials/economy/WalletHandler.java | package com.ForgeEssentials.economy;
import java.util.HashMap;
import net.minecraft.entity.player.EntityPlayer;
import com.ForgeEssentials.api.data.ClassContainer;
import com.ForgeEssentials.api.data.DataStorageManager;
import com.ForgeEssentials.api.economy.IEconManager;
import cpw.mods.fml.common.IPlayerTracker;
/**
* Call these methods to modify a target's Wallet.
*/
public class WalletHandler implements IPlayerTracker, IEconManager
{
private static ClassContainer con = new ClassContainer(Wallet.class);
private static HashMap<String, Wallet> wallets = new HashMap<String, Wallet>();
@Override
public void addToWallet(int amountToAdd, String player)
{
wallets.get(player).amount = wallets.get(player).amount + amountToAdd;
}
@Override
public int getWallet(String player)
{
return wallets.get(player).amount;
}
@Override
public void removeFromWallet(int amountToSubtract, String player)
{
wallets.get(player).amount = wallets.get(player).amount - amountToSubtract;
}
@Override
public void setWallet(int setAmount, EntityPlayer player)
{
wallets.get(player.username).amount = setAmount;
}
@Override
public String currency(int amount)
{
if (amount == 1)
return ConfigEconomy.currencySingular;
else
return ConfigEconomy.currencyPlural;
}
@Override
public String getMoneyString(String username)
{
int am = getWallet(username);
return am + " " + currency(am);
}
/*
* Player tracker stuff
*/
@Override
public void onPlayerLogin(EntityPlayer player)
{
Wallet wallet = (Wallet) DataStorageManager.getReccomendedDriver().loadObject(con, player.username);
if (wallet == null)
{
wallet = new Wallet(player, ModuleEconomy.startbuget);
}
wallets.put(wallet.getUsername(), wallet);
}
@Override
public void onPlayerLogout(EntityPlayer player)
{
if (wallets.containsKey(player.username))
{
DataStorageManager.getReccomendedDriver().saveObject(con, wallets.remove(player.username));
}
}
@Override
public void onPlayerChangedDimension(EntityPlayer player)
{
}
@Override
public void onPlayerRespawn(EntityPlayer player)
{
}
}
| Fixed unknown error for economy commands after player logs back in
| src/FE_SRC_COMMON/com/ForgeEssentials/economy/WalletHandler.java | Fixed unknown error for economy commands after player logs back in |
|
Java | epl-1.0 | error: pathspec 'src/main/java/prm4j/api/fsm/FSM.java' did not match any file(s) known to git
| ec1372b17d5fc43e255692bf16807147278135d5 | 1 | parzonka/prm4j | /*
* Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mateusz Parzonka - initial API and implementation
*/
package prm4j.api.fsm;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import prm4j.api.Alphabet;
import prm4j.api.MatchHandler;
import prm4j.old.v2.fsm.FSMState;
/**
* A finite state automaton.
*
* @param <A>
* the type of the auxiliary data usable by base monitors
*/
public class FSM<A> {
private final Alphabet alphabet;
private final Set<FSMState<A>> states;
private final Set<String> usedNames;
private int stateCount = 0;
private FSMState<A> initialState;
public FSM(Alphabet alphabet) {
this.alphabet = alphabet;
this.states = new HashSet<FSMState<A>>();
this.usedNames = new HashSet<String>();
}
/**
* Create a new state which is labeled with the name <code>"initial"</code>.
*
* @return the created state
*/
public FSMState<A> createInitialState() {
if (this.initialState != null)
throw new IllegalStateException("Initial state already created!");
this.initialState = createState("initial");
return this.initialState;
}
/**
* Create a new state which is labeled with a generated name of the form <code>"state_NUMBER"</code>.
*
* @return the created state
*/
public FSMState<A> createState() {
return createState(generateStateName());
}
/**
* Create a new state labeled with the given optional name.
*
* @return the created state
*/
public FSMState<A> createState(String optionalName) {
return createState(false, null, optionalName);
}
/**
* Create a new final state which is labeled with a generated name of the form <code>"state_NUMBER"</code>.
*
* @return the created final state
*/
public FSMState<A> createFinalState(MatchHandler matchHandler) {
return createFinalState(matchHandler, generateFinalStateName());
}
/**
* Create a new final state labeled with the given optional name.
*
* @return the created state
*/
public FSMState<A> createFinalState(MatchHandler matchHandler, String optionalName) {
if (matchHandler == null) {
throw new NullPointerException("MatchHandler may not be null!");
}
return createState(true, matchHandler, optionalName);
}
private String generateStateName() {
return "state " + this.stateCount;
}
private String generateFinalStateName() {
return "state " + this.stateCount + " (final)";
}
private FSMState<A> createState(boolean isFinal, MatchHandler eventHandler, String name) {
if (this.usedNames.contains(name))
throw new IllegalArgumentException("The name [" + name + "] has already been used!");
this.usedNames.add(name);
FSMState<A> state = new FSMState<A>(this.alphabet, false, eventHandler, name);
this.states.add(state);
this.stateCount++;
return state;
}
/**
* Returns the underlying alphabet for this FSM.
*
* @return the alphabet
*/
public Alphabet getAlphabet() {
return this.alphabet;
}
/**
* Returns all created states.
*
* @return an unmodifiable set of created states
*/
public Set<FSMState<A>> getStates() {
return this.states;
}
/**
* Returns the number of created states.
*
* @return the number of created states
*/
public int getStateCount() {
return this.stateCount;
}
/**
* Returns the names which where used for the states.
*
* @return an unmodifiable set of the used names
*/
public Set<String> getUsedNames() {
return Collections.unmodifiableSet(this.usedNames);
}
/**
* Returns the initial state.
*
* @return the initial state
*/
public FSMState<A> getInitialState() {
if (this.initialState == null)
throw new IllegalStateException("No initial state created!");
return this.initialState;
}
}
| src/main/java/prm4j/api/fsm/FSM.java | Add fsm
| src/main/java/prm4j/api/fsm/FSM.java | Add fsm |
|
Java | epl-1.0 | error: pathspec 'junit5-engine/src/main/java/org/junit/gen5/engine/junit5/execution/ConditionEvaluator.java' did not match any file(s) known to git
| ce7d854544c725b012a58e8f575ce57b8f6f9cc7 | 1 | junit-team/junit-lambda,marcphilipp/junit-lambda,marcphilipp/junit5,sbrannen/junit-lambda | /*
* Copyright 2015 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.engine.junit5.execution;
import org.junit.gen5.api.extension.Condition;
import org.junit.gen5.api.extension.Condition.Result;
import org.junit.gen5.api.extension.TestExecutionContext;
/**
* {@code ConditionEvaluator} evaluates all {@link Condition Conditions}
* registered in a {@link TestExecutionContext}.
*
* @since 5.0
* @see Condition
*/
class ConditionEvaluator {
private static final Result ENABLED = Result.enabled("No 'disabled' conditions encountered");
/**
* Evaluate all {@link Condition Conditions} registered for the supplied
* {@link TestExecutionContext}.
*
* @param context the current {@code TestExecutionContext}
* @return the first <em>disabled</em> {@code Result}, or a default
* <em>enabled</em> {@code Result} if no disabled conditions are
* encountered.
*/
Result evaluate(TestExecutionContext context) {
// @formatter:off
return context.getExtensions(Condition.class)
.map(condition -> evaluate(context, condition))
.filter(Result::isDisabled)
.findFirst()
.orElse(ENABLED);
// @formatter:on
}
private Result evaluate(TestExecutionContext context, Condition condition) {
try {
return condition.evaluate(context);
}
catch (Exception ex) {
throw new IllegalStateException(
String.format("Failed to evaluate condition [%s]", condition.getClass().getName()), ex);
}
}
}
| junit5-engine/src/main/java/org/junit/gen5/engine/junit5/execution/ConditionEvaluator.java | Reinstate ConditionEvaluator
| junit5-engine/src/main/java/org/junit/gen5/engine/junit5/execution/ConditionEvaluator.java | Reinstate ConditionEvaluator |
|
Java | agpl-3.0 | 9e305abb7200eb99c5f1dd6cb467d83a57bdee57 | 0 | relateiq/sql-layer,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,jaytaylor/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,relateiq/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,shunwang/sql-layer-1,shunwang/sql-layer-1,relateiq/sql-layer,wfxiang08/sql-layer-1,shunwang/sql-layer-1,ngaut/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer | /**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* 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.foundationdb.ais.model;
import java.util.ArrayList;
import java.util.List;
public class HKey
{
@Override
public synchronized String toString()
{
StringBuilder buffer = new StringBuilder();
buffer.append("HKey(");
boolean firstTable = true;
for (HKeySegment segment : segments) {
if (firstTable) {
firstTable = false;
} else {
buffer.append(", ");
}
buffer.append(segment.toString());
}
buffer.append(")");
return buffer.toString();
}
public Table table()
{
return table;
}
public List<HKeySegment> segments()
{
return segments;
}
public int nColumns()
{
ensureDerived();
return columns.length;
}
public Column column(int i)
{
ensureDerived();
return columns[i];
}
public HKey(Table table)
{
this.table = table;
}
public synchronized HKeySegment addSegment(Table segmentTable)
{
assert keyDepth == null : segmentTable; // Should only be computed after HKeySegments are completely formed.
Table lastSegmentTable = segments.isEmpty() ? null : segments.get(segments.size() - 1).table();
assert segmentTable.getParentTable() == lastSegmentTable;
HKeySegment segment = new HKeySegment(this, segmentTable);
segments.add(segment);
return segment;
}
public boolean containsColumn(Column column)
{
ensureDerived();
for (Column c : columns) {
if (c == column) {
return true;
}
}
return false;
}
public int[] keyDepth()
{
ensureDerived();
return keyDepth;
}
// For use by this class
private void ensureDerived()
{
if (columns == null) {
synchronized (this) {
if (columns == null) {
// columns
List<Column> columnList = new ArrayList<>();
for (HKeySegment segment : segments) {
for (HKeyColumn hKeyColumn : segment.columns()) {
columnList.add(hKeyColumn.column());
}
}
Column[] columnsTmp = new Column[columnList.size()];
int c = 0;
for (Column column : columnList) {
columnsTmp[c] = column;
c++;
}
// keyDepth
int[] keyDepthTmp = new int[segments.size() + 1];
int hKeySegments = segments.size();
for (int hKeySegment = 0; hKeySegment < hKeySegments; hKeySegment++) {
keyDepthTmp[hKeySegment] =
hKeySegment == 0
? 1
// + 1 to account for the ordinal
: keyDepthTmp[hKeySegment - 1] + 1 + segments.get(hKeySegment - 1).columns().size();
}
keyDepthTmp[hKeySegments] = columnsTmp.length + hKeySegments;
keyDepth = keyDepthTmp;
columns = columnsTmp;
}
}
}
}
// State
private final Table table;
private final List<HKeySegment> segments = new ArrayList<>();
// keyDepth[n] is the number of key segments (ordinals + key values) comprising an hkey of n parts.
// E.g. keyDepth[1] for the number of segments of the root hkey.
// keyDepth[2] for the number of key segments of the root's child + keyDepth[1].
private volatile int[] keyDepth;
private volatile Column[] columns;
}
| src/main/java/com/foundationdb/ais/model/HKey.java | /**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* 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.foundationdb.ais.model;
import java.util.ArrayList;
import java.util.List;
public class HKey
{
@Override
public synchronized String toString()
{
StringBuilder buffer = new StringBuilder();
buffer.append("HKey(");
boolean firstTable = true;
for (HKeySegment segment : segments) {
if (firstTable) {
firstTable = false;
} else {
buffer.append(", ");
}
buffer.append(segment.toString());
}
buffer.append(")");
return buffer.toString();
}
public Table table()
{
return table;
}
public List<HKeySegment> segments()
{
return segments;
}
public int nColumns()
{
ensureDerived();
return columns.length;
}
public Column column(int i)
{
ensureDerived();
return columns[i];
}
public HKey(Table table)
{
this.table = table;
}
public synchronized HKeySegment addSegment(Table segmentTable)
{
assert keyDepth == null : segmentTable; // Should only be computed after HKeySegments are completely formed.
Table lastSegmentTable = segments.isEmpty() ? null : segments.get(segments.size() - 1).table();
assert segmentTable.getParentTable() == lastSegmentTable;
HKeySegment segment = new HKeySegment(this, segmentTable);
segments.add(segment);
return segment;
}
public boolean containsColumn(Column column)
{
ensureDerived();
for (Column c : columns) {
if (c == column) {
return true;
}
}
return false;
}
public int[] keyDepth()
{
ensureDerived();
return keyDepth;
}
// For use by this class
private void ensureDerived()
{
if (columns == null) {
synchronized (this) {
if (columns == null) {
// columns
List<Column> columnList = new ArrayList<>();
for (HKeySegment segment : segments) {
for (HKeyColumn hKeyColumn : segment.columns()) {
columnList.add(hKeyColumn.column());
}
}
Column[] columnsTmp = new Column[columnList.size()];
int c = 0;
for (Column column : columnList) {
columnsTmp[c] = column;
c++;
}
// keyDepth
int[] keyDepthTmp = new int[segments.size() + 1];
int hKeySegments = segments.size();
for (int hKeySegment = 0; hKeySegment < hKeySegments; hKeySegment++) {
keyDepthTmp[hKeySegment] =
hKeySegment == 0
? 1
// + 1 to account for the ordinal
: keyDepthTmp[hKeySegment - 1] + 1 + segments.get(hKeySegment - 1).columns().size();
}
keyDepthTmp[hKeySegments] = columnsTmp.length + hKeySegments;
columns = columnsTmp;
keyDepth = keyDepthTmp;
}
}
}
}
// State
private final Table table;
private final List<HKeySegment> segments = new ArrayList<>();
// keyDepth[n] is the number of key segments (ordinals + key values) comprising an hkey of n parts.
// E.g. keyDepth[1] for the number of segments of the root hkey.
// keyDepth[2] for the number of key segments of the root's child + keyDepth[1].
private volatile int[] keyDepth;
private volatile Column[] columns;
}
| corrected the order
| src/main/java/com/foundationdb/ais/model/HKey.java | corrected the order |
|
Java | agpl-3.0 | 5b31d39f2838c0841a1f823f8bcbc398df813d1a | 0 | Heiner1/AndroidAPS,jotomo/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,MilosKozak/AndroidAPS,jotomo/AndroidAPS,PoweRGbg/AndroidAPS,PoweRGbg/AndroidAPS,PoweRGbg/AndroidAPS,winni67/AndroidAPS,winni67/AndroidAPS,MilosKozak/AndroidAPS | package de.jotomo.ruffyscripter.commands;
import android.os.SystemClock;
import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import de.jotomo.ruffy.spi.PumpState;
import de.jotomo.ruffy.spi.PumpWarningCodes;
import de.jotomo.ruffy.spi.WarningOrErrorCode;
public class SetTbrCommand extends BaseCommand {
private static final Logger log = LoggerFactory.getLogger(SetTbrCommand.class);
private final long percentage;
private final long duration;
public SetTbrCommand(long percentage, long duration) {
this.percentage = percentage;
this.duration = duration;
}
@Override
public List<String> validateArguments() {
List<String> violations = new ArrayList<>();
if (percentage % 10 != 0) {
violations.add("TBR percentage must be set in 10% steps");
}
if (percentage < 0 || percentage > 500) {
violations.add("TBR percentage must be within 0-500%");
}
if (percentage != 100) {
if (duration % 15 != 0) {
violations.add("TBR duration can only be set in 15 minute steps");
}
if (duration > 60 * 24) {
violations.add("Maximum TBR duration is 24 hours");
}
}
if (percentage == 0 && duration > 180) {
violations.add("Max allowed zero-temp duration is 3h");
}
return violations;
}
@Override
public Integer getReconnectWarningId() {
return PumpWarningCodes.TBR_CANCELLED;
}
@Override
public void execute() {
boolean cancellingTbr = percentage == 100;
try {
if (checkAndWaitIfExistingTbrIsAboutToEnd(cancellingTbr)) {
return;
}
enterTbrMenu();
boolean increasingPercentage = inputTbrPercentage();
verifyDisplayedTbrPercentage(increasingPercentage);
if (cancellingTbr) {
cancelTbrAndConfirmCancellationWarning();
} else {
// switch to TBR_DURATION menu by pressing menu key
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
scripter.pressMenuKey();
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
boolean increasingDuration = inputTbrDuration();
verifyDisplayedTbrDuration(increasingDuration);
// confirm TBR
scripter.pressCheckKey();
scripter.waitForMenuToBeLeft(MenuType.TBR_DURATION);
}
} catch (CommandException e) {
if (scripter.getCurrentMenu().getType() == MenuType.WARNING_OR_ERROR) {
// The pump raises a TBR CANCELLED warning when a running TBR finishes while we're
// programming a new one (TBR remaining time was last displayed as 0:01, the pump
// rounds seconds up to full minutes). In that case confirm the alert since we know
// we caused it (in a way), but still fail the command so the usual cleanups of returning
// to main menu etc are performed, after which this command can simply be retried.
WarningOrErrorCode warningOrErrorCode = scripter.readWarningOrErrorCode();
if (Objects.equals(warningOrErrorCode.warningCode, PumpWarningCodes.TBR_CANCELLED)) {
scripter.confirmAlert(PumpWarningCodes.TBR_CANCELLED);
}
}
throw e;
}
result.success = true;
}
/**
* When programming a new TBR while an existing TBR runs out, a TBR CANCELLED
* alert is raised (failing the command, requiring a reconnect and confirming alert
* and all). To avoid this, wait until the active TBR runs out if the active TBR
* is about to end.
*
* @return If we waited till the TBR ended an cancellation was request so all work is done.
*/
private boolean checkAndWaitIfExistingTbrIsAboutToEnd(boolean cancellingTbr) {
scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU);
long timeout = System.currentTimeMillis() + 65 * 1000;
PumpState state = scripter.readPumpStateInternal();
if (state.tbrRemainingDuration == 1) {
while (state.tbrActive && System.currentTimeMillis() < timeout) {
log.debug("Waiting for existing TBR to run out to avoid alert while setting TBR");
scripter.waitForScreenUpdate();
state = scripter.readPumpStateInternal();
}
// if we waited above and a cancellation was requested, we already completed the request
if (!state.tbrActive && cancellingTbr) {
result.success = true;
return true;
}
}
return false;
}
private void enterTbrMenu() {
scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU);
scripter.navigateToMenu(MenuType.TBR_MENU);
scripter.verifyMenuIsDisplayed(MenuType.TBR_MENU);
scripter.pressCheckKey();
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
}
private boolean inputTbrPercentage() {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
long currentPercent = readDisplayedPercentage();
log.debug("Current TBR %: " + currentPercent);
long percentageChange = percentage - currentPercent;
long percentageSteps = percentageChange / 10;
boolean increasePercentage = percentageSteps > 0;
log.debug("Pressing " + (increasePercentage ? "up" : "down") + " " + percentageSteps + " times");
for (int i = 0; i < Math.abs(percentageSteps); i++) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
log.debug("Push #" + (i + 1) + "/" + Math.abs(percentageSteps));
if (increasePercentage) scripter.pressUpKey();
else scripter.pressDownKey();
SystemClock.sleep(50);
}
return increasePercentage;
}
private void verifyDisplayedTbrPercentage(boolean increasingPercentage) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
// wait up to 5s for any scrolling to finish
long displayedPercentage = readDisplayedPercentage();
long timeout = System.currentTimeMillis() + 10 * 1000;
while (timeout > System.currentTimeMillis()
&& ((increasingPercentage && displayedPercentage < percentage)
|| (!increasingPercentage && displayedPercentage > percentage))) {
log.debug("Waiting for pump to process scrolling input for percentage, current: "
+ displayedPercentage + ", desired: " + percentage + ", scrolling "
+ (increasingPercentage ? "up" : "down"));
SystemClock.sleep(50);
displayedPercentage = readDisplayedPercentage();
}
log.debug("Final displayed TBR percentage: " + displayedPercentage);
if (displayedPercentage != percentage) {
throw new CommandException("Failed to set TBR percentage, requested: "
+ percentage + ", actual: " + displayedPercentage);
}
// check again to ensure the displayed value hasn't change and scrolled past the desired
// value due to due scrolling taking extremely long
SystemClock.sleep(1000);
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
long refreshedDisplayedTbrPecentage = readDisplayedPercentage();
if (displayedPercentage != refreshedDisplayedTbrPecentage) {
throw new CommandException("Failed to set TBR percentage: " +
"percentage changed after input stopped from "
+ displayedPercentage + " -> " + refreshedDisplayedTbrPecentage);
}
}
private boolean inputTbrDuration() {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
long durationSteps = calculateDurationSteps();
boolean increaseDuration = durationSteps > 0;
log.debug("Pressing " + (increaseDuration ? "up" : "down") + " " + durationSteps + " times");
for (int i = 0; i < Math.abs(durationSteps); i++) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
log.debug("Push #" + (i + 1) + "/" + Math.abs(durationSteps));
if (increaseDuration) scripter.pressUpKey();
else scripter.pressDownKey();
SystemClock.sleep(50);
}
return increaseDuration;
}
private long calculateDurationSteps() {
long currentDuration = readDisplayedDuration();
log.debug("Initial TBR duration: " + currentDuration);
long difference = duration - currentDuration;
long durationSteps = difference / 15;
long durationAfterInitialSteps = currentDuration + (durationSteps * 15);
if (durationAfterInitialSteps < duration) return durationSteps + 1;
else if (durationAfterInitialSteps > duration) return durationSteps - 1;
else return durationSteps;
}
private void verifyDisplayedTbrDuration(boolean increasingPercentage) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
// wait up to 5s for any scrolling to finish
long displayedDuration = readDisplayedDuration();
long timeout = System.currentTimeMillis() + 10 * 1000;
while (timeout > System.currentTimeMillis()
&& ((increasingPercentage && displayedDuration < duration)
|| (!increasingPercentage && displayedDuration > duration))) {
log.debug("Waiting for pump to process scrolling input for duration, current: "
+ displayedDuration + ", desired: " + duration
+ ", scrolling " + (increasingPercentage ? "up" : "down"));
SystemClock.sleep(50);
displayedDuration = readDisplayedDuration();
}
log.debug("Final displayed TBR duration: " + displayedDuration);
if (displayedDuration != duration) {
throw new CommandException("Failed to set TBR duration, requested: "
+ duration + ", actual: " + displayedDuration);
}
// check again to ensure the displayed value hasn't change and scrolled past the desired
// value due to due scrolling taking extremely long
SystemClock.sleep(1000);
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
long refreshedDisplayedTbrDuration = readDisplayedDuration();
if (displayedDuration != refreshedDisplayedTbrDuration) {
throw new CommandException("Failed to set TBR duration: " +
"duration changed after input stopped from "
+ displayedDuration + " -> " + refreshedDisplayedTbrDuration);
}
}
private void cancelTbrAndConfirmCancellationWarning() {
// confirm entered TBR
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
scripter.pressCheckKey();
// A "TBR CANCELLED alert" is only raised by the pump when the remaining time is
// greater than 60s (displayed as 0:01, the pump goes from there to finished.
// We could read the remaining duration from MAIN_MENU, but by the time we're here,
// the pump could have moved from 0:02 to 0:01, so instead, check if a "TBR CANCELLED" alert
// is raised and if so dismiss it
scripter.confirmAlert(PumpWarningCodes.TBR_CANCELLED, 2000);
}
private long readDisplayedDuration() {
MenuTime duration = scripter.readBlinkingValue(MenuTime.class, MenuAttribute.RUNTIME);
return duration.getHour() * 60 + duration.getMinute();
}
private long readDisplayedPercentage() {
return scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE).longValue();
}
@Override
public boolean needsRunMode() {
return true;
}
@Override
public String toString() {
return "SetTbrCommand{" +
"percentage=" + percentage +
", duration=" + duration +
'}';
}
}
| ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetTbrCommand.java | package de.jotomo.ruffyscripter.commands;
import android.os.SystemClock;
import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import de.jotomo.ruffy.spi.PumpState;
import de.jotomo.ruffy.spi.PumpWarningCodes;
import de.jotomo.ruffy.spi.WarningOrErrorCode;
public class SetTbrCommand extends BaseCommand {
private static final Logger log = LoggerFactory.getLogger(SetTbrCommand.class);
private final long percentage;
private final long duration;
public SetTbrCommand(long percentage, long duration) {
this.percentage = percentage;
this.duration = duration;
}
@Override
public List<String> validateArguments() {
List<String> violations = new ArrayList<>();
if (percentage % 10 != 0) {
violations.add("TBR percentage must be set in 10% steps");
}
if (percentage < 0 || percentage > 500) {
violations.add("TBR percentage must be within 0-500%");
}
if (percentage != 100) {
if (duration % 15 != 0) {
violations.add("TBR duration can only be set in 15 minute steps");
}
if (duration > 60 * 24) {
violations.add("Maximum TBR duration is 24 hours");
}
}
if (percentage == 0 && duration > 180) {
violations.add("Max allowed zero-temp duration is 3h");
}
return violations;
}
@Override
public Integer getReconnectWarningId() {
return PumpWarningCodes.TBR_CANCELLED;
}
@Override
public void execute() {
boolean cancellingTbr = percentage == 100;
try {
// When programming a new TBR while an existing TBR runs out, a TBR CANCELLED
// alert is raised (failing the command, requiring a reconnect and confirming alert
// and all). To avoid this, wait until the active TBR runs out if the active TBR
// is about to end
long timeout = System.currentTimeMillis() + 65 * 1000;
scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU);
PumpState state = scripter.readPumpStateInternal();
if (state.tbrRemainingDuration == 1) {
while (state.tbrActive && System.currentTimeMillis() < timeout) {
log.debug("Waiting for existing TBR to run out to avoid alert while setting TBR");
scripter.waitForScreenUpdate();
state = scripter.readPumpStateInternal();
}
// if we waited above and a cancellation was requested, we already completed the request
if (!state.tbrActive && cancellingTbr) {
result.success = true;
return;
}
}
enterTbrMenu();
boolean increasingPercentage = inputTbrPercentage();
verifyDisplayedTbrPercentage(increasingPercentage);
if (cancellingTbr) {
cancelTbrAndConfirmCancellationWarning();
} else {
// switch to TBR_DURATION menu by pressing menu key
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
scripter.pressMenuKey();
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
boolean increasingDuration = inputTbrDuration();
verifyDisplayedTbrDuration(increasingDuration);
// confirm TBR
scripter.pressCheckKey();
scripter.waitForMenuToBeLeft(MenuType.TBR_DURATION);
}
} catch (CommandException e) {
if (scripter.getCurrentMenu().getType() == MenuType.WARNING_OR_ERROR) {
// The pump raises a TBR CANCELLED warning when a running TBR finishes while we're
// programming a new one (TBR remaining time was last displayed as 0:01, the pump
// rounds seconds up to full minutes). In that case confirm the alert since we know
// we caused it (in a way), but still fail the command so the usual cleanups of returning
// to main menu etc are performed, after which this command can simply be retried.
WarningOrErrorCode warningOrErrorCode = scripter.readWarningOrErrorCode();
if (Objects.equals(warningOrErrorCode.warningCode, PumpWarningCodes.TBR_CANCELLED)) {
scripter.confirmAlert(PumpWarningCodes.TBR_CANCELLED);
}
}
throw e;
}
result.success = true;
}
private void enterTbrMenu() {
scripter.verifyMenuIsDisplayed(MenuType.MAIN_MENU);
scripter.navigateToMenu(MenuType.TBR_MENU);
scripter.verifyMenuIsDisplayed(MenuType.TBR_MENU);
scripter.pressCheckKey();
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
}
private boolean inputTbrPercentage() {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
long currentPercent = readDisplayedPercentage();
log.debug("Current TBR %: " + currentPercent);
long percentageChange = percentage - currentPercent;
long percentageSteps = percentageChange / 10;
boolean increasePercentage = percentageSteps > 0;
log.debug("Pressing " + (increasePercentage ? "up" : "down") + " " + percentageSteps + " times");
for (int i = 0; i < Math.abs(percentageSteps); i++) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
log.debug("Push #" + (i + 1) + "/" + Math.abs(percentageSteps));
if (increasePercentage) scripter.pressUpKey();
else scripter.pressDownKey();
SystemClock.sleep(50);
}
return increasePercentage;
}
private void verifyDisplayedTbrPercentage(boolean increasingPercentage) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
// wait up to 5s for any scrolling to finish
long displayedPercentage = readDisplayedPercentage();
long timeout = System.currentTimeMillis() + 10 * 1000;
while (timeout > System.currentTimeMillis()
&& ((increasingPercentage && displayedPercentage < percentage)
|| (!increasingPercentage && displayedPercentage > percentage))) {
log.debug("Waiting for pump to process scrolling input for percentage, current: "
+ displayedPercentage + ", desired: " + percentage + ", scrolling "
+ (increasingPercentage ? "up" : "down"));
SystemClock.sleep(50);
displayedPercentage = readDisplayedPercentage();
}
log.debug("Final displayed TBR percentage: " + displayedPercentage);
if (displayedPercentage != percentage) {
throw new CommandException("Failed to set TBR percentage, requested: "
+ percentage + ", actual: " + displayedPercentage);
}
// check again to ensure the displayed value hasn't change and scrolled past the desired
// value due to due scrolling taking extremely long
SystemClock.sleep(1000);
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
long refreshedDisplayedTbrPecentage = readDisplayedPercentage();
if (displayedPercentage != refreshedDisplayedTbrPecentage) {
throw new CommandException("Failed to set TBR percentage: " +
"percentage changed after input stopped from "
+ displayedPercentage + " -> " + refreshedDisplayedTbrPecentage);
}
}
private boolean inputTbrDuration() {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
long durationSteps = calculateDurationSteps();
boolean increaseDuration = durationSteps > 0;
log.debug("Pressing " + (increaseDuration ? "up" : "down") + " " + durationSteps + " times");
for (int i = 0; i < Math.abs(durationSteps); i++) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
log.debug("Push #" + (i + 1) + "/" + Math.abs(durationSteps));
if (increaseDuration) scripter.pressUpKey();
else scripter.pressDownKey();
SystemClock.sleep(50);
}
return increaseDuration;
}
private long calculateDurationSteps() {
long currentDuration = readDisplayedDuration();
log.debug("Initial TBR duration: " + currentDuration);
long difference = duration - currentDuration;
long durationSteps = difference / 15;
long durationAfterInitialSteps = currentDuration + (durationSteps * 15);
if (durationAfterInitialSteps < duration) return durationSteps + 1;
else if (durationAfterInitialSteps > duration) return durationSteps - 1;
else return durationSteps;
}
private void verifyDisplayedTbrDuration(boolean increasingPercentage) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
// wait up to 5s for any scrolling to finish
long displayedDuration = readDisplayedDuration();
long timeout = System.currentTimeMillis() + 10 * 1000;
while (timeout > System.currentTimeMillis()
&& ((increasingPercentage && displayedDuration < duration)
|| (!increasingPercentage && displayedDuration > duration))) {
log.debug("Waiting for pump to process scrolling input for duration, current: "
+ displayedDuration + ", desired: " + duration
+ ", scrolling " + (increasingPercentage ? "up" : "down"));
SystemClock.sleep(50);
displayedDuration = readDisplayedDuration();
}
log.debug("Final displayed TBR duration: " + displayedDuration);
if (displayedDuration != duration) {
throw new CommandException("Failed to set TBR duration, requested: "
+ duration + ", actual: " + displayedDuration);
}
// check again to ensure the displayed value hasn't change and scrolled past the desired
// value due to due scrolling taking extremely long
SystemClock.sleep(1000);
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
long refreshedDisplayedTbrDuration = readDisplayedDuration();
if (displayedDuration != refreshedDisplayedTbrDuration) {
throw new CommandException("Failed to set TBR duration: " +
"duration changed after input stopped from "
+ displayedDuration + " -> " + refreshedDisplayedTbrDuration);
}
}
private void cancelTbrAndConfirmCancellationWarning() {
// confirm entered TBR
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
scripter.pressCheckKey();
// A "TBR CANCELLED alert" is only raised by the pump when the remaining time is
// greater than 60s (displayed as 0:01, the pump goes from there to finished.
// We could read the remaining duration from MAIN_MENU, but by the time we're here,
// the pump could have moved from 0:02 to 0:01, so instead, check if a "TBR CANCELLED" alert
// is raised and if so dismiss it
scripter.confirmAlert(PumpWarningCodes.TBR_CANCELLED, 2000);
}
private long readDisplayedDuration() {
MenuTime duration = scripter.readBlinkingValue(MenuTime.class, MenuAttribute.RUNTIME);
return duration.getHour() * 60 + duration.getMinute();
}
private long readDisplayedPercentage() {
return scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE).longValue();
}
@Override
public boolean needsRunMode() {
return true;
}
@Override
public String toString() {
return "SetTbrCommand{" +
"percentage=" + percentage +
", duration=" + duration +
'}';
}
}
| Extract method checkAndWaitIfExistingTbrIsAboutToEnd.
| ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetTbrCommand.java | Extract method checkAndWaitIfExistingTbrIsAboutToEnd. |
|
Java | apache-2.0 | 262d4db3d8d8b03c2e8a63608b430469724a203a | 0 | RaffaelBild/arx,fstahnke/arx,fstahnke/arx,kbabioch/arx,jgaupp/arx,COWYARD/arx,kentoa/arx,COWYARD/arx,bitraten/arx,bitraten/arx,kentoa/arx,tijanat/arx,arx-deidentifier/arx,tijanat/arx,TheRealRasu/arx,kbabioch/arx,TheRealRasu/arx,jgaupp/arx,RaffaelBild/arx,arx-deidentifier/arx | /*
* ARX: Powerful Data Anonymization
* Copyright (C) 2012 - 2014 Florian Kohlmayer, Fabian Prasser
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.deidentifier.arx.gui.view.impl.explore;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.deidentifier.arx.ARXLattice;
import org.deidentifier.arx.ARXLattice.ARXNode;
import org.deidentifier.arx.ARXResult;
import org.deidentifier.arx.gui.Controller;
import org.deidentifier.arx.gui.model.ModelEvent;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;
import org.deidentifier.arx.gui.model.ModelNodeFilter;
import org.deidentifier.arx.gui.view.SWTUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import cern.colt.Arrays;
import de.linearbits.tiles.DecoratorColor;
import de.linearbits.tiles.DecoratorInteger;
import de.linearbits.tiles.DecoratorString;
import de.linearbits.tiles.Filter;
import de.linearbits.tiles.TileLayoutDynamic;
import de.linearbits.tiles.Tiles;
/**
* This class implements a tiles view on selected nodes.
*
* @author Fabian Prasser
* @author Florian Kohlmayer
*/
public class ViewTiles extends ViewSolutionSpace {
/** The tiles. */
private final Tiles<ARXNode> tiles;
/** Config */
private static final int NUM_COLUMNS = 10;
/** Config */
private static final int NUM_ROWS = 20;
/** Config */
private static final int MARGIN = 5;
/**
* Constructor
*
* @param parent
* @param controller
*/
public ViewTiles(final Composite parent, final Controller controller) {
// Super class
super(parent, controller);
tiles = new Tiles<ARXNode>(super.getPrimaryComposite(), SWT.NONE);
tiles.setLayoutData(SWTUtil.createFillGridData());
// Selection listener
tiles.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent arg0) {
ViewTiles.this.actionSelectNode(tiles.getSelectedItem());
}
});
// Show menu
tiles.addMouseListener(new MouseAdapter(){
@Override
public void mouseUp(MouseEvent arg0) {
if (arg0.button == 3) {
if (getSelectedNode() != null) {
Point display = tiles.toDisplay(arg0.x, arg0.y);
getModel().setSelectedNode(getSelectedNode());
controller.update(new ModelEvent(ViewTiles.this,
ModelPart.SELECTED_NODE, getSelectedNode()));
actionShowMenu(display.x, display.y);
}
}
}
});
// Set layout
tiles.setTileLayout(new TileLayoutDynamic(NUM_COLUMNS, NUM_ROWS, MARGIN, MARGIN));
tiles.setComparator(new Comparator<ARXNode>() {
public int compare(ARXNode o1, ARXNode o2) {
boolean unknown2 = o2.getMinimumInformationLoss().compareTo(o2.getMaximumInformationLoss())!=0 &&
asRelativeValue(o2.getMinimumInformationLoss())==0d;
boolean unknown1 = o1.getMinimumInformationLoss().compareTo(o1.getMaximumInformationLoss())!=0 &&
asRelativeValue(o1.getMinimumInformationLoss())==0d;
if (unknown1 && unknown2) return 0;
else if (unknown1 && !unknown2) return +1;
else if (!unknown1 && unknown2) return -1;
else {
int c1 = o1.getMinimumInformationLoss().compareTo(o2.getMinimumInformationLoss());
return c1 != 0 ? c1 : o1.getMaximumInformationLoss().compareTo(o2.getMaximumInformationLoss());
}
}
});
tiles.setFilter(new Filter<ARXNode>() {
public boolean accepts(ARXNode arg0) {
return true;
}
});
tiles.setDecoratorLabel(new DecoratorString<ARXNode>() {
@Override
public String decorate(ARXNode node) {
return Arrays.toString(node.getTransformation());
}
});
tiles.setDecoratorBackgroundColor(createDecoratorBackgroundColor());
tiles.setDecoratorTooltip(super.getTooltipDecorator());
tiles.setDecoratorLineColor(createDecoratorLineColor());
tiles.setDecoratorLineWidth(createDecoratorLineWidth());
tiles.setBackground(tiles.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
tiles.update();
}
/**
* Resets the view.
*/
@Override
public void reset() {
super.reset();
tiles.setRedraw(false);
tiles.setItems(new ArrayList<ARXNode>());
tiles.setRedraw(true);
tiles.setFilter(new Filter<ARXNode>() {
public boolean accepts(ARXNode arg0) {
return true;
}
});
tiles.update();
SWTUtil.disable(tiles);
}
/**
* Creates a background decorator
* @return
*/
private DecoratorColor<ARXNode> createDecoratorBackgroundColor() {
DecoratorColor<ARXNode> decorator = new DecoratorColor<ARXNode>() {
@Override
public Color decorate(ARXNode element) {
return ViewTiles.this.getUtilityColor(element);
}
};
return decorator;
}
/**
* Creates a decorator
* @return
*/
private DecoratorColor<ARXNode> createDecoratorLineColor() {
return new DecoratorColor<ARXNode>() {
@Override
public Color decorate(ARXNode node) {
return getInnerColor(node);
}
};
}
/**
* Creates a decorator
* @return
*/
private DecoratorInteger<ARXNode> createDecoratorLineWidth() {
return new DecoratorInteger<ARXNode>() {
@Override
public Integer decorate(ARXNode node) {
return getOuterStrokeWidth(node, (tiles.getSize().x - NUM_COLUMNS * MARGIN) / NUM_COLUMNS);
}
};
}
/**
* Updates the filter
*
* @param lattice
* @param filter
*/
private void updateFilter(final ARXLattice lattice, final ModelNodeFilter filter) {
if (filter == null) return;
final ModelNodeFilter filterClone = filter.clone();
getController().getResources().getDisplay().asyncExec(new Runnable() {
public void run() {
tiles.setFilter(new Filter<ARXNode>() {
public boolean accepts(ARXNode node) {
return filterClone.isAllowed(lattice, node);
}
});
tiles.update();
}
});
}
/**
* Updates the lattice
*
* @param lattice
*/
private void updateLattice(final ARXLattice lattice) {
if (lattice == null) {
reset();
return;
}
getController().getResources().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
SWTUtil.enable(tiles);
tiles.setRedraw(true);
List<ARXNode> list = new ArrayList<ARXNode>();
for (final ARXNode[] level : lattice.getLevels()) {
for (final ARXNode node : level) {
list.add(node);
}
}
// Set
tiles.setItems(list);
// Draw
tiles.update();
}
});
}
@Override
protected void actionRedraw() {
this.tiles.redraw();
}
@Override
protected void eventFilterChanged(ARXResult result, ModelNodeFilter filter) {
if (getModel() != null && result != null) {
updateFilter(result.getLattice(), filter);
} else {
reset();
}
}
@Override
protected void eventModelChanged() {
if (getModel() != null && getModel().getResult() != null) {
updateLattice(getModel().getResult().getLattice());
updateFilter(getModel().getResult().getLattice(), getModel().getNodeFilter());
}
}
@Override
protected void eventNodeSelected() {
tiles.setSelectedItem(super.getSelectedNode());
}
@Override
protected void eventResultChanged(ARXResult result) {
if (result == null) {
reset();
} else {
updateLattice(result.getLattice());
}
}
}
| src/gui/org/deidentifier/arx/gui/view/impl/explore/ViewTiles.java | /*
* ARX: Powerful Data Anonymization
* Copyright (C) 2012 - 2014 Florian Kohlmayer, Fabian Prasser
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.deidentifier.arx.gui.view.impl.explore;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.deidentifier.arx.ARXLattice;
import org.deidentifier.arx.ARXLattice.ARXNode;
import org.deidentifier.arx.ARXResult;
import org.deidentifier.arx.gui.Controller;
import org.deidentifier.arx.gui.model.ModelEvent;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;
import org.deidentifier.arx.gui.model.ModelNodeFilter;
import org.deidentifier.arx.gui.view.SWTUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import cern.colt.Arrays;
import de.linearbits.tiles.DecoratorColor;
import de.linearbits.tiles.DecoratorInteger;
import de.linearbits.tiles.DecoratorString;
import de.linearbits.tiles.Filter;
import de.linearbits.tiles.TileLayoutDynamic;
import de.linearbits.tiles.Tiles;
/**
* This class implements a tiles view on selected nodes.
*
* @author Fabian Prasser
* @author Florian Kohlmayer
*/
public class ViewTiles extends ViewSolutionSpace {
/** The tiles. */
private final Tiles<ARXNode> tiles;
/** Config */
private static final int NUM_COLUMNS = 10;
/** Config */
private static final int NUM_ROWS = 20;
/** Config */
private static final int MARGIN = 5;
/**
* Constructor
*
* @param parent
* @param controller
*/
public ViewTiles(final Composite parent, final Controller controller) {
// Super class
super(parent, controller);
tiles = new Tiles<ARXNode>(super.getPrimaryComposite(), SWT.NONE);
tiles.setLayoutData(SWTUtil.createFillGridData());
// Selection listener
tiles.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent arg0) {
ViewTiles.this.actionSelectNode(tiles.getSelectedItem());
}
});
// Show menu
tiles.addMouseListener(new MouseAdapter(){
@Override
public void mouseUp(MouseEvent arg0) {
if (arg0.button == 3) {
if (getSelectedNode() != null) {
Point display = tiles.toDisplay(arg0.x, arg0.y);
getModel().setSelectedNode(getSelectedNode());
controller.update(new ModelEvent(ViewTiles.this,
ModelPart.SELECTED_NODE, getSelectedNode()));
actionShowMenu(display.x, display.y);
}
}
}
});
// Set layout
tiles.setTileLayout(new TileLayoutDynamic(NUM_COLUMNS, NUM_ROWS, MARGIN, MARGIN));
tiles.setComparator(new Comparator<ARXNode>() {
public int compare(ARXNode o1, ARXNode o2) {
boolean unknown2 = o2.getMinimumInformationLoss().compareTo(o2.getMaximumInformationLoss())!=0 &&
asRelativeValue(o2.getMinimumInformationLoss())==0d;
boolean unknown1 = o1.getMinimumInformationLoss().compareTo(o1.getMaximumInformationLoss())!=0 &&
asRelativeValue(o1.getMinimumInformationLoss())==0d;
if (unknown1 && unknown2) return 0;
else if (unknown1 && !unknown2) return +1;
else if (!unknown1 && unknown2) return -1;
else {
int c1 = o1.getMinimumInformationLoss().compareTo(o2.getMinimumInformationLoss());
return c1 != 0 ? c1 : o1.getMaximumInformationLoss().compareTo(o2.getMaximumInformationLoss());
}
}
});
tiles.setFilter(new Filter<ARXNode>() {
public boolean accepts(ARXNode arg0) {
return true;
}
});
tiles.setDecoratorLabel(new DecoratorString<ARXNode>() {
@Override
public String decorate(ARXNode node) {
return Arrays.toString(node.getTransformation());
}
});
tiles.setDecoratorBackgroundColor(createDecoratorBackgroundColor());
tiles.setDecoratorTooltip(super.getTooltipDecorator());
tiles.setDecoratorLineColor(createDecoratorLineColor());
tiles.setDecoratorLineWidth(createDecoratorLineWidth());
tiles.update();
}
/**
* Resets the view.
*/
@Override
public void reset() {
super.reset();
tiles.setRedraw(false);
tiles.setItems(new ArrayList<ARXNode>());
tiles.setRedraw(true);
tiles.setFilter(new Filter<ARXNode>() {
public boolean accepts(ARXNode arg0) {
return true;
}
});
tiles.update();
SWTUtil.disable(tiles);
}
/**
* Creates a background decorator
* @return
*/
private DecoratorColor<ARXNode> createDecoratorBackgroundColor() {
DecoratorColor<ARXNode> decorator = new DecoratorColor<ARXNode>() {
@Override
public Color decorate(ARXNode element) {
return ViewTiles.this.getUtilityColor(element);
}
};
return decorator;
}
/**
* Creates a decorator
* @return
*/
private DecoratorColor<ARXNode> createDecoratorLineColor() {
return new DecoratorColor<ARXNode>() {
@Override
public Color decorate(ARXNode node) {
return getInnerColor(node);
}
};
}
/**
* Creates a decorator
* @return
*/
private DecoratorInteger<ARXNode> createDecoratorLineWidth() {
return new DecoratorInteger<ARXNode>() {
@Override
public Integer decorate(ARXNode node) {
return getOuterStrokeWidth(node, (tiles.getSize().x - NUM_COLUMNS * MARGIN) / NUM_COLUMNS);
}
};
}
/**
* Updates the filter
*
* @param lattice
* @param filter
*/
private void updateFilter(final ARXLattice lattice, final ModelNodeFilter filter) {
if (filter == null) return;
final ModelNodeFilter filterClone = filter.clone();
getController().getResources().getDisplay().asyncExec(new Runnable() {
public void run() {
tiles.setFilter(new Filter<ARXNode>() {
public boolean accepts(ARXNode node) {
return filterClone.isAllowed(lattice, node);
}
});
tiles.update();
}
});
}
/**
* Updates the lattice
*
* @param lattice
*/
private void updateLattice(final ARXLattice lattice) {
if (lattice == null) {
reset();
return;
}
getController().getResources().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
SWTUtil.enable(tiles);
tiles.setRedraw(true);
List<ARXNode> list = new ArrayList<ARXNode>();
for (final ARXNode[] level : lattice.getLevels()) {
for (final ARXNode node : level) {
list.add(node);
}
}
// Set
tiles.setItems(list);
// Draw
tiles.update();
}
});
}
@Override
protected void actionRedraw() {
this.tiles.redraw();
}
@Override
protected void eventFilterChanged(ARXResult result, ModelNodeFilter filter) {
if (getModel() != null && result != null) {
updateFilter(result.getLattice(), filter);
} else {
reset();
}
}
@Override
protected void eventModelChanged() {
if (getModel() != null && getModel().getResult() != null) {
updateLattice(getModel().getResult().getLattice());
updateFilter(getModel().getResult().getLattice(), getModel().getNodeFilter());
}
}
@Override
protected void eventNodeSelected() {
tiles.setSelectedItem(super.getSelectedNode());
}
@Override
protected void eventResultChanged(ARXResult result) {
if (result == null) {
reset();
} else {
updateLattice(result.getLattice());
}
}
}
| Set background color for Tiles | src/gui/org/deidentifier/arx/gui/view/impl/explore/ViewTiles.java | Set background color for Tiles |
|
Java | apache-2.0 | 546562c17520afec8f7819d851a251ab51117d0f | 0 | ebraminio/commafeed,Athou/commafeed,wesley1001/commafeed,ahmadassaf/CommaFeed-RSS-Reader,tlvince/commafeed,syshk/commafeed,Athou/commafeed,wesley1001/commafeed,syshk/commafeed,tlvince/commafeed,ahmadassaf/CommaFeed-RSS-Reader,ahmadassaf/CommaFeed-RSS-Reader,ebraminio/commafeed,Hubcapp/commafeed,RavenB/commafeed,zhangzuoqiang/commafeed,tlvince/commafeed,RavenB/commafeed,zhangzuoqiang/commafeed,Athou/commafeed,RavenB/commafeed,Hubcapp/commafeed,zhangzuoqiang/commafeed,syshk/commafeed,Hubcapp/commafeed,zhangzuoqiang/commafeed,Athou/commafeed,ebraminio/commafeed,syshk/commafeed,ahmadassaf/CommaFeed-RSS-Reader,Hubcapp/commafeed,tlvince/commafeed,ebraminio/commafeed,wesley1001/commafeed,wesley1001/commafeed,RavenB/commafeed | package com.commafeed.frontend.rest.resources;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ObjectUtils;
import com.commafeed.backend.model.Feed;
import com.commafeed.backend.model.FeedCategory;
import com.commafeed.backend.model.FeedSubscription;
import com.commafeed.frontend.model.Category;
import com.commafeed.frontend.model.Subscription;
import com.commafeed.frontend.model.SubscriptionRequest;
import com.commafeed.frontend.rest.resources.EntriesREST.Type;
import com.google.common.base.Preconditions;
import com.sun.syndication.io.FeedException;
@Path("subscriptions")
public class SubscriptionsREST extends AbstractREST {
@GET
@Path("fetch")
public Feed fetchFeed(@QueryParam("url") String url) {
Preconditions.checkNotNull(url);
url = prependHttp(url);
Feed feed = null;
try {
feed = feedFetcher.fetch(url);
} catch (FeedException e) {
throw new WebApplicationException(e, Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(e.getMessage()).build());
}
return feed;
}
@POST
@Path("subscribe")
public Response subscribe(SubscriptionRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getTitle());
Preconditions.checkNotNull(req.getUrl());
String url = prependHttp(req.getUrl());
Feed fetchedFeed = fetchFeed(url);
Feed feed = feedService.findByUrl(fetchedFeed.getUrl());
if (feed == null) {
feed = fetchedFeed;
feedService.save(feed);
}
FeedSubscription sub = new FeedSubscription();
sub.setCategory(EntriesREST.ALL.equals(req.getCategoryId()) ? null
: feedCategoryService.findById(Long.valueOf(req.getCategoryId())));
sub.setFeed(feed);
sub.setTitle(req.getTitle());
sub.setUser(getUser());
feedSubscriptionService.save(sub);
return Response.ok(Status.OK).build();
}
private String prependHttp(String url) {
if (!url.startsWith("http")) {
url = "http://" + url;
}
return url;
}
@GET
@Path("unsubscribe")
public Response unsubscribe(@QueryParam("id") Long subscriptionId) {
feedSubscriptionService.deleteById(subscriptionId);
return Response.ok(Status.OK).build();
}
@GET
@Path("rename")
public Response rename(@QueryParam("type") Type type,
@QueryParam("id") Long id, @QueryParam("name") String name) {
if (type == Type.feed) {
FeedSubscription subscription = feedSubscriptionService.findById(
getUser(), id);
subscription.setTitle(name);
feedSubscriptionService.update(subscription);
} else if (type == Type.category) {
FeedCategory category = feedCategoryService.findById(getUser(), id);
category.setName(name);
feedCategoryService.update(category);
}
return Response.ok(Status.OK).build();
}
@GET
@Path("collapse")
public Response collapse(@QueryParam("id") String id,
@QueryParam("collapse") boolean collapse) {
Preconditions.checkNotNull(id);
if (!EntriesREST.ALL.equals(id)) {
FeedCategory category = feedCategoryService.findById(getUser(),
Long.valueOf(id));
category.setCollapsed(collapse);
feedCategoryService.update(category);
}
return Response.ok(Status.OK).build();
}
@Path("addCategory")
@GET
public Response addCategory(@QueryParam("name") String name,
@QueryParam("parentId") String parentId) {
Preconditions.checkNotNull(name);
FeedCategory cat = new FeedCategory();
cat.setName(name);
cat.setUser(getUser());
if (parentId != null && !EntriesREST.ALL.equals(parentId)) {
FeedCategory parent = new FeedCategory();
parent.setId(Long.valueOf(parentId));
cat.setParent(parent);
}
feedCategoryService.save(cat);
return Response.ok().build();
}
@GET
@Path("deleteCategory")
public Response deleteCategory(@QueryParam("id") Long id) {
feedCategoryService.deleteById(id);
return Response.ok().build();
}
@POST
@Path("import")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response importOpml() {
try {
FileItemFactory factory = new DiskFileItemFactory(1000000, null);
ServletFileUpload upload = new ServletFileUpload(factory);
for (FileItem item : upload.parseRequest(request)) {
if ("file".equals(item.getFieldName())) {
opmlImporter.importOpml(getUser(),
IOUtils.toString(item.getInputStream(), "UTF-8"));
break;
}
}
} catch (Exception e) {
throw new WebApplicationException(Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(e.getMessage()).build());
}
return Response.ok(Status.OK).build();
}
@GET
public Category getSubscriptions() {
List<FeedCategory> categories = feedCategoryService.findAll(getUser());
List<FeedSubscription> subscriptions = feedSubscriptionService
.findAll(getUser());
Map<Long, Long> unreadCount = feedEntryStatusService
.getUnreadCount(getUser());
Category root = buildCategory(null, categories, subscriptions,
unreadCount);
root.setId("all");
root.setName("All");
return root;
}
private Category buildCategory(Long id, List<FeedCategory> categories,
List<FeedSubscription> subscriptions, Map<Long, Long> unreadCount) {
Category category = new Category();
category.setId(String.valueOf(id));
category.setExpanded(true);
for (FeedCategory c : categories) {
if ((id == null && c.getParent() == null)
|| (c.getParent() != null && ObjectUtils.equals(c
.getParent().getId(), id))) {
Category child = buildCategory(c.getId(), categories,
subscriptions, unreadCount);
child.setId(String.valueOf(c.getId()));
child.setName(c.getName());
child.setExpanded(!c.isCollapsed());
category.getChildren().add(child);
}
}
Collections.sort(category.getChildren(), new Comparator<Category>() {
@Override
public int compare(Category o1, Category o2) {
return ObjectUtils.compare(o1.getName(), o2.getName());
}
});
for (FeedSubscription subscription : subscriptions) {
if ((id == null && subscription.getCategory() == null)
|| (subscription.getCategory() != null && ObjectUtils
.equals(subscription.getCategory().getId(), id))) {
Subscription sub = new Subscription();
sub.setId(subscription.getId());
sub.setName(subscription.getTitle());
sub.setMessage(subscription.getFeed().getMessage());
sub.setFeedUrl(subscription.getFeed().getLink());
Long size = unreadCount.get(subscription.getId());
sub.setUnread(size == null ? 0 : size);
category.getFeeds().add(sub);
}
}
Collections.sort(category.getFeeds(), new Comparator<Subscription>() {
@Override
public int compare(Subscription o1, Subscription o2) {
return ObjectUtils.compare(o1.getName(), o2.getName());
}
});
return category;
}
}
| src/main/java/com/commafeed/frontend/rest/resources/SubscriptionsREST.java | package com.commafeed.frontend.rest.resources;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ObjectUtils;
import com.commafeed.backend.model.Feed;
import com.commafeed.backend.model.FeedCategory;
import com.commafeed.backend.model.FeedSubscription;
import com.commafeed.frontend.model.Category;
import com.commafeed.frontend.model.Subscription;
import com.commafeed.frontend.model.SubscriptionRequest;
import com.commafeed.frontend.rest.resources.EntriesREST.Type;
import com.google.common.base.Preconditions;
import com.sun.syndication.io.FeedException;
@Path("subscriptions")
public class SubscriptionsREST extends AbstractREST {
@GET
@Path("fetch")
public Feed fetchFeed(@QueryParam("url") String url) {
Preconditions.checkNotNull(url);
Feed feed = null;
try {
feed = feedFetcher.fetch(url);
} catch (FeedException e) {
throw new WebApplicationException(Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(e.getMessage()).build());
}
return feed;
}
@POST
@Path("subscribe")
public Response subscribe(SubscriptionRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getTitle());
Preconditions.checkNotNull(req.getUrl());
Feed fetchedFeed = fetchFeed(req.getUrl());
Feed feed = feedService.findByUrl(fetchedFeed.getUrl());
if (feed == null) {
feed = fetchedFeed;
feedService.save(feed);
}
FeedSubscription sub = new FeedSubscription();
sub.setCategory(EntriesREST.ALL.equals(req.getCategoryId()) ? null
: feedCategoryService.findById(Long.valueOf(req.getCategoryId())));
sub.setFeed(feed);
sub.setTitle(req.getTitle());
sub.setUser(getUser());
feedSubscriptionService.save(sub);
return Response.ok(Status.OK).build();
}
@GET
@Path("unsubscribe")
public Response unsubscribe(@QueryParam("id") Long subscriptionId) {
feedSubscriptionService.deleteById(subscriptionId);
return Response.ok(Status.OK).build();
}
@GET
@Path("rename")
public Response rename(@QueryParam("type") Type type,
@QueryParam("id") Long id, @QueryParam("name") String name) {
if (type == Type.feed) {
FeedSubscription subscription = feedSubscriptionService.findById(
getUser(), id);
subscription.setTitle(name);
feedSubscriptionService.update(subscription);
} else if (type == Type.category) {
FeedCategory category = feedCategoryService.findById(getUser(), id);
category.setName(name);
feedCategoryService.update(category);
}
return Response.ok(Status.OK).build();
}
@GET
@Path("collapse")
public Response collapse(@QueryParam("id") String id,
@QueryParam("collapse") boolean collapse) {
Preconditions.checkNotNull(id);
if (!EntriesREST.ALL.equals(id)) {
FeedCategory category = feedCategoryService.findById(getUser(),
Long.valueOf(id));
category.setCollapsed(collapse);
feedCategoryService.update(category);
}
return Response.ok(Status.OK).build();
}
@Path("addCategory")
@GET
public Response addCategory(@QueryParam("name") String name,
@QueryParam("parentId") String parentId) {
Preconditions.checkNotNull(name);
FeedCategory cat = new FeedCategory();
cat.setName(name);
cat.setUser(getUser());
if (parentId != null && !EntriesREST.ALL.equals(parentId)) {
FeedCategory parent = new FeedCategory();
parent.setId(Long.valueOf(parentId));
cat.setParent(parent);
}
feedCategoryService.save(cat);
return Response.ok().build();
}
@GET
@Path("deleteCategory")
public Response deleteCategory(@QueryParam("id") Long id) {
feedCategoryService.deleteById(id);
return Response.ok().build();
}
@POST
@Path("import")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response importOpml() {
try {
FileItemFactory factory = new DiskFileItemFactory(1000000, null);
ServletFileUpload upload = new ServletFileUpload(factory);
for (FileItem item : upload.parseRequest(request)) {
if ("file".equals(item.getFieldName())) {
opmlImporter.importOpml(getUser(),
IOUtils.toString(item.getInputStream(), "UTF-8"));
break;
}
}
} catch (Exception e) {
throw new WebApplicationException(Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(e.getMessage()).build());
}
return Response.ok(Status.OK).build();
}
@GET
public Category getSubscriptions() {
List<FeedCategory> categories = feedCategoryService.findAll(getUser());
List<FeedSubscription> subscriptions = feedSubscriptionService
.findAll(getUser());
Map<Long, Long> unreadCount = feedEntryStatusService
.getUnreadCount(getUser());
Category root = buildCategory(null, categories, subscriptions,
unreadCount);
root.setId("all");
root.setName("All");
return root;
}
private Category buildCategory(Long id, List<FeedCategory> categories,
List<FeedSubscription> subscriptions, Map<Long, Long> unreadCount) {
Category category = new Category();
category.setId(String.valueOf(id));
category.setExpanded(true);
for (FeedCategory c : categories) {
if ((id == null && c.getParent() == null)
|| (c.getParent() != null && ObjectUtils.equals(c
.getParent().getId(), id))) {
Category child = buildCategory(c.getId(), categories,
subscriptions, unreadCount);
child.setId(String.valueOf(c.getId()));
child.setName(c.getName());
child.setExpanded(!c.isCollapsed());
category.getChildren().add(child);
}
}
Collections.sort(category.getChildren(), new Comparator<Category>() {
@Override
public int compare(Category o1, Category o2) {
return ObjectUtils.compare(o1.getName(), o2.getName());
}
});
for (FeedSubscription subscription : subscriptions) {
if ((id == null && subscription.getCategory() == null)
|| (subscription.getCategory() != null && ObjectUtils
.equals(subscription.getCategory().getId(), id))) {
Subscription sub = new Subscription();
sub.setId(subscription.getId());
sub.setName(subscription.getTitle());
sub.setMessage(subscription.getFeed().getMessage());
sub.setFeedUrl(subscription.getFeed().getLink());
Long size = unreadCount.get(subscription.getId());
sub.setUnread(size == null ? 0 : size);
category.getFeeds().add(sub);
}
}
Collections.sort(category.getFeeds(), new Comparator<Subscription>() {
@Override
public int compare(Subscription o1, Subscription o2) {
return ObjectUtils.compare(o1.getName(), o2.getName());
}
});
return category;
}
}
| append http protocol if missing
| src/main/java/com/commafeed/frontend/rest/resources/SubscriptionsREST.java | append http protocol if missing |
|
Java | apache-2.0 | bf97e34809c057325ef818cd6e2d92e83102bcbc | 0 | PramodSSImmaneni/apex-malhar,brightchen/apex-malhar,tushargosavi/incubator-apex-malhar,chandnisingh/apex-malhar,chinmaykolhatkar/apex-malhar,skekre98/apex-mlhr,chinmaykolhatkar/incubator-apex-malhar,yogidevendra/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,patilvikram/apex-malhar,davidyan74/apex-malhar,tushargosavi/incubator-apex-malhar,patilvikram/apex-malhar,ilganeli/incubator-apex-malhar,trusli/apex-malhar,patilvikram/apex-malhar,vrozov/apex-malhar,patilvikram/apex-malhar,PramodSSImmaneni/apex-malhar,tushargosavi/incubator-apex-malhar,chandnisingh/apex-malhar,ilganeli/incubator-apex-malhar,brightchen/apex-malhar,siyuanh/incubator-apex-malhar,skekre98/apex-mlhr,ananthc/apex-malhar,apache/incubator-apex-malhar,yogidevendra/apex-malhar,patilvikram/apex-malhar,DataTorrent/Megh,siyuanh/apex-malhar,siyuanh/incubator-apex-malhar,vrozov/incubator-apex-malhar,chandnisingh/apex-malhar,vrozov/incubator-apex-malhar,ananthc/apex-malhar,siyuanh/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,siyuanh/incubator-apex-malhar,tweise/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,brightchen/apex-malhar,tweise/apex-malhar,apache/incubator-apex-malhar,apache/incubator-apex-malhar,tweise/incubator-apex-malhar,yogidevendra/apex-malhar,sandeep-n/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,ananthc/apex-malhar,trusli/apex-malhar,siyuanh/apex-malhar,vrozov/incubator-apex-malhar,vrozov/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,brightchen/apex-malhar,trusli/apex-malhar,vrozov/incubator-apex-malhar,ananthc/apex-malhar,DataTorrent/Megh,trusli/apex-malhar,trusli/apex-malhar,DataTorrent/incubator-apex-malhar,chandnisingh/apex-malhar,davidyan74/apex-malhar,siyuanh/apex-malhar,PramodSSImmaneni/apex-malhar,tushargosavi/incubator-apex-malhar,vrozov/apex-malhar,PramodSSImmaneni/apex-malhar,yogidevendra/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,DataTorrent/incubator-apex-malhar,vrozov/apex-malhar,chinmaykolhatkar/apex-malhar,ananthc/apex-malhar,PramodSSImmaneni/apex-malhar,skekre98/apex-mlhr,yogidevendra/incubator-apex-malhar,skekre98/apex-mlhr,vrozov/apex-malhar,sandeep-n/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,brightchen/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,ilganeli/incubator-apex-malhar,apache/incubator-apex-malhar,ilganeli/incubator-apex-malhar,prasannapramod/apex-malhar,davidyan74/apex-malhar,chinmaykolhatkar/apex-malhar,sandeep-n/incubator-apex-malhar,davidyan74/apex-malhar,skekre98/apex-mlhr,tweise/apex-malhar,davidyan74/apex-malhar,siyuanh/incubator-apex-malhar,tweise/apex-malhar,prasannapramod/apex-malhar,tweise/apex-malhar,yogidevendra/apex-malhar,yogidevendra/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,brightchen/apex-malhar,chinmaykolhatkar/apex-malhar,siyuanh/apex-malhar,tushargosavi/incubator-apex-malhar,siyuanh/incubator-apex-malhar,ilganeli/incubator-apex-malhar,prasannapramod/apex-malhar,siyuanh/apex-malhar,sandeep-n/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,trusli/apex-malhar,PramodSSImmaneni/apex-malhar,chandnisingh/apex-malhar,DataTorrent/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,prasannapramod/apex-malhar,skekre98/apex-mlhr,tweise/incubator-apex-malhar,vrozov/apex-malhar,yogidevendra/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,ananthc/apex-malhar,tushargosavi/incubator-apex-malhar,apache/incubator-apex-malhar,siyuanh/incubator-apex-malhar,yogidevendra/apex-malhar,yogidevendra/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,patilvikram/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,prasannapramod/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,vrozov/incubator-apex-malhar,vrozov/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,vrozov/apex-malhar,prasannapramod/apex-malhar,chandnisingh/apex-malhar,tweise/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,trusli/apex-malhar,tweise/incubator-apex-malhar,tweise/incubator-apex-malhar,apache/incubator-apex-malhar,patilvikram/apex-malhar,chandnisingh/apex-malhar,brightchen/apex-malhar,ilganeli/incubator-apex-malhar,tweise/apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,davidyan74/apex-malhar,ilganeli/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,siyuanh/incubator-apex-malhar,siyuanh/apex-malhar,sandeep-n/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,tweise/apex-malhar,tweise/incubator-apex-malhar | /*
* Copyright (c) 2014 DataTorrent, Inc. ALL Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datatorrent.contrib.hds;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.validation.constraints.Min;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.api.CheckpointListener;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.Operator;
import com.datatorrent.common.util.NameableThreadFactory;
import com.datatorrent.common.util.Slice;
import com.datatorrent.contrib.hds.HDSFileAccess.HDSFileReader;
import com.datatorrent.contrib.hds.HDSFileAccess.HDSFileWriter;
import com.esotericsoftware.kryo.io.Output;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Manager for buckets. Can be sub-classed as operator or used in composite pattern.
*/
public class HDSBucketManager extends HDSReader implements HDS.BucketManager, CheckpointListener, Operator
{
private final transient HashMap<Long, BucketMeta> metaCache = Maps.newHashMap();
private long windowId;
private transient long lastFlushWindowId;
private final transient HashMap<Long, Bucket> buckets = Maps.newHashMap();
@VisibleForTesting
protected transient ExecutorService writeExecutor;
private transient Exception writerError;
private int maxFileSize = 128 * 1024 * 1024; // 128m
private int maxWalFileSize = 64 * 1024 * 1024;
private int flushSize = 1000000;
private int flushIntervalCount = 30;
private final HashMap<Long, WalMeta> walMeta = Maps.newHashMap();
/**
* Size limit for data files. Files are rolled once the limit has been exceeded.
* The final size of a file can be larger than the limit by the size of the last/single entry written to it.
* @return
*/
public int getMaxFileSize()
{
return maxFileSize;
}
public void setMaxFileSize(int maxFileSize)
{
this.maxFileSize = maxFileSize;
}
/**
* Size limit for WAL files. Files are rolled once the limit has been exceeded.
* The final size of a file can be larger than the limit, as files are rolled at
* end of the operator window.
* @return
*/
public int getMaxWalFileSize()
{
return maxWalFileSize;
}
public void setMaxWalFileSize(int maxWalFileSize)
{
this.maxWalFileSize = maxWalFileSize;
}
/**
* The number of changes collected in memory before flushing to persistent storage.
* @return
*/
public int getFlushSize()
{
return flushSize;
}
public void setFlushSize(int flushSize)
{
this.flushSize = flushSize;
}
/**
* Cached writes are flushed to persistent storage periodically. The interval is specified as count of windows and
* establishes the maximum latency for changes to be written while below the {@link #flushSize} threshold.
*
* @return
*/
@Min(value=1)
public int getFlushIntervalCount()
{
return flushIntervalCount;
}
public void setFlushIntervalCount(int flushIntervalCount)
{
this.flushIntervalCount = flushIntervalCount;
}
public static byte[] asArray(Slice slice)
{
return Arrays.copyOfRange(slice.buffer, slice.offset, slice.offset + slice.length);
}
public static Slice toSlice(byte[] bytes)
{
return new Slice(bytes, 0, bytes.length);
}
/**
* Write data to size based rolling files
* @param bucket
* @param bucketMeta
* @param data
* @throws IOException
*/
private void writeFile(Bucket bucket, BucketMeta bucketMeta, TreeMap<Slice, byte[]> data) throws IOException
{
HDSFileWriter fw = null;
BucketFileMeta fileMeta = null;
for (Map.Entry<Slice, byte[]> dataEntry : data.entrySet()) {
if (fw == null) {
// next file
fileMeta = bucketMeta.addFile(bucket.bucketKey, dataEntry.getKey());
LOG.debug("writing new data file {} {}", bucket.bucketKey, fileMeta.name);
fw = this.store.getWriter(bucket.bucketKey, fileMeta.name + ".tmp");
}
fw.append(asArray(dataEntry.getKey()), dataEntry.getValue());
if ( fw.getBytesWritten() > this.maxFileSize) {
// roll file
fw.close();
this.store.rename(bucket.bucketKey, fileMeta.name + ".tmp", fileMeta.name);
LOG.debug("created new data file {} {}", bucket.bucketKey, fileMeta.name);
fw = null;
}
}
if (fw != null) {
fw.close();
this.store.rename(bucket.bucketKey, fileMeta.name + ".tmp", fileMeta.name);
LOG.debug("created new data file {} {}", bucket.bucketKey, fileMeta.name);
}
}
private Bucket getBucket(long bucketKey) throws IOException
{
Bucket bucket = this.buckets.get(bucketKey);
if (bucket == null) {
LOG.debug("Opening bucket {}", bucketKey);
bucket = new Bucket();
bucket.bucketKey = bucketKey;
this.buckets.put(bucketKey, bucket);
BucketMeta bmeta = getMeta(bucketKey);
WalMeta wmeta = getWalMeta(bucketKey);
bucket.wal = new HDSWalManager(this.store, bucketKey, wmeta.fileId, wmeta.offset);
bucket.wal.setMaxWalFileSize(maxWalFileSize);
// bmeta.componentLSN is data which is committed to disks.
// wmeta.windowId windowId till which data is available in WAL.
if (bmeta.committedWid < wmeta.windowId)
{
LOG.debug("Recovery for bucket {}", bucketKey);
bucket.recoveryInProgress = true;
// Get last committed LSN from store, and use that for recovery.
bucket.wal.runRecovery(this, wmeta.tailId, wmeta.tailOffset);
bucket.recoveryInProgress = false;
}
}
return bucket;
}
private transient Slice keyWrapper = new Slice(null, 0, 0);
/**
* Intercept query processing to incorporate unwritten changes.
*/
@Override
protected void processQuery(HDSQuery query)
{
byte[] key = query.key;
keyWrapper.buffer = key;
keyWrapper.length = key.length;
Bucket bucket = this.buckets.get(query.bucketKey);
if (bucket != null) {
// check unwritten changes first
byte[] v = bucket.writeCache.get(keyWrapper);
if (v != null) {
query.result = v;
query.processed = true;
return;
}
// check changes currently being flushed
v = bucket.frozenWriteCache.get(keyWrapper);
if (v != null) {
query.result = v;
query.processed = true;
return;
}
}
super.processQuery(query);
}
@Override
public byte[] get(long bucketKey, byte[] key) throws IOException
{
return super.get(bucketKey, key);
}
@Override
public void put(long bucketKey, byte[] key, byte[] value) throws IOException
{
Bucket bucket = getBucket(bucketKey);
/* Do not update WAL, if tuple being added is coming through recovery */
if (!bucket.recoveryInProgress) {
bucket.wal.append(key, value);
}
bucket.writeCache.put(new Slice(key, 0, key.length), value);
}
/**
* Flush changes from write cache to disk.
* New data files will be written and meta data replaced atomically.
* The flush frequency determines availability of changes to external readers.
* @throws IOException
*/
private void writeDataFiles(Bucket bucket) throws IOException
{
// bucket keys by file
BucketMeta bm = getMeta(bucket.bucketKey);
TreeMap<Slice, BucketFileMeta> bucketSeqStarts = bm.files;
Map<BucketFileMeta, Map<Slice, byte[]>> modifiedFiles = Maps.newHashMap();
for (Map.Entry<Slice, byte[]> entry : bucket.frozenWriteCache.entrySet()) {
// find file for key
Map.Entry<Slice, BucketFileMeta> floorEntry = bucketSeqStarts.floorEntry(entry.getKey());
BucketFileMeta floorFile;
if (floorEntry != null) {
floorFile = floorEntry.getValue();
} else {
floorEntry = bucketSeqStarts.firstEntry();
if (floorEntry == null || floorEntry.getValue().name != null) {
// no existing file or file with higher key
floorFile = new BucketFileMeta();
} else {
// placeholder for new keys, move start key
floorFile = floorEntry.getValue();
}
floorFile.startKey = entry.getKey();
bucketSeqStarts.put(floorFile.startKey, floorFile);
}
Map<Slice, byte[]> fileUpdates = modifiedFiles.get(floorFile);
if (fileUpdates == null) {
modifiedFiles.put(floorFile, fileUpdates = Maps.newHashMap());
}
fileUpdates.put(entry.getKey(), entry.getValue());
}
// copy meta data on write
BucketMeta bucketMetaCopy = kryo.copy(getMeta(bucket.bucketKey));
HashSet<String> filesToDelete = Sets.newHashSet();
// write modified files
for (Map.Entry<BucketFileMeta, Map<Slice, byte[]>> fileEntry : modifiedFiles.entrySet()) {
BucketFileMeta fileMeta = fileEntry.getKey();
TreeMap<Slice, byte[]> fileData = Maps.newTreeMap(getKeyComparator());
if (fileMeta.name != null) {
// load existing file
HDSFileReader reader = store.getReader(bucket.bucketKey, fileMeta.name);
reader.readFully(fileData);
reader.close();
filesToDelete.add(fileMeta.name);
}
// apply updates
fileData.putAll(fileEntry.getValue());
// new file
writeFile(bucket, bucketMetaCopy, fileData);
}
// flush meta data for new files
try {
OutputStream os = store.getOutputStream(bucket.bucketKey, FNAME_META + ".new");
Output output = new Output(os);
bucketMetaCopy.committedWid = windowId;
kryo.writeClassAndObject(output, bucketMetaCopy);
output.close();
os.close();
store.rename(bucket.bucketKey, FNAME_META + ".new", FNAME_META);
} catch (IOException e) {
throw new RuntimeException("Failed to write bucket meta data " + bucket.bucketKey, e);
}
// clear pending changes
bucket.frozenWriteCache.clear();
// switch to new version
this.metaCache.put(bucket.bucketKey, bucketMetaCopy);
// delete old files
for (String fileName : filesToDelete) {
store.delete(bucket.bucketKey, fileName);
invalidateReader(bucket.bucketKey, fileName);
}
WalMeta walMeta = getWalMeta(bucket.bucketKey);
walMeta.tailId = bucket.tailId;
walMeta.tailOffset = bucket.tailOffset;
bucket.wal.cleanup(walMeta.tailId);
}
@Override
public void setup(OperatorContext context)
{
super.setup(context);
writeExecutor = Executors.newSingleThreadScheduledExecutor(new NameableThreadFactory(this.getClass().getSimpleName()+"-Writer"));
}
@Override
public void teardown()
{
for (Bucket bucket : this.buckets.values()) {
IOUtils.closeQuietly(bucket.wal);
}
writeExecutor.shutdown();
super.teardown();
}
@Override
public void beginWindow(long windowId)
{
super.beginWindow(windowId);
this.windowId = windowId;
}
@Override
public void endWindow()
{
super.endWindow();
for (final Bucket bucket : this.buckets.values()) {
try {
if (bucket.wal != null) {
bucket.wal.endWindow(windowId);
WalMeta walMeta = getWalMeta(bucket.bucketKey);
walMeta.fileId = bucket.wal.getWalFileId();
walMeta.offset = bucket.wal.getCommittedLength();
walMeta.windowId = windowId;
}
} catch (IOException e) {
throw new RuntimeException("Failed to flush WAL", e);
}
if ((bucket.writeCache.size() > this.flushSize || windowId - lastFlushWindowId > flushIntervalCount) && !bucket.writeCache.isEmpty()) {
// ensure previous flush completed
if (bucket.frozenWriteCache.isEmpty()) {
bucket.frozenWriteCache = bucket.writeCache;
bucket.committedLSN = windowId;
bucket.tailId = bucket.wal.getWalFileId();
bucket.tailOffset = bucket.wal.getCommittedLength();
bucket.writeCache = Maps.newHashMap();
LOG.debug("Flushing data for bucket {} committedWid {}", bucket.bucketKey, bucket.committedLSN);
Runnable flushRunnable = new Runnable() {
@Override
public void run()
{
try {
writeDataFiles(bucket);
} catch (Exception e) {
LOG.debug("Error writing files", e);
writerError = e;
}
}
};
this.writeExecutor.execute(flushRunnable);
lastFlushWindowId = windowId;
}
}
}
// propagate any exceptions from writers
if (writerError != null) {
throw new RuntimeException("Error while flushing write cache.", this.writerError);
}
}
private WalMeta getWalMeta(long bucketKey)
{
WalMeta meta = walMeta.get(bucketKey);
if (meta == null) {
meta = new WalMeta();
walMeta.put(bucketKey, meta);
}
return meta;
}
@Override
public void checkpointed(long arg0)
{
}
/**
* Get meta data from cache or load it on first access
* @param bucketKey
* @return
*/
private BucketMeta getMeta(long bucketKey)
{
BucketMeta bm = metaCache.get(bucketKey);
if (bm == null) {
bm = loadBucketMeta(bucketKey);
metaCache.put(bucketKey, bm);
}
return bm;
}
@Override
public void committed(long committedWindowId)
{
}
private static class Bucket
{
private long bucketKey;
// keys that were modified and written to WAL, but not yet persisted
private HashMap<Slice, byte[]> writeCache = Maps.newHashMap();
// keys that are being flushed to data files
private HashMap<Slice, byte[]> frozenWriteCache = Maps.newHashMap();
private HDSWalManager wal;
private long committedLSN;
private boolean recoveryInProgress;
private long tailId;
private long tailOffset;
}
@VisibleForTesting
protected void forceWal() throws IOException
{
for(Bucket bucket : buckets.values())
{
bucket.wal.close();
}
}
@VisibleForTesting
protected int unflushedData(long bucketKey) throws IOException
{
Bucket b = getBucket(bucketKey);
return b.writeCache.size();
}
private static final Logger LOG = LoggerFactory.getLogger(HDSBucketManager.class);
/* Holds current file Id for WAL and current offset for WAL */
private static class WalMeta
{
/* The current WAL file and offset */
// Window Id which is written to the WAL.
public long windowId;
// Current Wal File sequence id
long fileId;
// Offset in current file after writing data for windowId.
long offset;
/* Flushed WAL file and offset, data till this point is flushed to disk */
public long tailId;
public long tailOffset;
}
}
| contrib/src/main/java/com/datatorrent/contrib/hds/HDSBucketManager.java | /*
* Copyright (c) 2014 DataTorrent, Inc. ALL Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datatorrent.contrib.hds;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.validation.constraints.Min;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.api.CheckpointListener;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.Operator;
import com.datatorrent.common.util.NameableThreadFactory;
import com.datatorrent.common.util.Slice;
import com.datatorrent.contrib.hds.HDSFileAccess.HDSFileReader;
import com.datatorrent.contrib.hds.HDSFileAccess.HDSFileWriter;
import com.esotericsoftware.kryo.io.Output;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Manager for buckets. Can be sub-classed as operator or used in composite pattern.
*/
public class HDSBucketManager extends HDSReader implements HDS.BucketManager, CheckpointListener, Operator
{
private final transient HashMap<Long, BucketMeta> metaCache = Maps.newHashMap();
private long windowId;
private transient long lastFlushWindowId;
private final transient HashMap<Long, Bucket> buckets = Maps.newHashMap();
@VisibleForTesting
protected transient ExecutorService writeExecutor;
private transient Exception writerError;
private int maxFileSize = 128 * 1024 * 1024; // 128m
private int maxWalFileSize = 64 * 1024 * 1024;
private int flushSize = 1000000;
private int flushIntervalCount = 30;
private final HashMap<Long, WalMeta> walMeta = Maps.newHashMap();
/**
* Size limit for data files. Files are rolled once the limit has been exceeded.
* The final size of a file can be larger than the limit by the size of the last/single entry written to it.
* @return
*/
public int getMaxFileSize()
{
return maxFileSize;
}
public void setMaxFileSize(int maxFileSize)
{
this.maxFileSize = maxFileSize;
}
/**
* Size limit for WAL files. Files are rolled once the limit has been exceeded.
* The final size of a file can be larger than the limit, as files are rolled at
* end of the operator window.
* @return
*/
public int getMaxWalFileSize()
{
return maxWalFileSize;
}
public void setMaxWalFileSize(int maxWalFileSize)
{
this.maxWalFileSize = maxWalFileSize;
}
/**
* The number of changes collected in memory before flushing to persistent storage.
* @return
*/
public int getFlushSize()
{
return flushSize;
}
public void setFlushSize(int flushSize)
{
this.flushSize = flushSize;
}
/**
* Cached writes are flushed to persistent storage periodically. The interval is specified as count of windows and
* establishes the maximum latency for changes to be written while below the {@link #flushSize} threshold.
*
* @return
*/
@Min(value=1)
public int getFlushIntervalCount()
{
return flushIntervalCount;
}
public void setFlushIntervalCount(int flushIntervalCount)
{
this.flushIntervalCount = flushIntervalCount;
}
public static byte[] asArray(Slice slice)
{
return Arrays.copyOfRange(slice.buffer, slice.offset, slice.offset + slice.length);
}
public static Slice toSlice(byte[] bytes)
{
return new Slice(bytes, 0, bytes.length);
}
/**
* Write data to size based rolling files
* @param bucket
* @param bucketMeta
* @param data
* @throws IOException
*/
private void writeFile(Bucket bucket, BucketMeta bucketMeta, TreeMap<Slice, byte[]> data) throws IOException
{
HDSFileWriter fw = null;
BucketFileMeta fileMeta = null;
for (Map.Entry<Slice, byte[]> dataEntry : data.entrySet()) {
if (fw == null) {
// next file
fileMeta = bucketMeta.addFile(bucket.bucketKey, dataEntry.getKey());
LOG.debug("writing new data file {} {}", bucket.bucketKey, fileMeta.name);
fw = this.store.getWriter(bucket.bucketKey, fileMeta.name + ".tmp");
}
fw.append(asArray(dataEntry.getKey()), dataEntry.getValue());
if ( fw.getBytesWritten() > this.maxFileSize) {
// roll file
fw.close();
this.store.rename(bucket.bucketKey, fileMeta.name + ".tmp", fileMeta.name);
LOG.debug("created new data file {} {}", bucket.bucketKey, fileMeta.name);
fw = null;
}
}
if (fw != null) {
fw.close();
this.store.rename(bucket.bucketKey, fileMeta.name + ".tmp", fileMeta.name);
LOG.debug("created new data file {} {}", bucket.bucketKey, fileMeta.name);
}
}
private Bucket getBucket(long bucketKey) throws IOException
{
Bucket bucket = this.buckets.get(bucketKey);
if (bucket == null) {
LOG.debug("Opening bucket {}", bucketKey);
bucket = new Bucket();
bucket.bucketKey = bucketKey;
this.buckets.put(bucketKey, bucket);
BucketMeta bmeta = getMeta(bucketKey);
WalMeta wmeta = getWalMeta(bucketKey);
bucket.wal = new HDSWalManager(this.store, bucketKey, wmeta.fileId, wmeta.offset);
bucket.wal.setMaxWalFileSize(maxWalFileSize);
// bmeta.componentLSN is data which is committed to disks.
// wmeta.windowId windowId till which data is available in WAL.
if (bmeta.committedWid < wmeta.windowId)
{
LOG.debug("Recovery for bucket {}", bucketKey);
bucket.recoveryInProgress = true;
// Get last committed LSN from store, and use that for recovery.
bucket.wal.runRecovery(this, wmeta.tailId, wmeta.tailOffset);
bucket.recoveryInProgress = false;
}
}
return bucket;
}
private transient Slice keyWrapper = new Slice(null, 0, 0);
/**
* Intercept query processing to incorporate unwritten changes.
*/
@Override
protected void processQuery(HDSQuery query)
{
byte[] key = query.key;
keyWrapper.buffer = key;
keyWrapper.length = key.length;
Bucket bucket = this.buckets.get(query.bucketKey);
if (bucket != null) {
// check unwritten changes first
byte[] v = bucket.writeCache.get(keyWrapper);
if (v != null) {
query.result = v;
query.processed = true;
return;
}
// check changes currently being flushed
v = bucket.frozenWriteCache.get(keyWrapper);
if (v != null) {
query.result = v;
query.processed = true;
return;
}
}
super.processQuery(query);
}
@Override
public byte[] get(long bucketKey, byte[] key) throws IOException
{
return super.get(bucketKey, key);
}
@Override
public void put(long bucketKey, byte[] key, byte[] value) throws IOException
{
Bucket bucket = getBucket(bucketKey);
/* Do not update WAL, if tuple being added is coming through recovery */
if (!bucket.recoveryInProgress) {
bucket.wal.append(key, value);
}
bucket.writeCache.put(new Slice(key, 0, key.length), value);
}
/**
* Flush changes from write cache to disk.
* New data files will be written and meta data replaced atomically.
* The flush frequency determines availability of changes to external readers.
* @throws IOException
*/
private void writeDataFiles(Bucket bucket) throws IOException
{
// bucket keys by file
BucketMeta bm = getMeta(bucket.bucketKey);
TreeMap<Slice, BucketFileMeta> bucketSeqStarts = bm.files;
Map<BucketFileMeta, Map<Slice, byte[]>> modifiedFiles = Maps.newHashMap();
for (Map.Entry<Slice, byte[]> entry : bucket.frozenWriteCache.entrySet()) {
// find file for key
Map.Entry<Slice, BucketFileMeta> floorEntry = bucketSeqStarts.floorEntry(entry.getKey());
BucketFileMeta floorFile;
if (floorEntry != null) {
floorFile = floorEntry.getValue();
} else {
floorEntry = bucketSeqStarts.firstEntry();
if (floorEntry == null || floorEntry.getValue().name != null) {
// no existing file or file with higher key
floorFile = new BucketFileMeta();
} else {
// placeholder for new keys, move start key
floorFile = floorEntry.getValue();
}
floorFile.startKey = entry.getKey();
bucketSeqStarts.put(floorFile.startKey, floorFile);
}
Map<Slice, byte[]> fileUpdates = modifiedFiles.get(floorFile);
if (fileUpdates == null) {
modifiedFiles.put(floorFile, fileUpdates = Maps.newHashMap());
}
fileUpdates.put(entry.getKey(), entry.getValue());
}
// copy meta data on write
BucketMeta bucketMetaCopy = kryo.copy(getMeta(bucket.bucketKey));
HashSet<String> filesToDelete = Sets.newHashSet();
// write modified files
for (Map.Entry<BucketFileMeta, Map<Slice, byte[]>> fileEntry : modifiedFiles.entrySet()) {
BucketFileMeta fileMeta = fileEntry.getKey();
TreeMap<Slice, byte[]> fileData = Maps.newTreeMap(getKeyComparator());
if (fileMeta.name != null) {
// load existing file
HDSFileReader reader = store.getReader(bucket.bucketKey, fileMeta.name);
reader.readFully(fileData);
reader.close();
filesToDelete.add(fileMeta.name);
}
// apply updates
fileData.putAll(fileEntry.getValue());
// new file
writeFile(bucket, bucketMetaCopy, fileData);
}
// flush meta data for new files
try {
OutputStream os = store.getOutputStream(bucket.bucketKey, FNAME_META + ".new");
Output output = new Output(os);
bucketMetaCopy.committedWid = windowId;
kryo.writeClassAndObject(output, bucketMetaCopy);
output.close();
os.close();
store.rename(bucket.bucketKey, FNAME_META + ".new", FNAME_META);
} catch (IOException e) {
throw new RuntimeException("Failed to write bucket meta data " + bucket.bucketKey, e);
}
// clear pending changes
bucket.frozenWriteCache.clear();
// switch to new version
this.metaCache.put(bucket.bucketKey, bucketMetaCopy);
// delete old files
for (String fileName : filesToDelete) {
store.delete(bucket.bucketKey, fileName);
invalidateReader(bucket.bucketKey, fileName);
}
WalMeta walMeta = getWalMeta(bucket.bucketKey);
walMeta.tailId = bucket.tailId;
walMeta.tailOffset = bucket.tailOffset;
bucket.wal.cleanup(walMeta.tailId);
}
@Override
public void setup(OperatorContext context)
{
super.setup(context);
writeExecutor = Executors.newSingleThreadScheduledExecutor(new NameableThreadFactory(this.getClass().getSimpleName()+"-Writer"));
}
@Override
public void teardown()
{
for (Bucket bucket : this.buckets.values()) {
IOUtils.closeQuietly(bucket.wal);
}
writeExecutor.shutdown();
super.teardown();
}
@Override
public void beginWindow(long windowId)
{
super.beginWindow(windowId);
this.windowId = windowId;
}
@Override
public void endWindow()
{
super.endWindow();
for (final Bucket bucket : this.buckets.values()) {
try {
if (bucket.wal != null) {
bucket.wal.endWindow(windowId);
WalMeta walMeta = getWalMeta(bucket.bucketKey);
walMeta.fileId = bucket.wal.getWalFileId();
walMeta.offset = bucket.wal.getCommittedLength();
walMeta.windowId = windowId;
}
} catch (IOException e) {
throw new RuntimeException("Failed to flush WAL", e);
}
if ((bucket.writeCache.size() > this.flushSize || windowId - lastFlushWindowId > flushIntervalCount) && !bucket.writeCache.isEmpty()) {
// ensure previous flush completed
if (bucket.frozenWriteCache.isEmpty()) {
bucket.frozenWriteCache = bucket.writeCache;
bucket.committedLSN = windowId;
bucket.tailId = bucket.wal.getWalFileId();
bucket.tailOffset = bucket.wal.getCommittedLength();
bucket.writeCache = Maps.newHashMap();
LOG.debug("Flushing data for bucket {} committedWid {}", bucket.bucketKey, bucket.committedLSN);
Runnable flushRunnable = new Runnable() {
@Override
public void run()
{
try {
writeDataFiles(bucket);
} catch (IOException e) {
writerError = e;
}
}
};
this.writeExecutor.execute(flushRunnable);
if (writerError != null) {
throw new RuntimeException("Error while flushing write cache.", this.writerError);
}
lastFlushWindowId = windowId;
}
}
}
}
private WalMeta getWalMeta(long bucketKey)
{
WalMeta meta = walMeta.get(bucketKey);
if (meta == null) {
meta = new WalMeta();
walMeta.put(bucketKey, meta);
}
return meta;
}
@Override
public void checkpointed(long arg0)
{
}
/**
* Get meta data from cache or load it on first access
* @param bucketKey
* @return
*/
private BucketMeta getMeta(long bucketKey)
{
BucketMeta bm = metaCache.get(bucketKey);
if (bm == null) {
bm = loadBucketMeta(bucketKey);
metaCache.put(bucketKey, bm);
}
return bm;
}
@Override
public void committed(long committedWindowId)
{
}
private static class Bucket
{
private long bucketKey;
// keys that were modified and written to WAL, but not yet persisted
private HashMap<Slice, byte[]> writeCache = Maps.newHashMap();
// keys that are being flushed to data files
private HashMap<Slice, byte[]> frozenWriteCache = Maps.newHashMap();
private HDSWalManager wal;
private long committedLSN;
private boolean recoveryInProgress;
private long tailId;
private long tailOffset;
}
@VisibleForTesting
protected void forceWal() throws IOException
{
for(Bucket bucket : buckets.values())
{
bucket.wal.close();
}
}
@VisibleForTesting
protected int unflushedData(long bucketKey) throws IOException
{
Bucket b = getBucket(bucketKey);
return b.writeCache.size();
}
private static final Logger LOG = LoggerFactory.getLogger(HDSBucketManager.class);
/* Holds current file Id for WAL and current offset for WAL */
private static class WalMeta
{
/* The current WAL file and offset */
// Window Id which is written to the WAL.
public long windowId;
// Current Wal File sequence id
long fileId;
// Offset in current file after writing data for windowId.
long offset;
/* Flushed WAL file and offset, data till this point is flushed to disk */
public long tailId;
public long tailOffset;
}
}
| Ensure writer errors are propagated.
| contrib/src/main/java/com/datatorrent/contrib/hds/HDSBucketManager.java | Ensure writer errors are propagated. |
|
Java | apache-2.0 | 56a5a319b26946e05427e022c7eb61991ade644f | 0 | MichaelNedzelsky/intellij-community,slisson/intellij-community,holmes/intellij-community,FHannes/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,supersven/intellij-community,caot/intellij-community,diorcety/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,caot/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,signed/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,robovm/robovm-studio,signed/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,holmes/intellij-community,vladmm/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,kool79/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,dslomov/intellij-community,kool79/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,samthor/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,izonder/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,dslomov/intellij-community,da1z/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ibinti/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,semonte/intellij-community,izonder/intellij-community,jagguli/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,xfournet/intellij-community,da1z/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,kool79/intellij-community,slisson/intellij-community,kdwink/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,ryano144/intellij-community,vladmm/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,clumsy/intellij-community,fitermay/intellij-community,izonder/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,apixandru/intellij-community,samthor/intellij-community,retomerz/intellij-community,robovm/robovm-studio,adedayo/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,holmes/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,Lekanich/intellij-community,supersven/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,supersven/intellij-community,petteyg/intellij-community,retomerz/intellij-community,jagguli/intellij-community,xfournet/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,allotria/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,caot/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,allotria/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,ibinti/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,samthor/intellij-community,jagguli/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,adedayo/intellij-community,kool79/intellij-community,youdonghai/intellij-community,slisson/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,diorcety/intellij-community,dslomov/intellij-community,petteyg/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,kdwink/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,caot/intellij-community,wreckJ/intellij-community,supersven/intellij-community,slisson/intellij-community,slisson/intellij-community,signed/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,amith01994/intellij-community,slisson/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,clumsy/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,fitermay/intellij-community,apixandru/intellij-community,semonte/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,retomerz/intellij-community,ibinti/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,izonder/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,caot/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,kool79/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,signed/intellij-community,semonte/intellij-community,youdonghai/intellij-community,holmes/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ibinti/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,caot/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,ahb0327/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,hurricup/intellij-community,semonte/intellij-community,xfournet/intellij-community,slisson/intellij-community,samthor/intellij-community,hurricup/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,apixandru/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,asedunov/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,izonder/intellij-community,hurricup/intellij-community,semonte/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,caot/intellij-community,diorcety/intellij-community,robovm/robovm-studio,adedayo/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,kool79/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,allotria/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ibinti/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,holmes/intellij-community,tmpgit/intellij-community,caot/intellij-community,diorcety/intellij-community,izonder/intellij-community,kool79/intellij-community,kdwink/intellij-community,vladmm/intellij-community,allotria/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,amith01994/intellij-community,slisson/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,diorcety/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,kdwink/intellij-community,vladmm/intellij-community,blademainer/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,samthor/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,dslomov/intellij-community,clumsy/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ibinti/intellij-community,izonder/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,apixandru/intellij-community,signed/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,dslomov/intellij-community,clumsy/intellij-community,fnouama/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,petteyg/intellij-community,dslomov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,da1z/intellij-community,retomerz/intellij-community,asedunov/intellij-community,holmes/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,allotria/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,supersven/intellij-community,clumsy/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,semonte/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,akosyakov/intellij-community,da1z/intellij-community,semonte/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,signed/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,vladmm/intellij-community,allotria/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,allotria/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,da1z/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,semonte/intellij-community,izonder/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,signed/intellij-community,FHannes/intellij-community,ryano144/intellij-community,jagguli/intellij-community,holmes/intellij-community,robovm/robovm-studio,vladmm/intellij-community,ryano144/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,jagguli/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,signed/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.impl.jar;
import com.intellij.openapi.diagnostic.LogUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.BufferExposingByteArrayInputStream;
import com.intellij.openapi.util.io.FileAttributes;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFile;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.reference.SoftReference;
import com.intellij.util.ArrayUtil;
import com.intellij.util.TimedReference;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class JarHandlerBase {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.jar.JarHandlerBase");
private static final long DEFAULT_LENGTH = 0L;
private static final long DEFAULT_TIMESTAMP = -1L;
private final TimedReference<JarFile> myJarFile = new TimedReference<JarFile>(null);
private Reference<Map<String, EntryInfo>> myRelPathsToEntries = new SoftReference<Map<String, EntryInfo>>(null);
private final Object lock = new Object();
protected final String myBasePath;
protected static class EntryInfo {
protected final boolean isDirectory;
protected final String shortName;
protected final EntryInfo parent;
public EntryInfo(@NotNull String shortName, final EntryInfo parent, final boolean directory) {
this.shortName = shortName;
this.parent = parent;
isDirectory = directory;
}
}
public JarHandlerBase(@NotNull String path) {
myBasePath = path;
}
protected void clear() {
synchronized (lock) {
myRelPathsToEntries = null;
myJarFile.set(null);
}
}
public File getMirrorFile(@NotNull File originalFile) {
return originalFile;
}
@Nullable
public JarFile getJar() {
JarFile jar = myJarFile.get();
if (jar == null) {
synchronized (lock) {
jar = myJarFile.get();
if (jar == null) {
jar = createJarFile();
if (jar != null) {
myJarFile.set(jar);
}
}
}
}
return jar;
}
@Nullable
protected JarFile createJarFile() {
final File originalFile = getOriginalFile();
try {
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final ZipFile zipFile = new ZipFile(getMirrorFile(originalFile));
class MyJarEntry implements JarFile.JarEntry {
private final ZipEntry myEntry;
MyJarEntry(ZipEntry entry) {
myEntry = entry;
}
public ZipEntry getEntry() {
return myEntry;
}
@Override
public String getName() {
return myEntry.getName();
}
@Override
public long getSize() {
return myEntry.getSize();
}
@Override
public long getTime() {
return myEntry.getTime();
}
@Override
public boolean isDirectory() {
return myEntry.isDirectory();
}
}
return new JarFile() {
@Override
public JarFile.JarEntry getEntry(String name) {
try {
ZipEntry entry = zipFile.getEntry(name);
if (entry != null) {
return new MyJarEntry(entry);
}
}
catch (IllegalArgumentException e) {
LOG.warn(e);
}
return null;
}
@Override
public InputStream getInputStream(JarFile.JarEntry entry) throws IOException {
return zipFile.getInputStream(((MyJarEntry)entry).myEntry);
}
@Override
public Enumeration<? extends JarFile.JarEntry> entries() {
return new Enumeration<JarEntry>() {
private final Enumeration<? extends ZipEntry> entries = zipFile.entries();
@Override
public boolean hasMoreElements() {
return entries.hasMoreElements();
}
@Override
public JarEntry nextElement() {
try {
ZipEntry entry = entries.nextElement();
if (entry != null) {
return new MyJarEntry(entry);
}
}
catch (IllegalArgumentException e) {
LOG.warn(e);
}
return null;
}
};
}
@Override
public ZipFile getZipFile() {
return zipFile;
}
};
}
catch (IOException e) {
LOG.warn(e.getMessage() + ": " + originalFile.getPath(), e);
return null;
}
}
@NotNull
protected File getOriginalFile() {
return new File(myBasePath);
}
@NotNull
private static EntryInfo getOrCreate(@NotNull String entryName, boolean isDirectory, @NotNull Map<String, EntryInfo> map) {
EntryInfo info = map.get(entryName);
if (info == null) {
int idx = entryName.lastIndexOf('/');
final String parentEntryName = idx > 0 ? entryName.substring(0, idx) : "";
String shortName = idx > 0 ? entryName.substring(idx + 1) : entryName;
if (".".equals(shortName)) return getOrCreate(parentEntryName, true, map);
info = new EntryInfo(shortName, getOrCreate(parentEntryName, true, map), isDirectory);
map.put(entryName, info);
}
return info;
}
@NotNull
public String[] list(@NotNull final VirtualFile file) {
synchronized (lock) {
EntryInfo parentEntry = getEntryInfo(file);
Set<String> names = new HashSet<String>();
for (EntryInfo info : getEntriesMap().values()) {
if (info.parent == parentEntry) {
names.add(info.shortName);
}
}
return ArrayUtil.toStringArray(names);
}
}
protected EntryInfo getEntryInfo(@NotNull VirtualFile file) {
synchronized (lock) {
String parentPath = getRelativePath(file);
return getEntryInfo(parentPath);
}
}
public EntryInfo getEntryInfo(@NotNull String parentPath) {
return getEntriesMap().get(parentPath);
}
@NotNull
protected Map<String, EntryInfo> getEntriesMap() {
synchronized (lock) {
Map<String, EntryInfo> map = myRelPathsToEntries != null ? myRelPathsToEntries.get() : null;
if (map == null) {
final JarFile zip = getJar();
LogUtil.debug(LOG, "mapping %s", myBasePath);
map = new THashMap<String, EntryInfo>();
if (zip != null) {
map.put("", new EntryInfo("", null, true));
final Enumeration<? extends JarFile.JarEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
JarFile.JarEntry entry = entries.nextElement();
final String name = entry.getName();
final boolean isDirectory = StringUtil.endsWithChar(name, '/');
getOrCreate(isDirectory ? name.substring(0, name.length() - 1) : name, isDirectory, map);
}
myRelPathsToEntries = new SoftReference<Map<String, EntryInfo>>(map);
}
}
return map;
}
}
@NotNull
private String getRelativePath(@NotNull VirtualFile file) {
final String path = file.getPath().substring(myBasePath.length() + 1);
return StringUtil.startsWithChar(path, '/') ? path.substring(1) : path;
}
@Nullable
private JarFile.JarEntry convertToEntry(@NotNull VirtualFile file) {
String path = getRelativePath(file);
final JarFile jar = getJar();
return jar == null ? null : jar.getEntry(path);
}
public long getLength(@NotNull final VirtualFile file) {
final JarFile.JarEntry entry = convertToEntry(file);
synchronized (lock) {
return entry == null ? DEFAULT_LENGTH : entry.getSize();
}
}
@NotNull
public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException {
return new BufferExposingByteArrayInputStream(contentsToByteArray(file));
}
@NotNull
public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException {
final JarFile.JarEntry entry = convertToEntry(file);
if (entry == null) {
return ArrayUtil.EMPTY_BYTE_ARRAY;
}
synchronized (lock) {
final JarFile jar = getJar();
assert jar != null : file;
final InputStream stream = jar.getInputStream(entry);
assert stream != null : file;
try {
return FileUtil.loadBytes(stream, (int)entry.getSize());
}
finally {
stream.close();
}
}
}
public long getTimeStamp(@NotNull final VirtualFile file) {
if (file.getParent() == null) return getOriginalFile().lastModified(); // Optimization
final JarFile.JarEntry entry = convertToEntry(file);
synchronized (lock) {
return entry == null ? DEFAULT_TIMESTAMP : entry.getTime();
}
}
public boolean isDirectory(@NotNull final VirtualFile file) {
if (file.getParent() == null) return true; // Optimization
synchronized (lock) {
final String path = getRelativePath(file);
final EntryInfo info = getEntryInfo(path);
return info == null || info.isDirectory;
}
}
public boolean exists(@NotNull final VirtualFile fileOrDirectory) {
if (fileOrDirectory.getParent() == null) {
// Optimization. Do not build entries if asked for jar root existence.
return myJarFile.get() != null || getOriginalFile().exists();
}
return getEntryInfo(fileOrDirectory) != null;
}
@Nullable
public FileAttributes getAttributes(@NotNull final VirtualFile file) {
final JarFile.JarEntry entry = convertToEntry(file);
synchronized (lock) {
final EntryInfo entryInfo = getEntryInfo(getRelativePath(file));
if (entryInfo == null) return null;
final long length = entry != null ? entry.getSize() : DEFAULT_LENGTH;
final long timeStamp = entry != null ? entry.getTime() : DEFAULT_TIMESTAMP;
return new FileAttributes(entryInfo.isDirectory, false, false, false, length, timeStamp, false);
}
}
}
| platform/core-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandlerBase.java | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.impl.jar;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.BufferExposingByteArrayInputStream;
import com.intellij.openapi.util.io.FileAttributes;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFile;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.reference.SoftReference;
import com.intellij.util.ArrayUtil;
import com.intellij.util.TimedReference;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class JarHandlerBase {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.jar.JarHandlerBase");
private static final long DEFAULT_LENGTH = 0L;
private static final long DEFAULT_TIMESTAMP = -1L;
private final TimedReference<JarFile> myJarFile = new TimedReference<JarFile>(null);
private Reference<Map<String, EntryInfo>> myRelPathsToEntries = new SoftReference<Map<String, EntryInfo>>(null);
private final Object lock = new Object();
protected final String myBasePath;
protected static class EntryInfo {
protected final boolean isDirectory;
protected final String shortName;
protected final EntryInfo parent;
public EntryInfo(@NotNull String shortName, final EntryInfo parent, final boolean directory) {
this.shortName = shortName;
this.parent = parent;
isDirectory = directory;
}
}
public JarHandlerBase(@NotNull String path) {
myBasePath = path;
}
protected void clear() {
synchronized (lock) {
myRelPathsToEntries = null;
myJarFile.set(null);
}
}
public File getMirrorFile(@NotNull File originalFile) {
return originalFile;
}
@Nullable
public JarFile getJar() {
JarFile jar = myJarFile.get();
if (jar == null) {
synchronized (lock) {
jar = myJarFile.get();
if (jar == null) {
jar = createJarFile();
if (jar != null) {
myJarFile.set(jar);
}
}
}
}
return jar;
}
@Nullable
protected JarFile createJarFile() {
final File originalFile = getOriginalFile();
try {
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final ZipFile zipFile = new ZipFile(getMirrorFile(originalFile));
class MyJarEntry implements JarFile.JarEntry {
private final ZipEntry myEntry;
MyJarEntry(ZipEntry entry) {
myEntry = entry;
}
public ZipEntry getEntry() {
return myEntry;
}
@Override
public String getName() {
return myEntry.getName();
}
@Override
public long getSize() {
return myEntry.getSize();
}
@Override
public long getTime() {
return myEntry.getTime();
}
@Override
public boolean isDirectory() {
return myEntry.isDirectory();
}
}
return new JarFile() {
@Override
public JarFile.JarEntry getEntry(String name) {
try {
ZipEntry entry = zipFile.getEntry(name);
if (entry != null) {
return new MyJarEntry(entry);
}
}
catch (IllegalArgumentException e) {
LOG.warn(e);
}
return null;
}
@Override
public InputStream getInputStream(JarFile.JarEntry entry) throws IOException {
return zipFile.getInputStream(((MyJarEntry)entry).myEntry);
}
@Override
public Enumeration<? extends JarFile.JarEntry> entries() {
return new Enumeration<JarEntry>() {
private final Enumeration<? extends ZipEntry> entries = zipFile.entries();
@Override
public boolean hasMoreElements() {
return entries.hasMoreElements();
}
@Override
public JarEntry nextElement() {
try {
ZipEntry entry = entries.nextElement();
if (entry != null) {
return new MyJarEntry(entry);
}
}
catch (IllegalArgumentException e) {
LOG.warn(e);
}
return null;
}
};
}
@Override
public ZipFile getZipFile() {
return zipFile;
}
};
}
catch (IOException e) {
LOG.warn(e.getMessage() + ": " + originalFile.getPath(), e);
return null;
}
}
@NotNull
protected File getOriginalFile() {
return new File(myBasePath);
}
@NotNull
private static EntryInfo getOrCreate(@NotNull String entryName, boolean isDirectory, @NotNull Map<String, EntryInfo> map) {
EntryInfo info = map.get(entryName);
if (info == null) {
int idx = entryName.lastIndexOf('/');
final String parentEntryName = idx > 0 ? entryName.substring(0, idx) : "";
String shortName = idx > 0 ? entryName.substring(idx + 1) : entryName;
if (".".equals(shortName)) return getOrCreate(parentEntryName, true, map);
info = new EntryInfo(shortName, getOrCreate(parentEntryName, true, map), isDirectory);
map.put(entryName, info);
}
return info;
}
@NotNull
public String[] list(@NotNull final VirtualFile file) {
synchronized (lock) {
EntryInfo parentEntry = getEntryInfo(file);
Set<String> names = new HashSet<String>();
for (EntryInfo info : getEntriesMap().values()) {
if (info.parent == parentEntry) {
names.add(info.shortName);
}
}
return ArrayUtil.toStringArray(names);
}
}
protected EntryInfo getEntryInfo(@NotNull VirtualFile file) {
synchronized (lock) {
String parentPath = getRelativePath(file);
return getEntryInfo(parentPath);
}
}
public EntryInfo getEntryInfo(@NotNull String parentPath) {
return getEntriesMap().get(parentPath);
}
@NotNull
protected Map<String, EntryInfo> getEntriesMap() {
synchronized (lock) {
Map<String, EntryInfo> map = myRelPathsToEntries != null ? myRelPathsToEntries.get() : null;
if (map == null) {
final JarFile zip = getJar();
LOG.info("mapping " + myBasePath);
map = new THashMap<String, EntryInfo>();
if (zip != null) {
map.put("", new EntryInfo("", null, true));
final Enumeration<? extends JarFile.JarEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
JarFile.JarEntry entry = entries.nextElement();
final String name = entry.getName();
final boolean isDirectory = StringUtil.endsWithChar(name, '/');
getOrCreate(isDirectory ? name.substring(0, name.length() - 1) : name, isDirectory, map);
}
myRelPathsToEntries = new SoftReference<Map<String, EntryInfo>>(map);
}
}
return map;
}
}
@NotNull
private String getRelativePath(@NotNull VirtualFile file) {
final String path = file.getPath().substring(myBasePath.length() + 1);
return StringUtil.startsWithChar(path, '/') ? path.substring(1) : path;
}
@Nullable
private JarFile.JarEntry convertToEntry(@NotNull VirtualFile file) {
String path = getRelativePath(file);
final JarFile jar = getJar();
return jar == null ? null : jar.getEntry(path);
}
public long getLength(@NotNull final VirtualFile file) {
final JarFile.JarEntry entry = convertToEntry(file);
synchronized (lock) {
return entry == null ? DEFAULT_LENGTH : entry.getSize();
}
}
@NotNull
public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException {
return new BufferExposingByteArrayInputStream(contentsToByteArray(file));
}
@NotNull
public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException {
final JarFile.JarEntry entry = convertToEntry(file);
if (entry == null) {
return ArrayUtil.EMPTY_BYTE_ARRAY;
}
synchronized (lock) {
final JarFile jar = getJar();
assert jar != null : file;
final InputStream stream = jar.getInputStream(entry);
assert stream != null : file;
try {
return FileUtil.loadBytes(stream, (int)entry.getSize());
}
finally {
stream.close();
}
}
}
public long getTimeStamp(@NotNull final VirtualFile file) {
if (file.getParent() == null) return getOriginalFile().lastModified(); // Optimization
final JarFile.JarEntry entry = convertToEntry(file);
synchronized (lock) {
return entry == null ? DEFAULT_TIMESTAMP : entry.getTime();
}
}
public boolean isDirectory(@NotNull final VirtualFile file) {
if (file.getParent() == null) return true; // Optimization
synchronized (lock) {
final String path = getRelativePath(file);
final EntryInfo info = getEntryInfo(path);
return info == null || info.isDirectory;
}
}
public boolean exists(@NotNull final VirtualFile fileOrDirectory) {
if (fileOrDirectory.getParent() == null) {
// Optimization. Do not build entries if asked for jar root existence.
return myJarFile.get() != null || getOriginalFile().exists();
}
return getEntryInfo(fileOrDirectory) != null;
}
@Nullable
public FileAttributes getAttributes(@NotNull final VirtualFile file) {
final JarFile.JarEntry entry = convertToEntry(file);
synchronized (lock) {
final EntryInfo entryInfo = getEntryInfo(getRelativePath(file));
if (entryInfo == null) return null;
final long length = entry != null ? entry.getSize() : DEFAULT_LENGTH;
final long timeStamp = entry != null ? entry.getTime() : DEFAULT_TIMESTAMP;
return new FileAttributes(entryInfo.isDirectory, false, false, false, length, timeStamp, false);
}
}
}
| IDEA-114283 (diagnostic)
| platform/core-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandlerBase.java | IDEA-114283 (diagnostic) |
|
Java | apache-2.0 | 3523e3e29e05b5200f678b15eb197b79f3e8d960 | 0 | semonte/intellij-community,signed/intellij-community,apixandru/intellij-community,xfournet/intellij-community,xfournet/intellij-community,semonte/intellij-community,ibinti/intellij-community,semonte/intellij-community,asedunov/intellij-community,semonte/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,signed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,allotria/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,da1z/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,signed/intellij-community,ibinti/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,FHannes/intellij-community,asedunov/intellij-community,da1z/intellij-community,ibinti/intellij-community,apixandru/intellij-community,xfournet/intellij-community,allotria/intellij-community,semonte/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,xfournet/intellij-community,signed/intellij-community,semonte/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,da1z/intellij-community,suncycheng/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,apixandru/intellij-community,xfournet/intellij-community,semonte/intellij-community,asedunov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,semonte/intellij-community,xfournet/intellij-community,semonte/intellij-community,FHannes/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,semonte/intellij-community,allotria/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,xfournet/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,asedunov/intellij-community,semonte/intellij-community,da1z/intellij-community,signed/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,signed/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,allotria/intellij-community,da1z/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,FHannes/intellij-community,ibinti/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,signed/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,allotria/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,signed/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,signed/intellij-community,asedunov/intellij-community | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.uiDesigner;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.DispatchThreadProgressWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.uiDesigner.compiler.AsmCodeGenerator;
import com.intellij.uiDesigner.make.FormSourceCodeGenerator;
import com.intellij.uiDesigner.radComponents.LayoutManagerRegistry;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class GuiDesignerConfigurable implements SearchableConfigurable, Configurable.NoScroll {
private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.GuiDesignerConfigurable");
private final Project myProject;
private MyGeneralUI myGeneralUI;
/**
* Invoked by reflection
*/
public GuiDesignerConfigurable(final Project project) {
myProject = project;
}
public String getDisplayName() {
return UIDesignerBundle.message("title.gui.designer");
}
@NotNull
public String getHelpTopic() {
return "project.propGUI";
}
public JComponent createComponent() {
if (myGeneralUI == null) {
myGeneralUI = new MyGeneralUI();
}
return myGeneralUI.myPanel;
}
public boolean isModified() {
final GuiDesignerConfiguration configuration = GuiDesignerConfiguration.getInstance(myProject);
if (myGeneralUI == null) {
return false;
}
if (myGeneralUI.myChkCopyFormsRuntime.isSelected() != configuration.COPY_FORMS_RUNTIME_TO_OUTPUT) {
return true;
}
if (!Comparing.equal(configuration.DEFAULT_LAYOUT_MANAGER, myGeneralUI.myLayoutManagerCombo.getSelectedItem())) {
return true;
}
if (!Comparing.equal(configuration.DEFAULT_FIELD_ACCESSIBILITY, myGeneralUI.myDefaultFieldAccessibilityCombo.getSelectedItem())) {
return true;
}
if (configuration.INSTRUMENT_CLASSES != myGeneralUI.myRbInstrumentClasses.isSelected()) {
return true;
}
if (configuration.RESIZE_HEADERS != myGeneralUI.myResizeHeaders.isSelected()) {
return true;
}
return false;
}
public void apply() {
final GuiDesignerConfiguration configuration = GuiDesignerConfiguration.getInstance(myProject);
configuration.COPY_FORMS_RUNTIME_TO_OUTPUT = myGeneralUI.myChkCopyFormsRuntime.isSelected();
configuration.DEFAULT_LAYOUT_MANAGER = (String)myGeneralUI.myLayoutManagerCombo.getSelectedItem();
configuration.INSTRUMENT_CLASSES = myGeneralUI.myRbInstrumentClasses.isSelected();
configuration.DEFAULT_FIELD_ACCESSIBILITY = (String)myGeneralUI .myDefaultFieldAccessibilityCombo.getSelectedItem();
configuration.RESIZE_HEADERS = myGeneralUI.myResizeHeaders.isSelected();
if (configuration.INSTRUMENT_CLASSES && !myProject.isDefault()) {
final DispatchThreadProgressWindow progressWindow = new DispatchThreadProgressWindow(false, myProject);
progressWindow.setRunnable(new MyApplyRunnable(progressWindow));
progressWindow.setTitle(UIDesignerBundle.message("title.converting.project"));
progressWindow.start();
}
}
public void reset() {
final GuiDesignerConfiguration configuration = GuiDesignerConfiguration.getInstance(myProject);
/*general*/
if (configuration.INSTRUMENT_CLASSES) {
myGeneralUI.myRbInstrumentClasses.setSelected(true);
}
else {
myGeneralUI.myRbInstrumentSources.setSelected(true);
}
myGeneralUI.myChkCopyFormsRuntime.setSelected(configuration.COPY_FORMS_RUNTIME_TO_OUTPUT);
myGeneralUI.myLayoutManagerCombo.setModel(new DefaultComboBoxModel(LayoutManagerRegistry.getNonDeprecatedLayoutManagerNames()));
myGeneralUI.myLayoutManagerCombo.setRenderer(new ListCellRendererWrapper<String>() {
@Override
public void customize(JList list, String value, int index, boolean selected, boolean hasFocus) {
setText(LayoutManagerRegistry.getLayoutManagerDisplayName(value));
}
});
myGeneralUI.myLayoutManagerCombo.setSelectedItem(configuration.DEFAULT_LAYOUT_MANAGER);
myGeneralUI.myDefaultFieldAccessibilityCombo.setSelectedItem(configuration.DEFAULT_FIELD_ACCESSIBILITY);
myGeneralUI.myResizeHeaders.setSelected(configuration.RESIZE_HEADERS);
}
public void disposeUIResources() {
myGeneralUI = null;
} /*UI for "General" tab*/
private static final class MyGeneralUI {
public JPanel myPanel;
public JRadioButton myRbInstrumentClasses;
public JRadioButton myRbInstrumentSources;
public JCheckBox myChkCopyFormsRuntime;
private JComboBox myLayoutManagerCombo;
private JComboBox myDefaultFieldAccessibilityCombo;
private JCheckBox myResizeHeaders;
}
private final class MyApplyRunnable implements Runnable {
private final DispatchThreadProgressWindow myProgressWindow;
public MyApplyRunnable(final DispatchThreadProgressWindow progressWindow) {
myProgressWindow = progressWindow;
}
/**
* Removes all generated sources
*/
private void vanishGeneratedSources() {
final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(myProject);
final PsiMethod[] methods = cache.getMethodsByName(AsmCodeGenerator.SETUP_METHOD_NAME, GlobalSearchScope.projectScope(myProject));
CodeInsightUtil.preparePsiElementsForWrite(methods);
for (int i = 0; i < methods.length; i++) {
final PsiMethod method = methods[i];
final PsiClass aClass = method.getContainingClass();
if (aClass != null) {
try {
final PsiFile psiFile = aClass.getContainingFile();
LOG.assertTrue(psiFile != null);
final VirtualFile vFile = psiFile.getVirtualFile();
LOG.assertTrue(vFile != null);
myProgressWindow.setText(UIDesignerBundle.message("progress.converting", vFile.getPresentableUrl()));
myProgressWindow.setFraction(((double)i) / ((double)methods.length));
if (vFile.isWritable()) {
WriteAction.run(() -> FormSourceCodeGenerator.cleanup(aClass));
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
}
/**
* Launches vanish/generate sources processes
*/
private void applyImpl() {
CommandProcessor.getInstance().executeCommand(myProject, () -> {
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
vanishGeneratedSources();
}, "", null);
}
public void run() {
ProgressManager.getInstance().runProcess(() -> applyImpl(), myProgressWindow);
}
}
@NotNull
public String getId() {
return getHelpTopic();
}
}
| plugins/ui-designer/src/com/intellij/uiDesigner/GuiDesignerConfigurable.java | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.uiDesigner;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.DispatchThreadProgressWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.uiDesigner.compiler.AsmCodeGenerator;
import com.intellij.uiDesigner.make.FormSourceCodeGenerator;
import com.intellij.uiDesigner.radComponents.LayoutManagerRegistry;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class GuiDesignerConfigurable implements SearchableConfigurable, Configurable.NoScroll {
private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.GuiDesignerConfigurable");
private final Project myProject;
private MyGeneralUI myGeneralUI;
/**
* Invoked by reflection
*/
public GuiDesignerConfigurable(final Project project) {
myProject = project;
}
public String getDisplayName() {
return UIDesignerBundle.message("title.gui.designer");
}
@NotNull
public String getHelpTopic() {
return "project.propGUI";
}
public JComponent createComponent() {
if (myGeneralUI == null) {
myGeneralUI = new MyGeneralUI();
}
return myGeneralUI.myPanel;
}
public boolean isModified() {
final GuiDesignerConfiguration configuration = GuiDesignerConfiguration.getInstance(myProject);
if (myGeneralUI == null) {
return false;
}
if (myGeneralUI.myChkCopyFormsRuntime.isSelected() != configuration.COPY_FORMS_RUNTIME_TO_OUTPUT) {
return true;
}
if (!Comparing.equal(configuration.DEFAULT_LAYOUT_MANAGER, myGeneralUI.myLayoutManagerCombo.getSelectedItem())) {
return true;
}
if (!Comparing.equal(configuration.DEFAULT_FIELD_ACCESSIBILITY, myGeneralUI.myDefaultFieldAccessibilityCombo.getSelectedItem())) {
return true;
}
if (configuration.INSTRUMENT_CLASSES != myGeneralUI.myRbInstrumentClasses.isSelected()) {
return true;
}
if (configuration.RESIZE_HEADERS != myGeneralUI.myResizeHeaders.isSelected()) {
return true;
}
return false;
}
public void apply() {
final GuiDesignerConfiguration configuration = GuiDesignerConfiguration.getInstance(myProject);
configuration.COPY_FORMS_RUNTIME_TO_OUTPUT = myGeneralUI.myChkCopyFormsRuntime.isSelected();
configuration.DEFAULT_LAYOUT_MANAGER = (String)myGeneralUI.myLayoutManagerCombo.getSelectedItem();
configuration.INSTRUMENT_CLASSES = myGeneralUI.myRbInstrumentClasses.isSelected();
configuration.DEFAULT_FIELD_ACCESSIBILITY = (String)myGeneralUI .myDefaultFieldAccessibilityCombo.getSelectedItem();
configuration.RESIZE_HEADERS = myGeneralUI.myResizeHeaders.isSelected();
if (configuration.INSTRUMENT_CLASSES && !myProject.isDefault()) {
final DispatchThreadProgressWindow progressWindow = new DispatchThreadProgressWindow(false, myProject);
progressWindow.setRunnable(new MyApplyRunnable(progressWindow));
progressWindow.setTitle(UIDesignerBundle.message("title.converting.project"));
progressWindow.start();
}
}
public void reset() {
final GuiDesignerConfiguration configuration = GuiDesignerConfiguration.getInstance(myProject);
/*general*/
if (configuration.INSTRUMENT_CLASSES) {
myGeneralUI.myRbInstrumentClasses.setSelected(true);
}
else {
myGeneralUI.myRbInstrumentSources.setSelected(true);
}
myGeneralUI.myChkCopyFormsRuntime.setSelected(configuration.COPY_FORMS_RUNTIME_TO_OUTPUT);
myGeneralUI.myLayoutManagerCombo.setModel(new DefaultComboBoxModel(LayoutManagerRegistry.getNonDeprecatedLayoutManagerNames()));
myGeneralUI.myLayoutManagerCombo.setRenderer(new ListCellRendererWrapper<String>() {
@Override
public void customize(JList list, String value, int index, boolean selected, boolean hasFocus) {
setText(LayoutManagerRegistry.getLayoutManagerDisplayName(value));
}
});
myGeneralUI.myLayoutManagerCombo.setSelectedItem(configuration.DEFAULT_LAYOUT_MANAGER);
myGeneralUI.myDefaultFieldAccessibilityCombo.setSelectedItem(configuration.DEFAULT_FIELD_ACCESSIBILITY);
myGeneralUI.myResizeHeaders.setSelected(configuration.RESIZE_HEADERS);
}
public void disposeUIResources() {
myGeneralUI = null;
} /*UI for "General" tab*/
private static final class MyGeneralUI {
public JPanel myPanel;
public JRadioButton myRbInstrumentClasses;
public JRadioButton myRbInstrumentSources;
public JCheckBox myChkCopyFormsRuntime;
private JComboBox myLayoutManagerCombo;
private JComboBox myDefaultFieldAccessibilityCombo;
private JCheckBox myResizeHeaders;
}
private final class MyApplyRunnable implements Runnable {
private final DispatchThreadProgressWindow myProgressWindow;
public MyApplyRunnable(final DispatchThreadProgressWindow progressWindow) {
myProgressWindow = progressWindow;
}
/**
* Removes all generated sources
*/
private void vanishGeneratedSources() {
final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(myProject);
final PsiMethod[] methods = cache.getMethodsByName(AsmCodeGenerator.SETUP_METHOD_NAME, GlobalSearchScope.projectScope(myProject));
CodeInsightUtil.preparePsiElementsForWrite(methods);
for (int i = 0; i < methods.length; i++) {
final PsiMethod method = methods[i];
final PsiClass aClass = method.getContainingClass();
if (aClass != null) {
try {
final PsiFile psiFile = aClass.getContainingFile();
LOG.assertTrue(psiFile != null);
final VirtualFile vFile = psiFile.getVirtualFile();
LOG.assertTrue(vFile != null);
myProgressWindow.setText(UIDesignerBundle.message("progress.converting", vFile.getPresentableUrl()));
myProgressWindow.setFraction(((double)i) / ((double)methods.length));
if (vFile.isWritable()) {
FormSourceCodeGenerator.cleanup(aClass);
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
}
/**
* Launches vanish/generate sources processes
*/
private void applyImpl() {
CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> {
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
vanishGeneratedSources();
}), "", null);
}
public void run() {
ProgressManager.getInstance().runProcess(() -> applyImpl(), myProgressWindow);
}
}
@NotNull
public String getId() {
return getHelpTopic();
}
}
| GuiDesignerConfigurable.MyApplyRunnable.vanishGeneratedSources: no swing events under write action (EA-97650 - assert: NoSwingUnderWriteAction.lambda$watchForEvents$)
| plugins/ui-designer/src/com/intellij/uiDesigner/GuiDesignerConfigurable.java | GuiDesignerConfigurable.MyApplyRunnable.vanishGeneratedSources: no swing events under write action (EA-97650 - assert: NoSwingUnderWriteAction.lambda$watchForEvents$) |
|
Java | apache-2.0 | c8abab83b6352214534fbd56e2694f505867ecd3 | 0 | vvv1559/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,da1z/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,hurricup/intellij-community,semonte/intellij-community,ibinti/intellij-community,allotria/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,retomerz/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,apixandru/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,FHannes/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,allotria/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,allotria/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,youdonghai/intellij-community,semonte/intellij-community,fitermay/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,signed/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,signed/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,allotria/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,xfournet/intellij-community,FHannes/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,asedunov/intellij-community,apixandru/intellij-community,retomerz/intellij-community,allotria/intellij-community,hurricup/intellij-community,FHannes/intellij-community,allotria/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,asedunov/intellij-community,signed/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,FHannes/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,FHannes/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,allotria/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,allotria/intellij-community,asedunov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ibinti/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,semonte/intellij-community,hurricup/intellij-community,da1z/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,semonte/intellij-community,semonte/intellij-community,hurricup/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,xfournet/intellij-community,signed/intellij-community,suncycheng/intellij-community,da1z/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,signed/intellij-community,apixandru/intellij-community,semonte/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,signed/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,allotria/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,FHannes/intellij-community,xfournet/intellij-community,da1z/intellij-community,signed/intellij-community,fitermay/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,da1z/intellij-community,da1z/intellij-community,fitermay/intellij-community,retomerz/intellij-community,semonte/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community | package org.zmlx.hg4idea.command;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.zmlx.hg4idea.HgVcsMessages;
import org.zmlx.hg4idea.action.HgCommandResultNotifier;
import org.zmlx.hg4idea.execution.HgCommandExecutor;
import org.zmlx.hg4idea.execution.HgCommandResult;
import org.zmlx.hg4idea.repo.HgRepository;
import org.zmlx.hg4idea.util.HgErrorUtil;
import java.util.ArrayList;
import java.util.List;
import static com.intellij.util.containers.ContainerUtil.emptyList;
import static java.util.Collections.singletonList;
import static org.zmlx.hg4idea.util.HgUtil.getRepositoryManager;
public class HgBookmarkCommand {
public static void createBookmarkAsynchronously(@NotNull List<HgRepository> repositories, @NotNull String name, boolean isActive) {
final Project project = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(repositories)).getProject();
if (StringUtil.isEmptyOrSpaces(name)) {
VcsNotifier.getInstance(project).notifyError("Hg Error", "Bookmark name is empty");
return;
}
new Task.Backgroundable(project, HgVcsMessages.message("hg4idea.progress.bookmark", name)) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
for (HgRepository repository : repositories) {
executeBookmarkCommandSynchronously(project, repository.getRoot(), name, isActive ? emptyList() : singletonList("--inactive"));
}
}
}.queue();
}
public static void deleteBookmarkSynchronously(@NotNull Project project, @NotNull VirtualFile repo, @NotNull String name) {
executeBookmarkCommandSynchronously(project, repo, name, singletonList("-d"));
}
private static void executeBookmarkCommandSynchronously(@NotNull Project project,
@NotNull VirtualFile repositoryRoot,
@NotNull String name,
@NotNull List<String> args) {
ArrayList<String> arguments = ContainerUtil.newArrayList(args);
arguments.add(name);
HgCommandResult result = new HgCommandExecutor(project).executeInCurrentThread(repositoryRoot, "bookmark", arguments);
getRepositoryManager(project).updateRepository(repositoryRoot);
if (HgErrorUtil.hasErrorsInCommandExecution(result)) {
new HgCommandResultNotifier(project)
.notifyError(result, "Hg Error",
String.format("Hg bookmark command failed for repository %s with name %s ", repositoryRoot.getName(), name));
}
}
}
| plugins/hg4idea/src/org/zmlx/hg4idea/command/HgBookmarkCommand.java | package org.zmlx.hg4idea.command;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.zmlx.hg4idea.HgVcsMessages;
import org.zmlx.hg4idea.action.HgCommandResultNotifier;
import org.zmlx.hg4idea.execution.HgCommandExecutor;
import org.zmlx.hg4idea.execution.HgCommandResult;
import org.zmlx.hg4idea.repo.HgRepository;
import org.zmlx.hg4idea.util.HgErrorUtil;
import java.util.ArrayList;
import java.util.List;
import static com.intellij.util.containers.ContainerUtil.emptyList;
import static java.util.Collections.singletonList;
import static org.zmlx.hg4idea.util.HgUtil.getRepositoryManager;
public class HgBookmarkCommand {
public static void createBookmarkAsynchronously(@NotNull List<HgRepository> repositories, @NotNull String name, boolean isActive) {
final Project project = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(repositories)).getProject();
if (StringUtil.isEmptyOrSpaces(name)) {
VcsNotifier.getInstance(project).notifyError("Hg Error", "Bookmark name is empty");
}
new Task.Backgroundable(project, HgVcsMessages.message("hg4idea.progress.bookmark", name)) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
for (HgRepository repository : repositories) {
executeBookmarkCommandSynchronously(project, repository.getRoot(), name, isActive ? emptyList() : singletonList("--inactive"));
}
}
}.queue();
}
public static void deleteBookmarkSynchronously(@NotNull Project project, @NotNull VirtualFile repo, @NotNull String name) {
executeBookmarkCommandSynchronously(project, repo, name, singletonList("-d"));
}
private static void executeBookmarkCommandSynchronously(@NotNull Project project,
@NotNull VirtualFile repositoryRoot,
@NotNull String name,
@NotNull List<String> args) {
ArrayList<String> arguments = ContainerUtil.newArrayList(args);
arguments.add(name);
HgCommandResult result = new HgCommandExecutor(project).executeInCurrentThread(repositoryRoot, "bookmark", arguments);
if (project.isDisposed()) return;
getRepositoryManager(project).updateRepository(repositoryRoot);
if (HgErrorUtil.hasErrorsInCommandExecution(result)) {
new HgCommandResultNotifier(project)
.notifyError(result, "Hg Error",
String.format("Hg bookmark command failed for repository %s with name %s ", repositoryRoot.getName(), name));
}
}
}
| [hg]: create bookmark cleanUp
| plugins/hg4idea/src/org/zmlx/hg4idea/command/HgBookmarkCommand.java | [hg]: create bookmark cleanUp |
|
Java | apache-2.0 | 739c709334bccbd1e2bcd6c379044ef46819f470 | 0 | ivan-fedorov/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,caot/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,adedayo/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,supersven/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,izonder/intellij-community,blademainer/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,diorcety/intellij-community,hurricup/intellij-community,jagguli/intellij-community,caot/intellij-community,clumsy/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,robovm/robovm-studio,blademainer/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,vladmm/intellij-community,robovm/robovm-studio,adedayo/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,holmes/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,signed/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,apixandru/intellij-community,slisson/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,slisson/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,jagguli/intellij-community,hurricup/intellij-community,diorcety/intellij-community,vladmm/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,petteyg/intellij-community,diorcety/intellij-community,caot/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,asedunov/intellij-community,holmes/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,ibinti/intellij-community,amith01994/intellij-community,xfournet/intellij-community,izonder/intellij-community,semonte/intellij-community,izonder/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,fitermay/intellij-community,hurricup/intellij-community,xfournet/intellij-community,samthor/intellij-community,holmes/intellij-community,petteyg/intellij-community,semonte/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,signed/intellij-community,allotria/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,supersven/intellij-community,kool79/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,allotria/intellij-community,suncycheng/intellij-community,semonte/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,caot/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,signed/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,kdwink/intellij-community,fnouama/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,kool79/intellij-community,izonder/intellij-community,adedayo/intellij-community,FHannes/intellij-community,robovm/robovm-studio,kool79/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,signed/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,da1z/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ryano144/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,amith01994/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,signed/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,caot/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,semonte/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,supersven/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,semonte/intellij-community,fitermay/intellij-community,fitermay/intellij-community,robovm/robovm-studio,dslomov/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,da1z/intellij-community,slisson/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,apixandru/intellij-community,supersven/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,caot/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,samthor/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,da1z/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,caot/intellij-community,xfournet/intellij-community,jagguli/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,slisson/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,semonte/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,caot/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,izonder/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,signed/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,Distrotech/intellij-community,slisson/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,asedunov/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,caot/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,diorcety/intellij-community,fitermay/intellij-community,samthor/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,izonder/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,supersven/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,supersven/intellij-community,retomerz/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,da1z/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,FHannes/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,samthor/intellij-community,adedayo/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,supersven/intellij-community,akosyakov/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,dslomov/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,ryano144/intellij-community,blademainer/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,adedayo/intellij-community,asedunov/intellij-community,hurricup/intellij-community,signed/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,signed/intellij-community,amith01994/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,allotria/intellij-community,fnouama/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,signed/intellij-community,clumsy/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,semonte/intellij-community,dslomov/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,dslomov/intellij-community,fitermay/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,fitermay/intellij-community,petteyg/intellij-community,samthor/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,slisson/intellij-community,retomerz/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,youdonghai/intellij-community,semonte/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,apixandru/intellij-community,clumsy/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,kdwink/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,kdwink/intellij-community,apixandru/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,allotria/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,da1z/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,diorcety/intellij-community,vladmm/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,holmes/intellij-community,holmes/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,caot/intellij-community,adedayo/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,kool79/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,fnouama/intellij-community,samthor/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,retomerz/intellij-community,xfournet/intellij-community,ibinti/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,izonder/intellij-community,blademainer/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,slisson/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,blademainer/intellij-community,slisson/intellij-community | package com.intellij.execution.configurations;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* Splits input String to tokens being aware of quoted tokens ("foo bar") and escaped spaces (foo\ bar),
* usually used for splitting command line to separate arguments that may contain space symbols.
* Escaped symbols are not handled so there's no way to get token that itself contains quotation mark.
*/
public class CommandLineTokenizer extends StringTokenizer {
private static String DEFAULT_DELIMITERS = " \t\n\r\f";
// keep source level 1.4
private List myTokens = new ArrayList();
private int myCurrentToken = 0;
private boolean myHandleEscapedWhitespaces = false;
public CommandLineTokenizer(String str) {
this(str, false);
}
public CommandLineTokenizer(String str, boolean handleEscapedWhitespaces) {
super(str, DEFAULT_DELIMITERS, true);
myHandleEscapedWhitespaces = handleEscapedWhitespaces;
parseTokens();
}
public CommandLineTokenizer(String str, String delim) {
super(str, delim, true);
parseTokens();
}
public boolean hasMoreTokens() {
return myCurrentToken < myTokens.size();
}
public String nextToken() {
return (String) myTokens.get(myCurrentToken++);
}
public String peekNextToken() {
return (String) myTokens.get(myCurrentToken);
}
public int countTokens() {
return myTokens.size() - myCurrentToken;
}
public String nextToken(String delim) {
throw new UnsupportedOperationException();
}
private void parseTokens() {
String token;
while ((token = nextTokenInternal()) != null) {
myTokens.add(token);
}
}
private String nextTokenInternal() {
String nextToken;
do {
if (super.hasMoreTokens()) {
nextToken = super.nextToken();
} else {
nextToken = null;
}
} while (nextToken != null && nextToken.length() == 1 && DEFAULT_DELIMITERS.indexOf(nextToken.charAt(0)) >= 0);
if (nextToken == null) {
return null;
}
int i;
int quotationMarks = 0;
final StringBuffer buffer = new StringBuffer();
do {
while ((i = nextToken.indexOf('"')) >= 0) {
quotationMarks++;
buffer.append(nextToken.substring(0, i));
nextToken = nextToken.substring(i + 1);
}
boolean isEscapedWhitespace = false;
if (myHandleEscapedWhitespaces && quotationMarks == 0 && nextToken.endsWith("\\") && super.hasMoreTokens()) {
isEscapedWhitespace = true;
buffer.append(nextToken.substring(0, nextToken.length() - 1));
buffer.append(super.nextToken());
}
else {
buffer.append(nextToken);
}
if ((isEscapedWhitespace || quotationMarks % 2 == 1) && super.hasMoreTokens()) {
nextToken = super.nextToken();
} else {
nextToken = null;
}
} while (nextToken != null);
return buffer.toString();
}
}
| platform/util/src/com/intellij/execution/configurations/CommandLineTokenizer.java | package com.intellij.execution.configurations;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* Splits input String to tokens being aware of quoted tokens,
* usually used for splitting command line to separate arguments that may contain space symbols.
* Escaped symbols are not handled so there's no way to get token that itself contains quotation mark.
*/
public class CommandLineTokenizer extends StringTokenizer {
private static String DEFAULT_DELIMITERS = " \t\n\r\f";
// keep source level 1.4
private List myTokens = new ArrayList();
private int myCurrentToken = 0;
public CommandLineTokenizer(String str) {
super(str, DEFAULT_DELIMITERS, true);
parseTokens();
}
public CommandLineTokenizer(String str, String delim) {
super(str, delim, true);
parseTokens();
}
public boolean hasMoreTokens() {
return myCurrentToken < myTokens.size();
}
public String nextToken() {
return (String) myTokens.get(myCurrentToken++);
}
public String peekNextToken() {
return (String) myTokens.get(myCurrentToken);
}
public int countTokens() {
return myTokens.size() - myCurrentToken;
}
public String nextToken(String delim) {
throw new UnsupportedOperationException();
}
private void parseTokens() {
String token;
while ((token = nextTokenInternal()) != null) {
myTokens.add(token);
}
}
private String nextTokenInternal() {
String nextToken;
do {
if (super.hasMoreTokens()) {
nextToken = super.nextToken();
} else {
nextToken = null;
}
} while (nextToken != null && nextToken.length() == 1 && DEFAULT_DELIMITERS.indexOf(nextToken.charAt(0)) >= 0);
if (nextToken == null) {
return null;
}
int i;
int quotationMarks = 0;
final StringBuffer buffer = new StringBuffer();
do {
while ((i = nextToken.indexOf('"')) >= 0) {
quotationMarks++;
buffer.append(nextToken.substring(0, i));
nextToken = nextToken.substring(i + 1);
}
buffer.append(nextToken);
if (quotationMarks % 2 == 1 && super.hasMoreTokens()) {
nextToken = super.nextToken();
} else {
nextToken = null;
}
} while (nextToken != null);
return buffer.toString();
}
}
| Platform: handle escaped whitespaces in command lines
| platform/util/src/com/intellij/execution/configurations/CommandLineTokenizer.java | Platform: handle escaped whitespaces in command lines |
|
Java | apache-2.0 | 008b5631e385d9a1b3e39531d57ed2009fc4f7dd | 0 | da1z/intellij-community,hurricup/intellij-community,hurricup/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,samthor/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,slisson/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,apixandru/intellij-community,amith01994/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,allotria/intellij-community,jagguli/intellij-community,adedayo/intellij-community,adedayo/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,kool79/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,allotria/intellij-community,caot/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,supersven/intellij-community,gnuhub/intellij-community,izonder/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,petteyg/intellij-community,slisson/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,signed/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,allotria/intellij-community,holmes/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,ibinti/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,signed/intellij-community,slisson/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,allotria/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,holmes/intellij-community,clumsy/intellij-community,hurricup/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,FHannes/intellij-community,izonder/intellij-community,izonder/intellij-community,kool79/intellij-community,samthor/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,signed/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,caot/intellij-community,petteyg/intellij-community,semonte/intellij-community,amith01994/intellij-community,petteyg/intellij-community,supersven/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,signed/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,signed/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,da1z/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,petteyg/intellij-community,petteyg/intellij-community,allotria/intellij-community,da1z/intellij-community,signed/intellij-community,semonte/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,fitermay/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,caot/intellij-community,apixandru/intellij-community,semonte/intellij-community,vladmm/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,semonte/intellij-community,fitermay/intellij-community,fnouama/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,caot/intellij-community,slisson/intellij-community,supersven/intellij-community,ryano144/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,FHannes/intellij-community,kool79/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,holmes/intellij-community,robovm/robovm-studio,kdwink/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,consulo/consulo,TangHao1987/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,da1z/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,slisson/intellij-community,holmes/intellij-community,dslomov/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,retomerz/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,signed/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,holmes/intellij-community,holmes/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,dslomov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,ryano144/intellij-community,samthor/intellij-community,fnouama/intellij-community,signed/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,izonder/intellij-community,hurricup/intellij-community,jagguli/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,dslomov/intellij-community,jagguli/intellij-community,semonte/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,consulo/consulo,salguarnieri/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,caot/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,consulo/consulo,jagguli/intellij-community,diorcety/intellij-community,kool79/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,ernestp/consulo,akosyakov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,allotria/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,dslomov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ernestp/consulo,ibinti/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,semonte/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,Lekanich/intellij-community,ernestp/consulo,SerCeMan/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,blademainer/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,dslomov/intellij-community,allotria/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,kdwink/intellij-community,robovm/robovm-studio,samthor/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,consulo/consulo,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,FHannes/intellij-community,petteyg/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,kool79/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,izonder/intellij-community,supersven/intellij-community,clumsy/intellij-community,ibinti/intellij-community,asedunov/intellij-community,fitermay/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,amith01994/intellij-community,fnouama/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,dslomov/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ibinti/intellij-community,petteyg/intellij-community,caot/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,slisson/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,clumsy/intellij-community,signed/intellij-community,samthor/intellij-community,signed/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,kdwink/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,kool79/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,samthor/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,da1z/intellij-community,blademainer/intellij-community,apixandru/intellij-community,jagguli/intellij-community,holmes/intellij-community,dslomov/intellij-community,ernestp/consulo,fitermay/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,semonte/intellij-community,nicolargo/intellij-community,caot/intellij-community,FHannes/intellij-community,kool79/intellij-community,vladmm/intellij-community,amith01994/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,asedunov/intellij-community,semonte/intellij-community,caot/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,slisson/intellij-community,ryano144/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,robovm/robovm-studio,amith01994/intellij-community,samthor/intellij-community,da1z/intellij-community,adedayo/intellij-community,diorcety/intellij-community,supersven/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,xfournet/intellij-community,samthor/intellij-community,Distrotech/intellij-community,signed/intellij-community,ibinti/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,allotria/intellij-community,fitermay/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,ernestp/consulo,ryano144/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,signed/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,ernestp/consulo,blademainer/intellij-community,consulo/consulo,ryano144/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,semonte/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.dialogs;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.DocumentAdapter;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.*;
import org.jetbrains.idea.svn.branchConfig.InfoReliability;
import org.jetbrains.idea.svn.branchConfig.InfoStorage;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigManager;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationNew;
import org.jetbrains.idea.svn.integrate.SvnBranchItem;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public class BranchConfigurationDialog extends DialogWrapper {
private JPanel myTopPanel;
private TextFieldWithBrowseButton myTrunkLocationTextField;
private JList myLocationList;
private JButton myAddButton;
private JButton myRemoveButton;
private final SvnBranchConfigManager mySvnBranchConfigManager;
private final VirtualFile myRoot;
public BranchConfigurationDialog(final Project project, final SvnBranchConfigurationNew configuration, final String rootUrl,
final VirtualFile root) {
super(project, true);
myRoot = root;
init();
setTitle(SvnBundle.message("configure.branches.title"));
final String trunkUrl = configuration.getTrunkUrl();
if (trunkUrl == null || trunkUrl.trim().length() == 0) {
configuration.setTrunkUrl(rootUrl);
}
mySvnBranchConfigManager = SvnBranchConfigurationManager.getInstance(project).getSvnBranchConfigManager();
myTrunkLocationTextField.setText(configuration.getTrunkUrl());
myTrunkLocationTextField.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
final String selectedUrl = SelectLocationDialog.selectLocation(project, myTrunkLocationTextField.getText());
if (selectedUrl != null) {
myTrunkLocationTextField.setText(selectedUrl);
}
}
});
final TrunkUrlValidator trunkUrlValidator = new TrunkUrlValidator(rootUrl, configuration);
myTrunkLocationTextField.getTextField().getDocument().addDocumentListener(trunkUrlValidator);
trunkUrlValidator.textChanged(null);
final MyListModel listModel = new MyListModel(configuration);
myLocationList.setModel(listModel);
myAddButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String selectedUrl = SelectLocationDialog.selectLocation(project, rootUrl);
if (selectedUrl != null) {
if (!configuration.getBranchUrls().contains(selectedUrl)) {
configuration.addBranches(selectedUrl, new InfoStorage<List<SvnBranchItem>>(new ArrayList<SvnBranchItem>(), InfoReliability.empty));
mySvnBranchConfigManager.reloadBranches(myRoot, selectedUrl, null);
listModel.fireItemAdded();
myLocationList.setSelectedIndex(listModel.getSize()-1);
}
}
}
});
myRemoveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selIndex = myLocationList.getSelectedIndex();
Object[] selection = myLocationList.getSelectedValues();
for(Object urlObj: selection) {
String url = (String) urlObj;
int index = configuration.getBranchUrls().indexOf(url);
configuration.removeBranch(url);
listModel.fireItemRemoved(index);
}
if (listModel.getSize() > 0) {
if (selIndex >= listModel.getSize())
selIndex = listModel.getSize()-1;
myLocationList.setSelectedIndex(selIndex);
}
}
});
}
private class TrunkUrlValidator extends DocumentAdapter {
private final String myRootUrl;
private final String myRootUrlPrefix;
private final SvnBranchConfigurationNew myConfiguration;
private TrunkUrlValidator(final String rootUrl, final SvnBranchConfigurationNew configuration) {
myRootUrl = rootUrl;
myRootUrlPrefix = rootUrl + "/";
myConfiguration = configuration;
}
protected void textChanged(final DocumentEvent e) {
final String currentValue = myTrunkLocationTextField.getText();
final boolean valueOk = (currentValue != null) && (currentValue.equals(myRootUrl) || currentValue.startsWith(myRootUrlPrefix));
final boolean prefixOk = (currentValue != null) && (currentValue.startsWith(myRootUrlPrefix)) &&
(currentValue.length() > myRootUrlPrefix.length());
myTrunkLocationTextField.getButton().setEnabled(valueOk);
setOKActionEnabled(prefixOk);
if (prefixOk) {
myConfiguration.setTrunkUrl(currentValue.endsWith("/") ? currentValue.substring(0, currentValue.length() - 1) : currentValue);
}
setErrorText(prefixOk ? null : SvnBundle.message("configure.branches.error.wrong.url"));
}
}
@Nullable
protected JComponent createCenterPanel() {
return myTopPanel;
}
@Override
@NonNls
protected String getDimensionServiceKey() {
return "Subversion.BranchConfigurationDialog";
}
public static void configureBranches(final Project project, final VirtualFile file) {
configureBranches(project, file, false);
}
public static void configureBranches(final Project project, final VirtualFile file, final boolean isRoot) {
final VirtualFile vcsRoot = (isRoot) ? file : ProjectLevelVcsManager.getInstance(project).getVcsRootFor(file);
if (vcsRoot == null) {
return;
}
final VirtualFile directory = SvnUtil.correctRoot(project, file);
if (directory == null) {
return;
}
final RootUrlInfo wcRoot = SvnVcs.getInstance(project).getSvnFileUrlMapping().getWcRootForFilePath(new File(directory.getPath()));
if (wcRoot == null) {
return;
}
final String rootUrl = wcRoot.getRepositoryUrl();
if (rootUrl == null) {
Messages.showErrorDialog(project, SvnBundle.message("configure.branches.error.no.connection.title"),
SvnBundle.message("configure.branches.title"));
return;
}
SvnBranchConfigurationNew configuration;
try {
configuration = SvnBranchConfigurationManager.getInstance(project).get(vcsRoot);
}
catch (VcsException ex) {
Messages.showErrorDialog(project, "Error loading branch configuration: " + ex.getMessage(),
SvnBundle.message("configure.branches.title"));
return;
}
final SvnBranchConfigurationNew clonedConfiguration = configuration.copy();
BranchConfigurationDialog dlg = new BranchConfigurationDialog(project, clonedConfiguration, rootUrl, vcsRoot);
dlg.show();
if (dlg.isOK()) {
SvnBranchConfigurationManager.getInstance(project).setConfiguration(vcsRoot, clonedConfiguration);
}
}
private static class MyListModel extends AbstractListModel {
private final SvnBranchConfigurationNew myConfiguration;
private List<String> myBranchUrls;
public MyListModel(final SvnBranchConfigurationNew configuration) {
myConfiguration = configuration;
myBranchUrls = myConfiguration.getBranchUrls();
}
public int getSize() {
return myBranchUrls.size();
}
public Object getElementAt(final int index) {
return myBranchUrls.get(index);
}
public void fireItemAdded() {
final int index = myConfiguration.getBranchUrls().size() - 1;
myBranchUrls = myConfiguration.getBranchUrls();
super.fireIntervalAdded(this, index, index);
}
public void fireItemRemoved(final int index) {
myBranchUrls = myConfiguration.getBranchUrls();
super.fireIntervalRemoved(this, index, index);
}
}
}
| plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/BranchConfigurationDialog.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.dialogs;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.DocumentAdapter;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.*;
import org.jetbrains.idea.svn.branchConfig.InfoReliability;
import org.jetbrains.idea.svn.branchConfig.InfoStorage;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigManager;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationNew;
import org.jetbrains.idea.svn.integrate.SvnBranchItem;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public class BranchConfigurationDialog extends DialogWrapper {
private JPanel myTopPanel;
private TextFieldWithBrowseButton myTrunkLocationTextField;
private JList myLocationList;
private JButton myAddButton;
private JButton myRemoveButton;
private final SvnBranchConfigManager mySvnBranchConfigManager;
private final VirtualFile myRoot;
public BranchConfigurationDialog(final Project project, final SvnBranchConfigurationNew configuration, final String rootUrl,
final VirtualFile root) {
super(project, true);
myRoot = root;
init();
setTitle(SvnBundle.message("configure.branches.title"));
final String trunkUrl = configuration.getTrunkUrl();
if (trunkUrl == null || trunkUrl.trim().length() == 0) {
configuration.setTrunkUrl(rootUrl);
}
mySvnBranchConfigManager = SvnBranchConfigurationManager.getInstance(project).getSvnBranchConfigManager();
myTrunkLocationTextField.setText(configuration.getTrunkUrl());
myTrunkLocationTextField.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
final String selectedUrl = SelectLocationDialog.selectLocation(project, myTrunkLocationTextField.getText());
if (selectedUrl != null) {
myTrunkLocationTextField.setText(selectedUrl);
}
}
});
final TrunkUrlValidator trunkUrlValidator = new TrunkUrlValidator(rootUrl, configuration);
myTrunkLocationTextField.getTextField().getDocument().addDocumentListener(trunkUrlValidator);
trunkUrlValidator.textChanged(null);
final MyListModel listModel = new MyListModel(configuration);
myLocationList.setModel(listModel);
myAddButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String selectedUrl = SelectLocationDialog.selectLocation(project, rootUrl);
if (selectedUrl != null) {
if (!configuration.getBranchUrls().contains(selectedUrl)) {
configuration.addBranches(selectedUrl, new InfoStorage<List<SvnBranchItem>>(new ArrayList<SvnBranchItem>(), InfoReliability.empty));
mySvnBranchConfigManager.reloadBranches(myRoot, selectedUrl, null);
listModel.fireItemAdded();
myLocationList.setSelectedIndex(listModel.getSize()-1);
}
}
}
});
myRemoveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selIndex = myLocationList.getSelectedIndex();
Object[] selection = myLocationList.getSelectedValues();
for(Object urlObj: selection) {
String url = (String) urlObj;
int index = configuration.getBranchUrls().indexOf(url);
configuration.removeBranch(url);
listModel.fireItemRemoved(index);
}
if (listModel.getSize() > 0) {
if (selIndex >= listModel.getSize())
selIndex = listModel.getSize()-1;
myLocationList.setSelectedIndex(selIndex);
}
}
});
}
private class TrunkUrlValidator extends DocumentAdapter {
private final String myRootUrl;
private final String myRootUrlPrefix;
private final SvnBranchConfigurationNew myConfiguration;
private TrunkUrlValidator(final String rootUrl, final SvnBranchConfigurationNew configuration) {
myRootUrl = rootUrl;
myRootUrlPrefix = rootUrl + "/";
myConfiguration = configuration;
}
protected void textChanged(final DocumentEvent e) {
final String currentValue = myTrunkLocationTextField.getText();
final boolean valueOk = (currentValue != null) && (currentValue.equals(myRootUrl) || currentValue.startsWith(myRootUrlPrefix));
final boolean prefixOk = (currentValue != null) && (currentValue.startsWith(myRootUrlPrefix)) &&
(currentValue.length() > myRootUrlPrefix.length());
myTrunkLocationTextField.getButton().setEnabled(valueOk);
setOKActionEnabled(prefixOk);
if (prefixOk) {
myConfiguration.setTrunkUrl(currentValue.endsWith("/") ? currentValue.substring(0, currentValue.length() - 1) : currentValue);
}
setErrorText(prefixOk ? null : SvnBundle.message("configure.branches.error.wrong.url"));
}
}
@Nullable
protected JComponent createCenterPanel() {
return myTopPanel;
}
@Override
@NonNls
protected String getDimensionServiceKey() {
return "Subversion.BranchConfigurationDialog";
}
public static void configureBranches(final Project project, final VirtualFile file) {
configureBranches(project, file, false);
}
public static void configureBranches(final Project project, final VirtualFile file, final boolean isRoot) {
final VirtualFile vcsRoot = (isRoot) ? file : ProjectLevelVcsManager.getInstance(project).getVcsRootFor(file);
if (vcsRoot == null) {
return;
}
final VirtualFile directory = SvnUtil.correctRoot(project, file);
if (directory == null) {
return;
}
final RootUrlInfo wcRoot = SvnVcs.getInstance(project).getSvnFileUrlMapping().getWcRootForFilePath(new File(directory.getPath()));
if (wcRoot == null) {
return;
}
final String rootUrl = wcRoot.getRepositoryUrl();
if (rootUrl == null) {
Messages.showErrorDialog(project, SvnBundle.message("configure.branches.error.no.connection.title"),
SvnBundle.message("configure.branches.title"));
return;
}
SvnBranchConfigurationNew configuration;
try {
configuration = SvnBranchConfigurationManager.getInstance(project).get(vcsRoot);
}
catch (VcsException ex) {
Messages.showErrorDialog(project, "Error loading branch configuration: " + ex.getMessage(),
SvnBundle.message("configure.branches.title"));
return;
}
final SvnBranchConfigurationNew clonedConfiguration = configuration.copy();
BranchConfigurationDialog dlg = new BranchConfigurationDialog(project, clonedConfiguration, rootUrl, vcsRoot);
dlg.show();
if (dlg.isOK()) {
SvnBranchConfigurationManager.getInstance(project).setConfiguration(vcsRoot, clonedConfiguration);
}
}
private static class MyListModel extends AbstractListModel {
private final SvnBranchConfigurationNew myConfiguration;
public MyListModel(final SvnBranchConfigurationNew configuration) {
myConfiguration = configuration;
}
public int getSize() {
return myConfiguration.getBranchUrls().size();
}
public Object getElementAt(final int index) {
return myConfiguration.getBranchUrls().get(index);
}
public void fireItemAdded() {
final int index = myConfiguration.getBranchUrls().size() - 1;
super.fireIntervalAdded(this, index, index);
}
public void fireItemRemoved(final int index) {
super.fireIntervalRemoved(this, index, index);
}
}
}
| SVN: branch configuration dialog: optimization: do not sort branches collection when returning branches number for getPrefferedSize() of JList
| plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/BranchConfigurationDialog.java | SVN: branch configuration dialog: optimization: do not sort branches collection when returning branches number for getPrefferedSize() of JList |
|
Java | apache-2.0 | 12d9d140ec94a6890155be9db47dedafa8c49277 | 0 | cuba-platform/cuba,dimone-kun/cuba,dimone-kun/cuba,cuba-platform/cuba,cuba-platform/cuba,dimone-kun/cuba | /*
* Copyright (c) 2012 Haulmont Technology Ltd. All Rights Reserved.
* Haulmont Technology proprietary and confidential.
* Use is subject to license terms.
*/
package com.haulmont.cuba.core.sys;
import com.haulmont.chile.core.model.Session;
import com.haulmont.chile.jpa.loader.JPAAnnotationsLoader;
import java.lang.reflect.Field;
/**
* @author krivopustov
* @version $Id$
*/
public class CubaAnnotationsLoader extends JPAAnnotationsLoader {
public CubaAnnotationsLoader(Session session) {
super(session);
}
@Override
protected boolean isMetaPropertyField(Field field) {
String name = field.getName();
return super.isMetaPropertyField(field)
&& !name.equals("pcVersionInit")
&& !name.equals("pcStateManager")
&& !name.equals("pcDetachedState")
&& !name.equals("__valueListeners");
}
}
| modules/global/src/com/haulmont/cuba/core/sys/CubaAnnotationsLoader.java | /*
* Copyright (c) 2012 Haulmont Technology Ltd. All Rights Reserved.
* Haulmont Technology proprietary and confidential.
* Use is subject to license terms.
*/
package com.haulmont.cuba.core.sys;
import com.haulmont.chile.core.model.Session;
import com.haulmont.chile.jpa.loader.JPAAnnotationsLoader;
import java.lang.reflect.Field;
/**
* @author krivopustov
* @version $Id$
*/
public class CubaAnnotationsLoader extends JPAAnnotationsLoader {
public CubaAnnotationsLoader(Session session) {
super(session);
}
@Override
protected boolean isMetaPropertyField(Field field) {
final String name = field.getName();
return super.isMetaPropertyField(field) &&
!name.startsWith("pc") && !name.startsWith("__") && super.isMetaPropertyField(field);
}
}
| Refs #1445 Ignore OpenJPA state fields by name, not by "pc" prefix
| modules/global/src/com/haulmont/cuba/core/sys/CubaAnnotationsLoader.java | Refs #1445 Ignore OpenJPA state fields by name, not by "pc" prefix |
|
Java | apache-2.0 | aef95acb5720a4bfe0d5b3c47bbb16b54c748bff | 0 | ryano144/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,diorcety/intellij-community,allotria/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,slisson/intellij-community,apixandru/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,slisson/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ryano144/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,supersven/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,caot/intellij-community,robovm/robovm-studio,slisson/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,caot/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,jagguli/intellij-community,slisson/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,amith01994/intellij-community,asedunov/intellij-community,petteyg/intellij-community,supersven/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,izonder/intellij-community,FHannes/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,da1z/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,fitermay/intellij-community,fitermay/intellij-community,diorcety/intellij-community,holmes/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,slisson/intellij-community,supersven/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,izonder/intellij-community,diorcety/intellij-community,petteyg/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,xfournet/intellij-community,semonte/intellij-community,kool79/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,allotria/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,signed/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,adedayo/intellij-community,ryano144/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,xfournet/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,allotria/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,izonder/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,xfournet/intellij-community,petteyg/intellij-community,slisson/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,xfournet/intellij-community,ibinti/intellij-community,slisson/intellij-community,apixandru/intellij-community,apixandru/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,semonte/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,robovm/robovm-studio,caot/intellij-community,semonte/intellij-community,ahb0327/intellij-community,caot/intellij-community,supersven/intellij-community,caot/intellij-community,signed/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,semonte/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,ryano144/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,Distrotech/intellij-community,kool79/intellij-community,clumsy/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,holmes/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,semonte/intellij-community,kdwink/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,ibinti/intellij-community,dslomov/intellij-community,petteyg/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,samthor/intellij-community,nicolargo/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,signed/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,supersven/intellij-community,youdonghai/intellij-community,signed/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,blademainer/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,diorcety/intellij-community,FHannes/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,semonte/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,semonte/intellij-community,clumsy/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,samthor/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,allotria/intellij-community,allotria/intellij-community,izonder/intellij-community,youdonghai/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,hurricup/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,hurricup/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,holmes/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,clumsy/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,signed/intellij-community,youdonghai/intellij-community,semonte/intellij-community,Lekanich/intellij-community,izonder/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,adedayo/intellij-community,jagguli/intellij-community,ibinti/intellij-community,retomerz/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,da1z/intellij-community,signed/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,apixandru/intellij-community,caot/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,dslomov/intellij-community,samthor/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,petteyg/intellij-community,da1z/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,holmes/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,signed/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,caot/intellij-community,vvv1559/intellij-community,izonder/intellij-community,amith01994/intellij-community,petteyg/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,asedunov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,caot/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,holmes/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,petteyg/intellij-community,diorcety/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,adedayo/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,adedayo/intellij-community,retomerz/intellij-community,blademainer/intellij-community,vladmm/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,dslomov/intellij-community,samthor/intellij-community,izonder/intellij-community,semonte/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,slisson/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,vladmm/intellij-community,ryano144/intellij-community,kool79/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,clumsy/intellij-community,caot/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,caot/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,izonder/intellij-community,kdwink/intellij-community,kool79/intellij-community,petteyg/intellij-community,kool79/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,signed/intellij-community,signed/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,robovm/robovm-studio,vladmm/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,ibinti/intellij-community,kool79/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,ibinti/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,petteyg/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,dslomov/intellij-community,fnouama/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,kool79/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.engine;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.actions.DebuggerActions;
import com.intellij.debugger.engine.evaluation.EvaluationContext;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.events.DebuggerCommandImpl;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerContextListener;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.debugger.impl.DebuggerStateManager;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.DebuggerContentInfo;
import com.intellij.debugger.ui.impl.ThreadsPanel;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.NodeDescriptorImpl;
import com.intellij.debugger.ui.impl.watch.NodeManagerImpl;
import com.intellij.debugger.ui.tree.NodeDescriptor;
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.execution.ui.RunnerLayoutUi;
import com.intellij.execution.ui.layout.PlaceInGrid;
import com.intellij.icons.AllIcons;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManagerAdapter;
import com.intellij.ui.content.ContentManagerEvent;
import com.intellij.xdebugger.*;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.intellij.xdebugger.frame.XSuspendContext;
import com.intellij.xdebugger.frame.XValueMarkerProvider;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.impl.actions.XDebuggerActions;
import com.intellij.xdebugger.ui.XDebugTabLayouter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author egor
*/
public class JavaDebugProcess extends XDebugProcess {
private static final JavaValueMarker MARKER = new JavaValueMarker();
private final DebuggerSession myJavaSession;
private final JavaDebuggerEditorsProvider myEditorsProvider;
private final XBreakpointHandler<?>[] myBreakpointHandlers;
private final MyDebuggerStateManager myStateManager = new MyDebuggerStateManager();
private final NodeManagerImpl myNodeManager;
public JavaDebugProcess(@NotNull XDebugSession session, DebuggerSession javaSession) {
super(session);
myJavaSession = javaSession;
myEditorsProvider = new JavaDebuggerEditorsProvider();
DebugProcessImpl process = javaSession.getProcess();
myBreakpointHandlers = new XBreakpointHandler[]{
new JavaBreakpointHandler.JavaLineBreakpointHandler(process),
new JavaBreakpointHandler.JavaExceptionBreakpointHandler(process),
new JavaBreakpointHandler.JavaFieldBreakpointHandler(process),
new JavaBreakpointHandler.JavaMethodBreakpointHandler(process),
new JavaBreakpointHandler.JavaWildcardBreakpointHandler(process),
};
process.addDebugProcessListener(new DebugProcessAdapter() {
@Override
public void paused(final SuspendContext suspendContext) {
//DebugProcessImpl process = (DebugProcessImpl)suspendContext.getDebugProcess();
//JdiSuspendContext context = new JdiSuspendContext(process, true);
//getSession().positionReached(new JavaSuspendContext(context, PositionManagerImpl.DEBUGGER_VIEW_SUPPORT, null));
((SuspendContextImpl)suspendContext).initExecutionStacks();
getSession().positionReached((XSuspendContext)suspendContext);
}
});
myJavaSession.getContextManager().addListener(new DebuggerContextListener() {
@Override
public void changeEvent(DebuggerContextImpl newContext, int event) {
myStateManager.fireStateChanged(newContext, event);
}
});
myNodeManager = new NodeManagerImpl(session.getProject(), null) {
@Override
public DebuggerTreeNodeImpl createNode(final NodeDescriptor descriptor, EvaluationContext evaluationContext) {
((NodeDescriptorImpl)descriptor).setContext((EvaluationContextImpl)evaluationContext);
final DebuggerTreeNodeImpl node = new DebuggerTreeNodeImpl(null, descriptor);
((NodeDescriptorImpl)descriptor).updateRepresentation((EvaluationContextImpl)evaluationContext, DescriptorLabelListener.DUMMY_LISTENER);
return node;
}
};
session.addSessionListener(new XDebugSessionAdapter() {
@Override
public void beforeSessionResume() {
myJavaSession.getProcess().getManagerThread().schedule(new DebuggerCommandImpl() {
@Override
protected void action() throws Exception {
myNodeManager.setHistoryByContext(myStateManager.getContext());
}
@Override
public Priority getPriority() {
return Priority.NORMAL;
}
});
}
});
}
@NotNull
@Override
public XDebuggerEditorsProvider getEditorsProvider() {
return myEditorsProvider;
}
@Override
public void startStepOver() {
myJavaSession.stepOver(false);
}
@Override
public void startStepInto() {
myJavaSession.stepInto(false, null);
}
@Override
public void startStepOut() {
myJavaSession.stepOut();
}
@Override
public void stop() {
}
@Override
public void startPausing() {
myJavaSession.pause();
}
@Override
public void resume() {
myJavaSession.resume();
}
@Override
public void runToPosition(@NotNull XSourcePosition position) {
Document document = FileDocumentManager.getInstance().getDocument(position.getFile());
myJavaSession.runToCursor(document, position.getLine(), false);
}
@NotNull
@Override
public XBreakpointHandler<?>[] getBreakpointHandlers() {
return myBreakpointHandlers;
}
@Override
public boolean checkCanInitBreakpoints() {
return false;
}
@Nullable
@Override
protected ProcessHandler doGetProcessHandler() {
return myJavaSession.getProcess().getExecutionResult().getProcessHandler();
}
@NotNull
@Override
public ExecutionConsole createConsole() {
return myJavaSession.getProcess().getExecutionResult().getExecutionConsole();
}
@NotNull
@Override
public XDebugTabLayouter createTabLayouter() {
return new XDebugTabLayouter() {
@Override
public void registerAdditionalContent(@NotNull RunnerLayoutUi ui) {
final ThreadsPanel panel = new ThreadsPanel(myJavaSession.getProject(), myStateManager);
final Content threadsContent = ui.createContent(
DebuggerContentInfo.THREADS_CONTENT, panel, XDebuggerBundle.message("debugger.session.tab.threads.title"),
AllIcons.Debugger.Threads, null);
threadsContent.setCloseable(false);
ui.addContent(threadsContent, 0, PlaceInGrid.left, true);
ui.addListener(new ContentManagerAdapter() {
@Override
public void selectionChanged(ContentManagerEvent event) {
if (event.getContent() == threadsContent) {
if (threadsContent.isSelected()) {
panel.setUpdateEnabled(true);
if (panel.isRefreshNeeded()) {
panel.rebuildIfVisible(DebuggerSession.EVENT_CONTEXT);
}
}
else {
panel.setUpdateEnabled(false);
}
}
}
}, threadsContent);
}
};
}
private class MyDebuggerStateManager extends DebuggerStateManager {
@Override
public void fireStateChanged(DebuggerContextImpl newContext, int event) {
super.fireStateChanged(newContext, event);
}
@Override
public DebuggerContextImpl getContext() {
return myJavaSession.getContextManager().getContext();
}
@Override
public void setState(DebuggerContextImpl context, int state, int event, String description) {
myJavaSession.getContextManager().setState(context, state, event, description);
}
}
@Override
public void registerAdditionalActions(@NotNull DefaultActionGroup leftToolbar, @NotNull DefaultActionGroup topToolbar) {
Constraints beforeRunner = new Constraints(Anchor.BEFORE, "Runner.Layout");
leftToolbar.add(Separator.getInstance(), beforeRunner);
leftToolbar.add(ActionManager.getInstance().getAction(DebuggerActions.EXPORT_THREADS), beforeRunner);
leftToolbar.add(ActionManager.getInstance().getAction(DebuggerActions.DUMP_THREADS), beforeRunner);
leftToolbar.add(Separator.getInstance(), beforeRunner);
final DefaultActionGroup settings = new DefaultActionGroup("DebuggerSettings", true) {
@Override
public void update(AnActionEvent e) {
e.getPresentation().setText(ActionsBundle.message("group.XDebugger.settings.text"));
e.getPresentation().setIcon(AllIcons.General.SecondaryGroup);
}
@Override
public boolean isDumbAware() {
return true;
}
};
settings.add(new WatchLastMethodReturnValueAction());
settings.add(new AutoVarsSwitchAction());
settings.add(new UnmuteOnStopAction());
settings.addSeparator();
addActionToGroup(settings, XDebuggerActions.AUTO_TOOLTIP);
leftToolbar.add(settings, new Constraints(Anchor.AFTER, "Runner.Layout"));
}
private static class AutoVarsSwitchAction extends ToggleAction {
private volatile boolean myAutoModeEnabled;
public AutoVarsSwitchAction() {
super("", "", AllIcons.Debugger.AutoVariablesMode);
myAutoModeEnabled = DebuggerSettings.getInstance().AUTO_VARIABLES_MODE;
}
@Override
public void update(final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean autoModeEnabled = (Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
presentation.setText(autoModeEnabled ? "All-Variables Mode" : "Auto-Variables Mode");
}
@Override
public boolean isSelected(AnActionEvent e) {
return myAutoModeEnabled;
}
@Override
public void setSelected(AnActionEvent e, boolean enabled) {
myAutoModeEnabled = enabled;
DebuggerSettings.getInstance().AUTO_VARIABLES_MODE = enabled;
XDebuggerUtilImpl.rebuildAllSessionsViews(e.getProject());
}
}
private class WatchLastMethodReturnValueAction extends ToggleAction {
private volatile boolean myWatchesReturnValues;
private final String myTextEnable;
private final String myTextUnavailable;
private final String myMyTextDisable;
public WatchLastMethodReturnValueAction() {
super("", DebuggerBundle.message("action.watch.method.return.value.description"), null);
myWatchesReturnValues = DebuggerSettings.getInstance().WATCH_RETURN_VALUES;
myTextEnable = DebuggerBundle.message("action.watches.method.return.value.enable");
myMyTextDisable = DebuggerBundle.message("action.watches.method.return.value.disable");
myTextUnavailable = DebuggerBundle.message("action.watches.method.return.value.unavailable.reason");
}
@Override
public void update(final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean watchValues = (Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
final DebugProcessImpl process = myJavaSession.getProcess();
final String actionText = watchValues ? myMyTextDisable : myTextEnable;
if (process != null && process.canGetMethodReturnValue()) {
presentation.setEnabled(true);
presentation.setText(actionText);
}
else {
presentation.setEnabled(false);
presentation.setText(process == null ? actionText : myTextUnavailable);
}
}
@Override
public boolean isSelected(AnActionEvent e) {
return myWatchesReturnValues;
}
@Override
public void setSelected(AnActionEvent e, boolean watch) {
myWatchesReturnValues = watch;
DebuggerSettings.getInstance().WATCH_RETURN_VALUES = watch;
final DebugProcessImpl process = myJavaSession.getProcess();
if (process != null) {
process.setWatchMethodReturnValuesEnabled(watch);
}
}
}
private static class UnmuteOnStopAction extends ToggleAction {
private volatile boolean myUnmuteOnStop;
private UnmuteOnStopAction() {
super(DebuggerBundle.message("action.unmute.on.stop.text"), DebuggerBundle.message("action.unmute.on.stop.text"), null);
myUnmuteOnStop = DebuggerSettings.getInstance().UNMUTE_ON_STOP;
}
@Override
public boolean isSelected(AnActionEvent e) {
return myUnmuteOnStop;
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
myUnmuteOnStop = state;
DebuggerSettings.getInstance().UNMUTE_ON_STOP = state;
}
}
private static void addActionToGroup(final DefaultActionGroup group, final String actionId) {
AnAction action = ActionManager.getInstance().getAction(actionId);
if (action != null) group.add(action);
}
public NodeManagerImpl getNodeManager() {
return myNodeManager;
}
@Nullable
@Override
public XValueMarkerProvider<?, ?> createValueMarkerProvider() {
return MARKER;
}
}
| java/debugger/impl/src/com/intellij/debugger/engine/JavaDebugProcess.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.engine;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.actions.DebuggerActions;
import com.intellij.debugger.engine.evaluation.EvaluationContext;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerContextListener;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.debugger.impl.DebuggerStateManager;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.DebuggerContentInfo;
import com.intellij.debugger.ui.impl.ThreadsPanel;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.NodeDescriptorImpl;
import com.intellij.debugger.ui.impl.watch.NodeManagerImpl;
import com.intellij.debugger.ui.tree.NodeDescriptor;
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.execution.ui.RunnerLayoutUi;
import com.intellij.execution.ui.layout.PlaceInGrid;
import com.intellij.icons.AllIcons;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManagerAdapter;
import com.intellij.ui.content.ContentManagerEvent;
import com.intellij.xdebugger.*;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.intellij.xdebugger.frame.XSuspendContext;
import com.intellij.xdebugger.frame.XValueMarkerProvider;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.impl.actions.XDebuggerActions;
import com.intellij.xdebugger.ui.XDebugTabLayouter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author egor
*/
public class JavaDebugProcess extends XDebugProcess {
private static final JavaValueMarker MARKER = new JavaValueMarker();
private final DebuggerSession myJavaSession;
private final JavaDebuggerEditorsProvider myEditorsProvider;
private final XBreakpointHandler<?>[] myBreakpointHandlers;
private final MyDebuggerStateManager myStateManager = new MyDebuggerStateManager();
private final NodeManagerImpl myNodeManager;
public JavaDebugProcess(@NotNull XDebugSession session, DebuggerSession javaSession) {
super(session);
myJavaSession = javaSession;
myEditorsProvider = new JavaDebuggerEditorsProvider();
DebugProcessImpl process = javaSession.getProcess();
myBreakpointHandlers = new XBreakpointHandler[]{
new JavaBreakpointHandler.JavaLineBreakpointHandler(process),
new JavaBreakpointHandler.JavaExceptionBreakpointHandler(process),
new JavaBreakpointHandler.JavaFieldBreakpointHandler(process),
new JavaBreakpointHandler.JavaMethodBreakpointHandler(process),
new JavaBreakpointHandler.JavaWildcardBreakpointHandler(process),
};
process.addDebugProcessListener(new DebugProcessAdapter() {
@Override
public void paused(final SuspendContext suspendContext) {
//DebugProcessImpl process = (DebugProcessImpl)suspendContext.getDebugProcess();
//JdiSuspendContext context = new JdiSuspendContext(process, true);
//getSession().positionReached(new JavaSuspendContext(context, PositionManagerImpl.DEBUGGER_VIEW_SUPPORT, null));
((SuspendContextImpl)suspendContext).initExecutionStacks();
getSession().positionReached((XSuspendContext)suspendContext);
}
});
myJavaSession.getContextManager().addListener(new DebuggerContextListener() {
@Override
public void changeEvent(DebuggerContextImpl newContext, int event) {
myStateManager.fireStateChanged(newContext, event);
}
});
myNodeManager = new NodeManagerImpl(session.getProject(), null) {
@Override
public DebuggerTreeNodeImpl createNode(final NodeDescriptor descriptor, EvaluationContext evaluationContext) {
((NodeDescriptorImpl)descriptor).setContext((EvaluationContextImpl)evaluationContext);
final DebuggerTreeNodeImpl node = new DebuggerTreeNodeImpl(null, descriptor);
((NodeDescriptorImpl)descriptor).updateRepresentation((EvaluationContextImpl)evaluationContext, DescriptorLabelListener.DUMMY_LISTENER);
return node;
}
};
session.addSessionListener(new XDebugSessionAdapter() {
@Override
public void beforeSessionResume() {
myNodeManager.setHistoryByContext(myStateManager.getContext());
}
});
}
@NotNull
@Override
public XDebuggerEditorsProvider getEditorsProvider() {
return myEditorsProvider;
}
@Override
public void startStepOver() {
myJavaSession.stepOver(false);
}
@Override
public void startStepInto() {
myJavaSession.stepInto(false, null);
}
@Override
public void startStepOut() {
myJavaSession.stepOut();
}
@Override
public void stop() {
}
@Override
public void startPausing() {
myJavaSession.pause();
}
@Override
public void resume() {
myJavaSession.resume();
}
@Override
public void runToPosition(@NotNull XSourcePosition position) {
Document document = FileDocumentManager.getInstance().getDocument(position.getFile());
myJavaSession.runToCursor(document, position.getLine(), false);
}
@NotNull
@Override
public XBreakpointHandler<?>[] getBreakpointHandlers() {
return myBreakpointHandlers;
}
@Override
public boolean checkCanInitBreakpoints() {
return false;
}
@Nullable
@Override
protected ProcessHandler doGetProcessHandler() {
return myJavaSession.getProcess().getExecutionResult().getProcessHandler();
}
@NotNull
@Override
public ExecutionConsole createConsole() {
return myJavaSession.getProcess().getExecutionResult().getExecutionConsole();
}
@NotNull
@Override
public XDebugTabLayouter createTabLayouter() {
return new XDebugTabLayouter() {
@Override
public void registerAdditionalContent(@NotNull RunnerLayoutUi ui) {
final ThreadsPanel panel = new ThreadsPanel(myJavaSession.getProject(), myStateManager);
final Content threadsContent = ui.createContent(
DebuggerContentInfo.THREADS_CONTENT, panel, XDebuggerBundle.message("debugger.session.tab.threads.title"),
AllIcons.Debugger.Threads, null);
threadsContent.setCloseable(false);
ui.addContent(threadsContent, 0, PlaceInGrid.left, true);
ui.addListener(new ContentManagerAdapter() {
@Override
public void selectionChanged(ContentManagerEvent event) {
if (event.getContent() == threadsContent) {
if (threadsContent.isSelected()) {
panel.setUpdateEnabled(true);
if (panel.isRefreshNeeded()) {
panel.rebuildIfVisible(DebuggerSession.EVENT_CONTEXT);
}
}
else {
panel.setUpdateEnabled(false);
}
}
}
}, threadsContent);
}
};
}
private class MyDebuggerStateManager extends DebuggerStateManager {
@Override
public void fireStateChanged(DebuggerContextImpl newContext, int event) {
super.fireStateChanged(newContext, event);
}
@Override
public DebuggerContextImpl getContext() {
return myJavaSession.getContextManager().getContext();
}
@Override
public void setState(DebuggerContextImpl context, int state, int event, String description) {
myJavaSession.getContextManager().setState(context, state, event, description);
}
}
@Override
public void registerAdditionalActions(@NotNull DefaultActionGroup leftToolbar, @NotNull DefaultActionGroup topToolbar) {
Constraints beforeRunner = new Constraints(Anchor.BEFORE, "Runner.Layout");
leftToolbar.add(Separator.getInstance(), beforeRunner);
leftToolbar.add(ActionManager.getInstance().getAction(DebuggerActions.EXPORT_THREADS), beforeRunner);
leftToolbar.add(ActionManager.getInstance().getAction(DebuggerActions.DUMP_THREADS), beforeRunner);
leftToolbar.add(Separator.getInstance(), beforeRunner);
final DefaultActionGroup settings = new DefaultActionGroup("DebuggerSettings", true) {
@Override
public void update(AnActionEvent e) {
e.getPresentation().setText(ActionsBundle.message("group.XDebugger.settings.text"));
e.getPresentation().setIcon(AllIcons.General.SecondaryGroup);
}
@Override
public boolean isDumbAware() {
return true;
}
};
settings.add(new WatchLastMethodReturnValueAction());
settings.add(new AutoVarsSwitchAction());
settings.add(new UnmuteOnStopAction());
settings.addSeparator();
addActionToGroup(settings, XDebuggerActions.AUTO_TOOLTIP);
leftToolbar.add(settings, new Constraints(Anchor.AFTER, "Runner.Layout"));
}
private static class AutoVarsSwitchAction extends ToggleAction {
private volatile boolean myAutoModeEnabled;
public AutoVarsSwitchAction() {
super("", "", AllIcons.Debugger.AutoVariablesMode);
myAutoModeEnabled = DebuggerSettings.getInstance().AUTO_VARIABLES_MODE;
}
@Override
public void update(final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean autoModeEnabled = (Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
presentation.setText(autoModeEnabled ? "All-Variables Mode" : "Auto-Variables Mode");
}
@Override
public boolean isSelected(AnActionEvent e) {
return myAutoModeEnabled;
}
@Override
public void setSelected(AnActionEvent e, boolean enabled) {
myAutoModeEnabled = enabled;
DebuggerSettings.getInstance().AUTO_VARIABLES_MODE = enabled;
XDebuggerUtilImpl.rebuildAllSessionsViews(e.getProject());
}
}
private class WatchLastMethodReturnValueAction extends ToggleAction {
private volatile boolean myWatchesReturnValues;
private final String myTextEnable;
private final String myTextUnavailable;
private final String myMyTextDisable;
public WatchLastMethodReturnValueAction() {
super("", DebuggerBundle.message("action.watch.method.return.value.description"), null);
myWatchesReturnValues = DebuggerSettings.getInstance().WATCH_RETURN_VALUES;
myTextEnable = DebuggerBundle.message("action.watches.method.return.value.enable");
myMyTextDisable = DebuggerBundle.message("action.watches.method.return.value.disable");
myTextUnavailable = DebuggerBundle.message("action.watches.method.return.value.unavailable.reason");
}
@Override
public void update(final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean watchValues = (Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
final DebugProcessImpl process = myJavaSession.getProcess();
final String actionText = watchValues ? myMyTextDisable : myTextEnable;
if (process != null && process.canGetMethodReturnValue()) {
presentation.setEnabled(true);
presentation.setText(actionText);
}
else {
presentation.setEnabled(false);
presentation.setText(process == null ? actionText : myTextUnavailable);
}
}
@Override
public boolean isSelected(AnActionEvent e) {
return myWatchesReturnValues;
}
@Override
public void setSelected(AnActionEvent e, boolean watch) {
myWatchesReturnValues = watch;
DebuggerSettings.getInstance().WATCH_RETURN_VALUES = watch;
final DebugProcessImpl process = myJavaSession.getProcess();
if (process != null) {
process.setWatchMethodReturnValuesEnabled(watch);
}
}
}
private static class UnmuteOnStopAction extends ToggleAction {
private volatile boolean myUnmuteOnStop;
private UnmuteOnStopAction() {
super(DebuggerBundle.message("action.unmute.on.stop.text"), DebuggerBundle.message("action.unmute.on.stop.text"), null);
myUnmuteOnStop = DebuggerSettings.getInstance().UNMUTE_ON_STOP;
}
@Override
public boolean isSelected(AnActionEvent e) {
return myUnmuteOnStop;
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
myUnmuteOnStop = state;
DebuggerSettings.getInstance().UNMUTE_ON_STOP = state;
}
}
private static void addActionToGroup(final DefaultActionGroup group, final String actionId) {
AnAction action = ActionManager.getInstance().getAction(actionId);
if (action != null) group.add(action);
}
public NodeManagerImpl getNodeManager() {
return myNodeManager;
}
@Nullable
@Override
public XValueMarkerProvider<?, ?> createValueMarkerProvider() {
return MARKER;
}
}
| java-xdebugger: use debugger thread to store descriptors tree
| java/debugger/impl/src/com/intellij/debugger/engine/JavaDebugProcess.java | java-xdebugger: use debugger thread to store descriptors tree |
|
Java | apache-2.0 | be62dec3d3058c7011c2f54645f1060936646c07 | 0 | slisson/intellij-community,joewalnes/idea-community,apixandru/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,samthor/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,FHannes/intellij-community,supersven/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,dslomov/intellij-community,fitermay/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,vladmm/intellij-community,ibinti/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,da1z/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,signed/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,allotria/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,kool79/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,da1z/intellij-community,caot/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,adedayo/intellij-community,izonder/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,asedunov/intellij-community,vladmm/intellij-community,kool79/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,kool79/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,amith01994/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,allotria/intellij-community,joewalnes/idea-community,diorcety/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,kool79/intellij-community,vladmm/intellij-community,fitermay/intellij-community,samthor/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,signed/intellij-community,izonder/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,semonte/intellij-community,supersven/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,adedayo/intellij-community,petteyg/intellij-community,kool79/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,joewalnes/idea-community,xfournet/intellij-community,dslomov/intellij-community,clumsy/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,diorcety/intellij-community,hurricup/intellij-community,asedunov/intellij-community,robovm/robovm-studio,ryano144/intellij-community,Lekanich/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,joewalnes/idea-community,ryano144/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ibinti/intellij-community,caot/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,kool79/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,semonte/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,slisson/intellij-community,hurricup/intellij-community,ryano144/intellij-community,asedunov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,signed/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,kool79/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,kdwink/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,petteyg/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,vladmm/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ernestp/consulo,ol-loginov/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,slisson/intellij-community,adedayo/intellij-community,signed/intellij-community,gnuhub/intellij-community,izonder/intellij-community,blademainer/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,hurricup/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,jexp/idea2,clumsy/intellij-community,kdwink/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,signed/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,signed/intellij-community,petteyg/intellij-community,xfournet/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,jexp/idea2,nicolargo/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,allotria/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,retomerz/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,samthor/intellij-community,signed/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,retomerz/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,adedayo/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,fnouama/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,jexp/idea2,nicolargo/intellij-community,Distrotech/intellij-community,ernestp/consulo,vladmm/intellij-community,jexp/idea2,diorcety/intellij-community,dslomov/intellij-community,semonte/intellij-community,tmpgit/intellij-community,da1z/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,kdwink/intellij-community,slisson/intellij-community,xfournet/intellij-community,jexp/idea2,fnouama/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,dslomov/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,signed/intellij-community,ahb0327/intellij-community,holmes/intellij-community,FHannes/intellij-community,caot/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,slisson/intellij-community,da1z/intellij-community,Lekanich/intellij-community,allotria/intellij-community,vladmm/intellij-community,ernestp/consulo,amith01994/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,slisson/intellij-community,ibinti/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,petteyg/intellij-community,slisson/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,slisson/intellij-community,fitermay/intellij-community,clumsy/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,samthor/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,xfournet/intellij-community,da1z/intellij-community,blademainer/intellij-community,joewalnes/idea-community,slisson/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,consulo/consulo,MER-GROUP/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,semonte/intellij-community,holmes/intellij-community,jexp/idea2,alphafoobar/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,samthor/intellij-community,orekyuu/intellij-community,supersven/intellij-community,xfournet/intellij-community,consulo/consulo,joewalnes/idea-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,samthor/intellij-community,allotria/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,amith01994/intellij-community,amith01994/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,akosyakov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,jagguli/intellij-community,signed/intellij-community,ibinti/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,consulo/consulo,samthor/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,dslomov/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,caot/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,suncycheng/intellij-community,consulo/consulo,supersven/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,signed/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,caot/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,da1z/intellij-community,nicolargo/intellij-community,caot/intellij-community,izonder/intellij-community,diorcety/intellij-community,consulo/consulo,jagguli/intellij-community,kool79/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,ernestp/consulo,da1z/intellij-community,holmes/intellij-community,fnouama/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,jagguli/intellij-community,kool79/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,caot/intellij-community,jagguli/intellij-community,kdwink/intellij-community,apixandru/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,FHannes/intellij-community,fitermay/intellij-community,blademainer/intellij-community,clumsy/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,kool79/intellij-community,robovm/robovm-studio,robovm/robovm-studio,samthor/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,MER-GROUP/intellij-community,jexp/idea2,xfournet/intellij-community,jagguli/intellij-community,xfournet/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,asedunov/intellij-community,petteyg/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community | package com.intellij.openapi.projectRoots.ex;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.ProjectJdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.rt.compiler.JavacRunner;
import com.intellij.rt.junit4.JUnit4Util;
import com.intellij.util.Function;
import com.intellij.util.PathUtil;
import com.intellij.util.PathsList;
import com.intellij.util.containers.ComparatorUtil;
import static com.intellij.util.containers.ContainerUtil.map;
import static com.intellij.util.containers.ContainerUtil.skipNulls;
import com.intellij.util.containers.Convertor;
import org.jetbrains.annotations.NonNls;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author Eugene Zhuravlev
* Date: Apr 14, 2004
*/
public class PathUtilEx {
@NonNls private static final String IDEA_PREPEND_RTJAR = "idea.prepend.rtjar";
private static final Function<Module, ProjectJdk> MODULE_JDK = new Function<Module, ProjectJdk>() {
public ProjectJdk fun(Module module) {
return ModuleRootManager.getInstance(module).getJdk();
}
};
private static final Convertor<ProjectJdk, String> JDK_VERSION = new Convertor<ProjectJdk, String>() {
public String convert(ProjectJdk jdk) {
return jdk.getVersionString();
}
};
public static void addRtJar(PathsList pathsList) {
final String ideaRtJarPath = getIdeaRtJarPath();
if (Boolean.getBoolean(IDEA_PREPEND_RTJAR)) {
pathsList.addFirst(ideaRtJarPath);
}
else {
pathsList.addTail(ideaRtJarPath);
}
}
public static void addJunit4RtJar(PathsList pathsList) {
final String path = getIdeaJunit4RtJarPath();
if (Boolean.getBoolean(IDEA_PREPEND_RTJAR)) {
pathsList.addFirst(path);
}
else {
pathsList.addTail(path);
}
}
public static String getIdeaJunit4RtJarPath() {
return PathUtil.getJarPathForClass(JUnit4Util.class);
}
public static String getJunit4JarPath() {
return PathUtil.getJarPathForClass(org.junit.Test.class);
}
public static String getJunit3JarPath() {
try {
return PathUtil.getJarPathForClass(Class.forName("junit.runner.TestSuiteLoader")); //junit3 specific class
}
catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static String getIdeaRtJarPath() {
return PathUtil.getJarPathForClass(JavacRunner.class);
}
public static ProjectJdk getAnyJdk(Project project) {
return chooseJdk(project, Arrays.asList(ModuleManager.getInstance(project).getModules()));
}
public static ProjectJdk chooseJdk(Project project, Collection<Module> modules) {
ProjectJdk projectJdk = ProjectRootManager.getInstance(project).getProjectJdk();
if (projectJdk != null) {
return projectJdk;
}
return chooseJdk(modules);
}
public static ProjectJdk chooseJdk(Collection<Module> modules) {
List<ProjectJdk> jdks = skipNulls(map(skipNulls(modules), MODULE_JDK));
if (jdks.isEmpty()) {
return null;
}
Collections.sort(jdks, ComparatorUtil.compareBy(JDK_VERSION, String.CASE_INSENSITIVE_ORDER));
return jdks.get(jdks.size() - 1);
}
}
| source/com/intellij/openapi/projectRoots/ex/PathUtilEx.java | package com.intellij.openapi.projectRoots.ex;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.ProjectJdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.rt.compiler.JavacRunner;
import com.intellij.rt.junit4.JUnit4Util;
import com.intellij.util.Function;
import com.intellij.util.PathUtil;
import com.intellij.util.PathsList;
import com.intellij.util.containers.ComparatorUtil;
import static com.intellij.util.containers.ContainerUtil.map;
import static com.intellij.util.containers.ContainerUtil.skipNulls;
import com.intellij.util.containers.Convertor;
import org.jetbrains.annotations.NonNls;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author Eugene Zhuravlev
* Date: Apr 14, 2004
*/
public class PathUtilEx {
@NonNls private static final String IDEA_PREPEND_RTJAR = "idea.prepend.rtjar";
private static final Function<Module, ProjectJdk> MODULE_JDK = new Function<Module, ProjectJdk>() {
public ProjectJdk fun(Module module) {
return ModuleRootManager.getInstance(module).getJdk();
}
};
private static final Convertor<ProjectJdk, String> JDK_VERSION = new Convertor<ProjectJdk, String>() {
public String convert(ProjectJdk jdk) {
return jdk.getVersionString();
}
};
public static void addRtJar(PathsList pathsList) {
final String ideaRtJarPath = getIdeaRtJarPath();
if (Boolean.getBoolean(IDEA_PREPEND_RTJAR)) {
pathsList.addFirst(ideaRtJarPath);
}
else {
pathsList.addTail(ideaRtJarPath);
}
}
public static void addJunit4RtJar(PathsList pathsList) {
final String path = getIdeaJunit4RtJarPath();
if (Boolean.getBoolean(IDEA_PREPEND_RTJAR)) {
pathsList.addFirst(path);
}
else {
pathsList.addTail(path);
}
}
public static String getIdeaJunit4RtJarPath() {
return PathUtil.getJarPathForClass(JUnit4Util.class);
}
public static String getJunit4JarPath() {
return PathUtil.getJarPathForClass(org.junit.Test.class);
}
public static String getJunit3JarPath() {
return PathUtil.getJarPathForClass(junit.framework.Test.class);
}
public static String getIdeaRtJarPath() {
return PathUtil.getJarPathForClass(JavacRunner.class);
}
public static ProjectJdk getAnyJdk(Project project) {
return chooseJdk(project, Arrays.asList(ModuleManager.getInstance(project).getModules()));
}
public static ProjectJdk chooseJdk(Project project, Collection<Module> modules) {
ProjectJdk projectJdk = ProjectRootManager.getInstance(project).getProjectJdk();
if (projectJdk != null) {
return projectJdk;
}
return chooseJdk(modules);
}
public static ProjectJdk chooseJdk(Collection<Module> modules) {
List<ProjectJdk> jdks = skipNulls(map(skipNulls(modules), MODULE_JDK));
if (jdks.isEmpty()) {
return null;
}
Collections.sort(jdks, ComparatorUtil.compareBy(JDK_VERSION, String.CASE_INSENSITIVE_ORDER));
return jdks.get(jdks.size() - 1);
}
}
| fix slow tests
| source/com/intellij/openapi/projectRoots/ex/PathUtilEx.java | fix slow tests |
|
Java | apache-2.0 | 661e30338c41254774f63feefedb8d376d5250e5 | 0 | h4ck4thon/jira-scrum-poker,h4ck4thon/jira-scrum-poker,codescape/jira-scrum-poker,codescape/jira-scrum-poker | package net.congstar.jira.plugins.scrumpoker.action;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import net.congstar.jira.plugins.scrumpoker.data.PlanningPokerStorage;
import net.congstar.jira.plugins.scrumpoker.data.StoryPointFieldSupport;
import net.congstar.jira.plugins.scrumpoker.model.PokerCard;
import net.congstar.jira.plugins.scrumpoker.model.ScrumPokerSession;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.IssueFieldConstants;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.RendererManager;
import com.atlassian.jira.issue.fields.layout.field.FieldLayout;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutManager;
import com.atlassian.jira.user.util.UserManager;
import com.atlassian.velocity.htmlsafe.HtmlSafe;
public final class StartPlanningPoker extends ScrumPokerAction {
private static final long serialVersionUID = 1L;
private final IssueManager issueManager;
private final PlanningPokerStorage planningPokerStorage;
private final StoryPointFieldSupport storyPointFieldSupport;
private String issueSummary;
private Double issueStoryPoints;
private String issueKey;
private String issueProjectName;
private String issueProjectKey;
private String issueReturnUrl = "test";
private Map<String, PokerCard> cardDeck = new HashMap<String, PokerCard>();
private FieldLayoutManager fieldLayoutManager;
private RendererManager rendererManager;
private UserManager userManager;
private ScrumPokerSession pokerSession;
@HtmlSafe
public String getIssueDescription() {
MutableIssue issue = issueManager.getIssueObject(issueKey);
FieldLayout fieldLayout = fieldLayoutManager.getFieldLayout(issue);
FieldLayoutItem fieldLayoutItem = fieldLayout.getFieldLayoutItem(IssueFieldConstants.DESCRIPTION);
String rendererType = (fieldLayoutItem != null) ? fieldLayoutItem.getRendererType() : null;
return rendererManager.getRenderedContent(rendererType, issue.getDescription(), issue.getIssueRenderContext());
}
public Double getIssueStoryPoints() {
return issueStoryPoints;
}
public String getIssueProjectKey() {
return issueProjectKey;
}
public String getIssueReturnUrl() {
return issueReturnUrl;
}
public String getIssueKey() {
return issueKey;
}
public String getIssueProjectName() {
return issueProjectName;
}
public String getIssueSummary() {
return issueSummary;
}
public Map<String, PokerCard> getCardDeck() {
return cardDeck;
}
public String getChosenCard() {
return pokerSession.getCards().get(getLoggedInApplicationUser().getKey());
}
public PokerCard[] getCards() {
return PokerUtil.pokerDeck;
}
public ScrumPokerSession getPokerSession() {
return pokerSession;
}
public StartPlanningPoker(IssueManager issueManager, PlanningPokerStorage planningPokerStorage, StoryPointFieldSupport storyPointFieldSupport, UserManager userManager) {
this.issueManager = issueManager;
this.planningPokerStorage = planningPokerStorage;
this.storyPointFieldSupport = storyPointFieldSupport;
this.userManager = userManager;
fieldLayoutManager = ComponentAccessor.getComponent(FieldLayoutManager.class);
rendererManager = ComponentAccessor.getComponent(RendererManager.class);
for (PokerCard card : PokerUtil.pokerDeck) {
cardDeck.put(card.getName(), card);
}
}
@Override
protected String doExecute() throws Exception {
String action = getHttpRequest().getParameter("action");
issueKey = getHttpRequest().getParameter(PARAM_ISSUE_KEY);
if (getLoggedInApplicationUser() == null) {
return "error";
}
MutableIssue issue = issueManager.getIssueObject(issueKey);
if (issue == null) {
addErrorMessage("Issue Key" + issueKey + " not found.");
return "error";
}
if (action == null || (action != null && !action.equals("update"))) {
// weird hack to check whether we have been called from "outside"
boolean outsideCall = true;
URL referrerURL = new URL(getHttpRequest().getHeader(PARAM_REFERRER_HEADER));
String selfAction = getActionName().toLowerCase();
String referrerPath = referrerURL.getPath().toLowerCase();
String regex = ".*/" + selfAction + "\\.?\\w*";
if (referrerPath.matches(regex)) {
outsideCall = false;
}
// remember the page we have to return to after finishing the poker round
String sessionUrl = (String) getHttpSession().getAttribute(PARAM_RETURN_URL);
issueReturnUrl = getReturnUrl();
if (sessionUrl == null || outsideCall) {
if (issueReturnUrl == null) {
issueReturnUrl = "/browse/" + issueKey;
}
getHttpSession().setAttribute(PARAM_RETURN_URL, issueReturnUrl);
} else {
issueReturnUrl = sessionUrl;
}
}
pokerSession = planningPokerStorage.sessionForIssue(issueKey);
issueSummary = issue.getSummary();
issueProjectName = issue.getProjectObject().getName();
issueProjectKey = issue.getProjectObject().getKey();
issueStoryPoints = storyPointFieldSupport.getValue(issueKey);
if (action != null && action.equals("update")) {
return "update";
} else
return "start";
}
public Collection<String> getBoundedVotes() {
return pokerSession.getBoundedVotes();
}
public String getUsername(String key) {
return userManager.getUserByKey(key).getDisplayName();
}
}
| src/main/java/net/congstar/jira/plugins/scrumpoker/action/StartPlanningPoker.java | package net.congstar.jira.plugins.scrumpoker.action;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import net.congstar.jira.plugins.scrumpoker.data.PlanningPokerStorage;
import net.congstar.jira.plugins.scrumpoker.data.StoryPointFieldSupport;
import net.congstar.jira.plugins.scrumpoker.model.PokerCard;
import net.congstar.jira.plugins.scrumpoker.model.ScrumPokerSession;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.IssueFieldConstants;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.RendererManager;
import com.atlassian.jira.issue.fields.layout.field.FieldLayout;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutManager;
import com.atlassian.jira.user.util.UserManager;
import com.atlassian.velocity.htmlsafe.HtmlSafe;
public final class StartPlanningPoker extends ScrumPokerAction {
private static final long serialVersionUID = 1L;
private final IssueManager issueManager;
private final PlanningPokerStorage planningPokerStorage;
private final StoryPointFieldSupport storyPointFieldSupport;
private String issueSummary;
private Double issueStoryPoints;
private String issueKey;
private String issueProjectName;
private String issueProjectKey;
private String issueReturnUrl = "test";
private Map<String, PokerCard> cardDeck = new HashMap<String, PokerCard>();
private FieldLayoutManager fieldLayoutManager;
private RendererManager rendererManager;
private UserManager userManager;
private ScrumPokerSession pokerSession;
@HtmlSafe
public String getIssueDescription() {
MutableIssue issue = issueManager.getIssueObject(issueKey);
FieldLayout fieldLayout = fieldLayoutManager.getFieldLayout(issue);
FieldLayoutItem fieldLayoutItem = fieldLayout.getFieldLayoutItem(IssueFieldConstants.DESCRIPTION);
String rendererType = (fieldLayoutItem != null) ? fieldLayoutItem.getRendererType() : null;
return rendererManager.getRenderedContent(rendererType, issue.getDescription(), issue.getIssueRenderContext());
}
public Double getIssueStoryPoints() {
return issueStoryPoints;
}
public String getIssueProjectKey() {
return issueProjectKey;
}
public String getIssueReturnUrl() {
return issueReturnUrl;
}
public String getIssueKey() {
return issueKey;
}
public String getIssueProjectName() {
return issueProjectName;
}
public String getIssueSummary() {
return issueSummary;
}
public Map<String, PokerCard> getCardDeck() {
return cardDeck;
}
public String getChosenCard() {
return pokerSession.getCards().get(getLoggedInApplicationUser().getKey());
}
public PokerCard[] getCards() {
return PokerUtil.pokerDeck;
}
public ScrumPokerSession getPokerSession() {
return pokerSession;
}
public StartPlanningPoker(IssueManager issueManager, PlanningPokerStorage planningPokerStorage, StoryPointFieldSupport storyPointFieldSupport, UserManager userManager) {
this.issueManager = issueManager;
this.planningPokerStorage = planningPokerStorage;
this.storyPointFieldSupport = storyPointFieldSupport;
this.userManager = userManager;
fieldLayoutManager = ComponentAccessor.getComponent(FieldLayoutManager.class);
rendererManager = ComponentAccessor.getComponent(RendererManager.class);
for (PokerCard card : PokerUtil.pokerDeck) {
cardDeck.put(card.getName(), card);
}
}
@Override
protected String doExecute() throws Exception {
String action = getHttpRequest().getParameter("action");
issueKey = getHttpRequest().getParameter(PARAM_ISSUE_KEY);
if (getLoggedInApplicationUser() == null) {
return "error";
}
MutableIssue issue = issueManager.getIssueObject(issueKey);
if (issue == null) {
addErrorMessage("Issue Key" + issueKey + " not found.");
return "error";
}
if (action == null || (action != null && !action.equals("update"))) {
// weird hack to check whether we have been called from "outside"
Boolean outsideCall = true;
URL referrerURL = new URL(getHttpRequest().getHeader(PARAM_REFERRER_HEADER));
String selfAction = getActionName().toLowerCase();
String referrerPath = referrerURL.getPath().toLowerCase();
String regex = ".*/" + selfAction + "\\.?\\w*";
if (referrerPath.matches(regex)) {
outsideCall = false;
}
// remember the page we have to return to after finishing the poker round
String sessionUrl = (String) getHttpSession().getAttribute(PARAM_RETURN_URL);
issueReturnUrl = getReturnUrl();
if (sessionUrl == null || outsideCall) {
if (issueReturnUrl == null) {
issueReturnUrl = "/browse/" + issueKey;
}
getHttpSession().setAttribute(PARAM_RETURN_URL, issueReturnUrl);
} else {
issueReturnUrl = sessionUrl;
}
}
pokerSession = planningPokerStorage.sessionForIssue(issueKey);
issueSummary = issue.getSummary();
issueProjectName = issue.getProjectObject().getName();
issueProjectKey = issue.getProjectObject().getKey();
issueStoryPoints = storyPointFieldSupport.getValue(issueKey);
if (action != null && action.equals("update")) {
return "update";
} else
return "start";
}
public Collection<String> getBoundedVotes() {
return pokerSession.getBoundedVotes();
}
public String getUsername(String key) {
return userManager.getUserByKey(key).getDisplayName();
}
}
| true or false but please never null
| src/main/java/net/congstar/jira/plugins/scrumpoker/action/StartPlanningPoker.java | true or false but please never null |
|
Java | apache-2.0 | 2b07543c94377b3359152715d0ed5742ed2894b6 | 0 | lemmingapex/mage-android-sdk,ngageoint/mage-android-sdk,lemmingapex/mage-android-sdk | package mil.nga.giat.mage.sdk.datastore;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
import mil.nga.giat.mage.sdk.datastore.layer.Layer;
import mil.nga.giat.mage.sdk.datastore.location.Location;
import mil.nga.giat.mage.sdk.datastore.location.LocationProperty;
import mil.nga.giat.mage.sdk.datastore.observation.Attachment;
import mil.nga.giat.mage.sdk.datastore.observation.Observation;
import mil.nga.giat.mage.sdk.datastore.observation.ObservationProperty;
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeature;
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeatureProperty;
import mil.nga.giat.mage.sdk.datastore.user.Event;
import mil.nga.giat.mage.sdk.datastore.user.Role;
import mil.nga.giat.mage.sdk.datastore.user.Team;
import mil.nga.giat.mage.sdk.datastore.user.TeamEvent;
import mil.nga.giat.mage.sdk.datastore.user.User;
import mil.nga.giat.mage.sdk.datastore.user.UserTeam;
/**
* This is an implementation of OrmLite android database Helper. Go here to get
* daos that you may need. Manage your table creation and update strategies here
* as well.
*
* @author travis, wiedemanns
*
*/
public class DaoStore extends OrmLiteSqliteOpenHelper {
private static DaoStore helperInstance;
private static final String DATABASE_NAME = "mage.db";
private static final String LOG_NAME = DaoStore.class.getName();
// Making this public so we can check if it has been upgraded and log the user out
public static final int DATABASE_VERSION = 8;
// Observation DAOS
private Dao<Observation, Long> observationDao;
private Dao<ObservationProperty, Long> observationPropertyDao;
private Dao<Attachment, Long> attachmentDao;
// User and Location DAOS
private Dao<User, Long> userDao;
private Dao<Role, Long> roleDao;
private Dao<Event, Long> eventDao;
private Dao<Team, Long> teamDao;
private Dao<UserTeam, Long> userTeamDao;
private Dao<TeamEvent, Long> teamEventDao;
private Dao<Location, Long> locationDao;
private Dao<LocationProperty, Long> locationPropertyDao;
// Layer and StaticFeature DAOS
private Dao<Layer, Long> layerDao;
private Dao<StaticFeature, Long> staticFeatureDao;
private Dao<StaticFeatureProperty, Long> staticFeaturePropertyDao;
/**
* Singleton implementation.
*
* @param context
* @return
*/
public static DaoStore getInstance(Context context) {
if (helperInstance == null) {
helperInstance = new DaoStore(context);
}
return helperInstance;
}
/**
* Constructor that takes an android Context.
*
* @param context
*
*/
private DaoStore(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// initialize DAOs
try {
getObservationDao();
getObservationPropertyDao();
getAttachmentDao();
getUserDao();
getRoleDao();
getEventDao();
getTeamDao();
getUserTeamDao();
getTeamEventDao();
getLocationDao();
getLocationPropertyDao();
getLayerDao();
getStaticFeatureDao();
getStaticFeaturePropertyDao();
} catch (SQLException sqle) {
// TODO: handle this...
sqle.printStackTrace();
}
}
public boolean isDatabaseEmpty() {
long countOfAllRecords = 0l;
try {
countOfAllRecords += getObservationDao().countOf();
countOfAllRecords += getObservationPropertyDao().countOf();
countOfAllRecords += getAttachmentDao().countOf();
countOfAllRecords += getUserDao().countOf();
countOfAllRecords += getRoleDao().countOf();
countOfAllRecords += getEventDao().countOf();
countOfAllRecords += getTeamDao().countOf();
countOfAllRecords += getUserTeamDao().countOf();
countOfAllRecords += getTeamEventDao().countOf();
countOfAllRecords += getLocationDao().countOf();
countOfAllRecords += getLocationPropertyDao().countOf();
countOfAllRecords += getLayerDao().countOf();
countOfAllRecords += getStaticFeatureDao().countOf();
countOfAllRecords += getStaticFeaturePropertyDao().countOf();
} catch (SQLException sqle) {
sqle.printStackTrace();
return false;
}
return countOfAllRecords == 0;
}
private void createTables() throws SQLException {
TableUtils.createTable(connectionSource, Observation.class);
TableUtils.createTable(connectionSource, ObservationProperty.class);
TableUtils.createTable(connectionSource, Attachment.class);
TableUtils.createTable(connectionSource, User.class);
TableUtils.createTable(connectionSource, Role.class);
TableUtils.createTable(connectionSource, Event.class);
TableUtils.createTable(connectionSource, Team.class);
TableUtils.createTable(connectionSource, UserTeam.class);
TableUtils.createTable(connectionSource, TeamEvent.class);
TableUtils.createTable(connectionSource, Location.class);
TableUtils.createTable(connectionSource, LocationProperty.class);
TableUtils.createTable(connectionSource, Layer.class);
TableUtils.createTable(connectionSource, StaticFeature.class);
TableUtils.createTable(connectionSource, StaticFeatureProperty.class);
}
@Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
try {
createTables();
} catch (SQLException se) {
Log.e(LOG_NAME, "Could not create tables.", se);
}
}
private void dropTables() throws SQLException {
TableUtils.dropTable(connectionSource, Observation.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, ObservationProperty.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Attachment.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, User.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Role.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Event.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Team.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, UserTeam.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, TeamEvent.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Location.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, LocationProperty.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Layer.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, StaticFeature.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, StaticFeatureProperty.class, Boolean.TRUE);
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
resetDatabase();
}
/**
* Drop and create all tables.
*/
public void resetDatabase() {
try {
Log.d(LOG_NAME, "Reseting Database.");
dropTables();
createTables();
Log.d(LOG_NAME, "Reset Database.");
} catch (SQLException se) {
Log.e(LOG_NAME, "Could not reset Database.", se);
}
}
@Override
public void close() {
helperInstance = null;
super.close();
}
/**
* Getter for the ObservationDao.
*
* @return This instance's ObservationDao
* @throws SQLException
*/
public Dao<Observation, Long> getObservationDao() throws SQLException {
if (observationDao == null) {
observationDao = getDao(Observation.class);
}
return observationDao;
}
/**
* Getter for the PropertyDao
*
* @return This instance's PropertyDao
* @throws SQLException
*/
public Dao<ObservationProperty, Long> getObservationPropertyDao() throws SQLException {
if (observationPropertyDao == null) {
observationPropertyDao = getDao(ObservationProperty.class);
}
return observationPropertyDao;
}
/**
* Getter for the AttachmentDao
*
* @return This instance's AttachmentDao
* @throws SQLException
*/
public Dao<Attachment, Long> getAttachmentDao() throws SQLException {
if (attachmentDao == null) {
attachmentDao = getDao(Attachment.class);
}
return attachmentDao;
}
/**
* Getter for the UserDao
*
* @return This instance's UserDao
* @throws SQLException
*/
public Dao<User, Long> getUserDao() throws SQLException {
if (userDao == null) {
userDao = getDao(User.class);
}
return userDao;
}
/**
* Getter for the RoleDao
*
* @return This instance's RoleDao
* @throws SQLException
*/
public Dao<Role, Long> getRoleDao() throws SQLException {
if (roleDao == null) {
roleDao = getDao(Role.class);
}
return roleDao;
}
/**
* Getter for the EventDao
*
* @return This instance's EventDao
* @throws SQLException
*/
public Dao<Event, Long> getEventDao() throws SQLException {
if (eventDao == null) {
eventDao = getDao(Event.class);
}
return eventDao;
}
/**
* Getter for the TeamDao
*
* @return This instance's TeamDao
* @throws SQLException
*/
public Dao<Team, Long> getTeamDao() throws SQLException {
if (teamDao == null) {
teamDao = getDao(Team.class);
}
return teamDao;
}
/**
* Getter for the UserTeamDao
*
* @return This instance's UserTeamDao
* @throws SQLException
*/
public Dao<UserTeam, Long> getUserTeamDao() throws SQLException {
if (userTeamDao == null) {
userTeamDao = getDao(UserTeam.class);
}
return userTeamDao;
}
/**
* Getter for the TeamEventDao
*
* @return This instance's TeamEventDao
* @throws SQLException
*/
public Dao<TeamEvent, Long> getTeamEventDao() throws SQLException {
if (teamEventDao == null) {
teamEventDao = getDao(TeamEvent.class);
}
return teamEventDao;
}
/**
* Getter for the LocationDao
*
* @return This instance's LocationDao
* @throws SQLException
*/
public Dao<Location, Long> getLocationDao() throws SQLException {
if (locationDao == null) {
locationDao = getDao(Location.class);
}
return locationDao;
}
/**
* Getter for the LocationPropertyDao
*
* @return This instance's LocationPropertyDao
* @throws SQLException
*/
public Dao<LocationProperty, Long> getLocationPropertyDao() throws SQLException {
if (locationPropertyDao == null) {
locationPropertyDao = getDao(LocationProperty.class);
}
return locationPropertyDao;
}
/**
* Getter for the LayerDao
*
* @return This instance's LayerDao
* @throws SQLException
*/
public Dao<Layer, Long> getLayerDao() throws SQLException {
if (layerDao == null) {
layerDao = getDao(Layer.class);
}
return layerDao;
}
/**
* Getter for the StaticFeatureDao
*
* @return This instance's StaticFeatureDao
* @throws SQLException
*/
public Dao<StaticFeature, Long> getStaticFeatureDao() throws SQLException {
if (staticFeatureDao == null) {
staticFeatureDao = getDao(StaticFeature.class);
}
return staticFeatureDao;
}
/**
* Getter for the StaticFeaturePropertyDao
*
* @return This instance's StaticFeaturePropertyDao
* @throws SQLException
*/
public Dao<StaticFeatureProperty, Long> getStaticFeaturePropertyDao() throws SQLException {
if (staticFeaturePropertyDao == null) {
staticFeaturePropertyDao = getDao(StaticFeatureProperty.class);
}
return staticFeaturePropertyDao;
}
}
| sdk/src/main/java/mil/nga/giat/mage/sdk/datastore/DaoStore.java | package mil.nga.giat.mage.sdk.datastore;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
import mil.nga.giat.mage.sdk.datastore.layer.Layer;
import mil.nga.giat.mage.sdk.datastore.location.Location;
import mil.nga.giat.mage.sdk.datastore.location.LocationProperty;
import mil.nga.giat.mage.sdk.datastore.observation.Attachment;
import mil.nga.giat.mage.sdk.datastore.observation.Observation;
import mil.nga.giat.mage.sdk.datastore.observation.ObservationProperty;
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeature;
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeatureProperty;
import mil.nga.giat.mage.sdk.datastore.user.Event;
import mil.nga.giat.mage.sdk.datastore.user.Role;
import mil.nga.giat.mage.sdk.datastore.user.Team;
import mil.nga.giat.mage.sdk.datastore.user.TeamEvent;
import mil.nga.giat.mage.sdk.datastore.user.User;
import mil.nga.giat.mage.sdk.datastore.user.UserTeam;
/**
* This is an implementation of OrmLite android database Helper. Go here to get
* daos that you may need. Manage your table creation and update strategies here
* as well.
*
* @author travis, wiedemanns
*
*/
public class DaoStore extends OrmLiteSqliteOpenHelper {
private static DaoStore helperInstance;
private static final String DATABASE_NAME = "mage.db";
private static final String LOG_NAME = DaoStore.class.getName();
// Making this public so we can check if it has been upgraded and log the user out
public static final int DATABASE_VERSION = 7;
// Observation DAOS
private Dao<Observation, Long> observationDao;
private Dao<ObservationProperty, Long> observationPropertyDao;
private Dao<Attachment, Long> attachmentDao;
// User and Location DAOS
private Dao<User, Long> userDao;
private Dao<Role, Long> roleDao;
private Dao<Event, Long> eventDao;
private Dao<Team, Long> teamDao;
private Dao<UserTeam, Long> userTeamDao;
private Dao<TeamEvent, Long> teamEventDao;
private Dao<Location, Long> locationDao;
private Dao<LocationProperty, Long> locationPropertyDao;
// Layer and StaticFeature DAOS
private Dao<Layer, Long> layerDao;
private Dao<StaticFeature, Long> staticFeatureDao;
private Dao<StaticFeatureProperty, Long> staticFeaturePropertyDao;
/**
* Singleton implementation.
*
* @param context
* @return
*/
public static DaoStore getInstance(Context context) {
if (helperInstance == null) {
helperInstance = new DaoStore(context);
}
return helperInstance;
}
/**
* Constructor that takes an android Context.
*
* @param context
*
*/
private DaoStore(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// initialize DAOs
try {
getObservationDao();
getObservationPropertyDao();
getAttachmentDao();
getUserDao();
getRoleDao();
getEventDao();
getTeamDao();
getUserTeamDao();
getTeamEventDao();
getLocationDao();
getLocationPropertyDao();
getLayerDao();
getStaticFeatureDao();
getStaticFeaturePropertyDao();
} catch (SQLException sqle) {
// TODO: handle this...
sqle.printStackTrace();
}
}
public boolean isDatabaseEmpty() {
long countOfAllRecords = 0l;
try {
countOfAllRecords += getObservationDao().countOf();
countOfAllRecords += getObservationPropertyDao().countOf();
countOfAllRecords += getAttachmentDao().countOf();
countOfAllRecords += getUserDao().countOf();
countOfAllRecords += getRoleDao().countOf();
countOfAllRecords += getEventDao().countOf();
countOfAllRecords += getTeamDao().countOf();
countOfAllRecords += getUserTeamDao().countOf();
countOfAllRecords += getTeamEventDao().countOf();
countOfAllRecords += getLocationDao().countOf();
countOfAllRecords += getLocationPropertyDao().countOf();
countOfAllRecords += getLayerDao().countOf();
countOfAllRecords += getStaticFeatureDao().countOf();
countOfAllRecords += getStaticFeaturePropertyDao().countOf();
} catch (SQLException sqle) {
sqle.printStackTrace();
return false;
}
return countOfAllRecords == 0;
}
private void createTables() throws SQLException {
TableUtils.createTable(connectionSource, Observation.class);
TableUtils.createTable(connectionSource, ObservationProperty.class);
TableUtils.createTable(connectionSource, Attachment.class);
TableUtils.createTable(connectionSource, User.class);
TableUtils.createTable(connectionSource, Role.class);
TableUtils.createTable(connectionSource, Event.class);
TableUtils.createTable(connectionSource, Team.class);
TableUtils.createTable(connectionSource, UserTeam.class);
TableUtils.createTable(connectionSource, TeamEvent.class);
TableUtils.createTable(connectionSource, Location.class);
TableUtils.createTable(connectionSource, LocationProperty.class);
TableUtils.createTable(connectionSource, Layer.class);
TableUtils.createTable(connectionSource, StaticFeature.class);
TableUtils.createTable(connectionSource, StaticFeatureProperty.class);
}
@Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
try {
createTables();
} catch (SQLException se) {
Log.e(LOG_NAME, "Could not create tables.", se);
}
}
private void dropTables() throws SQLException {
TableUtils.dropTable(connectionSource, Observation.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, ObservationProperty.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Attachment.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, User.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Role.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Event.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Team.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, UserTeam.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, TeamEvent.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Location.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, LocationProperty.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, Layer.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, StaticFeature.class, Boolean.TRUE);
TableUtils.dropTable(connectionSource, StaticFeatureProperty.class, Boolean.TRUE);
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
resetDatabase();
}
/**
* Drop and create all tables.
*/
public void resetDatabase() {
try {
Log.d(LOG_NAME, "Reseting Database.");
dropTables();
createTables();
Log.d(LOG_NAME, "Reset Database.");
} catch (SQLException se) {
Log.e(LOG_NAME, "Could not reset Database.", se);
}
}
@Override
public void close() {
helperInstance = null;
super.close();
}
/**
* Getter for the ObservationDao.
*
* @return This instance's ObservationDao
* @throws SQLException
*/
public Dao<Observation, Long> getObservationDao() throws SQLException {
if (observationDao == null) {
observationDao = getDao(Observation.class);
}
return observationDao;
}
/**
* Getter for the PropertyDao
*
* @return This instance's PropertyDao
* @throws SQLException
*/
public Dao<ObservationProperty, Long> getObservationPropertyDao() throws SQLException {
if (observationPropertyDao == null) {
observationPropertyDao = getDao(ObservationProperty.class);
}
return observationPropertyDao;
}
/**
* Getter for the AttachmentDao
*
* @return This instance's AttachmentDao
* @throws SQLException
*/
public Dao<Attachment, Long> getAttachmentDao() throws SQLException {
if (attachmentDao == null) {
attachmentDao = getDao(Attachment.class);
}
return attachmentDao;
}
/**
* Getter for the UserDao
*
* @return This instance's UserDao
* @throws SQLException
*/
public Dao<User, Long> getUserDao() throws SQLException {
if (userDao == null) {
userDao = getDao(User.class);
}
return userDao;
}
/**
* Getter for the RoleDao
*
* @return This instance's RoleDao
* @throws SQLException
*/
public Dao<Role, Long> getRoleDao() throws SQLException {
if (roleDao == null) {
roleDao = getDao(Role.class);
}
return roleDao;
}
/**
* Getter for the EventDao
*
* @return This instance's EventDao
* @throws SQLException
*/
public Dao<Event, Long> getEventDao() throws SQLException {
if (eventDao == null) {
eventDao = getDao(Event.class);
}
return eventDao;
}
/**
* Getter for the TeamDao
*
* @return This instance's TeamDao
* @throws SQLException
*/
public Dao<Team, Long> getTeamDao() throws SQLException {
if (teamDao == null) {
teamDao = getDao(Team.class);
}
return teamDao;
}
/**
* Getter for the UserTeamDao
*
* @return This instance's UserTeamDao
* @throws SQLException
*/
public Dao<UserTeam, Long> getUserTeamDao() throws SQLException {
if (userTeamDao == null) {
userTeamDao = getDao(UserTeam.class);
}
return userTeamDao;
}
/**
* Getter for the TeamEventDao
*
* @return This instance's TeamEventDao
* @throws SQLException
*/
public Dao<TeamEvent, Long> getTeamEventDao() throws SQLException {
if (teamEventDao == null) {
teamEventDao = getDao(TeamEvent.class);
}
return teamEventDao;
}
/**
* Getter for the LocationDao
*
* @return This instance's LocationDao
* @throws SQLException
*/
public Dao<Location, Long> getLocationDao() throws SQLException {
if (locationDao == null) {
locationDao = getDao(Location.class);
}
return locationDao;
}
/**
* Getter for the LocationPropertyDao
*
* @return This instance's LocationPropertyDao
* @throws SQLException
*/
public Dao<LocationProperty, Long> getLocationPropertyDao() throws SQLException {
if (locationPropertyDao == null) {
locationPropertyDao = getDao(LocationProperty.class);
}
return locationPropertyDao;
}
/**
* Getter for the LayerDao
*
* @return This instance's LayerDao
* @throws SQLException
*/
public Dao<Layer, Long> getLayerDao() throws SQLException {
if (layerDao == null) {
layerDao = getDao(Layer.class);
}
return layerDao;
}
/**
* Getter for the StaticFeatureDao
*
* @return This instance's StaticFeatureDao
* @throws SQLException
*/
public Dao<StaticFeature, Long> getStaticFeatureDao() throws SQLException {
if (staticFeatureDao == null) {
staticFeatureDao = getDao(StaticFeature.class);
}
return staticFeatureDao;
}
/**
* Getter for the StaticFeaturePropertyDao
*
* @return This instance's StaticFeaturePropertyDao
* @throws SQLException
*/
public Dao<StaticFeatureProperty, Long> getStaticFeaturePropertyDao() throws SQLException {
if (staticFeaturePropertyDao == null) {
staticFeaturePropertyDao = getDao(StaticFeatureProperty.class);
}
return staticFeaturePropertyDao;
}
}
| Bump DB version
| sdk/src/main/java/mil/nga/giat/mage/sdk/datastore/DaoStore.java | Bump DB version |
|
Java | apache-2.0 | 20b9326f672cf1b59e9ce22bb4f920a5ced97fca | 0 | caosg/BroadleafCommerce,ljshj/BroadleafCommerce,macielbombonato/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,TouK/BroadleafCommerce,sanlingdd/broadleaf,lgscofield/BroadleafCommerce,trombka/blc-tmp,macielbombonato/BroadleafCommerce,wenmangbo/BroadleafCommerce,alextiannus/BroadleafCommerce,rawbenny/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,udayinfy/BroadleafCommerce,wenmangbo/BroadleafCommerce,shopizer/BroadleafCommerce,zhaorui1/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,cogitoboy/BroadleafCommerce,zhaorui1/BroadleafCommerce,cloudbearings/BroadleafCommerce,zhaorui1/BroadleafCommerce,sanlingdd/broadleaf,trombka/blc-tmp,daniellavoie/BroadleafCommerce,alextiannus/BroadleafCommerce,liqianggao/BroadleafCommerce,caosg/BroadleafCommerce,lgscofield/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,rawbenny/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,daniellavoie/BroadleafCommerce,cloudbearings/BroadleafCommerce,sitexa/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,caosg/BroadleafCommerce,bijukunjummen/BroadleafCommerce,bijukunjummen/BroadleafCommerce,passion1014/metaworks_framework,trombka/blc-tmp,liqianggao/BroadleafCommerce,udayinfy/BroadleafCommerce,gengzhengtao/BroadleafCommerce,cloudbearings/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,shopizer/BroadleafCommerce,cogitoboy/BroadleafCommerce,macielbombonato/BroadleafCommerce,gengzhengtao/BroadleafCommerce,lgscofield/BroadleafCommerce,alextiannus/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,passion1014/metaworks_framework,ljshj/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,wenmangbo/BroadleafCommerce,ljshj/BroadleafCommerce,daniellavoie/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,gengzhengtao/BroadleafCommerce,passion1014/metaworks_framework,TouK/BroadleafCommerce,shopizer/BroadleafCommerce,TouK/BroadleafCommerce,liqianggao/BroadleafCommerce,sitexa/BroadleafCommerce,rawbenny/BroadleafCommerce,cogitoboy/BroadleafCommerce,udayinfy/BroadleafCommerce,bijukunjummen/BroadleafCommerce,sitexa/BroadleafCommerce | /*
* Copyright 2008-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.broadleafcommerce.openadmin.server.domain;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.broadleafcommerce.common.presentation.client.PersistencePerspectiveItemType;
import org.broadleafcommerce.openadmin.dto.AdornedTargetCollectionMetadata;
import org.broadleafcommerce.openadmin.dto.AdornedTargetList;
import org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata;
import org.broadleafcommerce.openadmin.dto.BasicFieldMetadata;
import org.broadleafcommerce.openadmin.dto.CollectionMetadata;
import org.broadleafcommerce.openadmin.dto.Entity;
import org.broadleafcommerce.openadmin.dto.FieldMetadata;
import org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria;
import org.broadleafcommerce.openadmin.dto.ForeignKey;
import org.broadleafcommerce.openadmin.dto.MapMetadata;
import org.broadleafcommerce.openadmin.dto.MapStructure;
import org.broadleafcommerce.openadmin.dto.OperationTypes;
import org.broadleafcommerce.openadmin.dto.visitor.MetadataVisitor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A DTO class used to seed a persistence package.
*
* @author Andre Azzolini (apazzolini)
*/
public class PersistencePackageRequest {
protected Type type;
protected String ceilingEntityClassname;
protected String configKey;
protected AdornedTargetList adornedList;
protected MapStructure mapStructure;
protected Entity entity;
protected ForeignKey foreignKey;
protected Integer startIndex;
protected Integer maxIndex;
protected Map<String, PersistencePackageRequest> subRequests = new LinkedHashMap<String, PersistencePackageRequest>();
protected boolean validateUnsubmittedProperties = true;
protected OperationTypes operationTypesOverride = null;
// These properties are accessed via getters and setters that operate on arrays.
// We back them with a list so that we can have the convenience .add methods
protected List<ForeignKey> additionalForeignKeys = new ArrayList<ForeignKey>();
protected List<String> customCriteria = new ArrayList<String>();
protected List<FilterAndSortCriteria> filterAndSortCriteria = new ArrayList<FilterAndSortCriteria>();
public enum Type {
STANDARD,
ADORNED,
MAP
}
/* ******************* */
/* STATIC INITIALIZERS */
/* ******************* */
public static PersistencePackageRequest standard() {
return new PersistencePackageRequest(Type.STANDARD);
}
public static PersistencePackageRequest adorned() {
return new PersistencePackageRequest(Type.ADORNED);
}
public static PersistencePackageRequest map() {
return new PersistencePackageRequest(Type.MAP);
}
/**
* Creates a semi-populate PersistencePacakageRequest based on the specified FieldMetadata. This initializer
* will copy over persistence perspective items from the metadata as well as set the appropriate OperationTypes
* as specified in the annotation/xml configuration for the field.
*
* @param md
* @return the newly created PersistencePackageRequest
*/
public static PersistencePackageRequest fromMetadata(FieldMetadata md) {
final PersistencePackageRequest request = new PersistencePackageRequest();
md.accept(new MetadataVisitor() {
@Override
public void visit(BasicFieldMetadata fmd) {
request.setType(Type.STANDARD);
request.setCeilingEntityClassname(fmd.getForeignKeyClass());
request.setCustomCriteria(fmd.getCustomCriteria());
}
@Override
public void visit(BasicCollectionMetadata fmd) {
ForeignKey foreignKey = (ForeignKey) fmd.getPersistencePerspective()
.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
request.setType(Type.STANDARD);
request.setCeilingEntityClassname(fmd.getCollectionCeilingEntity());
request.setOperationTypesOverride(fmd.getPersistencePerspective().getOperationTypes());
request.setForeignKey(foreignKey);
request.setCustomCriteria(fmd.getCustomCriteria());
}
@Override
public void visit(AdornedTargetCollectionMetadata fmd) {
AdornedTargetList adornedList = (AdornedTargetList) fmd.getPersistencePerspective()
.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST);
request.setType(Type.ADORNED);
request.setCeilingEntityClassname(fmd.getCollectionCeilingEntity());
request.setOperationTypesOverride(fmd.getPersistencePerspective().getOperationTypes());
request.setAdornedList(adornedList);
request.setCustomCriteria(fmd.getCustomCriteria());
}
@Override
public void visit(MapMetadata fmd) {
MapStructure mapStructure = (MapStructure) fmd.getPersistencePerspective()
.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE);
ForeignKey foreignKey = (ForeignKey) fmd.getPersistencePerspective().
getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
request.setType(Type.MAP);
request.setCeilingEntityClassname(foreignKey.getForeignKeyClass());
request.setOperationTypesOverride(fmd.getPersistencePerspective().getOperationTypes());
request.setMapStructure(mapStructure);
request.setForeignKey(foreignKey);
request.setCustomCriteria(fmd.getCustomCriteria());
}
});
if (md instanceof CollectionMetadata) {
request.setCustomCriteria(((CollectionMetadata) md).getCustomCriteria());
}
return request;
}
/* ************ */
/* CONSTRUCTORS */
/* ************ */
public PersistencePackageRequest() {
}
public PersistencePackageRequest(Type type) {
this.type = type;
}
/* ************ */
/* WITH METHODS */
/* ************ */
public PersistencePackageRequest withType(Type type) {
setType(type);
return this;
}
public PersistencePackageRequest withCeilingEntityClassname(String className) {
setCeilingEntityClassname(className);
return this;
}
public PersistencePackageRequest withForeignKey(ForeignKey foreignKey) {
setForeignKey(foreignKey);
return this;
}
public PersistencePackageRequest withConfigKey(String configKey) {
setConfigKey(configKey);
return this;
}
public PersistencePackageRequest withFilterAndSortCriteria(FilterAndSortCriteria[] filterAndSortCriteria) {
if (ArrayUtils.isNotEmpty(filterAndSortCriteria)) {
setFilterAndSortCriteria(filterAndSortCriteria);
}
return this;
}
public PersistencePackageRequest withAdornedList(AdornedTargetList adornedList) {
setAdornedList(adornedList);
return this;
}
public PersistencePackageRequest withMapStructure(MapStructure mapStructure) {
setMapStructure(mapStructure);
return this;
}
public PersistencePackageRequest withCustomCriteria(String[] customCriteria) {
if (ArrayUtils.isNotEmpty(customCriteria)) {
setCustomCriteria(customCriteria);
}
return this;
}
public PersistencePackageRequest withEntity(Entity entity) {
setEntity(entity);
return this;
}
public PersistencePackageRequest withStartIndex(Integer startIndex) {
setStartIndex(startIndex);
return this;
}
public PersistencePackageRequest withMaxIndex(Integer maxIndex) {
setMaxIndex(maxIndex);
return this;
}
/* *********** */
/* ADD METHODS */
/* *********** */
public PersistencePackageRequest addAdditionalForeignKey(ForeignKey foreignKey) {
additionalForeignKeys.add(foreignKey);
return this;
}
public PersistencePackageRequest addSubRequest(String infoPropertyName, PersistencePackageRequest subRequest) {
subRequests.put(infoPropertyName, subRequest);
return this;
}
public PersistencePackageRequest addCustomCriteria(String customCriteria) {
if (StringUtils.isNotBlank(customCriteria)) {
this.customCriteria.add(customCriteria);
}
return this;
}
public PersistencePackageRequest addFilterAndSortCriteria(FilterAndSortCriteria filterAndSortCriteria) {
this.filterAndSortCriteria.add(filterAndSortCriteria);
return this;
}
public PersistencePackageRequest addFilterAndSortCriteria(FilterAndSortCriteria[] filterAndSortCriteria) {
if (filterAndSortCriteria != null) {
this.filterAndSortCriteria.addAll(Arrays.asList(filterAndSortCriteria));
}
return this;
}
public PersistencePackageRequest addFilterAndSortCriteria(List<FilterAndSortCriteria> filterAndSortCriteria) {
this.filterAndSortCriteria.addAll(filterAndSortCriteria);
return this;
}
/* ************************ */
/* CUSTOM GETTERS / SETTERS */
/* ************************ */
public String[] getCustomCriteria() {
String[] arr = new String[this.customCriteria.size()];
arr = this.customCriteria.toArray(arr);
return arr;
}
public ForeignKey[] getAdditionalForeignKeys() {
ForeignKey[] arr = new ForeignKey[this.additionalForeignKeys.size()];
arr = this.additionalForeignKeys.toArray(arr);
return arr;
}
public void setAdditionalForeignKeys(ForeignKey[] additionalForeignKeys) {
this.additionalForeignKeys.addAll(Arrays.asList(additionalForeignKeys));
}
public void setCustomCriteria(String[] customCriteria) {
this.customCriteria.addAll(Arrays.asList(customCriteria));
}
public FilterAndSortCriteria[] getFilterAndSortCriteria() {
FilterAndSortCriteria[] arr = new FilterAndSortCriteria[this.filterAndSortCriteria.size()];
arr = this.filterAndSortCriteria.toArray(arr);
return arr;
}
public void setFilterAndSortCriteria(FilterAndSortCriteria[] filterAndSortCriteria) {
this.filterAndSortCriteria.addAll(Arrays.asList(filterAndSortCriteria));
}
/* ************************** */
/* STANDARD GETTERS / SETTERS */
/* ************************** */
public ForeignKey getForeignKey() {
return foreignKey;
}
public void setForeignKey(ForeignKey foreignKey) {
this.foreignKey = foreignKey;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getCeilingEntityClassname() {
return ceilingEntityClassname;
}
public void setCeilingEntityClassname(String ceilingEntityClassname) {
this.ceilingEntityClassname = ceilingEntityClassname;
}
public String getConfigKey() {
return configKey;
}
public void setConfigKey(String configKey) {
this.configKey = configKey;
}
public AdornedTargetList getAdornedList() {
return adornedList;
}
public void setAdornedList(AdornedTargetList adornedList) {
this.adornedList = adornedList;
}
public MapStructure getMapStructure() {
return mapStructure;
}
public void setMapStructure(MapStructure mapStructure) {
this.mapStructure = mapStructure;
}
public Entity getEntity() {
return entity;
}
public void setEntity(Entity entity) {
this.entity = entity;
}
public OperationTypes getOperationTypesOverride() {
return operationTypesOverride;
}
public void setOperationTypesOverride(OperationTypes operationTypesOverride) {
this.operationTypesOverride = operationTypesOverride;
}
public Integer getStartIndex() {
return startIndex;
}
public void setStartIndex(Integer startIndex) {
this.startIndex = startIndex;
}
public Integer getMaxIndex() {
return maxIndex;
}
public void setMaxIndex(Integer maxIndex) {
this.maxIndex = maxIndex;
}
public Map<String, PersistencePackageRequest> getSubRequests() {
return subRequests;
}
public void setSubRequests(Map<String, PersistencePackageRequest> subRequests) {
this.subRequests = subRequests;
}
public boolean isValidateUnsubmittedProperties() {
return validateUnsubmittedProperties;
}
public void setValidateUnsubmittedProperties(boolean validateUnsubmittedProperties) {
this.validateUnsubmittedProperties = validateUnsubmittedProperties;
}
}
| admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/domain/PersistencePackageRequest.java | /*
* Copyright 2008-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.broadleafcommerce.openadmin.server.domain;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.broadleafcommerce.common.presentation.client.PersistencePerspectiveItemType;
import org.broadleafcommerce.openadmin.dto.AdornedTargetCollectionMetadata;
import org.broadleafcommerce.openadmin.dto.AdornedTargetList;
import org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata;
import org.broadleafcommerce.openadmin.dto.BasicFieldMetadata;
import org.broadleafcommerce.openadmin.dto.CollectionMetadata;
import org.broadleafcommerce.openadmin.dto.Entity;
import org.broadleafcommerce.openadmin.dto.FieldMetadata;
import org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria;
import org.broadleafcommerce.openadmin.dto.ForeignKey;
import org.broadleafcommerce.openadmin.dto.MapMetadata;
import org.broadleafcommerce.openadmin.dto.MapStructure;
import org.broadleafcommerce.openadmin.dto.OperationTypes;
import org.broadleafcommerce.openadmin.dto.visitor.MetadataVisitor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A DTO class used to seed a persistence package.
*
* @author Andre Azzolini (apazzolini)
*/
public class PersistencePackageRequest {
protected Type type;
protected String ceilingEntityClassname;
protected String configKey;
protected AdornedTargetList adornedList;
protected MapStructure mapStructure;
protected Entity entity;
protected ForeignKey foreignKey;
protected Integer startIndex;
protected Integer maxIndex;
protected Map<String, PersistencePackageRequest> subRequests = new LinkedHashMap<String, PersistencePackageRequest>();
protected boolean validateUnsubmittedProperties = true;
protected OperationTypes operationTypesOverride = null;
// These properties are accessed via getters and setters that operate on arrays.
// We back them with a list so that we can have the convenience .add methods
protected List<ForeignKey> additionalForeignKeys = new ArrayList<ForeignKey>();
protected List<String> customCriteria = new ArrayList<String>();
protected List<FilterAndSortCriteria> filterAndSortCriteria = new ArrayList<FilterAndSortCriteria>();
public enum Type {
STANDARD,
ADORNED,
MAP
}
/* ******************* */
/* STATIC INITIALIZERS */
/* ******************* */
public static PersistencePackageRequest standard() {
return new PersistencePackageRequest(Type.STANDARD);
}
public static PersistencePackageRequest adorned() {
return new PersistencePackageRequest(Type.ADORNED);
}
public static PersistencePackageRequest map() {
return new PersistencePackageRequest(Type.MAP);
}
/**
* Creates a semi-populate PersistencePacakageRequest based on the specified FieldMetadata. This initializer
* will copy over persistence perspective items from the metadata as well as set the appropriate OperationTypes
* as specified in the annotation/xml configuration for the field.
*
* @param md
* @return the newly created PersistencePackageRequest
*/
public static PersistencePackageRequest fromMetadata(FieldMetadata md) {
final PersistencePackageRequest request = new PersistencePackageRequest();
md.accept(new MetadataVisitor() {
@Override
public void visit(BasicFieldMetadata fmd) {
request.setType(Type.STANDARD);
request.setCeilingEntityClassname(fmd.getForeignKeyClass());
}
@Override
public void visit(BasicCollectionMetadata fmd) {
ForeignKey foreignKey = (ForeignKey) fmd.getPersistencePerspective()
.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
request.setType(Type.STANDARD);
request.setCeilingEntityClassname(fmd.getCollectionCeilingEntity());
request.setOperationTypesOverride(fmd.getPersistencePerspective().getOperationTypes());
request.setForeignKey(foreignKey);
}
@Override
public void visit(AdornedTargetCollectionMetadata fmd) {
AdornedTargetList adornedList = (AdornedTargetList) fmd.getPersistencePerspective()
.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST);
request.setType(Type.ADORNED);
request.setCeilingEntityClassname(fmd.getCollectionCeilingEntity());
request.setOperationTypesOverride(fmd.getPersistencePerspective().getOperationTypes());
request.setAdornedList(adornedList);
}
@Override
public void visit(MapMetadata fmd) {
MapStructure mapStructure = (MapStructure) fmd.getPersistencePerspective()
.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE);
ForeignKey foreignKey = (ForeignKey) fmd.getPersistencePerspective().
getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
request.setType(Type.MAP);
request.setCeilingEntityClassname(foreignKey.getForeignKeyClass());
request.setOperationTypesOverride(fmd.getPersistencePerspective().getOperationTypes());
request.setMapStructure(mapStructure);
request.setForeignKey(foreignKey);
}
});
if (md instanceof CollectionMetadata) {
request.setCustomCriteria(((CollectionMetadata) md).getCustomCriteria());
}
return request;
}
/* ************ */
/* CONSTRUCTORS */
/* ************ */
public PersistencePackageRequest() {
}
public PersistencePackageRequest(Type type) {
this.type = type;
}
/* ************ */
/* WITH METHODS */
/* ************ */
public PersistencePackageRequest withType(Type type) {
setType(type);
return this;
}
public PersistencePackageRequest withCeilingEntityClassname(String className) {
setCeilingEntityClassname(className);
return this;
}
public PersistencePackageRequest withForeignKey(ForeignKey foreignKey) {
setForeignKey(foreignKey);
return this;
}
public PersistencePackageRequest withConfigKey(String configKey) {
setConfigKey(configKey);
return this;
}
public PersistencePackageRequest withFilterAndSortCriteria(FilterAndSortCriteria[] filterAndSortCriteria) {
if (ArrayUtils.isNotEmpty(filterAndSortCriteria)) {
setFilterAndSortCriteria(filterAndSortCriteria);
}
return this;
}
public PersistencePackageRequest withAdornedList(AdornedTargetList adornedList) {
setAdornedList(adornedList);
return this;
}
public PersistencePackageRequest withMapStructure(MapStructure mapStructure) {
setMapStructure(mapStructure);
return this;
}
public PersistencePackageRequest withCustomCriteria(String[] customCriteria) {
if (ArrayUtils.isNotEmpty(customCriteria)) {
setCustomCriteria(customCriteria);
}
return this;
}
public PersistencePackageRequest withEntity(Entity entity) {
setEntity(entity);
return this;
}
public PersistencePackageRequest withStartIndex(Integer startIndex) {
setStartIndex(startIndex);
return this;
}
public PersistencePackageRequest withMaxIndex(Integer maxIndex) {
setMaxIndex(maxIndex);
return this;
}
/* *********** */
/* ADD METHODS */
/* *********** */
public PersistencePackageRequest addAdditionalForeignKey(ForeignKey foreignKey) {
additionalForeignKeys.add(foreignKey);
return this;
}
public PersistencePackageRequest addSubRequest(String infoPropertyName, PersistencePackageRequest subRequest) {
subRequests.put(infoPropertyName, subRequest);
return this;
}
public PersistencePackageRequest addCustomCriteria(String customCriteria) {
if (StringUtils.isNotBlank(customCriteria)) {
this.customCriteria.add(customCriteria);
}
return this;
}
public PersistencePackageRequest addFilterAndSortCriteria(FilterAndSortCriteria filterAndSortCriteria) {
this.filterAndSortCriteria.add(filterAndSortCriteria);
return this;
}
public PersistencePackageRequest addFilterAndSortCriteria(FilterAndSortCriteria[] filterAndSortCriteria) {
if (filterAndSortCriteria != null) {
this.filterAndSortCriteria.addAll(Arrays.asList(filterAndSortCriteria));
}
return this;
}
public PersistencePackageRequest addFilterAndSortCriteria(List<FilterAndSortCriteria> filterAndSortCriteria) {
this.filterAndSortCriteria.addAll(filterAndSortCriteria);
return this;
}
/* ************************ */
/* CUSTOM GETTERS / SETTERS */
/* ************************ */
public String[] getCustomCriteria() {
String[] arr = new String[this.customCriteria.size()];
arr = this.customCriteria.toArray(arr);
return arr;
}
public ForeignKey[] getAdditionalForeignKeys() {
ForeignKey[] arr = new ForeignKey[this.additionalForeignKeys.size()];
arr = this.additionalForeignKeys.toArray(arr);
return arr;
}
public void setAdditionalForeignKeys(ForeignKey[] additionalForeignKeys) {
this.additionalForeignKeys = Arrays.asList(additionalForeignKeys);
}
public void setCustomCriteria(String[] customCriteria) {
this.customCriteria = Arrays.asList(customCriteria);
}
public FilterAndSortCriteria[] getFilterAndSortCriteria() {
FilterAndSortCriteria[] arr = new FilterAndSortCriteria[this.filterAndSortCriteria.size()];
arr = this.filterAndSortCriteria.toArray(arr);
return arr;
}
public void setFilterAndSortCriteria(FilterAndSortCriteria[] filterAndSortCriteria) {
this.filterAndSortCriteria.addAll(Arrays.asList(filterAndSortCriteria));
}
/* ************************** */
/* STANDARD GETTERS / SETTERS */
/* ************************** */
public ForeignKey getForeignKey() {
return foreignKey;
}
public void setForeignKey(ForeignKey foreignKey) {
this.foreignKey = foreignKey;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getCeilingEntityClassname() {
return ceilingEntityClassname;
}
public void setCeilingEntityClassname(String ceilingEntityClassname) {
this.ceilingEntityClassname = ceilingEntityClassname;
}
public String getConfigKey() {
return configKey;
}
public void setConfigKey(String configKey) {
this.configKey = configKey;
}
public AdornedTargetList getAdornedList() {
return adornedList;
}
public void setAdornedList(AdornedTargetList adornedList) {
this.adornedList = adornedList;
}
public MapStructure getMapStructure() {
return mapStructure;
}
public void setMapStructure(MapStructure mapStructure) {
this.mapStructure = mapStructure;
}
public Entity getEntity() {
return entity;
}
public void setEntity(Entity entity) {
this.entity = entity;
}
public OperationTypes getOperationTypesOverride() {
return operationTypesOverride;
}
public void setOperationTypesOverride(OperationTypes operationTypesOverride) {
this.operationTypesOverride = operationTypesOverride;
}
public Integer getStartIndex() {
return startIndex;
}
public void setStartIndex(Integer startIndex) {
this.startIndex = startIndex;
}
public Integer getMaxIndex() {
return maxIndex;
}
public void setMaxIndex(Integer maxIndex) {
this.maxIndex = maxIndex;
}
public Map<String, PersistencePackageRequest> getSubRequests() {
return subRequests;
}
public void setSubRequests(Map<String, PersistencePackageRequest> subRequests) {
this.subRequests = subRequests;
}
public boolean isValidateUnsubmittedProperties() {
return validateUnsubmittedProperties;
}
public void setValidateUnsubmittedProperties(boolean validateUnsubmittedProperties) {
this.validateUnsubmittedProperties = validateUnsubmittedProperties;
}
}
| #792 #793 - pre-populate persistence package request with any custom criteria and make sure that the collections aren't fixed-sized
| admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/domain/PersistencePackageRequest.java | #792 #793 - pre-populate persistence package request with any custom criteria and make sure that the collections aren't fixed-sized |
|
Java | apache-2.0 | a7f221725f6ac8c44ac641c1790d4268e7c0256b | 0 | Distrotech/intellij-community,diorcety/intellij-community,supersven/intellij-community,xfournet/intellij-community,diorcety/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,asedunov/intellij-community,adedayo/intellij-community,kdwink/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ibinti/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,supersven/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,petteyg/intellij-community,hurricup/intellij-community,semonte/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,lucafavatella/intellij-community,caot/intellij-community,semonte/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,wreckJ/intellij-community,kool79/intellij-community,adedayo/intellij-community,fitermay/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,jexp/idea2,izonder/intellij-community,semonte/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,samthor/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,diorcety/intellij-community,FHannes/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,vladmm/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,xfournet/intellij-community,FHannes/intellij-community,fnouama/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,izonder/intellij-community,samthor/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,vvv1559/intellij-community,slisson/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,supersven/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,samthor/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,da1z/intellij-community,xfournet/intellij-community,semonte/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,samthor/intellij-community,da1z/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,signed/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,izonder/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,orekyuu/intellij-community,supersven/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,vladmm/intellij-community,diorcety/intellij-community,clumsy/intellij-community,fnouama/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,holmes/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,signed/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,signed/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ibinti/intellij-community,consulo/consulo,Lekanich/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,ernestp/consulo,apixandru/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,hurricup/intellij-community,consulo/consulo,fnouama/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,fitermay/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,caot/intellij-community,slisson/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,signed/intellij-community,supersven/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,vladmm/intellij-community,FHannes/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,hurricup/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,apixandru/intellij-community,jexp/idea2,robovm/robovm-studio,mglukhikh/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,supersven/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ernestp/consulo,jagguli/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,da1z/intellij-community,caot/intellij-community,asedunov/intellij-community,robovm/robovm-studio,kdwink/intellij-community,dslomov/intellij-community,hurricup/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,joewalnes/idea-community,pwoodworth/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,orekyuu/intellij-community,izonder/intellij-community,ernestp/consulo,FHannes/intellij-community,joewalnes/idea-community,izonder/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,semonte/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,allotria/intellij-community,wreckJ/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,jexp/idea2,pwoodworth/intellij-community,adedayo/intellij-community,asedunov/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,jagguli/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,fnouama/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,ahb0327/intellij-community,kool79/intellij-community,holmes/intellij-community,retomerz/intellij-community,samthor/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,fitermay/intellij-community,diorcety/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,amith01994/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,apixandru/intellij-community,petteyg/intellij-community,izonder/intellij-community,clumsy/intellij-community,slisson/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,vvv1559/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,blademainer/intellij-community,caot/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,semonte/intellij-community,signed/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,ryano144/intellij-community,robovm/robovm-studio,asedunov/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,vladmm/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,fnouama/intellij-community,clumsy/intellij-community,asedunov/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,consulo/consulo,Distrotech/intellij-community,petteyg/intellij-community,caot/intellij-community,adedayo/intellij-community,robovm/robovm-studio,kool79/intellij-community,ibinti/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,holmes/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,caot/intellij-community,holmes/intellij-community,clumsy/intellij-community,petteyg/intellij-community,xfournet/intellij-community,caot/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,supersven/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,semonte/intellij-community,caot/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,signed/intellij-community,apixandru/intellij-community,allotria/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,holmes/intellij-community,consulo/consulo,ahb0327/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,jagguli/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,kool79/intellij-community,Distrotech/intellij-community,semonte/intellij-community,suncycheng/intellij-community,consulo/consulo,youdonghai/intellij-community,kdwink/intellij-community,jexp/idea2,consulo/consulo,signed/intellij-community,kdwink/intellij-community,slisson/intellij-community,ahb0327/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,adedayo/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,slisson/intellij-community,petteyg/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,samthor/intellij-community,supersven/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,asedunov/intellij-community,holmes/intellij-community,kdwink/intellij-community,retomerz/intellij-community,allotria/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,amith01994/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,nicolargo/intellij-community,holmes/intellij-community,ryano144/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,kdwink/intellij-community,retomerz/intellij-community,clumsy/intellij-community,jagguli/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,supersven/intellij-community,holmes/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,izonder/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,allotria/intellij-community,joewalnes/idea-community,robovm/robovm-studio,amith01994/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,robovm/robovm-studio,robovm/robovm-studio,kool79/intellij-community,signed/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,tmpgit/intellij-community,da1z/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,samthor/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,jexp/idea2,vladmm/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,diorcety/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,izonder/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,holmes/intellij-community,semonte/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ibinti/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,joewalnes/idea-community,slisson/intellij-community,izonder/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,caot/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,samthor/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,jexp/idea2,da1z/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,clumsy/intellij-community,diorcety/intellij-community,adedayo/intellij-community,jexp/idea2,alphafoobar/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community | package com.intellij.ui.content.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.UIBundle;
import com.intellij.ui.components.panels.Wrapper;
import com.intellij.ui.content.*;
import com.intellij.util.ui.UIUtil;
import com.intellij.peer.PeerFactory;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.EventListenerList;
import java.awt.*;
import java.awt.event.FocusListener;
import java.awt.event.FocusEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public class ContentManagerImpl implements ContentManager, PropertyChangeListener {
private static final Logger LOG = Logger.getInstance("#com.intellij.ui.content.impl.ContentManagerImpl");
private ContentUI myUI;
private ArrayList<Content> myContents;
private EventListenerList myListeners;
private List<Content> mySelection = new ArrayList<Content>();
private boolean myCanCloseContents;
private final Project myProject;
private final ProjectManagerAdapter myProjectManagerListener;
private boolean myListenerAdded;
private MyComponent myComponent = new MyComponent();
private Set<Content> myContentWithChangedComponent = new HashSet<Content>();
/**
* WARNING: as this class adds listener to the ProjectManager which is removed on projectClosed event, all instances of this class
* must be created on already OPENED projects, otherwise there will be memory leak!
*/
public ContentManagerImpl(ContentUI contentUI, boolean canCloseContents, Project project) {
myCanCloseContents = canCloseContents;
myContents = new ArrayList<Content>();
myListeners = new EventListenerList();
myUI = contentUI;
myUI.setManager(this);
myProject = project;
myProjectManagerListener = new ProjectManagerAdapter() {
public void projectClosed(Project project) {
if (project == myProject) {
Content[] contents = myContents.toArray(new Content[myContents.size()]);
for (Content content : contents) {
removeContent(content, false);
}
}
}
};
}
public boolean canCloseContents() {
return myCanCloseContents;
}
public JComponent getComponent() {
if (myComponent.getComponentCount() == 0) {
myComponent.setContent(myUI.getComponent());
}
return myComponent;
}
private class MyComponent extends Wrapper.FocusHolder implements DataProvider {
private List<DataProvider> myProviders = new ArrayList<DataProvider>();
public MyComponent() {
setOpaque(false);
}
public void addProvider(final DataProvider provider) {
myProviders.add(provider);
}
@Nullable
public Object getData(@NonNls final String dataId) {
for (DataProvider each : myProviders) {
final Object data = each.getData(dataId);
if (data != null) return data;
}
return null;
}
}
public void addContent(Content content) {
addContent(content, null);
}
public void addContent(final Content content, final Object constraints) {
try {
((ContentImpl)content).setManager(this);
myContents.add(content);
content.addPropertyChangeListener(this);
fireContentAdded(content, myContents.size() - 1);
if (myUI.isToSelectAddedContent() || mySelection.size() == 0) {
if (myUI.isSingleSelection()) {
setSelectedContent(content);
} else {
addSelectedContent(content);
}
}
} finally {
addProjectManagerListener();
}
}
public boolean removeContent(Content content) {
return removeContent(content, true);
}
private boolean removeContent(final Content content, boolean trackSelection) {
try {
int selectedIndex = myContents.indexOf(mySelection);
int indexToBeRemoved = myContents.indexOf(content);
if (indexToBeRemoved < 0) {
return false;
}
if (!fireContentRemoveQuery(content, indexToBeRemoved)) {
return false;
}
if (!content.isValid()) {
return false; // the content has already been invalidated by another thread or something
}
boolean wasSelected = isSelected(content);
if (wasSelected) {
removeSelectedContent(content);
}
int indexToSelect = -1;
if (wasSelected) {
int i = indexToBeRemoved - 1;
if (i >= 0) {
indexToSelect = i;
}
else if (getContentCount() > 1) {
indexToSelect = 0;
}
}
else if (selectedIndex > indexToBeRemoved) {
indexToSelect = selectedIndex - 1;
}
myContents.remove(content);
content.removePropertyChangeListener(this);
int newSize = myContents.size();
if (newSize > 0 && trackSelection) {
if (indexToSelect > -1) {
final Content toSelect = myContents.get(indexToSelect);
if (!isSelected(toSelect)) {
if (myUI.isSingleSelection()) {
setSelectedContent(toSelect);
} else {
addSelectedContent(toSelect);
}
}
}
}
else {
mySelection.clear();
}
fireContentRemoved(content, indexToBeRemoved);
((ContentImpl)content).setManager(null);
final Disposable disposer = content.getDisposer();
if (disposer != null) {
Disposer.dispose(disposer);
}
return true;
} finally {
removeProjectManagerListener();
}
}
private void addProjectManagerListener() {
if (!myListenerAdded && myContents.size() > 0) {
ProjectManager.getInstance().addProjectManagerListener(myProjectManagerListener);
myListenerAdded = true;
}
}
private void removeProjectManagerListener() {
if (myContents.size() == 0) {
if (ApplicationManager.getApplication().isDispatchThread()) {
myUI.getComponent().updateUI(); //cleanup visibleComponent from Alloy...TabbedPaneUI
}
if (myListenerAdded) {
ProjectManager.getInstance().removeProjectManagerListener(myProjectManagerListener);
myListenerAdded = false;
}
}
}
public void removeAllContents() {
Content[] contents = getContents();
for (Content content : contents) {
removeContent(content);
}
}
public int getContentCount() {
return myContents.size();
}
public Content[] getContents() {
return myContents.toArray(new ContentImpl[myContents.size()]);
}
//TODO[anton,vova] is this method needed?
public Content findContent(String displayName) {
for (Content content : myContents) {
if (content.getDisplayName().equals(displayName)) {
return content;
}
}
return null;
}
public Content getContent(int index) {
if (index >= 0 && index < myContents.size()) {
return myContents.get(index);
} else {
return null;
}
}
public Content getContent(JComponent component) {
Content[] contents = getContents();
for (Content content : contents) {
if (Comparing.equal(component, content.getComponent())) {
return content;
}
}
return null;
}
public int getIndexOfContent(Content content) {
return myContents.indexOf(content);
}
public String getCloseActionName() {
return UIBundle.message("tabbed.pane.close.tab.action.name");
}
public String getCloseAllButThisActionName() {
return UIBundle.message("tabbed.pane.close.all.tabs.but.this.action.name");
}
public List<AnAction> getAdditionalPopupActions(final Content content) {
return null;
}
public boolean canCloseAllContents() {
if (!canCloseContents()) {
return false;
}
for(Content content: myContents) {
if (content.isCloseable()) {
return true;
}
}
return false;
}
public void addSelectedContent(final Content content) {
if (!checkSelectionChangeShouldBeProcessed(content)) return;
int index;
if (content != null) {
index = getIndexOfContent(content);
if (index == -1) {
throw new IllegalArgumentException("content not found: " + content);
}
}
else {
index = -1;
}
if (!isSelected(content)) {
mySelection.add(content);
fireSelectionChanged(content);
}
}
private boolean checkSelectionChangeShouldBeProcessed(Content content) {
final boolean result = !isSelected(content) || myContentWithChangedComponent.contains(content);
myContentWithChangedComponent.remove(content);
return result;
}
public void removeSelectedContent(Content content) {
if (!isSelected(content)) return;
mySelection.remove(content);
fireSelectionChanged(content);
}
public boolean isSelected(Content content) {
return mySelection.contains(content);
}
public Content[] getSelectedContents() {
return mySelection.toArray(new Content[mySelection.size()]);
}
@Nullable
public Content getSelectedContent() {
return mySelection.size() > 0 ? mySelection.get(0) : null;
}
public void setSelectedContent(final Content content, final boolean requestFocus) {
if (!checkSelectionChangeShouldBeProcessed(content)) return;
if (!myContents.contains(content)) {
throw new IllegalArgumentException("Cannot find content:" + content.getDisplayName());
}
final boolean focused = isSelectionHoldsFocus();
final Content[] old = getSelectedContents();
Runnable selection = new Runnable() {
public void run() {
if (getIndexOfContent(content) == -1) return;
for (Content each : old) {
removeSelectedContent(each);
mySelection.clear();
}
addSelectedContent(content);
requestFocus(content);
}
};
if (focused || requestFocus) {
myComponent.requestFocus(selection);
} else {
selection.run();
}
}
private boolean isSelectionHoldsFocus() {
boolean focused = false;
final Content[] selection = getSelectedContents();
for (Content each : selection) {
if (UIUtil.isFocusAncestor(each.getComponent())) {
focused = true;
break;
}
}
return focused;
}
public void setSelectedContent(final Content content) {
setSelectedContent(content, false);
}
public void selectPreviousContent() {
int contentCount = getContentCount();
LOG.assertTrue(contentCount > 1);
Content selectedContent = getSelectedContent();
int index = getIndexOfContent(selectedContent);
index = (index - 1 + contentCount) % contentCount;
setSelectedContent(getContent(index));
}
public void selectNextContent() {
int contentCount = getContentCount();
LOG.assertTrue(contentCount > 1);
Content selectedContent = getSelectedContent();
int index = getIndexOfContent(selectedContent);
index = (index + 1) % contentCount;
setSelectedContent(getContent(index));
}
public void addContentManagerListener(ContentManagerListener l) {
myListeners.add(ContentManagerListener.class, l);
}
public void removeContentManagerListener(ContentManagerListener l) {
myListeners.remove(ContentManagerListener.class, l);
}
protected void fireContentAdded(Content content, int newIndex) {
ContentManagerEvent event = new ContentManagerEvent(this, content, newIndex);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.contentAdded(event);
}
}
protected void fireContentRemoved(Content content, int oldIndex) {
ContentManagerEvent event = new ContentManagerEvent(this, content, oldIndex);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.contentRemoved(event);
}
}
protected void fireSelectionChanged(Content content) {
ContentManagerEvent event = new ContentManagerEvent(this, content, myContents.indexOf(content));
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.selectionChanged(event);
}
}
protected boolean fireContentRemoveQuery(Content content, int oldIndex) {
ContentManagerEvent event = new ContentManagerEvent(this, content, oldIndex);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.contentRemoveQuery(event);
if (event.isConsumed()) {
return false;
}
}
return true;
}
public void requestFocus(Content content) {
Content toSelect = content == null ? getSelectedContent() : content;
if (toSelect == null) return;
assert myContents.contains(toSelect);
JComponent toFocus = toSelect.getPreferredFocusableComponent();
toFocus = IdeFocusTraversalPolicy.getPreferredFocusedComponent(toFocus);
if (toFocus != null) {
toFocus.requestFocus();
}
}
public void addDataProvider(final DataProvider provider) {
myComponent.addProvider(provider);
}
public void propertyChange(final PropertyChangeEvent evt) {
if (Content.PROP_COMPONENT.equals(evt.getPropertyName())) {
myContentWithChangedComponent.add((Content)evt.getSource());
}
}
public ContentFactory getFactory() {
return PeerFactory.getInstance().getContentFactory();
}
}
| ui/impl/com/intellij/ui/content/impl/ContentManagerImpl.java | package com.intellij.ui.content.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.UIBundle;
import com.intellij.ui.components.panels.Wrapper;
import com.intellij.ui.content.*;
import com.intellij.util.ui.UIUtil;
import com.intellij.peer.PeerFactory;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.EventListenerList;
import java.awt.*;
import java.awt.event.FocusListener;
import java.awt.event.FocusEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public class ContentManagerImpl implements ContentManager, PropertyChangeListener {
private static final Logger LOG = Logger.getInstance("#com.intellij.ui.content.impl.ContentManagerImpl");
private ContentUI myUI;
private ArrayList<Content> myContents;
private EventListenerList myListeners;
private List<Content> mySelection = new ArrayList<Content>();
private boolean myCanCloseContents;
private final Project myProject;
private final ProjectManagerAdapter myProjectManagerListener;
private boolean myListenerAdded;
private MyComponent myComponent = new MyComponent();
private Set<Content> myContentWithChangedComponent = new HashSet<Content>();
/**
* WARNING: as this class adds listener to the ProjectManager which is removed on projectClosed event, all instances of this class
* must be created on already OPENED projects, otherwise there will be memory leak!
*/
public ContentManagerImpl(ContentUI contentUI, boolean canCloseContents, Project project) {
myCanCloseContents = canCloseContents;
myContents = new ArrayList<Content>();
myListeners = new EventListenerList();
myUI = contentUI;
myUI.setManager(this);
myProject = project;
myProjectManagerListener = new ProjectManagerAdapter() {
public void projectClosed(Project project) {
if (project == myProject) {
Content[] contents = myContents.toArray(new Content[myContents.size()]);
for (Content content : contents) {
removeContent(content, false);
}
}
}
};
}
public boolean canCloseContents() {
return myCanCloseContents;
}
public JComponent getComponent() {
if (myComponent.getComponentCount() == 0) {
myComponent.setContent(myUI.getComponent());
}
return myComponent;
}
private class MyComponent extends Wrapper.FocusHolder implements DataProvider {
private List<DataProvider> myProviders = new ArrayList<DataProvider>();
public MyComponent() {
setOpaque(false);
}
public void addProvider(final DataProvider provider) {
myProviders.add(provider);
}
@Nullable
public Object getData(@NonNls final String dataId) {
for (DataProvider each : myProviders) {
final Object data = each.getData(dataId);
if (data != null) return data;
}
return null;
}
}
public void addContent(Content content) {
addContent(content, null);
}
public void addContent(final Content content, final Object constraints) {
try {
((ContentImpl)content).setManager(this);
myContents.add(content);
content.addPropertyChangeListener(this);
fireContentAdded(content, myContents.size() - 1);
if (myUI.isToSelectAddedContent() || mySelection.size() == 0) {
if (myUI.isSingleSelection()) {
setSelectedContent(content);
} else {
addSelectedContent(content);
}
}
} finally {
addProjectManagerListener();
}
}
public boolean removeContent(Content content) {
return removeContent(content, true);
}
private boolean removeContent(final Content content, boolean trackSelection) {
try {
int selectedIndex = myContents.indexOf(mySelection);
int indexToBeRemoved = myContents.indexOf(content);
if (indexToBeRemoved < 0) {
return false;
}
if (!fireContentRemoveQuery(content, indexToBeRemoved)) {
return false;
}
if (!content.isValid()) {
return false; // the content has already been invalidated by another thread or something
}
boolean wasSelected = isSelected(content);
if (wasSelected) {
removeSelectedContent(content);
}
int indexToSelect = -1;
if (wasSelected) {
int i = indexToBeRemoved - 1;
if (i >= 0) {
indexToSelect = i;
}
else if (getContentCount() > 1) {
indexToSelect = 0;
}
}
else if (selectedIndex > indexToBeRemoved) {
indexToSelect = selectedIndex - 1;
}
myContents.remove(content);
content.removePropertyChangeListener(this);
int newSize = myContents.size();
if (newSize > 0 && trackSelection) {
if (indexToSelect > -1) {
final Content toSelect = myContents.get(indexToSelect);
if (!isSelected(toSelect)) {
if (myUI.isSingleSelection()) {
setSelectedContent(toSelect);
} else {
addSelectedContent(toSelect);
}
}
}
}
else {
mySelection.clear();
}
fireContentRemoved(content, indexToBeRemoved);
((ContentImpl)content).setManager(null);
final Disposable disposer = content.getDisposer();
if (disposer != null) {
Disposer.dispose(disposer);
}
return true;
} finally {
removeProjectManagerListener();
}
}
private void addProjectManagerListener() {
if (!myListenerAdded && myContents.size() > 0) {
ProjectManager.getInstance().addProjectManagerListener(myProjectManagerListener);
myListenerAdded = true;
}
}
private void removeProjectManagerListener() {
if (myContents.size() == 0) {
if (ApplicationManager.getApplication().isDispatchThread()) {
myUI.getComponent().updateUI(); //cleanup visibleComponent from Alloy...TabbedPaneUI
}
if (myListenerAdded) {
ProjectManager.getInstance().removeProjectManagerListener(myProjectManagerListener);
myListenerAdded = false;
}
}
}
public void removeAllContents() {
Content[] contents = getContents();
for (Content content : contents) {
removeContent(content);
}
}
public int getContentCount() {
return myContents.size();
}
public Content[] getContents() {
return myContents.toArray(new ContentImpl[myContents.size()]);
}
//TODO[anton,vova] is this method needed?
public Content findContent(String displayName) {
for (Content content : myContents) {
if (content.getDisplayName().equals(displayName)) {
return content;
}
}
return null;
}
public Content getContent(int index) {
if (index >= 0 && index < myContents.size()) {
return myContents.get(index);
} else {
return null;
}
}
public Content getContent(JComponent component) {
Content[] contents = getContents();
for (Content content : contents) {
if (Comparing.equal(component, content.getComponent())) {
return content;
}
}
return null;
}
public int getIndexOfContent(Content content) {
return myContents.indexOf(content);
}
public String getCloseActionName() {
return UIBundle.message("tabbed.pane.close.tab.action.name");
}
public String getCloseAllButThisActionName() {
return UIBundle.message("tabbed.pane.close.all.tabs.but.this.action.name");
}
public List<AnAction> getAdditionalPopupActions(final Content content) {
return null;
}
public boolean canCloseAllContents() {
if (!canCloseContents()) {
return false;
}
for(Content content: myContents) {
if (content.isCloseable()) {
return true;
}
}
return false;
}
public void addSelectedContent(final Content content) {
if (!checkSelectionChangeShouldBeProcessed(content)) return;
int index;
if (content != null) {
index = getIndexOfContent(content);
if (index == -1) {
throw new IllegalArgumentException("content not found: " + content);
}
}
else {
index = -1;
}
if (!isSelected(content)) {
mySelection.add(content);
fireSelectionChanged(content);
}
}
private boolean checkSelectionChangeShouldBeProcessed(Content content) {
final boolean result = !isSelected(content) || myContentWithChangedComponent.contains(content);
myContentWithChangedComponent.remove(content);
return result;
}
public void removeSelectedContent(Content content) {
if (!isSelected(content)) return;
mySelection.remove(content);
fireSelectionChanged(content);
}
public boolean isSelected(Content content) {
return mySelection.contains(content);
}
public Content[] getSelectedContents() {
return mySelection.toArray(new Content[mySelection.size()]);
}
@Nullable
public Content getSelectedContent() {
return mySelection.size() > 0 ? mySelection.get(0) : null;
}
public void setSelectedContent(final Content content, final boolean requestFocus) {
if (!checkSelectionChangeShouldBeProcessed(content)) return;
if (!myContents.contains(content)) {
throw new IllegalArgumentException("Cannot find content:" + content.getDisplayName());
}
final boolean focused = isSelectionHoldsFocus();
final Content[] old = getSelectedContents();
Runnable selection = new Runnable() {
public void run() {
for (Content each : old) {
removeSelectedContent(each);
mySelection.clear();
}
addSelectedContent(content);
requestFocus(content);
}
};
if (focused || requestFocus) {
myComponent.requestFocus(selection);
} else {
selection.run();
}
}
private boolean isSelectionHoldsFocus() {
boolean focused = false;
final Content[] selection = getSelectedContents();
for (Content each : selection) {
if (UIUtil.isFocusAncestor(each.getComponent())) {
focused = true;
break;
}
}
return focused;
}
public void setSelectedContent(final Content content) {
setSelectedContent(content, false);
}
public void selectPreviousContent() {
int contentCount = getContentCount();
LOG.assertTrue(contentCount > 1);
Content selectedContent = getSelectedContent();
int index = getIndexOfContent(selectedContent);
index = (index - 1 + contentCount) % contentCount;
setSelectedContent(getContent(index));
}
public void selectNextContent() {
int contentCount = getContentCount();
LOG.assertTrue(contentCount > 1);
Content selectedContent = getSelectedContent();
int index = getIndexOfContent(selectedContent);
index = (index + 1) % contentCount;
setSelectedContent(getContent(index));
}
public void addContentManagerListener(ContentManagerListener l) {
myListeners.add(ContentManagerListener.class, l);
}
public void removeContentManagerListener(ContentManagerListener l) {
myListeners.remove(ContentManagerListener.class, l);
}
protected void fireContentAdded(Content content, int newIndex) {
ContentManagerEvent event = new ContentManagerEvent(this, content, newIndex);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.contentAdded(event);
}
}
protected void fireContentRemoved(Content content, int oldIndex) {
ContentManagerEvent event = new ContentManagerEvent(this, content, oldIndex);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.contentRemoved(event);
}
}
protected void fireSelectionChanged(Content content) {
ContentManagerEvent event = new ContentManagerEvent(this, content, myContents.indexOf(content));
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.selectionChanged(event);
}
}
protected boolean fireContentRemoveQuery(Content content, int oldIndex) {
ContentManagerEvent event = new ContentManagerEvent(this, content, oldIndex);
ContentManagerListener[] listeners = myListeners.getListeners(ContentManagerListener.class);
for (ContentManagerListener listener : listeners) {
listener.contentRemoveQuery(event);
if (event.isConsumed()) {
return false;
}
}
return true;
}
public void requestFocus(Content content) {
Content toSelect = content == null ? getSelectedContent() : content;
if (toSelect == null) return;
assert myContents.contains(toSelect);
JComponent toFocus = toSelect.getPreferredFocusableComponent();
toFocus = IdeFocusTraversalPolicy.getPreferredFocusedComponent(toFocus);
if (toFocus != null) {
toFocus.requestFocus();
}
}
public void addDataProvider(final DataProvider provider) {
myComponent.addProvider(provider);
}
public void propertyChange(final PropertyChangeEvent evt) {
if (Content.PROP_COMPONENT.equals(evt.getPropertyName())) {
myContentWithChangedComponent.add((Content)evt.getSource());
}
}
public ContentFactory getFactory() {
return PeerFactory.getInstance().getContentFactory();
}
}
| IDEADEV-17132 - selection of removed content
| ui/impl/com/intellij/ui/content/impl/ContentManagerImpl.java | IDEADEV-17132 - selection of removed content |
|
Java | apache-2.0 | error: pathspec 'src/org/LiHuaBot/ab/Main.java' did not match any file(s) known to git
| 43192aad453926aa47955eefb3190b0d47337330 | 1 | maitian13/LiHuaBot | package org.LiHuaBot.ab;
/**
* Created by maitian13 on 2016/1/31.
*/
public class Main {
public static void main(String args[]){
System.out.println("hello world!");
}
}
| src/org/LiHuaBot/ab/Main.java | Main Class
| src/org/LiHuaBot/ab/Main.java | Main Class |
|
Java | apache-2.0 | error: pathspec 'src/main/java/al/musi/osoba/Person.java' did not match any file(s) known to git
| 39d5666cb96ed16967004a6d0b4c414978797a3d | 1 | 912d/bug-free-couscous | package al.musi.entity;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
private LocalDateTime createdDate;
private LocalDateTime modifiedDate;
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public LocalDateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(LocalDateTime createdDate) {
this.createdDate = createdDate;
}
public LocalDateTime getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(LocalDateTime modifiedDate) {
this.modifiedDate = modifiedDate;
}
@Override
public String toString() {
return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", dateOfBirth="
+ dateOfBirth + ", createdDate=" + createdDate + ", modifiedDate=" + modifiedDate + "]";
}
}
| src/main/java/al/musi/osoba/Person.java | added osoba (entity) folder w/ person class
| src/main/java/al/musi/osoba/Person.java | added osoba (entity) folder w/ person class |
|
Java | apache-2.0 | error: pathspec 'src/main/java/br/edu/utfpr/dao/EMF.java' did not match any file(s) known to git
| 8e98734120bb0bfb2fd2c5ef35d7b67467a9221d | 1 | rafaelMarcari/ControleAcesso,rafaelMarcari/ControleAcesso | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.edu.utfpr.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* @author Rafael
*
*/
public class EMF {
private static EMF instance = null;
private static EntityManagerFactory factory = null;
private EMF() {}
public static EMF getInstance() {
if(instance==null) {
instance = new EMF();
}
return instance;
}
public EntityManager createEntityManager(){
if(factory==null) {
factory = Persistence.createEntityManagerFactory("default");
}
return factory.createEntityManager();
}
}
| src/main/java/br/edu/utfpr/dao/EMF.java | Criado a classe de conexão com a base de dados
| src/main/java/br/edu/utfpr/dao/EMF.java | Criado a classe de conexão com a base de dados |
|
Java | apache-2.0 | error: pathspec 'krati-main/src/test/java/test/misc/TestMisc.java' did not match any file(s) known to git
| ead639104b2f28a2ed0d8103035eb2e1b2373d63 | 1 | jingwei/krati,jingwei/krati,linkedin/krati,jingwei/krati,linkedin/krati,linkedin/krati | /*
* Copyright (c) 2010-2012 LinkedIn, 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 test.misc;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
/**
* TestMisc
*
* @author jwu
* @since 04/20, 2012
*/
public class TestMisc extends TestCase {
Random _rand = new Random();
public void testArrayListRemoveLast() {
List<Object> list = new ArrayList<Object>();
list.add(new Object());
int cnt = _rand.nextInt(100);
for(int i = 0; i < cnt; i++) {
list.add(new Object());
}
int size = list.size();
while(size > 0) {
list.set(size-1, null);
assertEquals(size, list.size());
assertTrue(list.get(size-1) == null);
list.remove(size - 1);
assertEquals(size - 1, list.size());
size = list.size();
}
}
}
| krati-main/src/test/java/test/misc/TestMisc.java | added TestMisc.java
| krati-main/src/test/java/test/misc/TestMisc.java | added TestMisc.java |
|
Java | apache-2.0 | error: pathspec 'src/main/java/edu/neu/ccs/pyramid/experiment/Exp210.java' did not match any file(s) known to git
| 40801089044303839424d4f9592a9f1d610dafc4 | 1 | cheng-li/pyramid,cheng-li/pyramid | package edu.neu.ccs.pyramid.experiment;
import edu.neu.ccs.pyramid.configuration.Config;
import edu.neu.ccs.pyramid.dataset.DataSetType;
import edu.neu.ccs.pyramid.dataset.MultiLabelClfDataSet;
import edu.neu.ccs.pyramid.dataset.TRECFormat;
import edu.neu.ccs.pyramid.eval.Accuracy;
import edu.neu.ccs.pyramid.eval.Overlap;
import edu.neu.ccs.pyramid.multilabel_classification.bmm.BMMClassifier;
import edu.neu.ccs.pyramid.multilabel_classification.bmm.BMMOptimizer;
import java.io.IOException;
/**
* BMM multi-label
* Created by chengli on 10/8/15.
*/
public class Exp210 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
if (args.length != 1) {
throw new IllegalArgumentException("Please specify a properties file.");
}
Config config = new Config(args[0]);
System.out.println(config);
MultiLabelClfDataSet trainSet = TRECFormat.loadMultiLabelClfDataSet(config.getString("input.trainData"),
DataSetType.ML_CLF_SPARSE, true);
MultiLabelClfDataSet testSet = TRECFormat.loadMultiLabelClfDataSet(config.getString("input.testData"),
DataSetType.ML_CLF_SPARSE, true);
int numClusters = config.getInt("numClusters");
double variance = config.getDouble("variance");
int numIterations = config.getInt("numIterations");
BMMClassifier bmmClassifier = new BMMClassifier(trainSet.getNumClasses(),numClusters,trainSet.getNumFeatures());
BMMOptimizer optimizer = new BMMOptimizer(bmmClassifier,trainSet,variance);
System.out.println("after initialization");
System.out.println("train acc = "+ Accuracy.accuracy(bmmClassifier, trainSet));
System.out.println("train overlap = "+ Overlap.overlap(bmmClassifier, trainSet));
System.out.println("test acc = "+ Accuracy.accuracy(bmmClassifier,testSet));
System.out.println("test overlap = "+ Overlap.overlap(bmmClassifier, testSet));
for (int i=1;i<=numIterations;i++){
optimizer.iterate();
System.out.println("after iteration "+i);
System.out.println("train acc = "+ Accuracy.accuracy(bmmClassifier,trainSet));
System.out.println("train overlap = "+ Overlap.overlap(bmmClassifier, trainSet));
System.out.println("test acc = "+ Accuracy.accuracy(bmmClassifier,testSet));
System.out.println("test overlap = "+ Overlap.overlap(bmmClassifier, testSet));
}
System.out.println("history = "+optimizer.getTerminator().getHistory());
System.out.println(bmmClassifier);
}
}
| src/main/java/edu/neu/ccs/pyramid/experiment/Exp210.java | add Exp210
| src/main/java/edu/neu/ccs/pyramid/experiment/Exp210.java | add Exp210 |
|
Java | apache-2.0 | error: pathspec 'src/core/org/apache/hadoop/net/CachedDNSToSwitchMapping.java' did not match any file(s) known to git
| 72315be9d6e4911fac6dd118c3174dfbc9fe384a | 1 | dhootha/hadoop-common,coderplay/hadoop-common,toddlipcon/hadoop,coderplay/hadoop-common,dhootha/hadoop-common,hn5092/hadoop-common,aseldawy/spatialhadoop,ShortMap/ShortMap,squidsolutions/hadoop-common,toddlipcon/hadoop,hn5092/hadoop-common,aseldawy/spatialhadoop,toddlipcon/hadoop,sztanko/hadoop-common,dongjiaqiang/hadoop-common,dhootha/hadoop-common,sztanko/hadoop-common,aseldawy/spatialhadoop,squidsolutions/hadoop-common,dongjiaqiang/hadoop-common,sztanko/hadoop-common,hn5092/hadoop-common,coderplay/hadoop-common,ShortMap/ShortMap,sztanko/hadoop-common,sztanko/hadoop-common,dongjiaqiang/hadoop-common,hn5092/hadoop-common,coderplay/hadoop-common,aseldawy/spatialhadoop,dongjiaqiang/hadoop-common,squidsolutions/hadoop-common,toddlipcon/hadoop,hn5092/hadoop-common,aseldawy/spatialhadoop,ShortMap/ShortMap,ShortMap/ShortMap,squidsolutions/hadoop-common,hn5092/hadoop-common,squidsolutions/hadoop-common,hn5092/hadoop-common,aseldawy/spatialhadoop,ShortMap/ShortMap,sztanko/hadoop-common,squidsolutions/hadoop-common,sztanko/hadoop-common,sztanko/hadoop-common,coderplay/hadoop-common,toddlipcon/hadoop,coderplay/hadoop-common,squidsolutions/hadoop-common,dhootha/hadoop-common,coderplay/hadoop-common,dhootha/hadoop-common,ShortMap/ShortMap,toddlipcon/hadoop,dongjiaqiang/hadoop-common,sztanko/hadoop-common,aseldawy/spatialhadoop,hn5092/hadoop-common,aseldawy/spatialhadoop,dhootha/hadoop-common,squidsolutions/hadoop-common,dhootha/hadoop-common,dongjiaqiang/hadoop-common,dhootha/hadoop-common,hn5092/hadoop-common,ShortMap/ShortMap,dongjiaqiang/hadoop-common,dhootha/hadoop-common,ShortMap/ShortMap,ShortMap/ShortMap,coderplay/hadoop-common,dongjiaqiang/hadoop-common,dhootha/hadoop-common,toddlipcon/hadoop,hn5092/hadoop-common,toddlipcon/hadoop,squidsolutions/hadoop-common,toddlipcon/hadoop,sztanko/hadoop-common,dongjiaqiang/hadoop-common,coderplay/hadoop-common,squidsolutions/hadoop-common,dongjiaqiang/hadoop-common,aseldawy/spatialhadoop | /**
* 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.net;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* A cached implementation of DNSToSwitchMapping that takes an
* raw DNSToSwitchMapping and stores the resolved network location in
* a cache. The following calls to a resolved network location
* will get its location from the cache.
*
*/
public class CachedDNSToSwitchMapping implements DNSToSwitchMapping {
private Map<String, String> cache = new TreeMap<String, String>();
protected DNSToSwitchMapping rawMapping;
public CachedDNSToSwitchMapping(DNSToSwitchMapping rawMapping) {
this.rawMapping = rawMapping;
}
public List<String> resolve(List<String> names) {
// normalize all input names to be in the form of IP addresses
names = NetUtils.normalizeHostNames(names);
List <String> result = new ArrayList<String>(names.size());
if (names.isEmpty()) {
return result;
}
// find out all names without cached resolved location
List<String> unCachedHosts = new ArrayList<String>(names.size());
for (String name : names) {
if (cache.get(name) == null) {
unCachedHosts.add(name);
}
}
// Resolve those names
List<String> rNames = rawMapping.resolve(unCachedHosts);
// Cache the result
if (rNames != null) {
for (int i=0; i<unCachedHosts.size(); i++) {
cache.put(unCachedHosts.get(i), rNames.get(i));
}
}
// Construct the result
for (String name : names) {
//now everything is in the cache
String networkLocation = cache.get(name);
if (networkLocation != null) {
result.add(networkLocation);
} else { //resolve all or nothing
return null;
}
}
return result;
}
}
| src/core/org/apache/hadoop/net/CachedDNSToSwitchMapping.java | HADOOP-3620. Added the file CacheDNSToSwitchMapping.java that was missed earlier.
git-svn-id: 5be3658b1da2303116c04834c161daea58df9cc4@682593 13f79535-47bb-0310-9956-ffa450edef68
| src/core/org/apache/hadoop/net/CachedDNSToSwitchMapping.java | HADOOP-3620. Added the file CacheDNSToSwitchMapping.java that was missed earlier. |
|
Java | apache-2.0 | error: pathspec 'ohmdb-test/src/test/java/com/ohmdb/perf/MultiThreadedTest.java' did not match any file(s) known to git
| f42a9246f628dd8331d6d550a2dc265f31f22624 | 1 | gitblit/ohmdb,gitblit/ohmdb,ohmdb/ohmdb,ohmdb/ohmdb | package com.ohmdb.perf;
/*
* #%L
* ohmdb-test
* %%
* Copyright (C) 2013 - 2014 Nikolche Mihajlovski
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.testng.annotations.Test;
import com.ohmdb.api.Table;
import com.ohmdb.test.Person;
import com.ohmdb.test.TestCommons;
public class MultiThreadedTest extends TestCommons {
private static final int total = 1000;
@Test
public void shouldPerformWell() throws Exception {
Thread[] threads = new Thread[100];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread() {
public void run() {
Table<Person> persons = db.table(Person.class);
long[] ids = new long[total];
for (int x = 0; x < total; x++) {
ids[x] = persons.insert(person("p" + x, x % 2));
}
// System.out.println(persons.size());
for (int x = 0; x < total; x++) {
Person person = persons.get(ids[x]);
eq(person.name, "p" + x);
eq(person.age, x % 2);
}
for (int x = 0; x < total; x++) {
Object val = persons.read(ids[x], "name");
eq(val, "p" + x);
}
for (int x = 0; x < total; x++) {
Object val = persons.read(ids[x], "age");
eq(val, x % 2);
}
for (int x = 0; x < total; x++) {
persons.delete(ids[x]);
}
};
};
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
}
}
| ohmdb-test/src/test/java/com/ohmdb/perf/MultiThreadedTest.java | Initial commit: MultiThreadedTest.java
| ohmdb-test/src/test/java/com/ohmdb/perf/MultiThreadedTest.java | Initial commit: MultiThreadedTest.java |
|
Java | apache-2.0 | error: pathspec 'src/main/java/es/tid/graphlib/clustering/SemiClusteringSimple.java' did not match any file(s) known to git
| 03c9e6ed41fd8b65ef561d7c3fff87fba2a57e44 | 1 | joseprupi/okapi,grafos-ml/okapi,grafos-ml/okapi,schlegel/okapi,schlegel/okapi,joseprupi/okapi | package es.tid.graphlib.clustering;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
import org.apache.giraph.Algorithm;
import org.apache.giraph.edge.Edge;
import org.apache.giraph.graph.Vertex;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import es.tid.graphlib.clustering.SemiClusteringSimple.SemiClusterTreeSetWritable;
/**
* Demonstrates the Semi Clustering implementation.
*/
@Algorithm(
name = "Semi Clustering",
description = "It puts vertices into clusters")
public class SemiClusteringSimple extends Vertex<LongWritable,
SemiClusterTreeSetWritable, DoubleWritable, SemiClusterTreeSetWritable> {
/** Keyword for parameter setting the number of iterations */
public static final String ITERATIONS_KEYWORD = "semi.iterations";
/** Default value for ITERATIONS */
public static final int ITERATIONS_DEFAULT = 10;
/** Keyword for parameter setting the Maximum number of Semi-Clusters */
public static final String CLUSTER_LIST_CAPACITY_KEYWORD =
"semi.clusters.max";
/** Default value for Maximum Number of Semi-Clusters */
public static final int CLUSTER_LIST_CAPACITY_DEFAULT = 2;
/** Keyword for parameter setting the Maximum No of vertices in a cluster */
public static final String CLUSTER_CAPACITY_KEYWORD =
"semi.cluster.capacity";
/** Default value for CAPACITY */
public static final int CLUSTER_CAPACITY_DEFAULT = 4;
/** Keyword for parameter setting the Boundary Edge Score Factor */
public static final String SCORE_FACTOR_KEYWORD = "semi.score.factor";
/** Default value for Boundary Edge Score Factor */
public static final float SCORE_FACTOR_DEFAULT = 0.5f;
/** Decimals for the value of score */
public static final int DECIMALS = 4;
/** Comparator to sort clusters in the list based on their score */
private final ClusterScoreComparator scoreComparator =
new ClusterScoreComparator();
/**
* Compute method
* @param messages Messages received
*/
public void compute(Iterable<SemiClusterTreeSetWritable> messages) {
// Set the number of iterations
int iterations = getContext().getConfiguration().getInt(ITERATIONS_KEYWORD,
ITERATIONS_DEFAULT);
// Set the maximum number of clusters
int clusterListCapacity =
getContext().getConfiguration().getInt(CLUSTER_LIST_CAPACITY_KEYWORD,
CLUSTER_LIST_CAPACITY_DEFAULT);
// Set the number of iterations
int clusterCapacity =
getContext().getConfiguration().getInt(CLUSTER_CAPACITY_KEYWORD,
CLUSTER_CAPACITY_DEFAULT);
// Boundary Edge Score Factor [0,1] - user-defined
double boundaryEdgeScoreFactor =
getContext().getConfiguration().getFloat(SCORE_FACTOR_KEYWORD,
SCORE_FACTOR_DEFAULT);
// In the first superstep:
// 1. Create an empty list of clusters
// 2. Create an empty cluster
// 3. Add vertex in the empty cluster
// 4. Add cluster in the list of clusters
// 5. Send list of clusters to neighbors
if (getSuperstep() == 0) {
SemiClusterTreeSetWritable clusterList =
new SemiClusterTreeSetWritable(scoreComparator);
SemiCluster myCluster = new SemiCluster();
myCluster.addVertex(this, boundaryEdgeScoreFactor);
clusterList.add(myCluster);
setValue(clusterList);
System.out.println("---S: " + getSuperstep() + ", id: " + getId() +
", clusterList: " + getValue());
//sendMessageToAllEdges(getValue());
for (Edge<LongWritable, DoubleWritable> edge : getEdges()) {
SemiClusterTreeSetWritable message = new SemiClusterTreeSetWritable();
message.addAll(getValue());
sendMessage(edge.getTargetVertexId(), message);
//System.out.println("send " + message.getMessage().toString() +
//" to " + edge.getTargetVertexId());
}
voteToHalt();
return;
}
if (getSuperstep() == iterations) {
voteToHalt();
return;
}
// In the next supersteps:
// For each message/list, for each cluster in the list
// if vertex is NOT part of the cluster:
// 1. Duplicate cluster c,
// 2. Add vertex to the duplicated cluster c' & compute score for c'
// 3. Sort all clusters (list)
// 4. Send the list to neighbors
SemiClusterTreeSetWritable tempList =
new SemiClusterTreeSetWritable(scoreComparator);
tempList.addAll(getValue());
// FOR LOOP - for each message/list
for (SemiClusterTreeSetWritable message : messages) {
System.out.println("S:" + getSuperstep() + ", id:" + getId() +
", message received " + message.toString());
for (SemiCluster cluster: message) {
//Iterator<SemiCluster> clusterIter = message.iterator();
// WHILE LOOP - for each cluster in the message/list
//while (clusterIter.hasNext()) {
//SemiCluster cluster = new SemiCluster(clusterIter.next());
if (!cluster.verticesList.contains(getId()) &&
cluster.verticesList.size() < clusterCapacity) {
SemiCluster newCluster = new SemiCluster(cluster);
newCluster.addVertex(this, boundaryEdgeScoreFactor);
boolean added = tempList.add(newCluster);
//tempList.addCluster(newCluster);
System.out.println("Cluster: " + cluster.verticesList.toString() +
", newCluster: " + newCluster.toString() + "added: " + added +
", tempList: " + tempList.toString());
}
} // END OF WHILE LOOP - (for each cluster)
} // END OF FOR LOOP - (for each message/list)
getValue().clear();
SemiClusterTreeSetWritable value =
new SemiClusterTreeSetWritable(scoreComparator);
Iterator<SemiCluster> iterator = tempList.iterator();
for (int i = 0; i < clusterListCapacity; i++) {
if (iterator.hasNext()) {
value.add(iterator.next());
setValue(value);
}
}
System.out.println("---S: " + getSuperstep() + ", id: " + getId() +
", clusterList: " + getValue());
SemiClusterTreeSetWritable message = new SemiClusterTreeSetWritable();
message.addAll(getValue());
for (SemiCluster c: message) {
System.out.println(c.toString());
}
sendMessageToAllEdges(message);
voteToHalt();
} // END OF Compute()
/***************************************************************************
***************************************************************************
***************************************************************************
*/
/** Utility class for facilitating the sorting of the cluster list */
private class ClusterScoreComparator implements Comparator<SemiCluster> {
@Override
/**
* Compare two objects for order.
* @param o1 the first object
* @param o2 the second object
*
* @return -1 if score for object1 is smaller than score of object2,
* 1 if score for object2 is smaller than score of object1
* or 0 if both scores are the same
*/
public int compare(SemiCluster o1, SemiCluster o2) {
if (o1.score < o2.score) {
return 1;
} else if (o1.score > o2.score) {
return -1;
} else {
if (!o1.equals(o2)) {
return 1;
}
}
return 0;
}
} // End of class ClusterScoreComparator
/***************************************************************************
***************************************************************************
***************************************************************************
*/
/**
* Utility class for delivering the array of clusters THIS vertex belongs to
*/
public static class SemiClusterTreeSetWritable extends TreeSet<SemiCluster>
implements WritableComparable<SemiClusterTreeSetWritable> {
/**
* Default Constructor
*/
public SemiClusterTreeSetWritable() {
super();
//clusterList = new TreeSet<SemiCluster>();
}
/**
* Constructor
*
* @param c Comparator object to sort clusterList with the score
*/
public SemiClusterTreeSetWritable(ClusterScoreComparator c) {
super(c);
//clusterList = new TreeSet<SemiCluster>();
}
/** Add a semi cluster in the list of clusters
*
* @param c Semi cluster to be added
*/
void addCluster(SemiCluster c) {
add(c);
}
/** CompareTo
* Two lists of semi clusters are the same when:
* --> they have the same number of clusters
* --> all their clusters are the same, i.e. contain the same vertices
* For each cluster, check if it exists in the other list of semi clusters
*
* @param other A list with clusters to be compared with the current list
*
* @return return 0 if two lists are the same
*/
public int compareTo(SemiClusterTreeSetWritable other) {
if (this.size() < other.size()) {
return -1;
}
if (this.size() > other.size()) {
return 1;
}
Iterator<SemiCluster> iterator1 = this.iterator();
Iterator<SemiCluster> iterator2 = other.iterator();
while (iterator1.hasNext()) {
if (iterator1.next().compareTo(iterator2.next()) != 0) {
return -1;
}
}
return 0;
}
/** Equals
* Two lists of semi clusters are equal when:
* --> they have the same number of clusters
* --> all their clusters are the same, i.e. contain the same vertices
* For each cluster, check if it exists in the other list of semi clusters
*
* @param other A list with clusters to be compared if it is equal
* with the current list
*
* @return return true if two lists are equal, otherwise false
*/
/*
public boolean equals2(SemiClusterTreeSetWritable other) {
if (this.size() < other.size() || this.size() > other.size()) {
return false;
}
Iterator<SemiCluster> iterator1 = this.iterator();
Iterator<SemiCluster> iterator2 = other.iterator();
while (iterator1.hasNext()) {
if (!iterator1.next().equals(iterator2.next())) {
return false;
}
}
return true;
}
*/
@Override
public void readFields(DataInput input) throws IOException {
//clusterList = new TreeSet<SemiCluster>();
int size = input.readInt();
for (int i = 0; i < size; i++) {
SemiCluster c = new SemiCluster();
c.readFields(input);
add(c);
}
}
@Override
public void write(DataOutput output) throws IOException {
output.writeInt(size());
for (SemiCluster c : this) {
c.write(output);
}
}
/*
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (SemiCluster c: this) {
builder.append("[ ");
for (LongWritable v: c.verticesList) {
builder.append(v.toString());
builder.append(' ');
}
builder.append(" ] ");
}
return builder.toString();
}*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (SemiCluster v: this) {
builder.append(v.toString() + " ");
}
builder.append("\n");
return builder.toString();
}
} // END OF class SemiClusterTreeSetWritable
/****************************************************************************
****************************************************************************
****************************************************************************
*/
/**
* Class SemiCluster
*/
public static class SemiCluster
implements Writable, Comparable<SemiCluster> {
/** List of Vertices belonged to current semi cluster */
private HashSet<LongWritable> verticesList;
/** Score of current semi cluster */
private double score;
/** Inner Score */
private double innerScore;
/** Boundary Score */
private double boundaryScore;
/** Constructor: Create a new empty Cluster */
public SemiCluster() {
verticesList = new HashSet<LongWritable>();
score = 1d;
innerScore = 0d;
boundaryScore = 0d;
}
/**
* Constructor: Initialize a new Cluster
*
* @param cluster cluster object to initialize the new object
*/
public SemiCluster(SemiCluster cluster) {
verticesList = new HashSet<LongWritable>();
verticesList.addAll(cluster.verticesList);
score = cluster.score;
innerScore = cluster.innerScore;
boundaryScore = cluster.boundaryScore;
}
/**
* Add a vertex to the cluster and recalculate the score
*
* @param vertex The new vertex to be added into the cluster
*/
public void addVertex(Vertex<LongWritable, ?, DoubleWritable, ?>
vertex, double boundaryEdgeScoreFactor) {
long vertexId = vertex.getId().get();
if (verticesList.add(new LongWritable(vertexId))) {
this.computeScore(vertex, boundaryEdgeScoreFactor);
score = keepXdecimals(score, DECIMALS);
innerScore = keepXdecimals(innerScore, DECIMALS);
boundaryScore = keepXdecimals(boundaryScore, DECIMALS);
}
}
/**
* Get size of semi cluster list.
*
* @return Number of semi clusters in the list
*/
public int getSize() {
return verticesList.size();
}
/**
* Compute the score of the semi-cluster
*
* @param vertex The recently added vertex
*
* @return the new score of the cluster
*/
private void computeScore(Vertex<LongWritable, ?, DoubleWritable, ?>
vertex, double boundaryEdgeScoreFactor) {
/*for (Edge<LongWritable, DoubleWritable> edge : vertex.getEdges()) {
System.out.println("v:" + vertex.getId() + ", target:" +
edge.getTargetVertexId() + ", edgeValue:" + edge.getValue());
}*/
if (getSize() == 1) {
score = 1d;
for (Edge<LongWritable, DoubleWritable> edge : vertex.getEdges()) {
boundaryScore += edge.getValue().get();
}
} else {
for (Edge<LongWritable, DoubleWritable> edge : vertex.getEdges()) {
if (verticesList.contains(edge.getTargetVertexId())) {
innerScore += edge.getValue().get();
boundaryScore -= edge.getValue().get();
} else {
boundaryScore += edge.getValue().get();
}
}
System.out.println("inner: " + innerScore + " - (boundary: " +
boundaryScore + " * " + boundaryEdgeScoreFactor + ") / size:" + getSize());
score = (innerScore - (boundaryEdgeScoreFactor * boundaryScore)) /
(getSize() * (getSize() - 1) / 2);
}
} // End of computeScore()
/**
* Return the list of vertices belonging to current semi cluster
* @return List of vertices belonging to current semi cluster
*/
public HashSet<LongWritable> getVerticesList() {
return verticesList;
}
/** CompareTo
* Two semi clusters are the same when:
* --> they have the same number of vertices
* --> all their vertices are the same
* For each vertex, check if it exists in the other cluster
*
* @param cluster Cluster to be compared with current cluster
*
* @return 0 if two clusters are the same
*/
@Override
public int compareTo(SemiCluster other) {
if (other == null) {
return 1;
}
if (this.getSize() < other.getSize()) {
return -1;
}
if (this.getSize() > other.getSize()) {
return 1;
}
if (other.verticesList.containsAll(verticesList)) {
return 0;
}
return -1;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((verticesList == null) ? 0 : verticesList.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SemiCluster other = (SemiCluster) obj;
if (verticesList == null) {
if (other.verticesList != null) {
return false;
}
} else if (!verticesList.equals(other.verticesList)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[ ");
for (LongWritable v: this.verticesList) {
builder.append(v.toString());
builder.append(" ");
}
builder.append(" | " + score + ", " + innerScore + ", " + boundaryScore + " ]");
return builder.toString();
}
/**
* Decimal Precision of latent vector values
*
* @param value Value to be truncated
* @param x Number of decimals to keep
*/
public double keepXdecimals(Double value, int x) {
double num = 1;
for (int i = 0; i < x; i++) {
num *= 10;
}
return Math.round(value * num) / num;
}
@Override
public void readFields(DataInput input) throws IOException {
verticesList = new HashSet<LongWritable>();
int size = input.readInt();
for (int i = 0; i < size; i++) {
LongWritable e = new LongWritable();
e.readFields(input);
verticesList.add(e);
}
score = input.readDouble();
innerScore = input.readDouble();
boundaryScore = input.readDouble();
}
@Override
public void write(DataOutput output) throws IOException {
output.writeInt(getSize());
for (LongWritable vertex: verticesList) {
vertex.write(output);
}
output.writeDouble(score);
output.writeDouble(innerScore);
output.writeDouble(boundaryScore);
}
} // End of SemiCluster Child Class
} // End of SemiClustering Parent Class | src/main/java/es/tid/graphlib/clustering/SemiClusteringSimple.java | SemiClusterinSimple
simplify the class of the message - same as vertex value
outputFormat depends on this class
| src/main/java/es/tid/graphlib/clustering/SemiClusteringSimple.java | SemiClusterinSimple simplify the class of the message - same as vertex value outputFormat depends on this class |
|
Java | apache-2.0 | error: pathspec 'src/main/java/com/javacook/testdatagenerator/TestDataGenerator.java' did not match any file(s) known to git
| e2fe9580881571721ba24d58fd3c84c62b2006b6 | 1 | javacook/test-data-generator | package com.javacook.testdatagenerator;
import com.javacook.coordinate.CoordinateInterface;
import com.javacook.testdatagenerator.excelreader.BeanPathCalculator;
import com.javacook.testdatagenerator.excelreader.MyExcelAccessor;
import com.javacook.testdatagenerator.model.BeanPath;
import java.io.File;
import java.io.IOException;
/**
* Created by vollmer on 21.12.16.
*/
public class TestDataGenerator {
final BeanPathCalculator beanPathCalculator;
final MyExcelAccessor excelAccessor;
final Integer headerStartIndex;
final Integer oidIndex;
protected TestDataGenerator(MyExcelAccessor excelAccessor, Integer headerStartIndex, Integer oidIndex) throws IOException {
this.headerStartIndex = (headerStartIndex == null)? 0 : headerStartIndex;
this.oidIndex = oidIndex;
this.excelAccessor = excelAccessor;
beanPathCalculator = new BeanPathCalculator(
excelAccessor, headerStartIndex, (oidIndex == null)? 0 : oidIndex);
}
public TestDataGenerator(String excelResource, int headerStartIndex, int oidIndex) throws IOException {
this(new MyExcelAccessor(excelResource), headerStartIndex, oidIndex);
}
public TestDataGenerator(String excelResource, int headerStartIndex) throws IOException {
this(new MyExcelAccessor(excelResource), headerStartIndex, null);
}
public TestDataGenerator(String excelResource) throws IOException {
this(new MyExcelAccessor(excelResource), null, null);
}
public TestDataGenerator(File excelFile, int headerStartIndex, int oidIndex) throws IOException {
this(new MyExcelAccessor(excelFile), headerStartIndex, oidIndex);
}
public TestDataGenerator(File excelFile, int headerStartIndex) throws IOException {
this(new MyExcelAccessor(excelFile), headerStartIndex, null);
}
public TestDataGenerator(File excelFile) throws IOException {
this(new MyExcelAccessor(excelFile), null, null);
}
public static class ExcelCell<T> {
public BeanPath beanPath;
public Object oid;
public T content;
@Override
public String toString() {
return "ExcelCell{" +
"beanPath=" + beanPath +
", oid=" + oid +
", content=" + content +
'}';
}
}
public <T> ExcelCell readCell(int sheet, CoordinateInterface coord) {
return new ExcelCell() {{
beanPath = beanPathCalculator.beanPath(sheet, coord);
if (oidIndex != null) oid = beanPathCalculator.oid(sheet, coord);
content = excelAccessor.readCell(sheet, coord);
}};
}
public <T> ExcelCell readCell(int sheet, CoordinateInterface coord, Class<T> clazz) {
return new ExcelCell() {{
beanPath = beanPathCalculator.beanPath(sheet, coord);
if (oidIndex != null) oid = beanPathCalculator.oid(sheet, coord);
content = excelAccessor.readCell(sheet, coord, clazz);
}};
}
}
| src/main/java/com/javacook/testdatagenerator/TestDataGenerator.java | initial
| src/main/java/com/javacook/testdatagenerator/TestDataGenerator.java | initial |
|
Java | apache-2.0 | error: pathspec 'projects/OG-Component/tests/unit/com/opengamma/component/ComponentTest.java' did not match any file(s) known to git
| 9aad9d07f0b888ab2cb0a67f3a41d8ef5363a5ba | 1 | DevStreet/FinanceAnalytics,McLeodMoores/starling,ChinaQuants/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,McLeodMoores/starling,codeaudit/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.component;
import static org.testng.AssertJUnit.assertNotNull;
import org.testng.annotations.Test;
/**
* Test.
*/
@Test
public class ComponentTest {
public void test() {
assertNotNull("Placeholder for ant");
}
}
| projects/OG-Component/tests/unit/com/opengamma/component/ComponentTest.java | [PLAT-1658] Placeholder test for components
| projects/OG-Component/tests/unit/com/opengamma/component/ComponentTest.java | [PLAT-1658] Placeholder test for components |
|
Java | apache-2.0 | error: pathspec 'addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java' did not match any file(s) known to git
| d656a07b20b5f14d96cae5a52c3e0c8f2bc64291 | 1 | kxbxzx/java_pft | package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.stqa.pft.addressbook.model.GroupData;
/**
* Created by Alexander on 22.03.2017.
*/
public class GroupHelper extends HelperBase {
public GroupHelper(FirefoxDriver wd) {
super(wd);
}
public void returnToGroupPage() {
click(By.linkText("group page"));
}
public void submitGroupCreation() {
click(By.name("submit"));
}
public void fillGroupForm(GroupData groupData) {
type(By.name("group_name"), groupData.getName());
type(By.name("group_header"), groupData.getHeader());
type(By.name("group_footer"), groupData.getFooter());
}
public void initGroupCreation() {
click(By.name("new"));
}
public void deleteSelectedGroups() {
click(By.name("delete"));
}
public void selectGroup() {
click(By.name("selected[]"));
}
}
| addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java | GroupHelper
| addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java | GroupHelper |
|
Java | apache-2.0 | error: pathspec 'core/src/main/java/org/axonframework/serialization/upcasting/ContextAwareSingleEntryUpcaster.java' did not match any file(s) known to git
| 29a3d9956b84ab38829e031eda381faf92714a10 | 1 | krosenvold/AxonFramework,AxonFramework/AxonFramework | package org.axonframework.serialization.upcasting;
import static java.util.Objects.requireNonNull;
import java.util.stream.Stream;
/**
* Abstract implementation of an {@link Upcaster} that eases the common process of upcasting one intermediate
* representation to another representation by applying a simple mapping function to the input stream of intermediate
* representations.
* Additionally, it's a context aware implementation, which enables it to store and reuse context information from one
* entry to another during upcasting.
*
* @param <T> the type of entry to be upcasted as {@code T}
* @param <C> the type of context used as {@code C}
*
* @author Steven van Beelen
*/
public abstract class ContextAwareSingleEntryUpcaster<T, C> implements Upcaster<T> {
@Override
public Stream<T> upcast(Stream<T> intermediateRepresentations) {
C context = buildContext();
return intermediateRepresentations.map(entry -> {
if (!canUpcast(entry, context)) {
return entry;
}
return requireNonNull(doUpcast(entry, context),
"Result from #doUpcast() should not be null. To remove an " +
"intermediateRepresentation add a filter to the input stream.");
});
}
/**
* Checks if this upcaster can upcast the given {@code intermediateRepresentation}.
* If the upcaster cannot upcast the representation the {@link #doUpcast(Object, Object)} is not invoked.
* The {@code context} can be used to store or retrieve entry specific information required to make the
* {@code canUpcast(Object, Object)} check.
*
* @param intermediateRepresentation the intermediate object representation to upcast as {@code T}
* @param context the context for this upcaster as {@code C}
* @return {@code true} if the representation can be upcast, {@code false} otherwise
*/
protected abstract boolean canUpcast(T intermediateRepresentation, C context);
/**
* Upcasts the given {@code intermediateRepresentation}. This method is only invoked if {@link #canUpcast(Object,
* Object)} returned {@code true} for the given representation. The {@code context} can be used to store or retrieve
* entry specific information required to perform the upcasting process.
* <p>
* Note that the returned representation should not be {@code null}.
* To remove an intermediateRepresentation add a filter to the input stream.
*
* @param intermediateRepresentation the representation of the object to upcast as {@code T}
* @param context the context for this upcaster as {@code C}
* @return the upcasted representation
*/
protected abstract T doUpcast(T intermediateRepresentation, C context);
/**
* Builds a context of generic type {@code C} to be used when processing the stream of intermediate object
* representations {@code T}.
*
* @return a context of generic type {@code C}
*/
protected abstract C buildContext();
}
| core/src/main/java/org/axonframework/serialization/upcasting/ContextAwareSingleEntryUpcaster.java | Introduce ContextAwareSingleEntryUpcaster
Introduce ContextAwareSingleEntryUpcaster, resembling the regular
SingleEntryUpcaster class, but with an added buildContext() function.
The context C created by the buildContext() is fed to the canUpcast()
and doUpcast() functions to be used to perform the 'can upcast' check or
the actual 'do upcast' process
#394
| core/src/main/java/org/axonframework/serialization/upcasting/ContextAwareSingleEntryUpcaster.java | Introduce ContextAwareSingleEntryUpcaster |
|
Java | apache-2.0 | error: pathspec 'eu.scasefp7.eclipse.services.nlp.provider/src/eu/scasefp7/eclipse/services/nlp/provider/config/NLPServiceConfigurator.java' did not match any file(s) known to git
| c9e1fbbd5befe23853339c4a7954205bf7d0fd27 | 1 | s-case/s-case-core,LeonoraG/s-case-core,LeonoraG/s-case-core | /**
* Copyright 2015 S-CASE Consortium
*
* 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 eu.scasefp7.eclipse.services.nlp.provider.config;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
/**
* @author emaorli
*
*/
public class NLPServiceConfigurator implements IPreferenceChangeListener {
/** Endpoint for the NLP service */
public static final String P_NLP_ENDPOINT = "nlpServiceURI"; //$NON-NLS-1$
/**
*
*/
public NLPServiceConfigurator() {
// TODO Auto-generated constructor stub
}
@Override
public void preferenceChange(PreferenceChangeEvent event) {
System.out.println(event);
if(event.getKey().equals(P_NLP_ENDPOINT)) {
}
}
}
| eu.scasefp7.eclipse.services.nlp.provider/src/eu/scasefp7/eclipse/services/nlp/provider/config/NLPServiceConfigurator.java | Add service configuration
| eu.scasefp7.eclipse.services.nlp.provider/src/eu/scasefp7/eclipse/services/nlp/provider/config/NLPServiceConfigurator.java | Add service configuration |
|
Java | bsd-2-clause | d3f97b3c398a9055e90dd3078e4b071b7ce35010 | 0 | nikgoodley-ibboost/jslint4java,mmayorivera/jslint4java,llwanghong/jslint4java,mmayorivera/jslint4java,rsingla/jslint4java,mmayorivera/jslint4java,llwanghong/jslint4java,mmayorivera/jslint4java,rsingla/jslint4java,nikgoodley-ibboost/jslint4java,llwanghong/jslint4java,rsingla/jslint4java,llwanghong/jslint4java,rsingla/jslint4java,nikgoodley-ibboost/jslint4java,rsingla/jslint4java,nikgoodley-ibboost/jslint4java,nikgoodley-ibboost/jslint4java,llwanghong/jslint4java,mmayorivera/jslint4java | package com.googlecode.jslint4java;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.ScriptableObject;
/**
* Construct {@link JSLint} instances.
*
* @author hdm
*/
public class JSLintBuilder {
private static final String JSLINT_FILE = "com/googlecode/jslint4java/jslint.js";
private static final Charset UTF8 = Charset.forName("UTF-8");
private ContextFactory contextFactory = new ContextFactory();
/**
* Initialize the scope from a jslint.js found in the classpath. Assumes a
* UTF-8 encoding.
*
* @param resource
* the location of jslint.js on the classpath.
* @return a configured {@link JSLint}
* @throws IOException
* if there are any problems reading the resource.
*/
public JSLint fromClasspathResource(String resource) throws IOException {
return fromClasspathResource(resource, UTF8);
}
/**
* Initialize the scope from a jslint.js found in the classpath.
*
* @param resource
* the location of jslint.js on the classpath.
* @param encoding
* the encoding of the resource.
* @return a configured {@link JSLint}
* @throws IOException
* if there are any problems reading the resource.
*/
public JSLint fromClasspathResource(String resource, Charset encoding) throws IOException {
Reader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader()
.getResourceAsStream(resource), encoding));
return fromReader(reader, resource);
}
/**
* Initialize the scope with a default jslint.js.
*
* @return a configured {@link JSLint}
* @throws RuntimeException
* if we fail to load the default jslint.js.
*/
public JSLint fromDefault() {
try {
return fromClasspathResource(JSLINT_FILE);
} catch (IOException e) {
// We wrap and rethrow, as there's nothing a caller can do in this
// case.
throw new RuntimeException(e);
}
}
/**
* Initialize the scope with the jslint.js passed in on the filesystem.
* Assumes a UTF-8 encoding.
*
* @param f
* the path to jslint.js
* @return a configured {@link JSLint}
* @throws IOException
* if the file can't be read.
*/
public JSLint fromFile(File f) throws IOException {
return fromFile(f, UTF8);
}
/**
* Initialize the scope with the jslint.js passed in on the filesystem.
*
* @param f
* the path to jslint.js
* @param encoding
* the encoding of the file
* @return a configured {@link JSLint}
* @throws IOException
* if the file can't be read.
*/
public JSLint fromFile(File f, Charset encoding) throws IOException {
Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), encoding));
return fromReader(reader, f.toString());
}
/**
* Initialize the scope with an arbitrary jslint.
*
* @param reader
* an input source providing jslint.js.
* @param name
* the name of the resource backed by the reader
* @return a configured {@link JSLint}
* @throws IOException
* if there are any problems reading from {@code reader} .
*/
@NeedsContext
public JSLint fromReader(Reader reader, String name) throws IOException {
try {
Context cx = contextFactory.enterContext();
ScriptableObject scope = cx.initStandardObjects(null, true);
cx.evaluateReader(scope, reader, name, 1, null);
Function lintFunc = (Function) scope.get("JSLINT", scope);
return new JSLint(contextFactory, lintFunc);
} finally {
Context.exit();
}
}
/**
* Set this JSLint instance to time out after maxTimeInSeconds.
*
* @param maxTimeInSeconds
* maximum execution time in seconds.
* @return this
*/
public JSLintBuilder timeout(long maxTimeInSeconds) {
return timeout(maxTimeInSeconds, TimeUnit.SECONDS);
}
/**
* Set this JSLint instance to timeout after maxTime.
*
* @param maxTime
* The maximum execution time.
* @param timeUnit
* The unit of maxTime.
* @return this
*/
public JSLintBuilder timeout(long maxTime, TimeUnit timeUnit) {
contextFactory = new TimeLimitedContextFactory(maxTime, timeUnit);
return this;
}
} | jslint4java/src/main/java/com/googlecode/jslint4java/JSLintBuilder.java | package com.googlecode.jslint4java;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.ScriptableObject;
/**
* Construct {@link JSLint} instances.
*
* @author hdm
*/
public class JSLintBuilder {
private static final String JSLINT_FILE = "com/googlecode/jslint4java/jslint.js";
private static final Charset UTF8 = Charset.forName("UTF-8");
private ContextFactory contextFactory = new ContextFactory();
/**
* Initialize the scope from a jslint.js found in the classpath. Assumes a
* UTF-8 encoding.
*
* @param resource
* the location of jslint.js on the classpath.
* @return a configured {@link JSLint}
* @throws IOException
* if there are any problems reading the resource.
*/
public JSLint fromClasspathResource(String resource) throws IOException {
return fromClasspathResource(resource, UTF8);
}
/**
* Initialize the scope from a jslint.js found in the classpath.
*
* @param resource
* the location of jslint.js on the classpath.
* @param encoding
* the encoding of the resource.
* @return a configured {@link JSLint}
* @throws IOException
* if there are any problems reading the resource.
*/
public JSLint fromClasspathResource(String resource, Charset encoding) throws IOException {
Reader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader()
.getResourceAsStream(resource), encoding));
return fromReader(reader, resource);
}
/**
* Initialize the scope with a default jslint.js.
*
* @return a configured {@link JSLint}
* @throws RuntimeException
* if we fail to load the default jslint.js.
*/
public JSLint fromDefault() {
try {
return fromClasspathResource(JSLINT_FILE);
} catch (IOException e) {
// We wrap and rethrow, as there's nothing a caller can do in this
// case.
throw new RuntimeException(e);
}
}
/**
* Initialize the scope with the jslint.js passed in on the filesystem.
* Assumes a UTF-8 encoding.
*
* @param f
* the path to jslint.js
* @return a configured {@link JSLint}
* @throws IOException
* if the file can't be read.
*/
public JSLint fromFile(File f) throws IOException {
return fromFile(f, UTF8);
}
/**
* Initialize the scope with the jslint.js passed in on the filesystem.
*
* @param f
* the path to jslint.js
* @param encoding
* the encoding of the file
* @return a configured {@link JSLint}
* @throws IOException
* if the file can't be read.
*/
public JSLint fromFile(File f, Charset encoding) throws IOException {
Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), encoding));
return fromReader(reader, f.toString());
}
/**
* Initialize the scope with an arbitrary jslint.
*
* @param reader
* an input source providing jslint.js.
* @param name
* the name of the resource backed by the reader
* @return a configured {@link JSLint}
* @throws IOException
* if there are any problems reading from {@code reader} .
*/
@NeedsContext
public JSLint fromReader(Reader reader, String name) throws IOException {
try {
Context cx = contextFactory.enterContext();
ScriptableObject scope = cx.initStandardObjects();
cx.evaluateReader(scope, reader, name, 1, null);
Function lintFunc = (Function) scope.get("JSLINT", scope);
return new JSLint(contextFactory, lintFunc);
} finally {
Context.exit();
}
}
/**
* Set this JSLint instance to time out after maxTimeInSeconds.
*
* @param maxTimeInSeconds
* maximum execution time in seconds.
* @return this
*/
public JSLintBuilder timeout(long maxTimeInSeconds) {
return timeout(maxTimeInSeconds, TimeUnit.SECONDS);
}
/**
* Set this JSLint instance to timeout after maxTime.
*
* @param maxTime
* The maximum execution time.
* @param timeUnit
* The unit of maxTime.
* @return this
*/
public JSLintBuilder timeout(long maxTime, TimeUnit timeUnit) {
contextFactory = new TimeLimitedContextFactory(maxTime, timeUnit);
return this;
}
} | Seal standard objects again. | jslint4java/src/main/java/com/googlecode/jslint4java/JSLintBuilder.java | Seal standard objects again. |
|
Java | bsd-3-clause | a5e1693320efd47fce7f5e9fbac72869ff55e5ab | 0 | TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,Chilledheart/chromium,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.compositor.layouts.phone;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.SystemClock;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.Tab;
import org.chromium.chrome.browser.compositor.LayerTitleCache;
import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation.Animatable;
import org.chromium.chrome.browser.compositor.layouts.Layout;
import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost;
import org.chromium.chrome.browser.compositor.layouts.LayoutUpdateHost;
import org.chromium.chrome.browser.compositor.layouts.components.LayoutTab;
import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.EdgeSwipeEventFilter.ScrollDirection;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.EventFilter;
import org.chromium.chrome.browser.compositor.layouts.phone.stack.Stack;
import org.chromium.chrome.browser.compositor.layouts.phone.stack.StackTab;
import org.chromium.chrome.browser.compositor.scene_layer.SceneLayer;
import org.chromium.chrome.browser.compositor.scene_layer.TabListSceneLayer;
import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager;
import org.chromium.chrome.browser.partnercustomizations.HomepageManager;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.chrome.browser.util.MathUtils;
import org.chromium.ui.base.LocalizationUtils;
import org.chromium.ui.resources.ResourceManager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
/**
* Defines the layout for 2 stacks and manages the events to switch between
* them.
*/
public class StackLayout extends Layout implements Animatable<StackLayout.Property> {
public enum Property {
INNER_MARGIN_PERCENT,
STACK_SNAP,
STACK_OFFSET_Y_PERCENT,
}
private enum SwipeMode { NONE, SEND_TO_STACK, SWITCH_STACK }
private static final String TAG = "StackLayout";
// Width of the partially shown stack when there are multiple stacks.
private static final int MIN_INNER_MARGIN_PERCENT_DP = 55;
private static final float INNER_MARGIN_PERCENT_PERCENT = 0.17f;
// Speed of the automatic fling in dp/ms
private static final float FLING_SPEED_DP = 1.5f; // dp / ms
private static final int FLING_MIN_DURATION = 100; // ms
private static final float THRESHOLD_TO_SWITCH_STACK = 0.4f;
private static final float THRESHOLD_TIME_TO_SWITCH_STACK_INPUT_MODE = 200;
/**
* The delta time applied on the velocity from the fling. This is to compute the kick to help
* switching the stack.
*/
private static final float SWITCH_STACK_FLING_DT = 1.0f / 30.0f;
/** The array of potentially visible stacks. The code works for only 2 stacks. */
private final Stack[] mStacks;
/** Rectangles that defines the area where each stack need to be laid out. */
private final RectF[] mStackRects;
private int mStackAnimationCount;
private float mFlingSpeed = 0; // pixel/ms
/** Whether the current fling animation is the result of switching stacks. */
private boolean mFlingFromModelChange;
private boolean mClicked;
// If not overscroll, then mRenderedScrollIndex == mScrollIndex;
// Otherwise, mRenderedScrollIndex is updated with the actual index passed in
// from the event handler; and mRenderedScrollIndex is the value we get
// after map mScrollIndex through a decelerate function.
// Here we use float as index so we can smoothly animate the transition between stack.
private float mRenderedScrollOffset = 0.0f;
private float mScrollIndexOffset = 0.0f;
private final int mMinMaxInnerMargin;
private float mInnerMarginPercent;
private float mStackOffsetYPercent;
private SwipeMode mInputMode = SwipeMode.NONE;
private float mLastOnDownX;
private float mLastOnDownY;
private long mLastOnDownTimeStamp;
private final float mMinShortPressThresholdSqr; // Computed from Android ViewConfiguration
private final float mMinDirectionThreshold; // Computed from Android ViewConfiguration
// Pre-allocated temporary arrays that store id of visible tabs.
// They can be used to call populatePriorityVisibilityList.
// We use StackTab[] instead of ArrayList<StackTab> because the sorting function does
// an allocation to iterate over the elements.
// Do not use out of the context of {@link #updateTabPriority}.
private StackTab[] mSortedPriorityArray = null;
private final ArrayList<Integer> mVisibilityArray = new ArrayList<Integer>();
private final VisibilityComparator mVisibilityComparator = new VisibilityComparator();
private final OrderComparator mOrderComparator = new OrderComparator();
private Comparator<StackTab> mSortingComparator = mVisibilityComparator;
private static final int LAYOUTTAB_ASYNCHRONOUS_INITIALIZATION_BATCH_SIZE = 4;
private boolean mDelayedLayoutTabInitRequired = false;
private Boolean mTemporarySelectedStack;
// Orientation Variables
private PortraitViewport mCachedPortraitViewport = null;
private PortraitViewport mCachedLandscapeViewport = null;
private final ViewGroup mViewContainer;
private final TabListSceneLayer mSceneLayer;
/**
* @param context The current Android's context.
* @param updateHost The {@link LayoutUpdateHost} view for this layout.
* @param renderHost The {@link LayoutRenderHost} view for this layout.
* @param eventFilter The {@link EventFilter} that is needed for this view.
*/
public StackLayout(Context context, LayoutUpdateHost updateHost, LayoutRenderHost renderHost,
EventFilter eventFilter) {
super(context, updateHost, renderHost, eventFilter);
final ViewConfiguration configuration = ViewConfiguration.get(context);
mMinDirectionThreshold = configuration.getScaledTouchSlop();
mMinShortPressThresholdSqr =
configuration.getScaledPagingTouchSlop() * configuration.getScaledPagingTouchSlop();
mMinMaxInnerMargin = (int) (MIN_INNER_MARGIN_PERCENT_DP + 0.5);
mFlingSpeed = FLING_SPEED_DP;
mStacks = new Stack[2];
mStacks[0] = new Stack(context, this);
mStacks[1] = new Stack(context, this);
mStackRects = new RectF[2];
mStackRects[0] = new RectF();
mStackRects[1] = new RectF();
mViewContainer = new FrameLayout(getContext());
mSceneLayer = new TabListSceneLayer();
}
@Override
public int getSizingFlags() {
return SizingFlags.ALLOW_TOOLBAR_SHOW | SizingFlags.REQUIRE_FULLSCREEN_SIZE;
}
@Override
public void setTabModelSelector(TabModelSelector modelSelector, TabContentManager manager) {
super.setTabModelSelector(modelSelector, manager);
mStacks[0].setTabModel(modelSelector.getModel(false));
mStacks[1].setTabModel(modelSelector.getModel(true));
resetScrollData();
}
/**
* Get the tab stack state for the specified mode.
*
* @param incognito Whether the TabStackState to be returned should be the one for incognito.
* @return The tab stack state for the given mode.
* @VisibleForTesting
*/
public Stack getTabStack(boolean incognito) {
return mStacks[incognito ? 1 : 0];
}
/**
* Get the tab stack state.
* @return The tab stack index for the given tab id.
*/
private int getTabStackIndex() {
return getTabStackIndex(Tab.INVALID_TAB_ID);
}
/**
* Get the tab stack state for the specified tab id.
*
* @param tabId The id of the tab to lookup.
* @return The tab stack index for the given tab id.
* @VisibleForTesting
*/
protected int getTabStackIndex(int tabId) {
if (tabId == Tab.INVALID_TAB_ID) {
boolean incognito = mTemporarySelectedStack != null
? mTemporarySelectedStack
: mTabModelSelector.isIncognitoSelected();
return incognito ? 1 : 0;
} else {
return TabModelUtils.getTabById(mTabModelSelector.getModel(true), tabId) != null ? 1
: 0;
}
}
/**
* Get the tab stack state for the specified tab id.
*
* @param tabId The id of the tab to lookup.
* @return The tab stack state for the given tab id.
* @VisibleForTesting
*/
protected Stack getTabStack(int tabId) {
return mStacks[getTabStackIndex(tabId)];
}
@Override
public void onTabSelecting(long time, int tabId) {
mStacks[1].ensureCleaningUpDyingTabs(time);
mStacks[0].ensureCleaningUpDyingTabs(time);
if (tabId == Tab.INVALID_TAB_ID) tabId = mTabModelSelector.getCurrentTabId();
super.onTabSelecting(time, tabId);
mStacks[getTabStackIndex()].tabSelectingEffect(time, tabId);
startMarginAnimation(false);
startYOffsetAnimation(false);
finishScrollStacks();
}
@Override
public void onTabClosing(long time, int id) {
Stack stack = getTabStack(id);
if (stack == null) return;
stack.tabClosingEffect(time, id);
// Just in case we closed the last tab of a stack we need to trigger the overlap animation.
startMarginAnimation(true);
// Animate the stack to leave incognito mode.
if (!mStacks[1].isDisplayable()) uiPreemptivelySelectTabModel(false);
}
@Override
public void onTabsAllClosing(long time, boolean incognito) {
super.onTabsAllClosing(time, incognito);
getTabStack(incognito).tabsAllClosingEffect(time);
// trigger the overlap animation.
startMarginAnimation(true);
// Animate the stack to leave incognito mode.
if (!mStacks[1].isDisplayable()) uiPreemptivelySelectTabModel(false);
}
@Override
public void onTabClosureCancelled(long time, int id, boolean incognito) {
super.onTabClosureCancelled(time, id, incognito);
getTabStack(incognito).undoClosure(time, id);
}
@Override
public boolean handlesCloseAll() {
return true;
}
@Override
public boolean handlesTabCreating() {
return true;
}
@Override
public boolean handlesTabClosing() {
return true;
}
@Override
public void attachViews(ViewGroup container) {
// TODO(dtrainor): This is a hack. We're attaching to the parent of the view container
// which is the content container of the Activity.
((ViewGroup) container.getParent())
.addView(mViewContainer,
new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
@Override
public void detachViews() {
if (mViewContainer.getParent() != null) {
((ViewGroup) mViewContainer.getParent()).removeView(mViewContainer);
}
mViewContainer.removeAllViews();
}
/**
* @return A {@link ViewGroup} that {@link Stack}s can use to interact with the Android view
* hierarchy.
*/
public ViewGroup getViewContainer() {
return mViewContainer;
}
@Override
public void onTabCreating(int sourceTabId) {
// Force any in progress animations to end. This was introduced because
// we end up with 0 tabs if the animation for all tabs closing is still
// running when a new tab is created.
// See http://crbug.com/496557
onUpdateAnimation(SystemClock.currentThreadTimeMillis(), true);
}
@Override
public void onTabCreated(long time, int id, int tabIndex, int sourceId, boolean newIsIncognito,
boolean background, float originX, float originY) {
super.onTabCreated(
time, id, tabIndex, sourceId, newIsIncognito, background, originX, originY);
startHiding(id, false);
mStacks[getTabStackIndex(id)].tabCreated(time, id);
startMarginAnimation(false);
uiPreemptivelySelectTabModel(newIsIncognito);
}
@Override
public void onTabModelSwitched(boolean toIncognitoTabModel) {
flingStacks(toIncognitoTabModel);
mFlingFromModelChange = true;
}
@Override
public boolean onUpdateAnimation(long time, boolean jumpToEnd) {
boolean animationsWasDone = super.onUpdateAnimation(time, jumpToEnd);
boolean finishedView0 = mStacks[0].onUpdateViewAnimation(time, jumpToEnd);
boolean finishedView1 = mStacks[1].onUpdateViewAnimation(time, jumpToEnd);
boolean finishedCompositor0 = mStacks[0].onUpdateCompositorAnimations(time, jumpToEnd);
boolean finishedCompositor1 = mStacks[1].onUpdateCompositorAnimations(time, jumpToEnd);
if (animationsWasDone && finishedView0 && finishedView1 && finishedCompositor0
&& finishedCompositor1) {
return true;
} else {
if (!animationsWasDone || !finishedCompositor0 || !finishedCompositor1) {
requestStackUpdate();
}
return false;
}
}
@Override
protected void onAnimationStarted() {
if (mStackAnimationCount == 0) super.onAnimationStarted();
}
@Override
protected void onAnimationFinished() {
mFlingFromModelChange = false;
if (mTemporarySelectedStack != null) {
mTabModelSelector.selectModel(mTemporarySelectedStack);
mTemporarySelectedStack = null;
}
if (mStackAnimationCount == 0) super.onAnimationFinished();
}
/**
* Called when a UI element is attempting to select a tab. This will perform the animation
* and then actually propagate the action. This starts hiding this layout which, when complete,
* will actually select the tab.
* @param time The current time of the app in ms.
* @param id The id of the tab to select.
*/
public void uiSelectingTab(long time, int id) {
onTabSelecting(time, id);
}
/**
* Called when a UI element is attempting to close a tab. This will perform the required close
* animations. When the UI is ready to actually close the tab
* {@link #uiDoneClosingTab(long, int, boolean, boolean)} should be called to actually propagate
* the event to the model.
* @param time The current time of the app in ms.
* @param id The id of the tab to close.
*/
public void uiRequestingCloseTab(long time, int id) {
// Start the tab closing effect if necessary.
getTabStack(id).tabClosingEffect(time, id);
int incognitoCount = mTabModelSelector.getModel(true).getCount();
TabModel model = mTabModelSelector.getModelForTabId(id);
if (model != null && model.isIncognito()) incognitoCount--;
boolean incognitoVisible = incognitoCount > 0;
// Make sure we show/hide both stacks depending on which tab we're closing.
startMarginAnimation(true, incognitoVisible);
if (!incognitoVisible) uiPreemptivelySelectTabModel(false);
}
/**
* Called when a UI element is done animating the close tab effect started by
* {@link #uiRequestingCloseTab(long, int)}. This actually pushes the close event to the model.
* @param time The current time of the app in ms.
* @param id The id of the tab to close.
* @param canUndo Whether or not this close can be undone.
* @param incognito Whether or not this was for the incognito stack or not.
*/
public void uiDoneClosingTab(long time, int id, boolean canUndo, boolean incognito) {
// If homepage is enabled and there is a maximum of 1 tab in both models
// (this is the last tab), the tab closure cannot be undone.
canUndo &= !(HomepageManager.isHomepageEnabled(getContext())
&& (mTabModelSelector.getModel(true).getCount()
+ mTabModelSelector.getModel(false).getCount()
< 2));
// Propagate the tab closure to the model.
TabModelUtils.closeTabById(mTabModelSelector.getModel(incognito), id, canUndo);
}
public void uiDoneClosingAllTabs(boolean incognito) {
// Propagate the tab closure to the model.
mTabModelSelector.getModel(incognito).closeAllTabs(false, false);
}
/**
* Called when a {@link Stack} instance is done animating the stack enter effect.
*/
public void uiDoneEnteringStack() {
mSortingComparator = mVisibilityComparator;
doneShowing();
}
private void uiPreemptivelySelectTabModel(boolean incognito) {
onTabModelSwitched(incognito);
}
/**
* Starts the animation for the opposite stack to slide in or out when entering
* or leaving stack view. The animation should be super fast to match more or less
* the fling animation.
* @param enter True if the stack view is being entered, false if the stack view
* is being left.
*/
private void startMarginAnimation(boolean enter) {
startMarginAnimation(enter, mStacks[1].isDisplayable());
}
private void startMarginAnimation(boolean enter, boolean showIncognito) {
float start = mInnerMarginPercent;
float end = enter && showIncognito ? 1.0f : 0.0f;
if (start != end) {
addToAnimation(this, Property.INNER_MARGIN_PERCENT, start, end, 200, 0);
}
}
private void startYOffsetAnimation(boolean enter) {
float start = mStackOffsetYPercent;
float end = enter ? 1.f : 0.f;
if (start != end) {
addToAnimation(this, Property.STACK_OFFSET_Y_PERCENT, start, end, 300, 0);
}
}
@Override
public void show(long time, boolean animate) {
super.show(time, animate);
Tab tab = mTabModelSelector.getCurrentTab();
if (tab != null && tab.isNativePage()) mTabContentManager.cacheTabThumbnail(tab);
// Remove any views in case we're getting another call to show before we hide (quickly
// toggling the tab switcher button).
mViewContainer.removeAllViews();
for (int i = mStacks.length - 1; i >= 0; --i) {
mStacks[i].reset();
if (mStacks[i].isDisplayable()) {
mStacks[i].show();
} else {
mStacks[i].cleanupTabs();
}
}
// Initialize the animation and the positioning of all the elements
mSortingComparator = mOrderComparator;
resetScrollData();
for (int i = mStacks.length - 1; i >= 0; --i) {
if (mStacks[i].isDisplayable()) {
boolean offscreen = (i != getTabStackIndex());
mStacks[i].stackEntered(time, !offscreen);
}
}
startMarginAnimation(true);
startYOffsetAnimation(true);
flingStacks(getTabStackIndex() == 1);
if (!animate) onUpdateAnimation(time, true);
// We will render before we get a call to updateLayout. Need to make sure all of the tabs
// we need to render are up to date.
updateLayout(time, 0);
}
@Override
public void swipeStarted(long time, ScrollDirection direction, float x, float y) {
mStacks[getTabStackIndex()].swipeStarted(time, direction, x, y);
}
@Override
public void swipeUpdated(long time, float x, float y, float dx, float dy, float tx, float ty) {
mStacks[getTabStackIndex()].swipeUpdated(time, x, y, dx, dy, tx, ty);
}
@Override
public void swipeFinished(long time) {
mStacks[getTabStackIndex()].swipeFinished(time);
}
@Override
public void swipeCancelled(long time) {
mStacks[getTabStackIndex()].swipeCancelled(time);
}
@Override
public void swipeFlingOccurred(
long time, float x, float y, float tx, float ty, float vx, float vy) {
mStacks[getTabStackIndex()].swipeFlingOccurred(time, x, y, tx, ty, vx, vy);
}
private void requestStackUpdate() {
// TODO(jgreenwald): It isn't always necessary to invalidate both
// stacks.
mStacks[0].requestUpdate();
mStacks[1].requestUpdate();
}
@Override
public void notifySizeChanged(float width, float height, int orientation) {
mCachedLandscapeViewport = null;
mCachedPortraitViewport = null;
mStacks[0].notifySizeChanged(width, height, orientation);
mStacks[1].notifySizeChanged(width, height, orientation);
resetScrollData();
requestStackUpdate();
}
@Override
public void contextChanged(Context context) {
super.contextChanged(context);
StackTab.resetDimensionConstants(context);
mStacks[0].contextChanged(context);
mStacks[1].contextChanged(context);
requestStackUpdate();
}
@Override
public void drag(long time, float x, float y, float amountX, float amountY) {
SwipeMode oldInputMode = mInputMode;
mInputMode = computeInputMode(time, x, y, amountX, amountY);
if (oldInputMode == SwipeMode.SEND_TO_STACK && mInputMode == SwipeMode.SWITCH_STACK) {
mStacks[getTabStackIndex()].onUpOrCancel(time);
} else if (oldInputMode == SwipeMode.SWITCH_STACK
&& mInputMode == SwipeMode.SEND_TO_STACK) {
onUpOrCancel(time);
}
if (mInputMode == SwipeMode.SEND_TO_STACK) {
mStacks[getTabStackIndex()].drag(time, x, y, amountX, amountY);
} else if (mInputMode == SwipeMode.SWITCH_STACK) {
scrollStacks(getOrientation() == Orientation.PORTRAIT ? amountX : amountY);
}
}
/**
* Computes the input mode for drag and fling based on the first event position.
* @param time The current time of the app in ms.
* @param x The x layout position of the mouse (without the displacement).
* @param y The y layout position of the mouse (without the displacement).
* @param dx The x displacement happening this frame.
* @param dy The y displacement happening this frame.
* @return The input mode to select.
*/
private SwipeMode computeInputMode(long time, float x, float y, float dx, float dy) {
if (!mStacks[1].isDisplayable()) return SwipeMode.SEND_TO_STACK;
int currentIndex = getTabStackIndex();
if (currentIndex != getViewportParameters().getStackIndexAt(x, y)) {
return SwipeMode.SWITCH_STACK;
}
float relativeX = mLastOnDownX - (x + dx);
float relativeY = mLastOnDownY - (y + dy);
float distanceToDownSqr = dx * dx + dy * dy;
float switchDelta = getOrientation() == Orientation.PORTRAIT ? relativeX : relativeY;
float otherDelta = getOrientation() == Orientation.PORTRAIT ? relativeY : relativeX;
// Dragging in the opposite direction of the stack switch
if (distanceToDownSqr > mMinDirectionThreshold * mMinDirectionThreshold
&& Math.abs(otherDelta) > Math.abs(switchDelta)) {
return SwipeMode.SEND_TO_STACK;
}
// Dragging in a direction the stack cannot switch
if (Math.abs(switchDelta) > mMinDirectionThreshold) {
if ((currentIndex == 0) ^ (switchDelta > 0)
^ (getOrientation() == Orientation.PORTRAIT
&& LocalizationUtils.isLayoutRtl())) {
return SwipeMode.SEND_TO_STACK;
}
}
if (isDraggingStackInWrongDirection(
mLastOnDownX, mLastOnDownY, x, y, dx, dy, getOrientation(), currentIndex)) {
return SwipeMode.SWITCH_STACK;
}
// Not moving the finger
if (time - mLastOnDownTimeStamp > THRESHOLD_TIME_TO_SWITCH_STACK_INPUT_MODE) {
return SwipeMode.SEND_TO_STACK;
}
// Dragging fast
if (distanceToDownSqr > mMinShortPressThresholdSqr) {
return SwipeMode.SWITCH_STACK;
}
return SwipeMode.NONE;
}
@Override
public void fling(long time, float x, float y, float vx, float vy) {
if (mInputMode == SwipeMode.NONE) {
mInputMode = computeInputMode(
time, x, y, vx * SWITCH_STACK_FLING_DT, vy * SWITCH_STACK_FLING_DT);
}
if (mInputMode == SwipeMode.SEND_TO_STACK) {
mStacks[getTabStackIndex()].fling(time, x, y, vx, vy);
} else if (mInputMode == SwipeMode.SWITCH_STACK) {
final float velocity = getOrientation() == Orientation.PORTRAIT ? vx : vy;
final float origin = getOrientation() == Orientation.PORTRAIT ? x : y;
final float max = getOrientation() == Orientation.PORTRAIT ? getWidth() : getHeight();
final float predicted = origin + velocity * SWITCH_STACK_FLING_DT;
final float delta = MathUtils.clamp(predicted, 0, max) - origin;
scrollStacks(delta);
}
requestStackUpdate();
}
class PortraitViewport {
protected float mWidth, mHeight;
PortraitViewport() {
mWidth = StackLayout.this.getWidth();
mHeight = StackLayout.this.getHeightMinusTopControls();
}
float getClampedRenderedScrollOffset() {
if (mStacks[1].isDisplayable() || mFlingFromModelChange) {
return MathUtils.clamp(mRenderedScrollOffset, 0, -1);
} else {
return 0;
}
}
float getInnerMargin() {
float margin = mInnerMarginPercent
* Math.max(mMinMaxInnerMargin, mWidth * INNER_MARGIN_PERCENT_PERCENT);
return margin;
}
int getStackIndexAt(float x, float y) {
if (LocalizationUtils.isLayoutRtl()) {
// On RTL portrait mode, stack1 (incognito) is on the left.
float separation = getStack0Left();
return x < separation ? 1 : 0;
} else {
float separation = getStack0Left() + getWidth();
return x < separation ? 0 : 1;
}
}
float getStack0Left() {
return LocalizationUtils.isLayoutRtl()
? getInnerMargin() - getClampedRenderedScrollOffset() * getFullScrollDistance()
: getClampedRenderedScrollOffset() * getFullScrollDistance();
}
float getWidth() {
return mWidth - getInnerMargin();
}
float getHeight() {
return mHeight;
}
float getStack0Top() {
return getTopHeightOffset();
}
float getStack0ToStack1TranslationX() {
return Math.round(LocalizationUtils.isLayoutRtl() ? -mWidth + getInnerMargin() : mWidth
- getInnerMargin());
}
float getStack0ToStack1TranslationY() {
return 0.0f;
}
float getTopHeightOffset() {
return (StackLayout.this.getHeight() - getHeightMinusTopControls())
* mStackOffsetYPercent;
}
}
class LandscapeViewport extends PortraitViewport {
LandscapeViewport() {
// This is purposefully inverted.
mWidth = StackLayout.this.getHeightMinusTopControls();
mHeight = StackLayout.this.getWidth();
}
@Override
float getInnerMargin() {
float margin = mInnerMarginPercent
* Math.max(mMinMaxInnerMargin, mWidth * INNER_MARGIN_PERCENT_PERCENT);
return margin;
}
@Override
int getStackIndexAt(float x, float y) {
float separation = getStack0Top() + getHeight();
return y < separation ? 0 : 1;
}
@Override
float getStack0Left() {
return 0.f;
}
@Override
float getStack0Top() {
return getClampedRenderedScrollOffset() * getFullScrollDistance()
+ getTopHeightOffset();
}
@Override
float getWidth() {
return super.getHeight();
}
@Override
float getHeight() {
return super.getWidth();
}
@Override
float getStack0ToStack1TranslationX() {
return super.getStack0ToStack1TranslationY();
}
@Override
float getStack0ToStack1TranslationY() {
return Math.round(mWidth - getInnerMargin());
}
}
private PortraitViewport getViewportParameters() {
if (getOrientation() == Orientation.PORTRAIT) {
if (mCachedPortraitViewport == null) {
mCachedPortraitViewport = new PortraitViewport();
}
return mCachedPortraitViewport;
} else {
if (mCachedLandscapeViewport == null) {
mCachedLandscapeViewport = new LandscapeViewport();
}
return mCachedLandscapeViewport;
}
}
@Override
public void click(long time, float x, float y) {
// Click event happens before the up event. mClicked is set to mute the up event.
mClicked = true;
PortraitViewport viewportParams = getViewportParameters();
int stackIndexAt = viewportParams.getStackIndexAt(x, y);
if (stackIndexAt == getTabStackIndex()) {
mStacks[getTabStackIndex()].click(time, x, y);
} else {
flingStacks(getTabStackIndex() == 0);
}
requestStackUpdate();
}
/**
* Check if we are dragging stack in a wrong direction.
*
* @param downX The X coordinate on the last down event.
* @param downY The Y coordinate on the last down event.
* @param x The current X coordinate.
* @param y The current Y coordinate.
* @param dx The amount of change in X coordinate.
* @param dy The amount of change in Y coordinate.
* @param orientation The device orientation (portrait / landscape).
* @param stackIndex The index of stack tab.
* @return True iff we are dragging stack in a wrong direction.
*/
@VisibleForTesting
public static boolean isDraggingStackInWrongDirection(float downX, float downY, float x,
float y, float dx, float dy, int orientation, int stackIndex) {
float switchDelta = orientation == Orientation.PORTRAIT ? x - downX : y - downY;
// Should not prevent scrolling even when switchDelta is in a wrong direction.
if (Math.abs(dx) < Math.abs(dy)) {
return false;
}
return (stackIndex == 0 && switchDelta < 0) || (stackIndex == 1 && switchDelta > 0);
}
private void scrollStacks(float delta) {
cancelAnimation(this, Property.STACK_SNAP);
float fullDistance = getFullScrollDistance();
mScrollIndexOffset += MathUtils.flipSignIf(delta / fullDistance,
getOrientation() == Orientation.PORTRAIT && LocalizationUtils.isLayoutRtl());
if (canScrollLinearly(getTabStackIndex())) {
mRenderedScrollOffset = mScrollIndexOffset;
} else {
mRenderedScrollOffset = (int) MathUtils.clamp(
mScrollIndexOffset, 0, mStacks[1].isDisplayable() ? -1 : 0);
}
requestStackUpdate();
}
private void flingStacks(boolean toIncognito) {
// velocityX is measured in pixel per second.
if (!canScrollLinearly(toIncognito ? 0 : 1)) return;
setActiveStackState(toIncognito);
finishScrollStacks();
requestStackUpdate();
}
/**
* Animate to the final position of the stack. Unfortunately, both touch-up
* and fling can be called and this depends on fling always being called last.
* If fling is called first, onUpOrCancel can override the fling position
* with the opposite. For example, if the user does a very small fling from
* incognito to non-incognito, which leaves the up event in the incognito side.
*/
private void finishScrollStacks() {
cancelAnimation(this, Property.STACK_SNAP);
final int currentModelIndex = getTabStackIndex();
float delta = Math.abs(currentModelIndex + mRenderedScrollOffset);
float target = -currentModelIndex;
if (delta != 0) {
long duration = FLING_MIN_DURATION
+ (long) Math.abs(delta * getFullScrollDistance() / mFlingSpeed);
addToAnimation(this, Property.STACK_SNAP, mRenderedScrollOffset, target, duration, 0);
} else {
setProperty(Property.STACK_SNAP, target);
if (mTemporarySelectedStack != null) {
mTabModelSelector.selectModel(mTemporarySelectedStack);
mTemporarySelectedStack = null;
}
}
}
@Override
public void onDown(long time, float x, float y) {
mLastOnDownX = x;
mLastOnDownY = y;
mLastOnDownTimeStamp = time;
mInputMode = computeInputMode(time, x, y, 0, 0);
mStacks[getTabStackIndex()].onDown(time);
}
@Override
public void onLongPress(long time, float x, float y) {
mStacks[getTabStackIndex()].onLongPress(time, x, y);
}
@Override
public void onUpOrCancel(long time) {
int currentIndex = getTabStackIndex();
int nextIndex = 1 - currentIndex;
if (!mClicked && Math.abs(currentIndex + mRenderedScrollOffset) > THRESHOLD_TO_SWITCH_STACK
&& mStacks[nextIndex].isDisplayable()) {
setActiveStackState(nextIndex == 1);
}
mClicked = false;
finishScrollStacks();
mStacks[getTabStackIndex()].onUpOrCancel(time);
mInputMode = SwipeMode.NONE;
}
/**
* Pushes a rectangle to be drawn on the screen on top of everything.
*
* @param rect The rectangle to be drawn on screen
* @param color The color of the rectangle
*/
public void pushDebugRect(Rect rect, int color) {
if (rect.left > rect.right) {
int tmp = rect.right;
rect.right = rect.left;
rect.left = tmp;
}
if (rect.top > rect.bottom) {
int tmp = rect.bottom;
rect.bottom = rect.top;
rect.top = tmp;
}
mRenderHost.pushDebugRect(rect, color);
}
@Override
public void onPinch(long time, float x0, float y0, float x1, float y1, boolean firstEvent) {
mStacks[getTabStackIndex()].onPinch(time, x0, y0, x1, y1, firstEvent);
}
@Override
protected void updateLayout(long time, long dt) {
super.updateLayout(time, dt);
boolean needUpdate = false;
final PortraitViewport viewport = getViewportParameters();
mStackRects[0].left = viewport.getStack0Left();
mStackRects[0].right = mStackRects[0].left + viewport.getWidth();
mStackRects[0].top = viewport.getStack0Top();
mStackRects[0].bottom = mStackRects[0].top + viewport.getHeight();
mStackRects[1].left = mStackRects[0].left + viewport.getStack0ToStack1TranslationX();
mStackRects[1].right = mStackRects[1].left + viewport.getWidth();
mStackRects[1].top = mStackRects[0].top + viewport.getStack0ToStack1TranslationY();
mStackRects[1].bottom = mStackRects[1].top + viewport.getHeight();
mStacks[0].setStackFocusInfo(1.0f + mRenderedScrollOffset,
mSortingComparator == mOrderComparator ? mTabModelSelector.getModel(false).index()
: -1);
mStacks[1].setStackFocusInfo(-mRenderedScrollOffset, mSortingComparator == mOrderComparator
? mTabModelSelector.getModel(true).index()
: -1);
// Compute position and visibility
mStacks[0].computeTabPosition(time, mStackRects[0]);
mStacks[1].computeTabPosition(time, mStackRects[1]);
// Pre-allocate/resize {@link #mLayoutTabs} before it get populated by
// computeTabPositionAndAppendLayoutTabs.
final int tabVisibleCount = mStacks[0].getVisibleCount() + mStacks[1].getVisibleCount();
if (tabVisibleCount == 0) {
mLayoutTabs = null;
} else if (mLayoutTabs == null || mLayoutTabs.length != tabVisibleCount) {
mLayoutTabs = new LayoutTab[tabVisibleCount];
}
int index = 0;
if (getTabStackIndex() == 1) {
index = appendVisibleLayoutTabs(time, 0, mLayoutTabs, index);
index = appendVisibleLayoutTabs(time, 1, mLayoutTabs, index);
} else {
index = appendVisibleLayoutTabs(time, 1, mLayoutTabs, index);
index = appendVisibleLayoutTabs(time, 0, mLayoutTabs, index);
}
assert index == tabVisibleCount : "index should be incremented up to tabVisibleCount";
// Update tab snapping
for (int i = 0; i < tabVisibleCount; i++) {
if (mLayoutTabs[i].updateSnap(dt)) needUpdate = true;
}
if (needUpdate) requestUpdate();
// Since we've updated the positions of the stacks and tabs, let's go ahead and update
// the visible tabs.
updateTabPriority();
}
private int appendVisibleLayoutTabs(long time, int stackIndex, LayoutTab[] tabs, int tabIndex) {
final StackTab[] stackTabs = mStacks[stackIndex].getTabs();
if (stackTabs != null) {
for (int i = 0; i < stackTabs.length; i++) {
LayoutTab t = stackTabs[i].getLayoutTab();
if (t.isVisible()) tabs[tabIndex++] = t;
}
}
return tabIndex;
}
/**
* Sets the active tab stack.
*
* @param isIncognito True if the model to select is incognito.
* @return Whether the tab stack index passed in differed from the currently selected stack.
*/
public boolean setActiveStackState(boolean isIncognito) {
if (isIncognito == mTabModelSelector.isIncognitoSelected()) return false;
mTemporarySelectedStack = isIncognito;
return true;
}
private void resetScrollData() {
mScrollIndexOffset = -getTabStackIndex();
mRenderedScrollOffset = mScrollIndexOffset;
}
/**
* Based on the current position, determine if we will map mScrollDistance linearly to
* mRenderedScrollDistance. The logic is, if there is only stack, we will not map linearly;
* if we are scrolling two the boundary of either of the stacks, we will not map linearly;
* otherwise yes.
*/
private boolean canScrollLinearly(int fromStackIndex) {
int count = mStacks.length;
if (!(mScrollIndexOffset <= 0 && -mScrollIndexOffset <= (count - 1))) {
return false;
}
// since we only have two stacks now, we have a shortcut to calculate
// empty stacks
return mStacks[fromStackIndex ^ 0x01].isDisplayable();
}
private float getFullScrollDistance() {
float distance =
getOrientation() == Orientation.PORTRAIT ? getWidth() : getHeightMinusTopControls();
return distance - 2 * getViewportParameters().getInnerMargin();
}
@Override
public void doneHiding() {
super.doneHiding();
mTabModelSelector.commitAllTabClosures();
}
/**
* Extracts the tabs from a stack and append them into a list.
* @param stack The stack that contains the tabs.
* @param outList The output list where will be the tabs from the stack.
* @param index The current number of item in the outList.
* @return The updated index incremented by the number of tabs in the stack.
*/
private static int addAllTabs(Stack stack, StackTab[] outList, int index) {
StackTab[] stackTabs = stack.getTabs();
if (stackTabs != null) {
for (int i = 0; i < stackTabs.length; ++i) {
outList[index++] = stackTabs[i];
}
}
return index;
}
/**
* Comparator that helps ordering StackTab's visibility sorting value in a decreasing order.
*/
private static class VisibilityComparator implements Comparator<StackTab>, Serializable {
@Override
public int compare(StackTab tab1, StackTab tab2) {
return (int) (tab2.getVisiblitySortingValue() - tab1.getVisiblitySortingValue());
}
}
/**
* Comparator that helps ordering StackTab's visibility sorting value in a decreasing order.
*/
private static class OrderComparator implements Comparator<StackTab>, Serializable {
@Override
public int compare(StackTab tab1, StackTab tab2) {
return tab1.getOrderSortingValue() - tab2.getOrderSortingValue();
}
}
private boolean updateSortedPriorityArray(Comparator<StackTab> comparator) {
final int allTabsCount = mStacks[0].getCount() + mStacks[1].getCount();
if (allTabsCount == 0) return false;
if (mSortedPriorityArray == null || mSortedPriorityArray.length != allTabsCount) {
mSortedPriorityArray = new StackTab[allTabsCount];
}
int sortedOffset = 0;
sortedOffset = addAllTabs(mStacks[0], mSortedPriorityArray, sortedOffset);
sortedOffset = addAllTabs(mStacks[1], mSortedPriorityArray, sortedOffset);
assert sortedOffset == mSortedPriorityArray.length;
Arrays.sort(mSortedPriorityArray, comparator);
return true;
}
/**
* Updates the priority list of the {@link LayoutTab} and sends it the systems having processing
* to do on a per {@link LayoutTab} basis. Priority meaning may change based on the current
* comparator stored in {@link #mSortingComparator}.
*
* Do not use {@link #mSortedPriorityArray} out side this context. It is only a member to avoid
* doing an allocation every frames.
*/
private void updateTabPriority() {
if (!updateSortedPriorityArray(mSortingComparator)) return;
updateTabsVisibility(mSortedPriorityArray);
updateDelayedLayoutTabInit(mSortedPriorityArray);
}
/**
* Updates the list of visible tab Id that the tab content manager is suppose to serve. The list
* is ordered by priority. The first ones must be in the manager, then the remaining ones should
* have at least approximations if possible.
*
* @param sortedPriorityArray The array of all the {@link StackTab} sorted by priority.
*/
private void updateTabsVisibility(StackTab[] sortedPriorityArray) {
mVisibilityArray.clear();
for (int i = 0; i < sortedPriorityArray.length; i++) {
mVisibilityArray.add(sortedPriorityArray[i].getId());
}
updateCacheVisibleIds(mVisibilityArray);
}
/**
* Initializes the {@link LayoutTab} a few at a time. This function is to be called once a
* frame.
* The logic of that function is not as trivial as it should be because the input array we want
* to initialize the tab from keeps getting reordered from calls to call. This is needed to
* get the highest priority tab initialized first.
*
* @param sortedPriorityArray The array of all the {@link StackTab} sorted by priority.
*/
private void updateDelayedLayoutTabInit(StackTab[] sortedPriorityArray) {
if (!mDelayedLayoutTabInitRequired) return;
int initialized = 0;
final int count = sortedPriorityArray.length;
for (int i = 0; i < count; i++) {
if (initialized >= LAYOUTTAB_ASYNCHRONOUS_INITIALIZATION_BATCH_SIZE) return;
LayoutTab layoutTab = sortedPriorityArray[i].getLayoutTab();
// The actual initialization is done by the parent class.
if (super.initLayoutTabFromHost(layoutTab)) {
initialized++;
}
}
if (initialized == 0) mDelayedLayoutTabInitRequired = false;
}
@Override
protected boolean initLayoutTabFromHost(LayoutTab layoutTab) {
if (layoutTab.isInitFromHostNeeded()) mDelayedLayoutTabInitRequired = true;
return false;
}
/**
* Sets properties for animations.
* @param prop The property to update
* @param p New value of the property
*/
@Override
public void setProperty(Property prop, float p) {
switch (prop) {
case STACK_SNAP:
mRenderedScrollOffset = p;
mScrollIndexOffset = p;
break;
case INNER_MARGIN_PERCENT:
mInnerMarginPercent = p;
break;
case STACK_OFFSET_Y_PERCENT:
mStackOffsetYPercent = p;
break;
}
}
/**
* Called by the stacks whenever they start an animation.
*/
public void onStackAnimationStarted() {
if (mStackAnimationCount == 0) super.onAnimationStarted();
mStackAnimationCount++;
}
/**
* Called by the stacks whenever they finish their animations.
*/
public void onStackAnimationFinished() {
mStackAnimationCount--;
if (mStackAnimationCount == 0) super.onAnimationFinished();
}
@Override
protected SceneLayer getSceneLayer() {
return mSceneLayer;
}
@Override
protected void updateSceneLayer(Rect viewport, Rect contentViewport,
LayerTitleCache layerTitleCache, TabContentManager tabContentManager,
ResourceManager resourceManager, ChromeFullscreenManager fullscreenManager) {
super.updateSceneLayer(viewport, contentViewport, layerTitleCache, tabContentManager,
resourceManager, fullscreenManager);
assert mSceneLayer != null;
mSceneLayer.pushLayers(getContext(), viewport, contentViewport, this, layerTitleCache,
tabContentManager, resourceManager);
}
}
| chrome/android/java_staging/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayout.java | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.compositor.layouts.phone;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.Tab;
import org.chromium.chrome.browser.compositor.LayerTitleCache;
import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation.Animatable;
import org.chromium.chrome.browser.compositor.layouts.Layout;
import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost;
import org.chromium.chrome.browser.compositor.layouts.LayoutUpdateHost;
import org.chromium.chrome.browser.compositor.layouts.components.LayoutTab;
import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.EdgeSwipeEventFilter.ScrollDirection;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.EventFilter;
import org.chromium.chrome.browser.compositor.layouts.phone.stack.Stack;
import org.chromium.chrome.browser.compositor.layouts.phone.stack.StackTab;
import org.chromium.chrome.browser.compositor.scene_layer.SceneLayer;
import org.chromium.chrome.browser.compositor.scene_layer.TabListSceneLayer;
import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager;
import org.chromium.chrome.browser.partnercustomizations.HomepageManager;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.chrome.browser.util.MathUtils;
import org.chromium.ui.base.LocalizationUtils;
import org.chromium.ui.resources.ResourceManager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
/**
* Defines the layout for 2 stacks and manages the events to switch between
* them.
*/
public class StackLayout extends Layout implements Animatable<StackLayout.Property> {
public enum Property {
INNER_MARGIN_PERCENT,
STACK_SNAP,
STACK_OFFSET_Y_PERCENT,
}
private enum SwipeMode { NONE, SEND_TO_STACK, SWITCH_STACK }
private static final String TAG = "StackLayout";
// Width of the partially shown stack when there are multiple stacks.
private static final int MIN_INNER_MARGIN_PERCENT_DP = 55;
private static final float INNER_MARGIN_PERCENT_PERCENT = 0.17f;
// Speed of the automatic fling in dp/ms
private static final float FLING_SPEED_DP = 1.5f; // dp / ms
private static final int FLING_MIN_DURATION = 100; // ms
private static final float THRESHOLD_TO_SWITCH_STACK = 0.4f;
private static final float THRESHOLD_TIME_TO_SWITCH_STACK_INPUT_MODE = 200;
/**
* The delta time applied on the velocity from the fling. This is to compute the kick to help
* switching the stack.
*/
private static final float SWITCH_STACK_FLING_DT = 1.0f / 30.0f;
/** The array of potentially visible stacks. The code works for only 2 stacks. */
private final Stack[] mStacks;
/** Rectangles that defines the area where each stack need to be laid out. */
private final RectF[] mStackRects;
private int mStackAnimationCount;
private float mFlingSpeed = 0; // pixel/ms
/** Whether the current fling animation is the result of switching stacks. */
private boolean mFlingFromModelChange;
private boolean mClicked;
// If not overscroll, then mRenderedScrollIndex == mScrollIndex;
// Otherwise, mRenderedScrollIndex is updated with the actual index passed in
// from the event handler; and mRenderedScrollIndex is the value we get
// after map mScrollIndex through a decelerate function.
// Here we use float as index so we can smoothly animate the transition between stack.
private float mRenderedScrollOffset = 0.0f;
private float mScrollIndexOffset = 0.0f;
private final int mMinMaxInnerMargin;
private float mInnerMarginPercent;
private float mStackOffsetYPercent;
private SwipeMode mInputMode = SwipeMode.NONE;
private float mLastOnDownX;
private float mLastOnDownY;
private long mLastOnDownTimeStamp;
private final float mMinShortPressThresholdSqr; // Computed from Android ViewConfiguration
private final float mMinDirectionThreshold; // Computed from Android ViewConfiguration
// Pre-allocated temporary arrays that store id of visible tabs.
// They can be used to call populatePriorityVisibilityList.
// We use StackTab[] instead of ArrayList<StackTab> because the sorting function does
// an allocation to iterate over the elements.
// Do not use out of the context of {@link #updateTabPriority}.
private StackTab[] mSortedPriorityArray = null;
private final ArrayList<Integer> mVisibilityArray = new ArrayList<Integer>();
private final VisibilityComparator mVisibilityComparator = new VisibilityComparator();
private final OrderComparator mOrderComparator = new OrderComparator();
private Comparator<StackTab> mSortingComparator = mVisibilityComparator;
private static final int LAYOUTTAB_ASYNCHRONOUS_INITIALIZATION_BATCH_SIZE = 4;
private boolean mDelayedLayoutTabInitRequired = false;
private Boolean mTemporarySelectedStack;
// Orientation Variables
private PortraitViewport mCachedPortraitViewport = null;
private PortraitViewport mCachedLandscapeViewport = null;
private final ViewGroup mViewContainer;
private final TabListSceneLayer mSceneLayer;
/**
* @param context The current Android's context.
* @param updateHost The {@link LayoutUpdateHost} view for this layout.
* @param renderHost The {@link LayoutRenderHost} view for this layout.
* @param eventFilter The {@link EventFilter} that is needed for this view.
*/
public StackLayout(Context context, LayoutUpdateHost updateHost, LayoutRenderHost renderHost,
EventFilter eventFilter) {
super(context, updateHost, renderHost, eventFilter);
final ViewConfiguration configuration = ViewConfiguration.get(context);
mMinDirectionThreshold = configuration.getScaledTouchSlop();
mMinShortPressThresholdSqr =
configuration.getScaledPagingTouchSlop() * configuration.getScaledPagingTouchSlop();
mMinMaxInnerMargin = (int) (MIN_INNER_MARGIN_PERCENT_DP + 0.5);
mFlingSpeed = FLING_SPEED_DP;
mStacks = new Stack[2];
mStacks[0] = new Stack(context, this);
mStacks[1] = new Stack(context, this);
mStackRects = new RectF[2];
mStackRects[0] = new RectF();
mStackRects[1] = new RectF();
mViewContainer = new FrameLayout(getContext());
mSceneLayer = new TabListSceneLayer();
}
@Override
public int getSizingFlags() {
return SizingFlags.ALLOW_TOOLBAR_SHOW | SizingFlags.REQUIRE_FULLSCREEN_SIZE;
}
@Override
public void setTabModelSelector(TabModelSelector modelSelector, TabContentManager manager) {
super.setTabModelSelector(modelSelector, manager);
mStacks[0].setTabModel(modelSelector.getModel(false));
mStacks[1].setTabModel(modelSelector.getModel(true));
resetScrollData();
}
/**
* Get the tab stack state for the specified mode.
*
* @param incognito Whether the TabStackState to be returned should be the one for incognito.
* @return The tab stack state for the given mode.
* @VisibleForTesting
*/
public Stack getTabStack(boolean incognito) {
return mStacks[incognito ? 1 : 0];
}
/**
* Get the tab stack state.
* @return The tab stack index for the given tab id.
*/
private int getTabStackIndex() {
return getTabStackIndex(Tab.INVALID_TAB_ID);
}
/**
* Get the tab stack state for the specified tab id.
*
* @param tabId The id of the tab to lookup.
* @return The tab stack index for the given tab id.
* @VisibleForTesting
*/
protected int getTabStackIndex(int tabId) {
if (tabId == Tab.INVALID_TAB_ID) {
boolean incognito = mTemporarySelectedStack != null
? mTemporarySelectedStack
: mTabModelSelector.isIncognitoSelected();
return incognito ? 1 : 0;
} else {
return TabModelUtils.getTabById(mTabModelSelector.getModel(true), tabId) != null ? 1
: 0;
}
}
/**
* Get the tab stack state for the specified tab id.
*
* @param tabId The id of the tab to lookup.
* @return The tab stack state for the given tab id.
* @VisibleForTesting
*/
protected Stack getTabStack(int tabId) {
return mStacks[getTabStackIndex(tabId)];
}
@Override
public void onTabSelecting(long time, int tabId) {
mStacks[1].ensureCleaningUpDyingTabs(time);
mStacks[0].ensureCleaningUpDyingTabs(time);
if (tabId == Tab.INVALID_TAB_ID) tabId = mTabModelSelector.getCurrentTabId();
super.onTabSelecting(time, tabId);
mStacks[getTabStackIndex()].tabSelectingEffect(time, tabId);
startMarginAnimation(false);
startYOffsetAnimation(false);
finishScrollStacks();
}
@Override
public void onTabClosing(long time, int id) {
Stack stack = getTabStack(id);
if (stack == null) return;
stack.tabClosingEffect(time, id);
// Just in case we closed the last tab of a stack we need to trigger the overlap animation.
startMarginAnimation(true);
// Animate the stack to leave incognito mode.
if (!mStacks[1].isDisplayable()) uiPreemptivelySelectTabModel(false);
}
@Override
public void onTabsAllClosing(long time, boolean incognito) {
super.onTabsAllClosing(time, incognito);
getTabStack(incognito).tabsAllClosingEffect(time);
// trigger the overlap animation.
startMarginAnimation(true);
// Animate the stack to leave incognito mode.
if (!mStacks[1].isDisplayable()) uiPreemptivelySelectTabModel(false);
}
@Override
public void onTabClosureCancelled(long time, int id, boolean incognito) {
super.onTabClosureCancelled(time, id, incognito);
getTabStack(incognito).undoClosure(time, id);
}
@Override
public boolean handlesCloseAll() {
return true;
}
@Override
public boolean handlesTabCreating() {
return true;
}
@Override
public boolean handlesTabClosing() {
return true;
}
@Override
public void attachViews(ViewGroup container) {
// TODO(dtrainor): This is a hack. We're attaching to the parent of the view container
// which is the content container of the Activity.
((ViewGroup) container.getParent())
.addView(mViewContainer,
new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
@Override
public void detachViews() {
if (mViewContainer.getParent() != null) {
((ViewGroup) mViewContainer.getParent()).removeView(mViewContainer);
}
mViewContainer.removeAllViews();
}
/**
* @return A {@link ViewGroup} that {@link Stack}s can use to interact with the Android view
* hierarchy.
*/
public ViewGroup getViewContainer() {
return mViewContainer;
}
@Override
public void onTabCreated(long time, int id, int tabIndex, int sourceId, boolean newIsIncognito,
boolean background, float originX, float originY) {
super.onTabCreated(
time, id, tabIndex, sourceId, newIsIncognito, background, originX, originY);
startHiding(id, false);
mStacks[getTabStackIndex(id)].tabCreated(time, id);
startMarginAnimation(false);
uiPreemptivelySelectTabModel(newIsIncognito);
}
@Override
public void onTabModelSwitched(boolean toIncognitoTabModel) {
flingStacks(toIncognitoTabModel);
mFlingFromModelChange = true;
}
@Override
public boolean onUpdateAnimation(long time, boolean jumpToEnd) {
boolean animationsWasDone = super.onUpdateAnimation(time, jumpToEnd);
boolean finishedView0 = mStacks[0].onUpdateViewAnimation(time, jumpToEnd);
boolean finishedView1 = mStacks[1].onUpdateViewAnimation(time, jumpToEnd);
boolean finishedCompositor0 = mStacks[0].onUpdateCompositorAnimations(time, jumpToEnd);
boolean finishedCompositor1 = mStacks[1].onUpdateCompositorAnimations(time, jumpToEnd);
if (animationsWasDone && finishedView0 && finishedView1 && finishedCompositor0
&& finishedCompositor1) {
return true;
} else {
if (!animationsWasDone || !finishedCompositor0 || !finishedCompositor1) {
requestStackUpdate();
}
return false;
}
}
@Override
protected void onAnimationStarted() {
if (mStackAnimationCount == 0) super.onAnimationStarted();
}
@Override
protected void onAnimationFinished() {
mFlingFromModelChange = false;
if (mTemporarySelectedStack != null) {
mTabModelSelector.selectModel(mTemporarySelectedStack);
mTemporarySelectedStack = null;
}
if (mStackAnimationCount == 0) super.onAnimationFinished();
}
/**
* Called when a UI element is attempting to select a tab. This will perform the animation
* and then actually propagate the action. This starts hiding this layout which, when complete,
* will actually select the tab.
* @param time The current time of the app in ms.
* @param id The id of the tab to select.
*/
public void uiSelectingTab(long time, int id) {
onTabSelecting(time, id);
}
/**
* Called when a UI element is attempting to close a tab. This will perform the required close
* animations. When the UI is ready to actually close the tab
* {@link #uiDoneClosingTab(long, int, boolean, boolean)} should be called to actually propagate
* the event to the model.
* @param time The current time of the app in ms.
* @param id The id of the tab to close.
*/
public void uiRequestingCloseTab(long time, int id) {
// Start the tab closing effect if necessary.
getTabStack(id).tabClosingEffect(time, id);
int incognitoCount = mTabModelSelector.getModel(true).getCount();
TabModel model = mTabModelSelector.getModelForTabId(id);
if (model != null && model.isIncognito()) incognitoCount--;
boolean incognitoVisible = incognitoCount > 0;
// Make sure we show/hide both stacks depending on which tab we're closing.
startMarginAnimation(true, incognitoVisible);
if (!incognitoVisible) uiPreemptivelySelectTabModel(false);
}
/**
* Called when a UI element is done animating the close tab effect started by
* {@link #uiRequestingCloseTab(long, int)}. This actually pushes the close event to the model.
* @param time The current time of the app in ms.
* @param id The id of the tab to close.
* @param canUndo Whether or not this close can be undone.
* @param incognito Whether or not this was for the incognito stack or not.
*/
public void uiDoneClosingTab(long time, int id, boolean canUndo, boolean incognito) {
// If homepage is enabled and there is a maximum of 1 tab in both models
// (this is the last tab), the tab closure cannot be undone.
canUndo &= !(HomepageManager.isHomepageEnabled(getContext())
&& (mTabModelSelector.getModel(true).getCount()
+ mTabModelSelector.getModel(false).getCount()
< 2));
// Propagate the tab closure to the model.
TabModelUtils.closeTabById(mTabModelSelector.getModel(incognito), id, canUndo);
}
public void uiDoneClosingAllTabs(boolean incognito) {
// Propagate the tab closure to the model.
mTabModelSelector.getModel(incognito).closeAllTabs(false, false);
}
/**
* Called when a {@link Stack} instance is done animating the stack enter effect.
*/
public void uiDoneEnteringStack() {
mSortingComparator = mVisibilityComparator;
doneShowing();
}
private void uiPreemptivelySelectTabModel(boolean incognito) {
onTabModelSwitched(incognito);
}
/**
* Starts the animation for the opposite stack to slide in or out when entering
* or leaving stack view. The animation should be super fast to match more or less
* the fling animation.
* @param enter True if the stack view is being entered, false if the stack view
* is being left.
*/
private void startMarginAnimation(boolean enter) {
startMarginAnimation(enter, mStacks[1].isDisplayable());
}
private void startMarginAnimation(boolean enter, boolean showIncognito) {
float start = mInnerMarginPercent;
float end = enter && showIncognito ? 1.0f : 0.0f;
if (start != end) {
addToAnimation(this, Property.INNER_MARGIN_PERCENT, start, end, 200, 0);
}
}
private void startYOffsetAnimation(boolean enter) {
float start = mStackOffsetYPercent;
float end = enter ? 1.f : 0.f;
if (start != end) {
addToAnimation(this, Property.STACK_OFFSET_Y_PERCENT, start, end, 300, 0);
}
}
@Override
public void show(long time, boolean animate) {
super.show(time, animate);
Tab tab = mTabModelSelector.getCurrentTab();
if (tab != null && tab.isNativePage()) mTabContentManager.cacheTabThumbnail(tab);
// Remove any views in case we're getting another call to show before we hide (quickly
// toggling the tab switcher button).
mViewContainer.removeAllViews();
for (int i = mStacks.length - 1; i >= 0; --i) {
mStacks[i].reset();
if (mStacks[i].isDisplayable()) {
mStacks[i].show();
} else {
mStacks[i].cleanupTabs();
}
}
// Initialize the animation and the positioning of all the elements
mSortingComparator = mOrderComparator;
resetScrollData();
for (int i = mStacks.length - 1; i >= 0; --i) {
if (mStacks[i].isDisplayable()) {
boolean offscreen = (i != getTabStackIndex());
mStacks[i].stackEntered(time, !offscreen);
}
}
startMarginAnimation(true);
startYOffsetAnimation(true);
flingStacks(getTabStackIndex() == 1);
if (!animate) onUpdateAnimation(time, true);
// We will render before we get a call to updateLayout. Need to make sure all of the tabs
// we need to render are up to date.
updateLayout(time, 0);
}
@Override
public void swipeStarted(long time, ScrollDirection direction, float x, float y) {
mStacks[getTabStackIndex()].swipeStarted(time, direction, x, y);
}
@Override
public void swipeUpdated(long time, float x, float y, float dx, float dy, float tx, float ty) {
mStacks[getTabStackIndex()].swipeUpdated(time, x, y, dx, dy, tx, ty);
}
@Override
public void swipeFinished(long time) {
mStacks[getTabStackIndex()].swipeFinished(time);
}
@Override
public void swipeCancelled(long time) {
mStacks[getTabStackIndex()].swipeCancelled(time);
}
@Override
public void swipeFlingOccurred(
long time, float x, float y, float tx, float ty, float vx, float vy) {
mStacks[getTabStackIndex()].swipeFlingOccurred(time, x, y, tx, ty, vx, vy);
}
private void requestStackUpdate() {
// TODO(jgreenwald): It isn't always necessary to invalidate both
// stacks.
mStacks[0].requestUpdate();
mStacks[1].requestUpdate();
}
@Override
public void notifySizeChanged(float width, float height, int orientation) {
mCachedLandscapeViewport = null;
mCachedPortraitViewport = null;
mStacks[0].notifySizeChanged(width, height, orientation);
mStacks[1].notifySizeChanged(width, height, orientation);
resetScrollData();
requestStackUpdate();
}
@Override
public void contextChanged(Context context) {
super.contextChanged(context);
StackTab.resetDimensionConstants(context);
mStacks[0].contextChanged(context);
mStacks[1].contextChanged(context);
requestStackUpdate();
}
@Override
public void drag(long time, float x, float y, float amountX, float amountY) {
SwipeMode oldInputMode = mInputMode;
mInputMode = computeInputMode(time, x, y, amountX, amountY);
if (oldInputMode == SwipeMode.SEND_TO_STACK && mInputMode == SwipeMode.SWITCH_STACK) {
mStacks[getTabStackIndex()].onUpOrCancel(time);
} else if (oldInputMode == SwipeMode.SWITCH_STACK
&& mInputMode == SwipeMode.SEND_TO_STACK) {
onUpOrCancel(time);
}
if (mInputMode == SwipeMode.SEND_TO_STACK) {
mStacks[getTabStackIndex()].drag(time, x, y, amountX, amountY);
} else if (mInputMode == SwipeMode.SWITCH_STACK) {
scrollStacks(getOrientation() == Orientation.PORTRAIT ? amountX : amountY);
}
}
/**
* Computes the input mode for drag and fling based on the first event position.
* @param time The current time of the app in ms.
* @param x The x layout position of the mouse (without the displacement).
* @param y The y layout position of the mouse (without the displacement).
* @param dx The x displacement happening this frame.
* @param dy The y displacement happening this frame.
* @return The input mode to select.
*/
private SwipeMode computeInputMode(long time, float x, float y, float dx, float dy) {
if (!mStacks[1].isDisplayable()) return SwipeMode.SEND_TO_STACK;
int currentIndex = getTabStackIndex();
if (currentIndex != getViewportParameters().getStackIndexAt(x, y)) {
return SwipeMode.SWITCH_STACK;
}
float relativeX = mLastOnDownX - (x + dx);
float relativeY = mLastOnDownY - (y + dy);
float distanceToDownSqr = dx * dx + dy * dy;
float switchDelta = getOrientation() == Orientation.PORTRAIT ? relativeX : relativeY;
float otherDelta = getOrientation() == Orientation.PORTRAIT ? relativeY : relativeX;
// Dragging in the opposite direction of the stack switch
if (distanceToDownSqr > mMinDirectionThreshold * mMinDirectionThreshold
&& Math.abs(otherDelta) > Math.abs(switchDelta)) {
return SwipeMode.SEND_TO_STACK;
}
// Dragging in a direction the stack cannot switch
if (Math.abs(switchDelta) > mMinDirectionThreshold) {
if ((currentIndex == 0) ^ (switchDelta > 0)
^ (getOrientation() == Orientation.PORTRAIT
&& LocalizationUtils.isLayoutRtl())) {
return SwipeMode.SEND_TO_STACK;
}
}
if (isDraggingStackInWrongDirection(
mLastOnDownX, mLastOnDownY, x, y, dx, dy, getOrientation(), currentIndex)) {
return SwipeMode.SWITCH_STACK;
}
// Not moving the finger
if (time - mLastOnDownTimeStamp > THRESHOLD_TIME_TO_SWITCH_STACK_INPUT_MODE) {
return SwipeMode.SEND_TO_STACK;
}
// Dragging fast
if (distanceToDownSqr > mMinShortPressThresholdSqr) {
return SwipeMode.SWITCH_STACK;
}
return SwipeMode.NONE;
}
@Override
public void fling(long time, float x, float y, float vx, float vy) {
if (mInputMode == SwipeMode.NONE) {
mInputMode = computeInputMode(
time, x, y, vx * SWITCH_STACK_FLING_DT, vy * SWITCH_STACK_FLING_DT);
}
if (mInputMode == SwipeMode.SEND_TO_STACK) {
mStacks[getTabStackIndex()].fling(time, x, y, vx, vy);
} else if (mInputMode == SwipeMode.SWITCH_STACK) {
final float velocity = getOrientation() == Orientation.PORTRAIT ? vx : vy;
final float origin = getOrientation() == Orientation.PORTRAIT ? x : y;
final float max = getOrientation() == Orientation.PORTRAIT ? getWidth() : getHeight();
final float predicted = origin + velocity * SWITCH_STACK_FLING_DT;
final float delta = MathUtils.clamp(predicted, 0, max) - origin;
scrollStacks(delta);
}
requestStackUpdate();
}
class PortraitViewport {
protected float mWidth, mHeight;
PortraitViewport() {
mWidth = StackLayout.this.getWidth();
mHeight = StackLayout.this.getHeightMinusTopControls();
}
float getClampedRenderedScrollOffset() {
if (mStacks[1].isDisplayable() || mFlingFromModelChange) {
return MathUtils.clamp(mRenderedScrollOffset, 0, -1);
} else {
return 0;
}
}
float getInnerMargin() {
float margin = mInnerMarginPercent
* Math.max(mMinMaxInnerMargin, mWidth * INNER_MARGIN_PERCENT_PERCENT);
return margin;
}
int getStackIndexAt(float x, float y) {
if (LocalizationUtils.isLayoutRtl()) {
// On RTL portrait mode, stack1 (incognito) is on the left.
float separation = getStack0Left();
return x < separation ? 1 : 0;
} else {
float separation = getStack0Left() + getWidth();
return x < separation ? 0 : 1;
}
}
float getStack0Left() {
return LocalizationUtils.isLayoutRtl()
? getInnerMargin() - getClampedRenderedScrollOffset() * getFullScrollDistance()
: getClampedRenderedScrollOffset() * getFullScrollDistance();
}
float getWidth() {
return mWidth - getInnerMargin();
}
float getHeight() {
return mHeight;
}
float getStack0Top() {
return getTopHeightOffset();
}
float getStack0ToStack1TranslationX() {
return Math.round(LocalizationUtils.isLayoutRtl() ? -mWidth + getInnerMargin() : mWidth
- getInnerMargin());
}
float getStack0ToStack1TranslationY() {
return 0.0f;
}
float getTopHeightOffset() {
return (StackLayout.this.getHeight() - getHeightMinusTopControls())
* mStackOffsetYPercent;
}
}
class LandscapeViewport extends PortraitViewport {
LandscapeViewport() {
// This is purposefully inverted.
mWidth = StackLayout.this.getHeightMinusTopControls();
mHeight = StackLayout.this.getWidth();
}
@Override
float getInnerMargin() {
float margin = mInnerMarginPercent
* Math.max(mMinMaxInnerMargin, mWidth * INNER_MARGIN_PERCENT_PERCENT);
return margin;
}
@Override
int getStackIndexAt(float x, float y) {
float separation = getStack0Top() + getHeight();
return y < separation ? 0 : 1;
}
@Override
float getStack0Left() {
return 0.f;
}
@Override
float getStack0Top() {
return getClampedRenderedScrollOffset() * getFullScrollDistance()
+ getTopHeightOffset();
}
@Override
float getWidth() {
return super.getHeight();
}
@Override
float getHeight() {
return super.getWidth();
}
@Override
float getStack0ToStack1TranslationX() {
return super.getStack0ToStack1TranslationY();
}
@Override
float getStack0ToStack1TranslationY() {
return Math.round(mWidth - getInnerMargin());
}
}
private PortraitViewport getViewportParameters() {
if (getOrientation() == Orientation.PORTRAIT) {
if (mCachedPortraitViewport == null) {
mCachedPortraitViewport = new PortraitViewport();
}
return mCachedPortraitViewport;
} else {
if (mCachedLandscapeViewport == null) {
mCachedLandscapeViewport = new LandscapeViewport();
}
return mCachedLandscapeViewport;
}
}
@Override
public void click(long time, float x, float y) {
// Click event happens before the up event. mClicked is set to mute the up event.
mClicked = true;
PortraitViewport viewportParams = getViewportParameters();
int stackIndexAt = viewportParams.getStackIndexAt(x, y);
if (stackIndexAt == getTabStackIndex()) {
mStacks[getTabStackIndex()].click(time, x, y);
} else {
flingStacks(getTabStackIndex() == 0);
}
requestStackUpdate();
}
/**
* Check if we are dragging stack in a wrong direction.
*
* @param downX The X coordinate on the last down event.
* @param downY The Y coordinate on the last down event.
* @param x The current X coordinate.
* @param y The current Y coordinate.
* @param dx The amount of change in X coordinate.
* @param dy The amount of change in Y coordinate.
* @param orientation The device orientation (portrait / landscape).
* @param stackIndex The index of stack tab.
* @return True iff we are dragging stack in a wrong direction.
*/
@VisibleForTesting
public static boolean isDraggingStackInWrongDirection(float downX, float downY, float x,
float y, float dx, float dy, int orientation, int stackIndex) {
float switchDelta = orientation == Orientation.PORTRAIT ? x - downX : y - downY;
// Should not prevent scrolling even when switchDelta is in a wrong direction.
if (Math.abs(dx) < Math.abs(dy)) {
return false;
}
return (stackIndex == 0 && switchDelta < 0) || (stackIndex == 1 && switchDelta > 0);
}
private void scrollStacks(float delta) {
cancelAnimation(this, Property.STACK_SNAP);
float fullDistance = getFullScrollDistance();
mScrollIndexOffset += MathUtils.flipSignIf(delta / fullDistance,
getOrientation() == Orientation.PORTRAIT && LocalizationUtils.isLayoutRtl());
if (canScrollLinearly(getTabStackIndex())) {
mRenderedScrollOffset = mScrollIndexOffset;
} else {
mRenderedScrollOffset = (int) MathUtils.clamp(
mScrollIndexOffset, 0, mStacks[1].isDisplayable() ? -1 : 0);
}
requestStackUpdate();
}
private void flingStacks(boolean toIncognito) {
// velocityX is measured in pixel per second.
if (!canScrollLinearly(toIncognito ? 0 : 1)) return;
setActiveStackState(toIncognito);
finishScrollStacks();
requestStackUpdate();
}
/**
* Animate to the final position of the stack. Unfortunately, both touch-up
* and fling can be called and this depends on fling always being called last.
* If fling is called first, onUpOrCancel can override the fling position
* with the opposite. For example, if the user does a very small fling from
* incognito to non-incognito, which leaves the up event in the incognito side.
*/
private void finishScrollStacks() {
cancelAnimation(this, Property.STACK_SNAP);
final int currentModelIndex = getTabStackIndex();
float delta = Math.abs(currentModelIndex + mRenderedScrollOffset);
float target = -currentModelIndex;
if (delta != 0) {
long duration = FLING_MIN_DURATION
+ (long) Math.abs(delta * getFullScrollDistance() / mFlingSpeed);
addToAnimation(this, Property.STACK_SNAP, mRenderedScrollOffset, target, duration, 0);
} else {
setProperty(Property.STACK_SNAP, target);
if (mTemporarySelectedStack != null) {
mTabModelSelector.selectModel(mTemporarySelectedStack);
mTemporarySelectedStack = null;
}
}
}
@Override
public void onDown(long time, float x, float y) {
mLastOnDownX = x;
mLastOnDownY = y;
mLastOnDownTimeStamp = time;
mInputMode = computeInputMode(time, x, y, 0, 0);
mStacks[getTabStackIndex()].onDown(time);
}
@Override
public void onLongPress(long time, float x, float y) {
mStacks[getTabStackIndex()].onLongPress(time, x, y);
}
@Override
public void onUpOrCancel(long time) {
int currentIndex = getTabStackIndex();
int nextIndex = 1 - currentIndex;
if (!mClicked && Math.abs(currentIndex + mRenderedScrollOffset) > THRESHOLD_TO_SWITCH_STACK
&& mStacks[nextIndex].isDisplayable()) {
setActiveStackState(nextIndex == 1);
}
mClicked = false;
finishScrollStacks();
mStacks[getTabStackIndex()].onUpOrCancel(time);
mInputMode = SwipeMode.NONE;
}
/**
* Pushes a rectangle to be drawn on the screen on top of everything.
*
* @param rect The rectangle to be drawn on screen
* @param color The color of the rectangle
*/
public void pushDebugRect(Rect rect, int color) {
if (rect.left > rect.right) {
int tmp = rect.right;
rect.right = rect.left;
rect.left = tmp;
}
if (rect.top > rect.bottom) {
int tmp = rect.bottom;
rect.bottom = rect.top;
rect.top = tmp;
}
mRenderHost.pushDebugRect(rect, color);
}
@Override
public void onPinch(long time, float x0, float y0, float x1, float y1, boolean firstEvent) {
mStacks[getTabStackIndex()].onPinch(time, x0, y0, x1, y1, firstEvent);
}
@Override
protected void updateLayout(long time, long dt) {
super.updateLayout(time, dt);
boolean needUpdate = false;
final PortraitViewport viewport = getViewportParameters();
mStackRects[0].left = viewport.getStack0Left();
mStackRects[0].right = mStackRects[0].left + viewport.getWidth();
mStackRects[0].top = viewport.getStack0Top();
mStackRects[0].bottom = mStackRects[0].top + viewport.getHeight();
mStackRects[1].left = mStackRects[0].left + viewport.getStack0ToStack1TranslationX();
mStackRects[1].right = mStackRects[1].left + viewport.getWidth();
mStackRects[1].top = mStackRects[0].top + viewport.getStack0ToStack1TranslationY();
mStackRects[1].bottom = mStackRects[1].top + viewport.getHeight();
mStacks[0].setStackFocusInfo(1.0f + mRenderedScrollOffset,
mSortingComparator == mOrderComparator ? mTabModelSelector.getModel(false).index()
: -1);
mStacks[1].setStackFocusInfo(-mRenderedScrollOffset, mSortingComparator == mOrderComparator
? mTabModelSelector.getModel(true).index()
: -1);
// Compute position and visibility
mStacks[0].computeTabPosition(time, mStackRects[0]);
mStacks[1].computeTabPosition(time, mStackRects[1]);
// Pre-allocate/resize {@link #mLayoutTabs} before it get populated by
// computeTabPositionAndAppendLayoutTabs.
final int tabVisibleCount = mStacks[0].getVisibleCount() + mStacks[1].getVisibleCount();
if (tabVisibleCount == 0) {
mLayoutTabs = null;
} else if (mLayoutTabs == null || mLayoutTabs.length != tabVisibleCount) {
mLayoutTabs = new LayoutTab[tabVisibleCount];
}
int index = 0;
if (getTabStackIndex() == 1) {
index = appendVisibleLayoutTabs(time, 0, mLayoutTabs, index);
index = appendVisibleLayoutTabs(time, 1, mLayoutTabs, index);
} else {
index = appendVisibleLayoutTabs(time, 1, mLayoutTabs, index);
index = appendVisibleLayoutTabs(time, 0, mLayoutTabs, index);
}
assert index == tabVisibleCount : "index should be incremented up to tabVisibleCount";
// Update tab snapping
for (int i = 0; i < tabVisibleCount; i++) {
if (mLayoutTabs[i].updateSnap(dt)) needUpdate = true;
}
if (needUpdate) requestUpdate();
// Since we've updated the positions of the stacks and tabs, let's go ahead and update
// the visible tabs.
updateTabPriority();
}
private int appendVisibleLayoutTabs(long time, int stackIndex, LayoutTab[] tabs, int tabIndex) {
final StackTab[] stackTabs = mStacks[stackIndex].getTabs();
if (stackTabs != null) {
for (int i = 0; i < stackTabs.length; i++) {
LayoutTab t = stackTabs[i].getLayoutTab();
if (t.isVisible()) tabs[tabIndex++] = t;
}
}
return tabIndex;
}
/**
* Sets the active tab stack.
*
* @param isIncognito True if the model to select is incognito.
* @return Whether the tab stack index passed in differed from the currently selected stack.
*/
public boolean setActiveStackState(boolean isIncognito) {
if (isIncognito == mTabModelSelector.isIncognitoSelected()) return false;
mTemporarySelectedStack = isIncognito;
return true;
}
private void resetScrollData() {
mScrollIndexOffset = -getTabStackIndex();
mRenderedScrollOffset = mScrollIndexOffset;
}
/**
* Based on the current position, determine if we will map mScrollDistance linearly to
* mRenderedScrollDistance. The logic is, if there is only stack, we will not map linearly;
* if we are scrolling two the boundary of either of the stacks, we will not map linearly;
* otherwise yes.
*/
private boolean canScrollLinearly(int fromStackIndex) {
int count = mStacks.length;
if (!(mScrollIndexOffset <= 0 && -mScrollIndexOffset <= (count - 1))) {
return false;
}
// since we only have two stacks now, we have a shortcut to calculate
// empty stacks
return mStacks[fromStackIndex ^ 0x01].isDisplayable();
}
private float getFullScrollDistance() {
float distance =
getOrientation() == Orientation.PORTRAIT ? getWidth() : getHeightMinusTopControls();
return distance - 2 * getViewportParameters().getInnerMargin();
}
@Override
public void doneHiding() {
super.doneHiding();
mTabModelSelector.commitAllTabClosures();
}
/**
* Extracts the tabs from a stack and append them into a list.
* @param stack The stack that contains the tabs.
* @param outList The output list where will be the tabs from the stack.
* @param index The current number of item in the outList.
* @return The updated index incremented by the number of tabs in the stack.
*/
private static int addAllTabs(Stack stack, StackTab[] outList, int index) {
StackTab[] stackTabs = stack.getTabs();
if (stackTabs != null) {
for (int i = 0; i < stackTabs.length; ++i) {
outList[index++] = stackTabs[i];
}
}
return index;
}
/**
* Comparator that helps ordering StackTab's visibility sorting value in a decreasing order.
*/
private static class VisibilityComparator implements Comparator<StackTab>, Serializable {
@Override
public int compare(StackTab tab1, StackTab tab2) {
return (int) (tab2.getVisiblitySortingValue() - tab1.getVisiblitySortingValue());
}
}
/**
* Comparator that helps ordering StackTab's visibility sorting value in a decreasing order.
*/
private static class OrderComparator implements Comparator<StackTab>, Serializable {
@Override
public int compare(StackTab tab1, StackTab tab2) {
return tab1.getOrderSortingValue() - tab2.getOrderSortingValue();
}
}
private boolean updateSortedPriorityArray(Comparator<StackTab> comparator) {
final int allTabsCount = mStacks[0].getCount() + mStacks[1].getCount();
if (allTabsCount == 0) return false;
if (mSortedPriorityArray == null || mSortedPriorityArray.length != allTabsCount) {
mSortedPriorityArray = new StackTab[allTabsCount];
}
int sortedOffset = 0;
sortedOffset = addAllTabs(mStacks[0], mSortedPriorityArray, sortedOffset);
sortedOffset = addAllTabs(mStacks[1], mSortedPriorityArray, sortedOffset);
assert sortedOffset == mSortedPriorityArray.length;
Arrays.sort(mSortedPriorityArray, comparator);
return true;
}
/**
* Updates the priority list of the {@link LayoutTab} and sends it the systems having processing
* to do on a per {@link LayoutTab} basis. Priority meaning may change based on the current
* comparator stored in {@link #mSortingComparator}.
*
* Do not use {@link #mSortedPriorityArray} out side this context. It is only a member to avoid
* doing an allocation every frames.
*/
private void updateTabPriority() {
if (!updateSortedPriorityArray(mSortingComparator)) return;
updateTabsVisibility(mSortedPriorityArray);
updateDelayedLayoutTabInit(mSortedPriorityArray);
}
/**
* Updates the list of visible tab Id that the tab content manager is suppose to serve. The list
* is ordered by priority. The first ones must be in the manager, then the remaining ones should
* have at least approximations if possible.
*
* @param sortedPriorityArray The array of all the {@link StackTab} sorted by priority.
*/
private void updateTabsVisibility(StackTab[] sortedPriorityArray) {
mVisibilityArray.clear();
for (int i = 0; i < sortedPriorityArray.length; i++) {
mVisibilityArray.add(sortedPriorityArray[i].getId());
}
updateCacheVisibleIds(mVisibilityArray);
}
/**
* Initializes the {@link LayoutTab} a few at a time. This function is to be called once a
* frame.
* The logic of that function is not as trivial as it should be because the input array we want
* to initialize the tab from keeps getting reordered from calls to call. This is needed to
* get the highest priority tab initialized first.
*
* @param sortedPriorityArray The array of all the {@link StackTab} sorted by priority.
*/
private void updateDelayedLayoutTabInit(StackTab[] sortedPriorityArray) {
if (!mDelayedLayoutTabInitRequired) return;
int initialized = 0;
final int count = sortedPriorityArray.length;
for (int i = 0; i < count; i++) {
if (initialized >= LAYOUTTAB_ASYNCHRONOUS_INITIALIZATION_BATCH_SIZE) return;
LayoutTab layoutTab = sortedPriorityArray[i].getLayoutTab();
// The actual initialization is done by the parent class.
if (super.initLayoutTabFromHost(layoutTab)) {
initialized++;
}
}
if (initialized == 0) mDelayedLayoutTabInitRequired = false;
}
@Override
protected boolean initLayoutTabFromHost(LayoutTab layoutTab) {
if (layoutTab.isInitFromHostNeeded()) mDelayedLayoutTabInitRequired = true;
return false;
}
/**
* Sets properties for animations.
* @param prop The property to update
* @param p New value of the property
*/
@Override
public void setProperty(Property prop, float p) {
switch (prop) {
case STACK_SNAP:
mRenderedScrollOffset = p;
mScrollIndexOffset = p;
break;
case INNER_MARGIN_PERCENT:
mInnerMarginPercent = p;
break;
case STACK_OFFSET_Y_PERCENT:
mStackOffsetYPercent = p;
break;
}
}
/**
* Called by the stacks whenever they start an animation.
*/
public void onStackAnimationStarted() {
if (mStackAnimationCount == 0) super.onAnimationStarted();
mStackAnimationCount++;
}
/**
* Called by the stacks whenever they finish their animations.
*/
public void onStackAnimationFinished() {
mStackAnimationCount--;
if (mStackAnimationCount == 0) super.onAnimationFinished();
}
@Override
protected SceneLayer getSceneLayer() {
return mSceneLayer;
}
@Override
protected void updateSceneLayer(Rect viewport, Rect contentViewport,
LayerTitleCache layerTitleCache, TabContentManager tabContentManager,
ResourceManager resourceManager, ChromeFullscreenManager fullscreenManager) {
super.updateSceneLayer(viewport, contentViewport, layerTitleCache, tabContentManager,
resourceManager, fullscreenManager);
assert mSceneLayer != null;
mSceneLayer.pushLayers(getContext(), viewport, contentViewport, this, layerTitleCache,
tabContentManager, resourceManager);
}
}
| Force the close all tabs animation to finish before creating a new tab
If the close all tabs animation is still in progress when a new tab is created,
we end up with 0 tabs and a (mostly) blank screen. Forcing the animation to
finish before creating the new tab leaves TabModelBase in a good state for
creating the new tab.
BUG=496557
Review URL: https://codereview.chromium.org/1175243007
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#334418}
| chrome/android/java_staging/src/org/chromium/chrome/browser/compositor/layouts/phone/StackLayout.java | Force the close all tabs animation to finish before creating a new tab |
|
Java | bsd-3-clause | error: pathspec 'gws-core/src/main/java/au/gov/ga/geodesy/domain/service/SiteLogReceivedNotificationService.java' did not match any file(s) known to git
| 6481de899956e7909313ef4943e95e092471a946 | 1 | GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services | package au.gov.ga.geodesy.domain.service;
import org.springframework.stereotype.Component;
import au.gov.ga.geodesy.domain.model.event.Event;
import au.gov.ga.geodesy.domain.model.event.SiteLogReceived;
@Component
public class SiteLogReceivedNotificationService extends EventNotificationService<SiteLogReceived> {
@Override
public boolean canHandle(Event e) {
return e instanceof SiteLogReceived;
}
}
| gws-core/src/main/java/au/gov/ga/geodesy/domain/service/SiteLogReceivedNotificationService.java | Add site log received notification service
| gws-core/src/main/java/au/gov/ga/geodesy/domain/service/SiteLogReceivedNotificationService.java | Add site log received notification service |
|
Java | mit | error: pathspec 'dcserver.java' did not match any file(s) known to git
| 41486870903c22215f7f6f635e6b1424c17a47de | 1 | dragonwolverines/SocketProgramming | import java.io.*;
import java.net.*;
public class dcserver
{
public static void main(String[] args) throws Exception
{
//create server socket
ServerSocket sersock = new ServerSocket(3000);
System.out.println("DeCentralized Server ready for communication");
//Make the server wait till a client accepts connection
Socket sock = sersock.accept( );
//Sending to client
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
OutputStream ostream = sock.getOutputStream();
//To accept contents from client
PrintWriter pwrite = new PrintWriter(ostream, true);
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
//Read contents from the client
String receiveMessage, sendMessage;
receiveMessage = receiveRead.readLine();
pwrite.println("Start Test \n 5+5=");
while(true)
{
if(receiveMessage.equals("10"))
{
pwrite.println("answer is correct");
}
else
{
pwrite.println("answer is wrong");
} // end of if else loop
} // end of while loop
} // end of main
} // end of class
| dcserver.java | Decentralized first server - MATH | dcserver.java | Decentralized first server - MATH |
|
Java | mit | error: pathspec 'java/Test.java' did not match any file(s) known to git
| 718a6472bcdf5f9add36349054a6c83f4e966b67 | 1 | antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4 | /*
[The "BSD license"]
Copyright (c) 2013 Terence Parr
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.DiagnosticErrorListener;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.atn.LexerATNSimulator;
import org.antlr.v4.runtime.atn.PredictionMode;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/* This more or less duplicates the functionality of grun (TestRig) but it
* has a few specific options for benchmarking like -x2 and -threaded.
* It also allows directory names as commandline arguments. The simplest test is
* for the current directory:
~/antlr/code/grammars-v4/java $ java Test .
/Users/parrt/antlr/code/grammars-v4/java/./JavaBaseListener.java
/Users/parrt/antlr/code/grammars-v4/java/./JavaLexer.java
/Users/parrt/antlr/code/grammars-v4/java/./JavaListener.java
/Users/parrt/antlr/code/grammars-v4/java/./JavaParser.java
/Users/parrt/antlr/code/grammars-v4/java/./Test.java
Total lexer+parser time 1867ms.
*/
class Test {
// public static long lexerTime = 0;
public static boolean profile = false;
public static boolean notree = false;
public static boolean gui = false;
public static boolean printTree = false;
public static boolean SLL = false;
public static boolean diag = false;
public static boolean bail = false;
public static boolean x2 = false;
public static boolean threaded = false;
public static boolean quiet = false;
// public static long parserStart;
// public static long parserStop;
public static Worker[] workers = new Worker[3];
static int windex = 0;
public static CyclicBarrier barrier;
public static volatile boolean firstPassDone = false;
public static class Worker implements Runnable {
public long parserStart;
public long parserStop;
List<String> files;
public Worker(List<String> files) {
this.files = files;
}
@Override
public void run() {
parserStart = System.currentTimeMillis();
for (String f : files) {
parseFile(f);
}
parserStop = System.currentTimeMillis();
try {
barrier.await();
}
catch (InterruptedException ex) {
return;
}
catch (BrokenBarrierException ex) {
return;
}
}
}
public static void main(String[] args) {
doAll(args);
}
public static void doAll(String[] args) {
List<String> inputFiles = new ArrayList<String>();
long start = System.currentTimeMillis();
try {
if (args.length > 0 ) {
// for each directory/file specified on the command line
for(int i=0; i< args.length;i++) {
if ( args[i].equals("-notree") ) notree = true;
else if ( args[i].equals("-gui") ) gui = true;
else if ( args[i].equals("-ptree") ) printTree = true;
else if ( args[i].equals("-SLL") ) SLL = true;
else if ( args[i].equals("-bail") ) bail = true;
else if ( args[i].equals("-diag") ) diag = true;
else if ( args[i].equals("-2x") ) x2 = true;
else if ( args[i].equals("-threaded") ) threaded = true;
else if ( args[i].equals("-quiet") ) quiet = true;
if ( args[i].charAt(0)!='-' ) { // input file name
inputFiles.add(args[i]);
}
}
List<String> javaFiles = new ArrayList<String>();
for (String fileName : inputFiles) {
List<String> files = getFilenames(new File(fileName));
javaFiles.addAll(files);
}
doFiles(javaFiles);
// DOTGenerator gen = new DOTGenerator(null);
// String dot = gen.getDOT(JavaParser._decisionToDFA[112], false);
// System.out.println(dot);
// dot = gen.getDOT(JavaParser._decisionToDFA[81], false);
// System.out.println(dot);
if ( x2 ) {
System.gc();
System.out.println("waiting for 1st pass");
if ( threaded ) while ( !firstPassDone ) { } // spin
System.out.println("2nd pass");
doFiles(javaFiles);
}
}
else {
System.err.println("Usage: java Main <directory or file name>");
}
}
catch(Exception e) {
System.err.println("exception: "+e);
e.printStackTrace(System.err); // so we can get stack trace
}
long stop = System.currentTimeMillis();
// System.out.println("Overall time " + (stop - start) + "ms.");
System.gc();
}
public static void doFiles(List<String> files) throws Exception {
long parserStart = System.currentTimeMillis();
// lexerTime = 0;
if ( threaded ) {
barrier = new CyclicBarrier(3,new Runnable() {
public void run() {
report(); firstPassDone = true;
}
});
int chunkSize = files.size() / 3; // 10/3 = 3
int p1 = chunkSize; // 0..3
int p2 = 2 * chunkSize; // 4..6, then 7..10
workers[0] = new Worker(files.subList(0,p1+1));
workers[1] = new Worker(files.subList(p1+1,p2+1));
workers[2] = new Worker(files.subList(p2+1,files.size()));
new Thread(workers[0], "worker-"+windex++).start();
new Thread(workers[1], "worker-"+windex++).start();
new Thread(workers[2], "worker-"+windex++).start();
}
else {
for (String f : files) {
parseFile(f);
}
long parserStop = System.currentTimeMillis();
System.out.println("Total lexer+parser time " + (parserStop - parserStart) + "ms.");
}
}
private static void report() {
// parserStop = System.currentTimeMillis();
// System.out.println("Lexer total time " + lexerTime + "ms.");
long time = 0;
if ( workers!=null ) {
// compute max as it's overlapped time
for (Worker w : workers) {
long wtime = w.parserStop - w.parserStart;
time = Math.max(time,wtime);
System.out.println("worker time " + wtime + "ms.");
}
}
System.out.println("Total lexer+parser time " + time + "ms.");
System.out.println("finished parsing OK");
System.out.println(LexerATNSimulator.match_calls+" lexer match calls");
// System.out.println(ParserATNSimulator.predict_calls +" parser predict calls");
// System.out.println(ParserATNSimulator.retry_with_context +" retry_with_context after SLL conflict");
// System.out.println(ParserATNSimulator.retry_with_context_indicates_no_conflict +" retry sees no conflict");
// System.out.println(ParserATNSimulator.retry_with_context_predicts_same_alt +" retry predicts same alt as resolving conflict");
}
public static List<String> getFilenames(File f) throws Exception {
List<String> files = new ArrayList<String>();
getFilenames_(f, files);
return files;
}
public static void getFilenames_(File f, List<String> files) throws Exception {
// If this is a directory, walk each file/dir in that directory
if (f.isDirectory()) {
String flist[] = f.list();
for(int i=0; i < flist.length; i++) {
getFilenames_(new File(f, flist[i]), files);
}
}
// otherwise, if this is a java file, parse it!
else if ( ((f.getName().length()>5) &&
f.getName().substring(f.getName().length()-5).equals(".java")) )
{
files.add(f.getAbsolutePath());
}
}
// This method decides what action to take based on the type of
// file we are looking at
// public static void doFile_(File f) throws Exception {
// // If this is a directory, walk each file/dir in that directory
// if (f.isDirectory()) {
// String files[] = f.list();
// for(int i=0; i < files.length; i++) {
// doFile_(new File(f, files[i]));
// }
// }
//
// // otherwise, if this is a java file, parse it!
// else if ( ((f.getName().length()>5) &&
// f.getName().substring(f.getName().length()-5).equals(".java")) )
// {
// System.err.println(f.getAbsolutePath());
// parseFile(f.getAbsolutePath());
// }
// }
public static void parseFile(String f) {
try {
if ( !quiet ) System.err.println(f);
// Create a scanner that reads from the input stream passed to us
Lexer lexer = new JavaLexer(new ANTLRFileStream(f));
CommonTokenStream tokens = new CommonTokenStream(lexer);
// long start = System.currentTimeMillis();
// tokens.fill(); // load all and check time
// long stop = System.currentTimeMillis();
// lexerTime += stop-start;
// Create a parser that reads from the scanner
JavaParser parser = new JavaParser(tokens);
if ( diag ) parser.addErrorListener(new DiagnosticErrorListener());
if ( bail ) parser.setErrorHandler(new BailErrorStrategy());
if ( SLL ) parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
// start parsing at the compilationUnit rule
ParserRuleContext t = parser.compilationUnit();
if ( notree ) parser.setBuildParseTree(false);
if ( gui ) t.inspect(parser);
if ( printTree ) System.out.println(t.toStringTree(parser));
}
catch (Exception e) {
System.err.println("parser exception: "+e);
e.printStackTrace(); // so we can get stack trace
}
}
}
| java/Test.java | add Test rig for Java
| java/Test.java | add Test rig for Java |
|
Java | mit | error: pathspec 'MainActivity.java' did not match any file(s) known to git
| ea074bbb9fefd9154c01111f232bdb7745dda301 | 1 | cdbkr/AndroidFacebookCustomStory | import java.util.ArrayList;
import java.util.List;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.OpenGraphAction;
import com.facebook.model.OpenGraphObject;
import com.facebook.widget.FacebookDialog;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button;
private UiLifecycleHelper uiHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
post();
}
});
}
Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState sessionState, Exception exception) {
Log.e(this.getClass().toString(), String.format("SessionState: %s", sessionState.isOpened()));
}
};
private void post() {
OpenGraphObject object = OpenGraphObject.Factory.createForPost("namespaceapp:object");
object.setProperty("title", "Buffalo Tacos");
object.setProperty("url", "https://example.com/cooking-app/meal/Buffalo-Tacos.html");
object.setProperty("description", "Leaner than beef and great flavor.");
OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
action.setProperty("object", object);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher, options);
List<Bitmap> images = new ArrayList<Bitmap>();
images.add(bitmap);
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "namespaceapp:action", "object")
.setImageAttachmentsForAction(images, true)
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
@Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
Log.e("Activity", String.format("Error: %s", error.toString()));
}
@Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.i("Activity", "Success!");
}
});
}
@Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
}
| MainActivity.java | Create MainActivity.java
A simple raw activity made to post a custom story to facebook. | MainActivity.java | Create MainActivity.java |
|
Java | mit | error: pathspec 'src/menu/Star.java' did not match any file(s) known to git
| 58e2b7f45fcb343d17dfd4b21160fed3da492418 | 1 | Hypersonic/Starlorn | import org.lwjgl.opengl.GL11;
public class Star extends Rectangle {
private double _size;
private double _svel;
private boolean _show;
private int _color;
public Star(double displayx, double displayy, double s) {
super(Math.random() * (displayx - s + 1), Math.random()
* (displayy - s + 1), s, s);
_show = false;
_size = s;
_svel = 0;
}
public void draw() {
if (_show) {
GL11.glColor3d(1, 1, 1);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2d(getXcor(), getYcor());
GL11.glVertex2d(getXcor() + _size, getYcor());
GL11.glVertex2d(getXcor() + _size, getYcor() + _size);
GL11.glVertex2d(getXcor(), getYcor() + _size);
GL11.glEnd();
}
}
public double setSize(double s) {
double temp = _size;
_size = s;
return _size;
}
public void update(int delta) {
super.update(delta);
double dist = Math.sqrt(Math.abs(540 - getXcor()) * Math.abs(540 - getXcor())
+ Math.abs(360 - getYcor()) * Math.abs(360 - getYcor()));
setXvel((getXcor() - 540) / 1);
setYvel((getYcor() - 360) / 1);
_size += _svel;
_svel = dist * dist / 700000;
if (getXcor() <= 0 || getYcor() <= 0 || getXcor() >= 1080
|| getYcor() >= 720) {
setXcor(Math.random() * 1080);
setYcor(Math.random() * 720);
setXvel(0);
setYvel(0);
_size = 1;
_show = true;
}
}
}
| src/menu/Star.java | Create Star.java | src/menu/Star.java | Create Star.java |
|
Java | mit | error: pathspec 'IdealDelay/IdealDelay.java' did not match any file(s) known to git
| 556c04d23562006906bc0cd361a707666dd9eb33 | 1 | dekoperez/ArtificialIntelligence,dekoperez/ArtificialIntelligence | /**
Program: Ideal Delay
Author: André Perez
Contact: [email protected]
Last Modified: 10 October 2015
*/
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class IdealDelay {
public static void main(String[] args){
// # INPUT #
int samplingRate = GetSamplingRate();
int dataCounter = samplingRate * 300;
double[] originalData = GetDataFile();
double[] modifiedData = new double[dataCounter];
// # DATA PROCESSING #
// - Ideal Delay: 5ms -> 40 samples forward
// - Ideal Delay: 10ms -> 80 samples forward
// - Ideal Delay: 15ms -> 120 samples forward
int delay = 5;
while(delay <= 15){
for(int i=0, j=0 ; i<dataCounter; i++){
if(i<delay*samplingRate){
modifiedData[i] = 0;
}
else{
modifiedData[i] = originalData[j];
j++;
}
}
modifiedData = NormalizeData(modifiedData, originalData, dataCounter);
PutDataFile(dataCounter, modifiedData, "normalizedModifiedData"+ delay +".txt");
delay += 5;
}
// # OUTPUT #
originalData = NormalizeData(originalData, originalData, dataCounter);
PutDataFile(dataCounter, originalData, "normalizedOriginalData.txt");
}
public static int GetSamplingRate(){
//Gets the Sampling Rate in kilo Hertz (kHz).
Scanner fileInput = null;
try{
fileInput = new Scanner(new FileInputStream("originalData.txt"));
}
catch(FileNotFoundException e){
System.out.println("SR: File not found !");
System.exit(0);
}
int dataCounter=0, samplingRate, audioLength=300;
while(fileInput.hasNextLine()){
fileInput.nextLine();
dataCounter++;
}
fileInput.close();
samplingRate = dataCounter / audioLength;
return samplingRate;
}
public static double[] GetDataFile(){
Scanner fileInput = null;
try{
fileInput = new Scanner(new FileInputStream("originalData.txt"));
}
catch(FileNotFoundException e){
System.out.println("GETDATA: File not found !");
System.exit(0);
}
int dataCounter=0;
while(fileInput.hasNextLine()){
fileInput.nextLine();
dataCounter++;
}
fileInput.close();
fileInput = null;
try{
fileInput = new Scanner(new FileInputStream("originalData.txt"));
}
catch(FileNotFoundException e){
System.out.println("GETDATA: File not found !");
System.exit(0);
}
double[] fileData = new double[dataCounter];
for(int i=0 ; i<dataCounter ; i++){
fileData[i] = fileInput.nextInt();
if(fileInput.hasNextLine()){
fileInput.nextLine();
}
}
fileInput.close();
return fileData;
}
public static double[] NormalizeData(double[] modifiedArray, double[] originalArray,int dataCounter){
double max = Double.MIN_VALUE;
for(int i=0 ; i<dataCounter ; i++){
if(Math.abs(originalArray[i])>max){
max = Math.abs(originalArray[i]);
}
}
for(int i=0 ; i<dataCounter ; i++){
modifiedArray[i] = modifiedArray[i] / max;
}
return modifiedArray;
}
public static void PutDataFile(int dataCounter, double[] dataArray, String fileName){
PrintWriter fileOutput = null;
try{
fileOutput = new PrintWriter(new FileOutputStream(fileName));
}
catch(FileNotFoundException e){
System.out.println("PUTDATA: File not found !");
System.exit(0);
}
for(int i=0 ; i<dataCounter ; i++){
fileOutput.println(dataArray[i]);
}
fileOutput.close();
}
}
| IdealDelay/IdealDelay.java | Create IdealDelay.java | IdealDelay/IdealDelay.java | Create IdealDelay.java |
|
Java | mit | error: pathspec 'src/test/ActionCreator.java' did not match any file(s) known to git
| 4c944d1f56c63011ef62855544ddcbdcf727346f | 1 | argonium/beetle-cli | package test;
import java.util.GregorianCalendar;
import io.miti.beetle.util.Faker;
import io.miti.beetle.util.FileBuilder;
public class ActionCreator
{
public static long getDate(final int min, final int max) {
GregorianCalendar gc = new GregorianCalendar();
int year = randBetween(min, max);
gc.set(gc.YEAR, year);
int dayOfYear = randBetween(1, gc.getActualMaximum(gc.DAY_OF_YEAR));
gc.set(gc.DAY_OF_YEAR, dayOfYear);
// System.out.println(gc.get(gc.YEAR) + "-" + gc.get(gc.MONTH) + "-" + gc.get(gc.DAY_OF_MONTH));
return gc.getTime().getTime();
}
public static int randBetween(int start, int end) {
return start + (int)Math.round(Math.random() * (end - start));
}
public static void main(String[] args) {
FileBuilder fb = new FileBuilder("actions.csv");
fb.append("id,name,assignee,createdDate,dueDate")
.appendEOL();
for (int i = 0; i < 100; ++i) {
long created = getDate(2005, 2008);
long due = getDate(2009, 2013);
fb.append(i + 1).append(',').append(Faker.getWord(5, 7, true))
.append(' ').append(Faker.getWord(4,6, false)).append(',')
.append(Faker.getFullName()).append(',').append(created)
.append(',').append(due).appendEOL();
}
fb.close();
}
}
| src/test/ActionCreator.java | Test data generator. | src/test/ActionCreator.java | Test data generator. |
|
Java | mit | error: pathspec 'src/com/neco4j/graph/IOperations.java' did not match any file(s) known to git
| f036bf9ac98991aa66c4e3791046c2f7be11dd76 | 1 | necatikartal/leader-election-in-wireless-environments | package com.neco4j.graph;
import java.io.IOException;
/**
* Operations interface
* @author Necati Kartal
*/
public interface IOperations {
/**
* Initialize the graph
* @return graph
*/
public Graph initialGraph();
/**
* Build graph by using graph capacity and growth percentage
* @param graphCapacity
* @param growthPercentage
* @return graph
*/
public Graph buildGraph(int graphCapacity, int growthPercentage);
/**
* Build graph by reading data from nodes.txt and edges.txt
* @param vericesPath
* @param edgesPath
* @return graph
* @throws IOException
*/
public Graph buildGraph (String vericesPath, String edgesPath) throws IOException;
} | src/com/neco4j/graph/IOperations.java | operations interface
| src/com/neco4j/graph/IOperations.java | operations interface |
|
Java | mit | error: pathspec 'src/test/java/com/autotest/HttpTest.java' did not match any file(s) known to git
| 4e07c1da5aeb827ee8354f1627e90ad6146b49e4 | 1 | ychaoyang/autotest | package com.autotest;
import com.autotest.annotation.AutoTest;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
/**
* Created by yu on 17/12/26.
*/
public class HttpTest {
protected RestTemplate restTemplate = new RestTemplate();
/**
* 百度翻译接口
*/
@AutoTest(file = "csvTest.csv")
void httpTest(int test) {
String url = "http://fanyi.baidu.com/v2transapi";
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
//需要翻译的单词
String word = "自行车";
map.add("query", word);
map.add("from", "auto");
map.add("to", "auto");
// 调用接口
ResponseEntity<String> response = restTemplate.postForEntity(url, map, String.class);
System.out.println(response.getBody());
}
}
| src/test/java/com/autotest/HttpTest.java | 添加接口测试用例
| src/test/java/com/autotest/HttpTest.java | 添加接口测试用例 |
|
Java | mit | error: pathspec 'Code08/Java/MultipleInheritanceIssue.java' did not match any file(s) known to git
| 60fd8c1b18fb3ca2b9cee255e1dae4965936e79d | 1 | wolfdale/Spaghetti-code,wolfdale/Spaghetti-code,wolfdale/Spaghetti-code,wolfdale/Spaghetti-code,wolfdale/Spaghetti-code,wolfdale/Spaghetti-code,wolfdale/Spaghetti-code,wolfdale/Spaghetti-code,wolfdale/Spaghetti-code | interface X1{
public default void M1(){
System.out.println("X1M1");
};
}
interface X2{
public default void M1(){
System.out.println("X2M2");
}
}
class Runner implements X1,X2{
//Multiple inheritance problem
//Here it is must to redefine M1 method for compilation
public void M1(){
System.out.println("Runner");
}
}
class Activator{
public static void main(String[] agr){
Runner xyz = new Runner();
xyz.M1();
}
}
| Code08/Java/MultipleInheritanceIssue.java | Create MultipleInheritanceIssue.java | Code08/Java/MultipleInheritanceIssue.java | Create MultipleInheritanceIssue.java |
|
Java | mit | error: pathspec 'src/pp/arithmetic/offer/_07_buildTree.java' did not match any file(s) known to git
| 73c680b19c3d2e5c5cc8d3001389021bf42b2caf | 1 | pphdsny/ArithmeticTest | package pp.arithmetic.offer;
import pp.arithmetic.Util;
import pp.arithmetic.model.TreeNode;
/**
* Created by wangpeng on 2020-08-04.
*
* 剑指 Offer 07. 重建二叉树
*
* 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
*
*
*
* 例如,给出
*
* 前序遍历 preorder = [3,9,20,15,7]
* 中序遍历 inorder = [9,3,15,20,7]
* 返回如下的二叉树:
*
* 3
* / \
* 9 20
* / \
* 15 7
*
*
* 限制:
*
* 0 <= 节点个数 <= 5000
*
*
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class _07_buildTree {
public static void main(String[] args) {
_07_buildTree buildTree = new _07_buildTree();
int[] preorder = {3, 9, 20, 15, 7};
int[] inorder = {9,3,15,20,7};
TreeNode treeNode = buildTree.buildTree(preorder, inorder);
Util.printTree(treeNode);
}
/**
* 解题思路:
* 1、知道前序遍历,首位就是根节点
* 2、由于不存在重复数字,根据根节点找到中序遍历的位置I,I前就是左子树的中序,I后就是右子树的中序
* 3、在前序数组中,根据左右子树中序的长度,能找到左右子树对应的前序遍历数组
* 4、循环1-3,得到左右子树的对应的前序&中序数组,最终得到构建的树
*
* 优化建议:得到左右子树对应的数组的时候,有两种方案:
* 一、拷贝新数组
* 二、原数组上理由index指针获取结果(性能和效率都更高)
*
* 本题解基于方案二
*
* @param preorder
* @param inorder
* @return
*/
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0) return null;
return dfs(preorder.length,preorder,0,inorder,0);
}
// 从前序和中序构造二叉树,前序和中序是大数组中的一段[start, start + count)
private TreeNode dfs(int count, int[] preOrder, int preStart, int[] inOrder, int inStart) {
if (count <= 0) return null;
int rootValue = preOrder[preStart];
TreeNode root = new TreeNode(rootValue);
// 从inorder中找到root值,(inorder)左边就是左子树,(inorder)右边就是右子树
// 然后在preorder中,数出与inorder中相同的个数即可
int pos = inStart + count - 1;
for (; pos >= inStart; --pos) {
if (inOrder[pos] == rootValue) {
break;
}
}
int leftCount = pos - inStart;
int rightCount = inStart + count - pos - 1;
if (leftCount > 0) {
int leftInStart = inStart;
int leftPreStart = preStart + 1;
root.left = dfs(leftCount, preOrder, leftPreStart, inOrder, leftInStart);
}
if (rightCount > 0) {
int rightInStart = pos + 1;
int rightPreStart = preStart + 1 + leftCount;
root.right = dfs(rightCount, preOrder, rightPreStart, inOrder, rightInStart);
}
return root;
}
}
| src/pp/arithmetic/offer/_07_buildTree.java | feat(MEDIUM): add _07_buildTree
| src/pp/arithmetic/offer/_07_buildTree.java | feat(MEDIUM): add _07_buildTree |
|
Java | mit | error: pathspec 'main/src/com/peter/codewars/PaginationHelper.java' did not match any file(s) known to git
| 7caff46c3bf65f5d9410a84bca609ea961a46fcf | 1 | Peter-Liang/CodeWars-Java | package com.peter.codewars;
/**
* PaginationHelper
* http://www.codewars.com/kata/515bb423de843ea99400000a/train/java
*/
import java.util.List;
public class PaginationHelper<I> {
private final List<I> collection;
private final int itemsPerPage;
/**
* The constructor takes in an array of items and a integer indicating how many
* items fit within a single page
*/
public PaginationHelper(List<I> collection, int itemsPerPage) {
this.collection = collection;
this.itemsPerPage = itemsPerPage;
}
/**
* returns the number of items within the entire collection
*/
public int itemCount() {
return this.collection.size();
}
/**
* returns the number of pages
*/
public int pageCount() {
if (this.itemsPerPage == 0 || this.collection.size() == 0) {
return 0;
}
return this.collection.size() / this.itemsPerPage + 1;
}
/**
* returns the number of items on the current page. page_index is zero based.
* this method should return -1 for pageIndex values that are out of range
*/
public int pageItemCount(int pageIndex) {
if (pageIndex >= this.pageCount()) {
return -1;
}
if (pageIndex < this.pageCount() - 1) {
return this.itemsPerPage;
}
return this.collection.size() - this.itemsPerPage * pageIndex;
}
/**
* determines what page an item is on. Zero based indexes
* this method should return -1 for itemIndex values that are out of range
*/
public int pageIndex(int itemIndex) {
if (itemIndex >= this.collection.size() || itemIndex < 0) {
return -1;
}
return itemIndex / this.itemsPerPage;
}
} | main/src/com/peter/codewars/PaginationHelper.java | Solved the kata 'PaginationHelper'.
http://www.codewars.com/kata/515bb423de843ea99400000a/solutions/java
| main/src/com/peter/codewars/PaginationHelper.java | Solved the kata 'PaginationHelper'. http://www.codewars.com/kata/515bb423de843ea99400000a/solutions/java |
|
Java | mit | error: pathspec 'src/com/carloan/integration/database/SqlConnector.java' did not match any file(s) known to git
| e71a71788c3752a3b6d59876072533a99a1ea491 | 1 | Spronghi/software-engineering | package com.carloan.integration.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class SqlConnector implements Connector{
private static String DRIVER_CLASS_NAME = "org.gjt.mm.mysql.Driver";
private final static String SQL_PATH = "jdbc:mysql://localhost:3306/carloan";
private final static String USER_ID = "CarloanUser";
private final static String PASSWORD = "popo";
private Connection connection;
private static SqlConnector instance;
private SqlConnector(){
initConnection();
initDb();
}
private void initConnection(){
try {
Class.forName(DRIVER_CLASS_NAME).newInstance();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
connection = DriverManager.getConnection(SQL_PATH, USER_ID, PASSWORD);
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
private void initDb(){
try{
Statement stmt=connection.createStatement();
for(String sql : Queries.array())
stmt.executeUpdate(sql);
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static SqlConnector getInstance(){
if(instance==null)
instance = new SqlConnector();
return instance;
}
public Connection getConnection(){
return connection;
}
@Override
public ResultSet executeQuery(String query){
ResultSet resultSet = null;
try {
Statement stmt = connection.createStatement();
resultSet = stmt.executeQuery(query);
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
@Override
public int executeUpdate(String query){
int id=0;
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
ResultSet generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next())
id = generatedKeys.getInt(1);
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
return id;
}
}
| src/com/carloan/integration/database/SqlConnector.java | Connector to mysql database
| src/com/carloan/integration/database/SqlConnector.java | Connector to mysql database |
|
Java | mit | error: pathspec 'src/main/java/fi/csc/microarray/webstart/JnlpServlet.java' did not match any file(s) known to git
| ce286870ac1bf3389a45f302c698aba1354fb8b9 | 1 | chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster | package fi.csc.microarray.webstart;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import fi.csc.microarray.config.DirectoryLayout;
import fi.csc.microarray.util.XmlUtil;
/**
* Servlet for generating modified jnlp files according to url query parameters.
*
* Don't use this with sensitive information, because javaws caches all jnlp files. Current
* Java version (1.7) seems to delete application shortcuts when there is a question
* mark in the href attribute in the jnlp file.
*
* @author klemela
*/
public class JnlpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws javax.servlet.ServletException, java.io.IOException {
resp.setContentType("application/x-java-jnlp-file");
String memoryString = req.getParameter("memory");
Integer memory = null;
if (memoryString != null) {
try {
memory = Integer.parseInt(memoryString);
} catch (NumberFormatException e) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "parameter 'memory' must be an integer");
return;
}
}
resp.setStatus(HttpServletResponse.SC_OK);
PrintWriter writer = resp.getWriter();
Document jnlp;
try {
jnlp = getJnlp(memory);
XmlUtil.printXml(jnlp, writer);
} catch (Exception e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "jnlp modification failed");
return;
}
}
private Document getJnlp(Integer memory) throws SAXException, IOException, ParserConfigurationException {
File wsConfigFile = new File(DirectoryLayout.WEB_ROOT + File.separator + "chipster.jnlp");
if (!wsConfigFile.exists()) {
throw new IOException("chipster.jnlp not found");
}
Document doc = XmlUtil.parseFile(wsConfigFile);
Element jnlp = (Element)doc.getDocumentElement();
/* When javaws installs a application, it doesn't use the jnlp file that was just downloaded, but
* downloads the jnlp again from the url denoted by the file's href attribute. We must generate a query string
* that calls this servlet with the exactly same parameters again. This way the parameters are relayed
* reliably regardless whether the application was already installed or not.
*/
String href="servlet.jnlp";
if (memory != null) {
href += "?";
}
if (memory != null) {
href += "memory=" + memory;
}
jnlp.setAttribute("href", href);
if (memory != null) {
Element resources = (Element) jnlp.getElementsByTagName("resources").item(0);
Element j2se = (Element) resources.getElementsByTagName("j2se").item(0);
j2se.setAttribute("java-vm-args", "-Xmx" + memory + "m");
}
// // use this to give parameters for main method
// Element applicationDesc = (Element)jnlp.getElementsByTagName("application-desc").item(0);
//
// Element keyArgument = doc.createElement("argument");
// Element valueArgument = doc.createElement("argument");
// keyArgument.setTextContent("-parameter-name");
// valueArgument.setTextContent(parameterValue);
// applicationDesc.appendChild(keyArgument);
// applicationDesc.appendChild(valueArgument);
return doc;
}
}
| src/main/java/fi/csc/microarray/webstart/JnlpServlet.java | Fix backport | src/main/java/fi/csc/microarray/webstart/JnlpServlet.java | Fix backport |
|
Java | mit | error: pathspec 'projects/os_p2/src/com/egurnee/school/os/p2/AssemblyLine.java' did not match any file(s) known to git
| 2fece27ce6c367faa2fe88ea1c1eb89d52710723 | 1 | pegurnee/2015-02-592,pegurnee/2015-02-592,pegurnee/2015-02-592 | package com.egurnee.school.os.p2;
public class AssemblyLine {
private final static int DEFAULT_NUMBER_OF_WIDGETS = 24;
private final static int DEFAULT_NUMBER_OF_WORKERS = 4;
private final int numberOfWidgetsDesired;
private final AssemblyLineSegment[] segments;
private final WidgetWorker[] workers;
public AssemblyLine() {
this(AssemblyLine.DEFAULT_NUMBER_OF_WORKERS,
AssemblyLine.DEFAULT_NUMBER_OF_WIDGETS);
}
public AssemblyLine(int numberOfWorkers, int numberOfWidgetsDesired) {
this.numberOfWidgetsDesired = numberOfWidgetsDesired;
this.segments = new AssemblyLineSegment[numberOfWorkers - 1];
for (int i = 0; i < this.segments.length; i++) {
this.segments[i] = new AssemblyLineSegment();
}
this.workers = new WidgetWorker[numberOfWorkers];
for (int i = 0; i < (this.workers.length - 1); i++) {
this.workers[i] = new WidgetWorker(this.segments[i],
this.segments[i + 1], i);
}
}
}
| projects/os_p2/src/com/egurnee/school/os/p2/AssemblyLine.java | added assemblyline constructor
| projects/os_p2/src/com/egurnee/school/os/p2/AssemblyLine.java | added assemblyline constructor |
|
Java | mit | error: pathspec 'src/com/coderevisited/coding/matrix/MaximumSizeSquareSubMatrix.java' did not match any file(s) known to git
| 5450c7ad80cba956bd4ddeeb740e546d250a3d0b | 1 | sureshsajja/CodingProblems,sureshsajja/CodeRevisited | package com.coderevisited.coding.matrix;
public class MaximumSizeSquareSubMatrix
{
public static void main(String[] args)
{
int N = 6, M = 5;
int[][] matrix = new int[][]{{0, 1, 1, 0, 1},
{1, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{1, 1, 1, 1, 0},
{1, 1, 1, 1, 1},
{0, 0, 0, 0, 0}};
printMaxSizeSquareSubMatrix(matrix, N, M);
}
private static void printMaxSizeSquareSubMatrix(int[][] matrix, int N, int M)
{
int[][] s = new int[N][M];
System.arraycopy(matrix[0], 0, s[0], 0, M);
for (int i = 0; i < N; i++) {
s[i][0] = matrix[i][0];
}
for (int i = 1; i < N; i++) {
for (int j = 1; j < M; j++) {
if (matrix[i][j] == 1) {
//top
int min = s[i - 1][j];
//left
if (s[i][j - 1] < min) {
min = s[i][j - 1];
}
//top left corner
if (s[i - 1][j - 1] < min) {
min = s[i - 1][j - 1];
}
s[i][j] = min + 1;
} else {
s[i][j] = 0;
}
}
}
int max = s[0][0], p = 0, q = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (max < s[i][j]) {
max = s[i][j];
p = i;
q = j;
}
}
}
for (int i = p - max + 1; i <= p; i++) {
for (int j = q - max + 1; j <= q; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
| src/com/coderevisited/coding/matrix/MaximumSizeSquareSubMatrix.java | Maximum Size square sub matrix
| src/com/coderevisited/coding/matrix/MaximumSizeSquareSubMatrix.java | Maximum Size square sub matrix |
|
Java | mit | error: pathspec 'src/net/maizegenetics/pal/popgen/KnownParentMinorWindowImputation.java' did not match any file(s) known to git
| e848265a8565425c63b397aa6a5bd9c3fbd5b002 | 1 | yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.maizegenetics.pal.popgen;
import cern.jet.random.Binomial;
import edu.cornell.lassp.houle.RngPack.RandomJava;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Random;
import java.util.TreeMap;
import net.maizegenetics.baseplugins.ConvertSBitTBitPlugin;
import net.maizegenetics.pal.alignment.*;
import net.maizegenetics.pal.distance.DistanceMatrix;
import net.maizegenetics.pal.distance.IBSDistanceMatrix;
import net.maizegenetics.pal.ids.Identifier;
import net.maizegenetics.pal.statistics.ApproxFastChiSquareDistribution;
import net.maizegenetics.pipeline.EdTests;
import net.maizegenetics.util.BitUtil;
import net.maizegenetics.util.ProgressListener;
/**
* Finds the nearest neighbor for every 64 site window. In case of ties, it
* extends to neighboring 64bp windows.
*
* @author edbuckler
*/
public class KnownParentMinorWindowImputation {
private Alignment ldAlign;
int minSites=256;
int maxWindow=2048/64;
double minIdentityDiff=0.01;
int[][][] null64Share; //region, site cnt, siteIdentity
float[][][] null64ShareProb; //region, site cnt, siteIdentity
int blocks=-1;
int[] hSite, hTaxon;
byte[] hState;
int maskSitCnt=0;
int maxNN=50;
double minProb=0.0001;
boolean maskAndTest=true;
ApproxFastChiSquareDistribution fcs=new ApproxFastChiSquareDistribution(1000,200);
public KnownParentMinorWindowImputation(Alignment inldAlign, String exportFile) {
this.ldAlign=ConvertSBitTBitPlugin.convertAlignment(inldAlign, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, null);
if(maskAndTest) maskSites(300);
blocks=ldAlign.getAllelePresenceForAllSites(0, 0).getNumWords();
// this.createNull64Share(ldAlign, 500);
this.createNull64Share(ldAlign);
MutableNucleotideAlignment mna=MutableNucleotideAlignment.getInstance(this.ldAlign);
int impSiteCnt=0;
for (int bt = 0; bt < ldAlign.getSequenceCount(); bt++) {
int taxaImpCnt=0;
String name=ldAlign.getIdGroup().getIdentifier(bt).getFullName();
System.out.printf("Imputing %d:%s ...", bt,name);
long time=System.currentTimeMillis();
float[][] idp=getTaxaIdentityProbMatrix(bt);
System.out.printf("IDmatrixTime %d ", System.currentTimeMillis()-time);
for (int x = 0; x < idp[0].length; x++) {
int startSite=x*64;
int endSite=startSite+63;
if(endSite>=ldAlign.getSiteCount()) endSite=ldAlign.getSiteCount()-1;
TreeMap<Double, ShareSize> bestTaxa=new TreeMap<Double, ShareSize>();
for (int t = 0; t < idp.length; t++) {
ShareSize xss=new ShareSize(bt,t, x, x);
ShareSize fss=getMaxShare(idp,xss);
if(fss.p>minProb) continue;
if((bestTaxa.size()<maxNN)||(fss.p<bestTaxa.lastEntry().getKey())) {
bestTaxa.put(fss.p, fss);
if(bestTaxa.size()>maxNN) bestTaxa.remove(bestTaxa.lastEntry().getKey());
}
//System.out.printf("%g\t",idp[t][x]);
}
for(int cs=startSite; cs<=endSite; cs++) {
if(mna.getBase(bt, cs)==Alignment.UNKNOWN_DIPLOID_ALLELE) {
mna.setBase(bt, cs, getBestBase(mna,bestTaxa.values(),cs));
impSiteCnt++;
taxaImpCnt++;
}
}
}
System.out.printf("Finished %d Imp %d %d %n", System.currentTimeMillis()-time, impSiteCnt, taxaImpCnt);
if(bt%10==0) compareSites(mna);
}
if(maskAndTest) compareSites(mna);
ExportUtils.writeToHapmap(mna, false, exportFile, '\t', null);
//if we put the share size in the tree map, only remove those at a transiti0n boundary
// System.out.printf("L%d R%d p:%g %n",ss.left, ss.right, ss.p);
}
private byte getBestBase(Alignment mna, Collection<ShareSize> bestTaxa, int cs) {
byte mjA=mna.getMajorAllele(cs);
mjA=(byte)((mjA<<4)|mjA);
byte mnA=mna.getMinorAllele(cs);
mnA=(byte)((mnA<<4)|mnA);
int mjCnt=0, mnCnt=0, unkCnt=0;
double mjLnSum=0, mnLnSum=0, unkLnSum=0;
for(ShareSize c: bestTaxa) {
int ct=c.compTaxon;
byte nb=ldAlign.getBase(ct, cs);
if(nb==Alignment.UNKNOWN_DIPLOID_ALLELE) {
unkCnt++;
// unkLnSum+=Math.log(c.p);
} else if(nb==mjA) {
mjCnt++;
// mjLnSum+=Math.log(c.p);
} else if(nb==mnA) {
mnCnt++;
// mnLnSum+=Math.log(c.p);
}
}
if((mnCnt>(mjCnt+1))&&(mnCnt>0)) return mnA;
if(((1+mnCnt)<mjCnt)&&(mjCnt>0)) return mjA;
return Alignment.UNKNOWN_DIPLOID_ALLELE;
}
private byte[] consensusCallBit(int taxon, int block, TreeMap<Double,ShareSize> taxa,
boolean callhets, double majority, int minCount, boolean ignoreKnownBases, boolean imputeGaps) {
int[] taxaIndex=new int[taxa.size()];
ArrayList<ShareSize> taxaList=new ArrayList(taxa.values());
for (int t = 0; t < taxaIndex.length; t++) {
taxaIndex[t]=taxaList.get(t).compTaxon;
}
short[][] siteCnt=new short[2][64];
// double[] sumExpPresent=new double[endBase-startBase];
// int[] sumNNxSitePresent=new int[endBase-startBase];
// int sumNNPresent=0;
// for (int t = 0; t < taxaIndex.length; t++) sumNNPresent+=presentCntForTaxa[taxaIndex[t]];
int currWord=block;
int callSite=0;
for (int t = 0; t < taxaIndex.length; t++) {
// long bmj=ldAlign.getAllelePresenceForSitesBlock(taxaIndex[t], 0,currWord, currWord+1)[0];
// long bmn=ldAlign.getAllelePresenceForSitesBlock(taxaIndex[t], 1,currWord, currWord+1)[0];
long bmj=ldAlign.getAllelePresenceForAllSites(taxaIndex[t], 0).getBits()[block];
long bmn=ldAlign.getAllelePresenceForAllSites(taxaIndex[t], 1).getBits()[block];
int cs=callSite;
for (int j = 0; j < 64; j++) {
boolean presentFlag=false;
if((bmj & 0x01)!=0) {siteCnt[0][cs]++; presentFlag=true;}
bmj=bmj>>1;
if((bmn & 0x01)!=0) {siteCnt[1][cs]++; presentFlag=true;}
bmn=bmn>>1;
// sumExpPresent[cs]+=presentProp[taxaIndex[t]];
// if(presentFlag) sumNNxSitePresent[cs]++;
cs++;
}
}
// System.out.println("Bit:"+Arrays.toString(siteCnt[0]));
byte[] calls=new byte[64];
Arrays.fill(calls, Alignment.UNKNOWN_DIPLOID_ALLELE);
int startSite=block*64;
int endSite=startSite+63;
for (int alignS = startSite; alignS <= endSite; alignS++) {
int callS=alignS-startSite;
byte ob=ldAlign.getBase(taxon,alignS);
if(ignoreKnownBases) ob=Alignment.UNKNOWN_DIPLOID_ALLELE;
calls[callS]=ob;
byte mj=ldAlign.getMajorAllele(alignS);
byte mn=ldAlign.getMinorAllele(alignS);
mj=(byte)((mj<<4)+mj);
mn=(byte)((mn<<4)+mn);
int totalCnt=siteCnt[0][callS]+siteCnt[1][callS];
// double expPres=sumExpPresent[callS]/(double)taxaIndex.length;
if(totalCnt<minCount) continue; //no data leave missing
if((double)siteCnt[0][callS]/(double)totalCnt>majority) {
if((ob!=Alignment.UNKNOWN_DIPLOID_ALLELE)&&(ob!=mj)) {calls[callS]=Alignment.UNKNOWN_DIPLOID_ALLELE;}
else {calls[callS] = mj;}
}
else if((double)siteCnt[1][callS]/(double)totalCnt>majority) {
if((ob!=Alignment.UNKNOWN_DIPLOID_ALLELE)&&(ob!=mn)) {calls[callS]=Alignment.UNKNOWN_DIPLOID_ALLELE;}
else {calls[callS] = mn;}
}
else if(callhets) {
// byte[] snpValue={mj,mn};
// byte het=IUPACNucleotides.getDegerateSNPByteFromTwoSNPs(snpValue);
// calls[callS]=het;
}
// System.out.printf("Taxon:%d orig:%d mj:%d mn:%d call:%d %s %n", taxon, ldAlign.getBase(taxon,alignS), mj, mn, calls[callS], AlignmentUtils.isHeterozygous(calls[callS]));
}
return calls;
}
private void maskSites(int sampIntensity) {
System.out.println("Beginning to mask sites");
MutableNucleotideAlignment mna=MutableNucleotideAlignment.getInstance(ldAlign);
int maxSites=mna.getSequenceCount()*((mna.getSiteCount()/sampIntensity)+1);
hSite=new int[maxSites];
hTaxon=new int[maxSites];
hState=new byte[maxSites];
int cnt=0;
for (int t = 0; t < mna.getSequenceCount(); t++) {
for (int s = t%sampIntensity; s < mna.getSiteCount(); s+=sampIntensity) {
hSite[cnt]=s;
hTaxon[cnt]=t;
hState[cnt]=mna.getBase(t, s);
mna.setBase(t, s, Alignment.UNKNOWN_DIPLOID_ALLELE);
cnt++;
}
// System.out.println(t+":"+cnt);
}
maskSitCnt=cnt;
mna.clean();
compareSites(ldAlign);
ldAlign=BitAlignment.getInstance(mna, false);
compareSites(ldAlign);
System.out.println("Sites masked");
}
private void compareSites(Alignment a) {
int missingCnt=0, correctCnt=0, errorCnt=0, notImp=0, hetCnt=0;
for (int i = 0; i < maskSitCnt; i++) {
if(hState[i]==Alignment.UNKNOWN_DIPLOID_ALLELE) {
missingCnt++;
continue;
}
byte impb=a.getBase(hTaxon[i], hSite[i]);
if(AlignmentUtils.isHeterozygous(impb)) {
hetCnt++;
} else if(impb==Alignment.UNKNOWN_DIPLOID_ALLELE) {
notImp++;
} else if(impb==hState[i]) {
correctCnt++;
} else {errorCnt++;}
}
double errRate=(double)errorCnt/(double)(errorCnt+correctCnt);
System.out.printf("Missing: %d Het: %d NotImp: %d Error: %d Correct: %d ErrorRate: %g %n",
missingCnt, hetCnt, notImp, errorCnt, correctCnt, errRate);
}
private ShareSize getMaxShare(float[][] idp, ShareSize currShare) {
if(currShare.left==currShare.right) {
currShare.fsum=idp[currShare.compTaxon][currShare.left];
// currShare.p=1.0-ChiSquareDistribution.cdf(currShare.fsum, 2);
currShare.p=1.0-fcs.cdfFastApprox(currShare.fsum, 2);
}
double tL=-1, tR=-1;
if(currShare.left>0) {
tL=idp[currShare.compTaxon][currShare.left-1];
}
if(currShare.right<idp[0].length-1) {
tR=idp[currShare.compTaxon][currShare.right+1];
}
if(tL>tR) {
double testFsum=currShare.fsum+tL;
// double testp=1.0-ChiSquareDistribution.cdf(testFsum, currShare.df+2);
double testp=1.0-fcs.cdfFastApprox(testFsum, currShare.df+2);
if(testp<currShare.p) {
currShare.moveLeft(testp, testFsum);
return getMaxShare(idp, currShare);
}
} else {
double testFsum=currShare.fsum+tR;
// double testp=1.0-ChiSquareDistribution.cdf(testFsum, currShare.df+2);
double testp=1.0-fcs.cdfFastApprox(testFsum, currShare.df+2);
if(testp<currShare.p) {
currShare.moveRight(testp, testFsum);
return getMaxShare(idp, currShare);
}
}
return currShare;
}
private void createNull64Share(Alignment a, int maxSampling) {
a = ConvertSBitTBitPlugin.convertAlignment(a, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, null);
System.out.println("Creating the null distribution");
IBSDistanceMatrix dm=new IBSDistanceMatrix(a,100,null);
System.out.printf("Distances estimated. Mean:%g %n", dm.meanDistance());
double meanDist=dm.meanDistance();
null64Share=new int[blocks][65][65];
for (int i = 0; i < blocks; i++) {
for (int j = 0; j < null64Share[0].length; j++) {
for (int k = 0; k <=j; k++) {
null64Share[i][j][k]=1;
}
}
}
Random r=new Random(0);
// int samplingPerTaxon=maxSampling/(a.getSequenceCount()*a.getSequenceCount()/2);
System.out.println("samplingPerTaxonContrast: "+maxSampling);
for (int t1 = 0; t1 < a.getSequenceCount(); t1++) {
long[] iMj=a.getAllelePresenceForAllSites(t1, 0).getBits();
long[] iMn=a.getAllelePresenceForAllSites(t1, 1).getBits();
for (int samp = 0; samp < maxSampling; samp++) {
int d=0;
int t2=r.nextInt(a.getSequenceCount());
while(dm.getDistance(t1, t2)<meanDist) {
t2=r.nextInt(a.getSequenceCount());
}
// int t2=r.nextInt(a.getSequenceCount());
// int t2=getIndexOfMaxDistance(dm, t1);
if(t1==t2) continue;
long[] jMj=a.getAllelePresenceForAllSites(t2, 0).getBits();
long[] jMn=a.getAllelePresenceForAllSites(t2, 1).getBits();
for (int sN = 0; sN < blocks; sN++) {
// int br=r.nextInt(numBins);
int b=sN;
int[] results=this.getIdentity(iMj[b], iMn[b], jMj[b], jMn[b]);
// if((sN==0)&&((t1==39)||(t2==39))) System.out.printf("%d %d %d %s %n",sN, t1, t2, Arrays.toString(results));
null64Share[sN][results[0]][results[2]]++;
}
}
}
null64ShareProb=new float[blocks][65][65];
for (int i = 0; i < blocks; i++) {
for (int j = 0; j < null64Share[0].length; j++) {
int sum=0, bsum=0;
for (int k = 0; k <=j; k++) {
sum+=null64Share[i][j][k];
}
for (int k = j; k >=0; k--) {
bsum+=null64Share[i][j][k];
// null64ShareProb[i][j][k]=(float)bsum/(float)sum;
null64ShareProb[i][j][k]=(float)(-2*Math.log((double)bsum/(double)sum));
}
// System.out.printf("%d %g %d %s %n", i, 0.5, j, Arrays.toString(null64ShareProb[i][j]));
}
}
}
private void createNull64Share(Alignment a) {
a = ConvertSBitTBitPlugin.convertAlignment(a, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, null);
System.out.println("Creating the SBitAlignment distribution");
Alignment sbit=BitAlignment.getInstance(a, true);
System.out.printf("SBitAlignment created %n");
null64ShareProb=new float[blocks][65][66];
net.maizegenetics.pal.math.Binomial bn=new net.maizegenetics.pal.math.Binomial();
for (int i = 0; i < blocks; i++) {
double mafSum=0;
int cnt=0;
for (int s = i*64; (s < (i+1)*64)&&(s<sbit.getSiteCount()); s++) {
mafSum+=sbit.getMinorAlleleFrequency(s);
cnt++;
}
double avgMAF=mafSum/(double)cnt;
for (int j = 1; j < null64ShareProb[0].length; j++) {
Binomial binomFunc=new Binomial(j, 1.0-avgMAF, new RandomJava());
Arrays.fill(null64ShareProb[i][j], 0);
for (int k = j; k >=0; k--) {
null64ShareProb[i][j][k]=(float)(binomFunc.pdf(k))+null64ShareProb[i][j][k+1];
}
for (int k = j; k >=0; k--) {
if(null64ShareProb[i][j][k]>1) null64ShareProb[i][j][k]=1;
null64ShareProb[i][j][k]=-2*(float)Math.log(null64ShareProb[i][j][k]);
}
// System.out.printf("%d %g %d %s %n", i, avgMAF, j, Arrays.toString(null64ShareProb[i][j]));
}
}
}
private int getIndexOfMaxDistance(DistanceMatrix dm, int compTaxon) {
int resultTaxon=compTaxon;
double maxDist=dm.getDistance(compTaxon, compTaxon);
for (int i = 0; i < dm.getSize(); i++) {
if(dm.getDistance(compTaxon, i)>maxDist) {
maxDist=dm.getDistance(compTaxon, i);
resultTaxon=i;
}
}
return resultTaxon;
}
private String reportTaxaMakeUp(ArrayList<Integer>[] data) {
StringBuilder s=new StringBuilder();
for (int i = 0; i < data[0].size(); i++) {
s.append(data[0].get(i));
s.append(":");
s.append(data[1].get(i));
s.append("\t");
}
return s.toString();
}
private float[][] getTaxaIdentityProbMatrix(int taxa) {
long[] iMj=ldAlign.getAllelePresenceForAllSites(taxa, 0).getBits();
long[] iMn=ldAlign.getAllelePresenceForAllSites(taxa, 1).getBits();
int sections=iMj.length;
float[][] result=new float[ldAlign.getSequenceCount()][sections];
for (int t = 0; t < ldAlign.getSequenceCount(); t++) {
long[] jMj=ldAlign.getAllelePresenceForAllSites(t, 0).getBits();
long[] jMn=ldAlign.getAllelePresenceForAllSites(t, 1).getBits();
for(int x=0; x<sections; x++) {
int[] results=this.getIdentity(iMj[x], iMn[x], jMj[x], jMn[x]);
result[t][x]=null64ShareProb[x][results[0]][results[2]];
}
}
return result;
}
/**
*
* @param iMj
* @param iMn
* @param jMj
* @param jMn
* @return [0]= number of sites in comparison,
* [1]=number of minor alleles in comparison from taxon i
* [2]=sites that agree
*/
private int[] getIdentity(long iMj, long iMn, long jMj, long jMn) {
int[] results=new int[3];
long iMnjMn=iMn&jMn;
long iMnjMj=iMn&jMj;
long iMnComps=iMnjMn|iMnjMj;
long sameL=(iMj&jMj)|(iMnjMn);
long diffL=(iMj&jMn)|(iMnjMj);
long hetsL=sameL&diffL;
int same=(int)BitUtil.pop(sameL);
int diff=(int)BitUtil.pop(diffL);
int hets=(int)BitUtil.pop(hetsL);
results[1]=(int)BitUtil.pop(iMnComps);
int sum=same+diff+hets;
results[0]=sum-(2*hets);
results[2]=same-(hets/2); //check the minus sign
return results;
}
private static void createSynthetic(String donorFile, String unImpTargetFile, int blockSize,
double propPresent, double homoProp, int taxaNumber) {
Alignment a=ImportUtils.readFromHapmap(donorFile, (ProgressListener)null);
System.out.printf("Read %s Sites %d Taxa %d %n", donorFile, a.getSiteCount(), a.getSequenceCount());
MutableNucleotideAlignment mna= MutableNucleotideAlignment.getInstance(a, taxaNumber, a.getSiteCount());
Random r=new Random();
for (int t = 0; t < taxaNumber; t++) {
StringBuilder tName=new StringBuilder("ZM"+t);
for (int b = 0; b < a.getSiteCount(); b+=blockSize) {
int p1=r.nextInt(a.getSequenceCount());
int p2=r.nextInt(a.getSequenceCount());
tName.append("|"+p1+"_"+p2+"s"+b);
for (int s = b; (s < b+blockSize) && (s<a.getSiteCount()); s++) {
if(r.nextDouble()<propPresent) {
if(r.nextDouble()<0.5) {
mna.setBase(t, s, a.getBase(p1, s));
} else {
mna.setBase(t, s, a.getBase(p2, s));
}
} else {
mna.setBase(t, s, Alignment.UNKNOWN_DIPLOID_ALLELE);
}
}//end of site
} //end of blocks
System.out.println(tName.toString());
mna.setTaxonName(t, new Identifier(tName.toString()));
}
mna.clean();
ExportUtils.writeToHapmap(mna, false, unImpTargetFile, '\t', null);
}
public static void main(String[] args) {
// String root="/Users/edbuckler/SolexaAnal/bigprojection/";
String root="/Volumes/LaCie/build20120110/imp/";
String donorFile=root+"NAMfounder20120110.imp.hmp.txt";
String unImpTargetFile=root+"ZeaSyn20120110.hmp.txt";
String impTargetFile=root+"ZeaSyn20120110.imp.hmp.txt";
boolean buildInput=false;
boolean filterTrue=true;
createSynthetic(donorFile, unImpTargetFile, 1024, 0.4, -1, 100);
// if(buildInput) {
// Alignment a=ImportUtils.readFromHapmap(donorFile, (ProgressListener)null);
// System.out.println("GBS Map Read");
// if(filterTrue) a=FilterAlignment.getInstance(a, 0, a.getSiteCount()/10);
// Alignment gbsMap=BitAlignment.getInstance(a, false);
//
// // TBitAlignment gbsMap=TBitAlignment.getInstance(ImportUtils.readFromHapmap(gFile, (ProgressListener)null));
// System.out.println("GBS converted and filtered");
// // SBitAlignment hapMap=(SBitAlignment)readGZOfSBit(hapFileAGP1, true);
// Alignment hapMap=ImportUtils.readFromHapmap(hFile, true, (ProgressListener)null);
// System.out.println("HapMap Read");
// hapMap=EdTests.fixHapMapNames(hapMap); //adds tags so that HapMapNames are recognizable
// System.out.println("HapMap Names Fixed");
// MutableNucleotideAlignment mna=EdTests.combineAlignments(hapMap, gbsMap);
// System.out.println("HapMap and GBS combined");
// mna.clean();
// ExportUtils.writeToHapmap(mna, false, unImpTargetFile, '\t', null);
// }
// Alignment mergeMap=ImportUtils.readFromHapmap(unImpTargetFile, false, (ProgressListener)null);
// KnownParentMinorWindowImputation e64NNI=new KnownParentMinorWindowImputation(mergeMap, impTargetFile);
// // TBitAlignment mergeMap=TBitAlignment.getInstance(mna);
}
}
class ShareSizeX {
int baseTaxon=-1;
int compTaxon=-1;
int left=-1;
int right=-1;
double p=1;
double fsum=0;
int df=0;
public ShareSizeX(int baseTaxon, int compTaxon, int left, int right, double p, double fsum) {
this(baseTaxon, compTaxon, left, right);
this.p=p;
this.fsum=fsum;
}
public ShareSizeX(int baseTaxon, int compTaxon, int left, int right) {
this.baseTaxon=baseTaxon;
this.compTaxon=compTaxon;
this.left=left;
this.right=right;
df=(right-left+1)*2;
}
public void moveLeft(double p, double fsum) {
left--;
this.p=p;
this.fsum=fsum;
df=df+2;
}
public void moveRight(double p, double fsum) {
right++;
this.p=p;
this.fsum=fsum;
df=df+2;
}
public String toString() {
return String.format("BTx:%d CTx:%d L:%d R:%d FSum:%g P:%g ", baseTaxon,
compTaxon, left, right, fsum, p);
}
}
| src/net/maizegenetics/pal/popgen/KnownParentMinorWindowImputation.java | Beginnings of class for known parent imputation | src/net/maizegenetics/pal/popgen/KnownParentMinorWindowImputation.java | Beginnings of class for known parent imputation |
|
Java | mit | error: pathspec 'library/src/main/java/io/nlopez/smartadapters/views/BindableViewLayout.java' did not match any file(s) known to git
| 514de99a5916eb3f77913f45507b99893d691bdb | 1 | mrmans0n/smart-adapters | package io.nlopez.smartadapters.views;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import io.nlopez.smartadapters.utils.ViewEventListener;
public abstract class BindableViewLayout<T> extends View implements BindableLayout<T> {
protected ViewEventListener<T> viewEventListener;
protected T item;
protected int position;
public BindableViewLayout(Context context) {
super(context);
initView(context);
}
public BindableViewLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public BindableViewLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public BindableViewLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView(context);
}
protected void initView(Context context) {
onViewCreated();
}
protected void onViewCreated() {
// To override by the subclass
}
@Override
public void bind(T item, int position) {
this.item = item;
this.position = position;
bind(item);
}
@Override
public abstract void bind(T item);
@Override
@Nullable
public ViewEventListener<T> getViewEventListener() {
return viewEventListener;
}
@Override
public void setViewEventListener(ViewEventListener<T> viewEventListener) {
this.viewEventListener = viewEventListener;
}
@Override
public void notifyItemAction(int actionId, T theItem, View view) {
if (viewEventListener != null) {
viewEventListener.onViewEvent(actionId, theItem, position, view);
}
}
public void notifyItemAction(int actionId, View view) {
notifyItemAction(actionId, item, view);
}
public void notifyItemAction(int actionId) {
notifyItemAction(actionId, item, this);
}
public T getItem() {
return item;
}
public void setItem(T item) {
this.item = item;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
}
| library/src/main/java/io/nlopez/smartadapters/views/BindableViewLayout.java | Added BindableViewLayout for the adventurers
| library/src/main/java/io/nlopez/smartadapters/views/BindableViewLayout.java | Added BindableViewLayout for the adventurers |
|
Java | epl-1.0 | ff156234fa6452c2bc5a4a27616e7f9d404cbb70 | 0 | StBurcher/hawkbit,StBurcher/hawkbit,stormc/hawkbit,bsinno/hawkbit,eclipse/hawkbit,stormc/hawkbit,StBurcher/hawkbit,eclipse/hawkbit,eclipse/hawkbit,bsinno/hawkbit,bsinno/hawkbit,eclipse/hawkbit,stormc/hawkbit | /**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.amqp;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Bean which holds the necessary properties for configuring the AMQP
* connection.
*
*/
@ConfigurationProperties("hawkbit.dmf.rabbitmq")
public class AmqpProperties {
/**
* DMF API dead letter queue.
*/
private String deadLetterQueue = "dmf_receiver_deadletter";
/**
* DMF API dead letter exchange.
*/
private String deadLetterExchange = "dmf.receiver.deadletter";
/**
* DMF API receiving queue.
*/
private String receiverQueue = "dmf_receiver";
/**
* Missing queue fatal.
*/
private boolean missingQueuesFatal = false;
/**
* Is missingQueuesFatal enabled
*
* @see SimpleMessageListenerContainer#setMissingQueuesFatal
* @return the missingQueuesFatal <true> enabled <false> disabled
*/
public boolean isMissingQueuesFatal() {
return missingQueuesFatal;
}
/**
* @param missingQueuesFatal
* the missingQueuesFatal to set.
* @see SimpleMessageListenerContainer#setMissingQueuesFatal
*/
public void setMissingQueuesFatal(final boolean missingQueuesFatal) {
this.missingQueuesFatal = missingQueuesFatal;
}
/**
* Returns the dead letter exchange.
*
* @return dead letter exchange
*/
public String getDeadLetterExchange() {
return deadLetterExchange;
}
/**
* Sets the dead letter exchange.
*
* @param deadLetterExchange
* the deadLetterExchange to be set
*/
public void setDeadLetterExchange(final String deadLetterExchange) {
this.deadLetterExchange = deadLetterExchange;
}
/**
* Returns the dead letter queue.
*
* @return the dead letter queue
*/
public String getDeadLetterQueue() {
return deadLetterQueue;
}
/**
* Sets the dead letter queue.
*
* @param deadLetterQueue
* the deadLetterQueue ro be set
*/
public void setDeadLetterQueue(final String deadLetterQueue) {
this.deadLetterQueue = deadLetterQueue;
}
public String getReceiverQueue() {
return receiverQueue;
}
public void setReceiverQueue(final String receiverQueue) {
this.receiverQueue = receiverQueue;
}
}
| hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java | /**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.amqp;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Bean which holds the necessary properties for configuring the AMQP
* connection.
*
*/
@Component
@ConfigurationProperties("hawkbit.dmf.rabbitmq")
public class AmqpProperties {
/**
* DMF API dead letter queue.
*/
private String deadLetterQueue = "dmf_receiver_deadletter";
/**
* DMF API dead letter exchange.
*/
private String deadLetterExchange = "dmf.receiver.deadletter";
/**
* DMF API receiving queue.
*/
private String receiverQueue = "dmf_receiver";
/**
* Missing queue fatal.
*/
private boolean missingQueuesFatal = false;
/**
* Is missingQueuesFatal enabled
*
* @see SimpleMessageListenerContainer#setMissingQueuesFatal
* @return the missingQueuesFatal <true> enabled <false> disabled
*/
public boolean isMissingQueuesFatal() {
return missingQueuesFatal;
}
/**
* @param missingQueuesFatal
* the missingQueuesFatal to set.
* @see SimpleMessageListenerContainer#setMissingQueuesFatal
*/
public void setMissingQueuesFatal(final boolean missingQueuesFatal) {
this.missingQueuesFatal = missingQueuesFatal;
}
/**
* Returns the dead letter exchange.
*
* @return dead letter exchange
*/
public String getDeadLetterExchange() {
return deadLetterExchange;
}
/**
* Sets the dead letter exchange.
*
* @param deadLetterExchange
* the deadLetterExchange to be set
*/
public void setDeadLetterExchange(final String deadLetterExchange) {
this.deadLetterExchange = deadLetterExchange;
}
/**
* Returns the dead letter queue.
*
* @return the dead letter queue
*/
public String getDeadLetterQueue() {
return deadLetterQueue;
}
/**
* Sets the dead letter queue.
*
* @param deadLetterQueue
* the deadLetterQueue ro be set
*/
public void setDeadLetterQueue(final String deadLetterQueue) {
this.deadLetterQueue = deadLetterQueue;
}
public String getReceiverQueue() {
return receiverQueue;
}
public void setReceiverQueue(final String receiverQueue) {
this.receiverQueue = receiverQueue;
}
}
| Annotation component must be removed because bean will otherwise
registered twice because of EnableAutoConfiguration in the
AmqpConfiguration
Signed-off-by: Michael Hirsch <[email protected]> | hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java | Annotation component must be removed because bean will otherwise registered twice because of EnableAutoConfiguration in the AmqpConfiguration |
|
Java | epl-1.0 | error: pathspec 'JavaSE/day01/JavaString.java' did not match any file(s) known to git
| 830234bb503dc308bebbc844e63dc7c15938dac8 | 1 | planetarianZero/JavaStudy | package day01;
/**
* String类常用方法
*
* int length()
* 获取字符串长度,无论中文还是英文都是一个长度,返回字符串下标,若返回-1表示没有该字符串
*
* int indexOf(String str)
* 查找给定字符串在当前字符串中的位置,该方法有几个重载方法
*
* int lastIndexOf(String str)
* 查找给定字符串在当前字符串中最后出现的位置
*
* String substring(int start,int end)
* 截取字符串,从指定位置(start)开始,到指定位置(end)结束,截取的字符串包含开始位置,不包含
* 结束位置
*
* char charAt(int index)
* 获取当前字符串指定下标的字符
*
* boolean startWith(String str)
* boolean endsWith(String str)
* 字符串是否以指定字符串开始或结束
*
* String toUpperCase()
* String toLowerCase()
* 将字符串转换为大写或小写
*
* 若干静态方法
* static String valueOf(XXX xxx)
* 将Java中的其他类型转换为字符串
*
* @author admin
*
*/
public class JavaString
{
private static String str="HelloWorld";
public static void main(String[] args)
{
TheStringIndex();
TheSubString();
TheCharAt();
TheStartOrEnd();
TheUpperOrLower();
TheValueOf();
}
public static void TheStringIndex()
{
int index=str.indexOf("H");
int theNull=str.indexOf("S");
System.out.println(index);
System.out.println(theNull);
/*
* 重载方法允许从指定位置开始查找
*/
index=str.indexOf("W", 4);
System.out.println(index);
index=str.lastIndexOf("o");
System.out.println(index);
}
public static void TheSubString()
{
String host="www.tedu.com.cn";
String sub=str.substring(5, 10);
System.out.println(sub);
sub=host.substring(host.indexOf(".")+1, host.indexOf(".",host.indexOf(".")+1));
System.out.println(sub);
}
public static void TheCharAt()
{
System.out.println(str.charAt(5));
String text="abcdcba";
for(int i=0;i<text.length()/2;i++)
{
if(text.charAt(i)!=text.charAt(text.length()-i-1))
{
System.out.println("不是回文");
return;
}
}
System.out.println("是回文");
}
public static void TheStartOrEnd()
{
System.out.println(str.startsWith("H")+":"+str.endsWith("d"));
}
public static void TheUpperOrLower()
{
System.out.println("全大写:"+str.toUpperCase()+":"+"全小写:"+str.toLowerCase());
}
public static void TheValueOf()
{
System.out.println(String.valueOf(12));
}
}
| JavaSE/day01/JavaString.java | Create JavaString.java | JavaSE/day01/JavaString.java | Create JavaString.java |
|
Java | epl-1.0 | error: pathspec 'src/main/java/SimpleMain.java' did not match any file(s) known to git
| 003305f3b74e316fc8ba48f5116e23941592c6a4 | 1 | dynamid/golo-lang-insa-citilab-historical-reference,franckverrot/golo-lang,jeffmaury/golo-lang,Mogztter/golo-lang,jeffmaury/golo-lang,smarr/golo-lang,titimoby/golo-lang,franckverrot/golo-lang,dynamid/golo-lang-insa-citilab-historical-reference,smarr/golo-lang,mojavelinux/golo-lang,titimoby/golo-lang,jeffmaury/golo-lang,Mogztter/golo-lang,mojavelinux/golo-lang,Mogztter/golo-lang,dynamid/golo-lang-insa-citilab-historical-reference | import sample.parser.*;
public class SimpleMain {
public static void main(String... args) throws ParseException {
Simple parser = new Simple(System.in);
SimpleNode start = parser.Start();
start.dump("# ");
start.childrenAccept(new SimpleVisitor() {
@Override
public Object visit(SimpleNode node, Object data) {
return null;
}
@Override
public Object visit(ASTStart node, Object data) {
return null;
}
@Override
public Object visit(ASTNumber node, Object data) {
System.out.println(">>> " + node.jjtGetValue());
return null;
}
}, null);
}
}
| src/main/java/SimpleMain.java | Testing with a SimpleMain class.
This class does nothing but checks that the generated code
is indeed usable for our needs.
| src/main/java/SimpleMain.java | Testing with a SimpleMain class. |
|
Java | mpl-2.0 | 6da65fc8773f2a78c6e00e835b26685f80c075b3 | 0 | Pilarbrist/rhino,lv7777/egit_test,Angelfirenze/rhino,lv7777/egit_test,ashwinrayaprolu1984/rhino,tntim96/rhino-jscover-repackaged,AlexTrotsenko/rhino,InstantWebP2P/rhino-android,Pilarbrist/rhino,tntim96/rhino-apigee,sainaen/rhino,swannodette/rhino,AlexTrotsenko/rhino,Angelfirenze/rhino,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,tejassaoji/RhinoCoarseTainting,tuchida/rhino,tuchida/rhino,Angelfirenze/rhino,Pilarbrist/rhino,AlexTrotsenko/rhino,lv7777/egit_test,Angelfirenze/rhino,AlexTrotsenko/rhino,qhanam/rhino,ashwinrayaprolu1984/rhino,sainaen/rhino,InstantWebP2P/rhino-android,Pilarbrist/rhino,swannodette/rhino,tejassaoji/RhinoCoarseTainting,tntim96/htmlunit-rhino-fork,swannodette/rhino,qhanam/rhino,jsdoc3/rhino,swannodette/rhino,tntim96/rhino-jscover,ashwinrayaprolu1984/rhino,ashwinrayaprolu1984/rhino,sainaen/rhino,swannodette/rhino,AlexTrotsenko/rhino,Angelfirenze/rhino,ashwinrayaprolu1984/rhino,swannodette/rhino,sainaen/rhino,tejassaoji/RhinoCoarseTainting,Pilarbrist/rhino,sainaen/rhino,tntim96/htmlunit-rhino-fork,jsdoc3/rhino,tuchida/rhino,tejassaoji/RhinoCoarseTainting,sam/htmlunit-rhino-fork,rasmuserik/rhino,sainaen/rhino,qhanam/rhino,tntim96/rhino-jscover-repackaged,tuchida/rhino,tejassaoji/RhinoCoarseTainting,Angelfirenze/rhino,Distrotech/rhino,tuchida/rhino,ashwinrayaprolu1984/rhino,swannodette/rhino,ashwinrayaprolu1984/rhino,tntim96/rhino-apigee,sainaen/rhino,AlexTrotsenko/rhino,tuchida/rhino,lv7777/egit_test,tntim96/rhino-apigee,Angelfirenze/rhino,lv7777/egit_test,AlexTrotsenko/rhino,Pilarbrist/rhino,tejassaoji/RhinoCoarseTainting,lv7777/egit_test,Pilarbrist/rhino,tejassaoji/RhinoCoarseTainting,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,rasmuserik/rhino,jsdoc3/rhino,lv7777/egit_test,sam/htmlunit-rhino-fork,qhanam/rhino,Distrotech/rhino,tntim96/rhino-jscover,tuchida/rhino | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Frank Mitchell
* Mike Shaver
* Kurt Westerfeld
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.lang.reflect.*;
import java.util.Hashtable;
import java.util.Enumeration;
/**
*
* @author Mike Shaver
* @author Norris Boyd
* @see NativeJavaObject
* @see NativeJavaClass
*/
class JavaMembers
{
JavaMembers(Scriptable scope, Class cl)
{
this.members = new Hashtable(23);
this.staticMembers = new Hashtable(7);
this.cl = cl;
reflect(scope);
}
boolean has(String name, boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Object obj = ht.get(name);
if (obj != null) {
return true;
} else {
return null != findExplicitFunction(name, isStatic);
}
}
Object get(Scriptable scope, String name, Object javaObject,
boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Object member = ht.get(name);
if (!isStatic && member == null) {
// Try to get static member from instance (LC3)
member = staticMembers.get(name);
}
if (member == null) {
member = this.getExplicitFunction(scope, name,
javaObject, isStatic);
if (member == null)
return Scriptable.NOT_FOUND;
}
if (member instanceof Scriptable)
return member; // why is this here?
Context cx = Context.getContext();
Object rval;
Class type;
try {
if (member instanceof BeanProperty) {
BeanProperty bp = (BeanProperty) member;
rval = bp.getter.invoke(javaObject, null);
type = bp.getter.method().getReturnType();
} else {
Field field = (Field) member;
rval = field.get(isStatic ? null : javaObject);
type = field.getType();
}
} catch (Exception ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
// Need to wrap the object before we return it.
scope = ScriptableObject.getTopLevelScope(scope);
return cx.getWrapFactory().wrap(cx, scope, rval, type);
}
public void put(Scriptable scope, String name, Object javaObject,
Object value, boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Object member = ht.get(name);
if (!isStatic && member == null) {
// Try to get static member from instance (LC3)
member = staticMembers.get(name);
}
if (member == null)
throw reportMemberNotFound(name);
if (member instanceof FieldAndMethods) {
FieldAndMethods fam = (FieldAndMethods) ht.get(name);
member = fam.field;
}
// Is this a bean property "set"?
if (member instanceof BeanProperty) {
BeanProperty bp = (BeanProperty)member;
if (bp.setter == null) {
throw reportMemberNotFound(name);
}
Class setType = bp.setter.argTypes[0];
Object[] args = { NativeJavaObject.coerceType(setType, value,
true) };
try {
bp.setter.invoke(javaObject, args);
} catch (Exception ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
}
else {
if (!(member instanceof Field)) {
String str = (member == null) ? "msg.java.internal.private"
: "msg.java.method.assign";
throw Context.reportRuntimeError1(str, name);
}
Field field = (Field)member;
Object javaValue = NativeJavaObject.coerceType(field.getType(),
value, true);
try {
field.set(javaObject, javaValue);
} catch (IllegalAccessException accessEx) {
throw new RuntimeException("unexpected IllegalAccessException "+
"accessing Java field");
} catch (IllegalArgumentException argEx) {
throw Context.reportRuntimeError3(
"msg.java.internal.field.type",
value.getClass().getName(), field,
javaObject.getClass().getName());
}
}
}
Object[] getIds(boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
int len = ht.size();
Object[] result = new Object[len];
Enumeration keys = ht.keys();
for (int i=0; i < len; i++)
result[i] = keys.nextElement();
return result;
}
static String javaSignature(Class type)
{
if (!type.isArray()) {
return type.getName();
} else {
int arrayDimension = 0;
do {
++arrayDimension;
type = type.getComponentType();
} while (type.isArray());
String name = type.getName();
String suffix = "[]";
if (arrayDimension == 1) {
return name.concat(suffix);
} else {
int length = name.length() + arrayDimension * suffix.length();
StringBuffer sb = new StringBuffer(length);
sb.append(name);
while (arrayDimension != 0) {
--arrayDimension;
sb.append(suffix);
}
return sb.toString();
}
}
}
static String liveConnectSignature(Class[] argTypes)
{
int N = argTypes.length;
if (N == 0) { return "()"; }
StringBuffer sb = new StringBuffer();
sb.append('(');
for (int i = 0; i != N; ++i) {
if (i != 0) {
sb.append(',');
}
sb.append(javaSignature(argTypes[i]));
}
sb.append(')');
return sb.toString();
}
private MemberBox findExplicitFunction(String name, boolean isStatic)
{
int sigStart = name.indexOf('(');
if (sigStart < 0) { return null; }
Hashtable ht = isStatic ? staticMembers : members;
MemberBox[] methodsOrCtors = null;
boolean isCtor = (isStatic && sigStart == 0);
if (isCtor) {
// Explicit request for an overloaded constructor
methodsOrCtors = ctors;
} else {
// Explicit request for an overloaded method
String trueName = name.substring(0,sigStart);
Object obj = ht.get(trueName);
if (!isStatic && obj == null) {
// Try to get static member from instance (LC3)
obj = staticMembers.get(trueName);
}
if (obj instanceof NativeJavaMethod) {
NativeJavaMethod njm = (NativeJavaMethod)obj;
methodsOrCtors = njm.methods;
}
}
if (methodsOrCtors != null) {
for (int i = 0; i < methodsOrCtors.length; i++) {
Class[] type = methodsOrCtors[i].argTypes;
String sig = liveConnectSignature(type);
if (sigStart + sig.length() == name.length()
&& name.regionMatches(sigStart, sig, 0, sig.length()))
{
return methodsOrCtors[i];
}
}
}
return null;
}
private Object getExplicitFunction(Scriptable scope, String name,
Object javaObject, boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Object member = null;
MemberBox methodOrCtor = findExplicitFunction(name, isStatic);
if (methodOrCtor != null) {
Scriptable prototype =
ScriptableObject.getFunctionPrototype(scope);
if (methodOrCtor.isCtor()) {
NativeJavaConstructor fun =
new NativeJavaConstructor(methodOrCtor);
fun.setPrototype(prototype);
member = fun;
ht.put(name, fun);
} else {
String trueName = methodOrCtor.getName();
member = ht.get(trueName);
if (member instanceof NativeJavaMethod &&
((NativeJavaMethod)member).methods.length > 1 ) {
NativeJavaMethod fun =
new NativeJavaMethod(methodOrCtor, name);
fun.setPrototype(prototype);
ht.put(name, fun);
member = fun;
}
}
}
return member;
}
private void reflect(Scriptable scope)
{
// We reflect methods first, because we want overloaded field/method
// names to be allocated to the NativeJavaMethod before the field
// gets in the way.
reflectMethods(scope);
reflectFields(scope);
makeBeanProperties(scope, false);
makeBeanProperties(scope, true);
reflectCtors();
}
private void reflectMethods(Scriptable scope)
{
Method[] methods = cl.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
int mods = method.getModifiers();
if (!Modifier.isPublic(mods)) {
continue;
}
boolean isStatic = Modifier.isStatic(mods);
Hashtable ht = isStatic ? staticMembers : members;
String name = method.getName();
Object value = ht.get(name);
if (value == null) {
ht.put(name, method);
} else {
ObjArray overloadedMethods;
if (value instanceof ObjArray) {
overloadedMethods = (ObjArray)value;
} else {
if (!(value instanceof Method)) Context.codeBug();
// value should be instance of Method as reflectMethods is
// called when staticMembers and members are empty
overloadedMethods = new ObjArray();
overloadedMethods.add(value);
ht.put(name, overloadedMethods);
}
overloadedMethods.add(method);
}
}
initNativeMethods(staticMembers, scope);
initNativeMethods(members, scope);
}
private void reflectFields(Scriptable scope)
{
Field[] fields = cl.getFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
int mods = field.getModifiers();
if (!Modifier.isPublic(mods)) {
continue;
}
boolean isStatic = Modifier.isStatic(mods);
Hashtable ht = isStatic ? staticMembers : members;
String name = field.getName();
Object member = ht.get(name);
if (member == null) {
ht.put(name, field);
} else if (member instanceof NativeJavaMethod) {
NativeJavaMethod method = (NativeJavaMethod) member;
FieldAndMethods fam = new FieldAndMethods(method.methods,
field);
fam.setPrototype(ScriptableObject.getFunctionPrototype(scope));
getFieldAndMethodsTable(isStatic).put(name, fam);
ht.put(name, fam);
} else if (member instanceof Field) {
Field oldField = (Field) member;
// If this newly reflected field shadows an inherited field,
// then replace it. Otherwise, since access to the field
// would be ambiguous from Java, no field should be reflected.
// For now, the first field found wins, unless another field
// explicitly shadows it.
if (oldField.getDeclaringClass().
isAssignableFrom(field.getDeclaringClass()))
{
ht.put(name, field);
}
} else {
// "unknown member type"
Context.codeBug();
}
}
}
private void makeBeanProperties(Scriptable scope, boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Hashtable toAdd = new Hashtable();
// Now, For each member, make "bean" properties.
for (Enumeration e = ht.keys(); e.hasMoreElements(); ) {
// Is this a getter?
String name = (String) e.nextElement();
boolean memberIsGetMethod = name.startsWith("get");
boolean memberIsIsMethod = name.startsWith("is");
if (memberIsGetMethod || memberIsIsMethod) {
// Double check name component.
String nameComponent = name.substring(memberIsGetMethod ? 3 : 2);
if (nameComponent.length() == 0)
continue;
// Make the bean property name.
String beanPropertyName = nameComponent;
char ch0 = nameComponent.charAt(0);
if (Character.isUpperCase(ch0)) {
if (nameComponent.length() == 1) {
beanPropertyName = nameComponent.toLowerCase();
} else {
char ch1 = nameComponent.charAt(1);
if (!Character.isUpperCase(ch1)) {
beanPropertyName = Character.toLowerCase(ch0)
+nameComponent.substring(1);
}
}
}
// If we already have a member by this name, don't do this
// property.
if (ht.containsKey(beanPropertyName))
continue;
// Get the method by this name.
Object member = ht.get(name);
if (!(member instanceof NativeJavaMethod))
continue;
NativeJavaMethod njmGet = (NativeJavaMethod)member;
MemberBox getter = extractGetMethod(njmGet.methods, isStatic);
if (getter != null) {
// We have a getter. Now, do we have a setter?
NativeJavaMethod njmSet = null;
MemberBox setter = null;
String setterName = "set".concat(nameComponent);
if (ht.containsKey(setterName)) {
// Is this value a method?
member = ht.get(setterName);
if (member instanceof NativeJavaMethod) {
njmSet = (NativeJavaMethod)member;
Class type = getter.method().getReturnType();
setter = extractSetMethod(type, njmSet.methods,
isStatic);
}
}
// Make the property.
BeanProperty bp = new BeanProperty(getter, setter);
toAdd.put(beanPropertyName, bp);
}
}
}
// Add the new bean properties.
for (Enumeration e = toAdd.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
Object value = toAdd.get(key);
ht.put(key, value);
}
}
private void reflectCtors()
{
Constructor[] constructors = cl.getConstructors();
int N = constructors.length;
ctors = new MemberBox[N];
for (int i = 0; i != N; ++i) {
ctors[i] = new MemberBox(constructors[i]);
}
}
private static void initNativeMethods(Hashtable ht, Scriptable scope)
{
Enumeration e = ht.keys();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
MemberBox[] methods;
Object value = ht.get(name);
if (value instanceof Method) {
methods = new MemberBox[1];
methods[0] = new MemberBox((Method)value);
} else {
ObjArray overloadedMethods = (ObjArray)value;
int N = overloadedMethods.size();
if (N < 2) Context.codeBug();
methods = new MemberBox[N];
for (int i = 0; i != N; ++i) {
Method method = (Method)overloadedMethods.get(i);
methods[i] = new MemberBox(method);
}
}
NativeJavaMethod fun = new NativeJavaMethod(methods);
if (scope != null) {
fun.setPrototype(ScriptableObject.getFunctionPrototype(scope));
}
ht.put(name, fun);
}
}
private Hashtable getFieldAndMethodsTable(boolean isStatic)
{
Hashtable fmht = isStatic ? staticFieldAndMethods
: fieldAndMethods;
if (fmht == null) {
fmht = new Hashtable(11);
if (isStatic)
staticFieldAndMethods = fmht;
else
fieldAndMethods = fmht;
}
return fmht;
}
private static MemberBox extractGetMethod(MemberBox[] methods,
boolean isStatic)
{
// Grab and inspect the getter method; does it have an empty parameter
// list with a return value (eg. a getSomething() or isSomething())?
if (methods.length == 1) {
MemberBox method = methods[0];
// Make sure the method static-ness is preserved for this property.
if (!isStatic || method.isStatic()) {
if (method.argTypes.length == 0) {
Class type = method.method().getReturnType();
if (type != Void.TYPE) {
return method;
}
}
}
}
return null;
}
private static MemberBox extractSetMethod(Class type, MemberBox[] methods,
boolean isStatic)
{
//
// Note: it may be preferable to allow NativeJavaMethod.findFunction()
// to find the appropriate setter; unfortunately, it requires an
// instance of the target arg to determine that.
//
// Make two passes: one to find a method with direct type assignment,
// and one to find a widening conversion.
for (int pass = 1; pass <= 2; ++pass) {
for (int i = 0; i < methods.length; ++i) {
MemberBox method = methods[i];
if (!isStatic || method.isStatic()) {
if (method.method().getReturnType() == Void.TYPE) {
Class[] params = method.argTypes;
if (params.length == 1) {
if (pass == 1) {
if (params[0] == type) {
return method;
}
} else {
if (pass != 2) Context.codeBug();
if (params[0].isAssignableFrom(type)) {
return method;
}
}
}
}
}
}
}
return null;
}
Hashtable getFieldAndMethodsObjects(Scriptable scope, Object javaObject,
boolean isStatic)
{
Hashtable ht = isStatic ? staticFieldAndMethods : fieldAndMethods;
if (ht == null)
return null;
int len = ht.size();
Hashtable result = new Hashtable(len);
Enumeration e = ht.elements();
while (len-- > 0) {
FieldAndMethods fam = (FieldAndMethods) e.nextElement();
FieldAndMethods famNew = new FieldAndMethods(fam.methods,
fam.field);
famNew.javaObject = javaObject;
result.put(fam.field.getName(), famNew);
}
return result;
}
static JavaMembers lookupClass(Scriptable scope, Class dynamicType,
Class staticType)
{
JavaMembers members;
Hashtable ct = classTable; // use local reference to avoid synchronize
Class cl = dynamicType;
for (;;) {
members = (JavaMembers)ct.get(cl);
if (members != null) {
return members;
}
try {
members = new JavaMembers(scope, cl);
break;
} catch (SecurityException e) {
// Reflection may fail for objects that are in a restricted
// access package (e.g. sun.*). If we get a security
// exception, try again with the static type if it is interface.
// Otherwise, try superclass
if (staticType != null && staticType.isInterface()) {
cl = staticType;
staticType = null; // try staticType only once
} else {
Class parent = cl.getSuperclass();
if (parent == null) {
if (cl.isInterface()) {
// last resort after failed staticType interface
parent = ScriptRuntime.ObjectClass;
} else {
throw e;
}
}
cl = parent;
}
}
}
if (Context.isCachingEnabled)
ct.put(cl, members);
return members;
}
RuntimeException reportMemberNotFound(String memberName)
{
return Context.reportRuntimeError2(
"msg.java.member.not.found", cl.getName(), memberName);
}
static Hashtable classTable = new Hashtable();
private Class cl;
private Hashtable members;
private Hashtable fieldAndMethods;
private Hashtable staticMembers;
private Hashtable staticFieldAndMethods;
MemberBox[] ctors;
}
class BeanProperty
{
BeanProperty(MemberBox getter, MemberBox setter)
{
this.getter = getter;
this.setter = setter;
}
MemberBox getter;
MemberBox setter;
}
class FieldAndMethods extends NativeJavaMethod
{
FieldAndMethods(MemberBox[] methods, Field field)
{
super(methods);
this.field = field;
}
public Object getDefaultValue(Class hint)
{
if (hint == ScriptRuntime.FunctionClass)
return this;
Object rval;
Class type;
try {
rval = field.get(javaObject);
type = field.getType();
} catch (IllegalAccessException accEx) {
throw Context.reportRuntimeError1(
"msg.java.internal.private", field.getName());
}
Context cx = Context.getContext();
rval = cx.getWrapFactory().wrap(cx, this, rval, type);
if (rval instanceof Scriptable) {
rval = ((Scriptable) rval).getDefaultValue(hint);
}
return rval;
}
Field field;
Object javaObject;
}
| src/org/mozilla/javascript/JavaMembers.java | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Frank Mitchell
* Mike Shaver
* Kurt Westerfeld
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.lang.reflect.*;
import java.util.Hashtable;
import java.util.Enumeration;
/**
*
* @author Mike Shaver
* @author Norris Boyd
* @see NativeJavaObject
* @see NativeJavaClass
*/
class JavaMembers
{
JavaMembers(Scriptable scope, Class cl)
{
this.members = new Hashtable(23);
this.staticMembers = new Hashtable(7);
this.cl = cl;
reflect(scope);
}
boolean has(String name, boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Object obj = ht.get(name);
if (obj != null) {
return true;
} else {
return null != findExplicitFunction(name, isStatic);
}
}
Object get(Scriptable scope, String name, Object javaObject,
boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Object member = ht.get(name);
if (!isStatic && member == null) {
// Try to get static member from instance (LC3)
member = staticMembers.get(name);
}
if (member == null) {
member = this.getExplicitFunction(scope, name,
javaObject, isStatic);
if (member == null)
return Scriptable.NOT_FOUND;
}
if (member instanceof Scriptable)
return member; // why is this here?
Context cx = Context.getContext();
Object rval;
Class type;
try {
if (member instanceof BeanProperty) {
BeanProperty bp = (BeanProperty) member;
rval = bp.getter.invoke(javaObject, null);
type = bp.getter.method().getReturnType();
} else {
Field field = (Field) member;
rval = field.get(isStatic ? null : javaObject);
type = field.getType();
}
} catch (Exception ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
// Need to wrap the object before we return it.
scope = ScriptableObject.getTopLevelScope(scope);
return cx.getWrapFactory().wrap(cx, scope, rval, type);
}
public void put(Scriptable scope, String name, Object javaObject,
Object value, boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Object member = ht.get(name);
if (!isStatic && member == null) {
// Try to get static member from instance (LC3)
member = staticMembers.get(name);
}
if (member == null)
throw reportMemberNotFound(name);
if (member instanceof FieldAndMethods) {
FieldAndMethods fam = (FieldAndMethods) ht.get(name);
member = fam.field;
}
// Is this a bean property "set"?
if (member instanceof BeanProperty) {
BeanProperty bp = (BeanProperty)member;
if (bp.setter == null) {
throw reportMemberNotFound(name);
}
Class setType = bp.setter.argTypes[0];
Object[] args = { NativeJavaObject.coerceType(setType, value,
true) };
try {
bp.setter.invoke(javaObject, args);
} catch (Exception ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
}
else {
if (!(member instanceof Field)) {
String str = (member == null) ? "msg.java.internal.private"
: "msg.java.method.assign";
throw Context.reportRuntimeError1(str, name);
}
Field field = (Field)member;
Object javaValue = NativeJavaObject.coerceType(field.getType(),
value, true);
try {
field.set(javaObject, javaValue);
} catch (IllegalAccessException accessEx) {
throw new RuntimeException("unexpected IllegalAccessException "+
"accessing Java field");
} catch (IllegalArgumentException argEx) {
throw Context.reportRuntimeError3(
"msg.java.internal.field.type",
value.getClass().getName(), field,
javaObject.getClass().getName());
}
}
}
Object[] getIds(boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
int len = ht.size();
Object[] result = new Object[len];
Enumeration keys = ht.keys();
for (int i=0; i < len; i++)
result[i] = keys.nextElement();
return result;
}
static String javaSignature(Class type)
{
if (!type.isArray()) {
return type.getName();
} else {
int arrayDimension = 0;
do {
++arrayDimension;
type = type.getComponentType();
} while (type.isArray());
String name = type.getName();
String suffix = "[]";
if (arrayDimension == 1) {
return name.concat(suffix);
} else {
int length = name.length() + arrayDimension * suffix.length();
StringBuffer sb = new StringBuffer(length);
sb.append(name);
while (arrayDimension != 0) {
--arrayDimension;
sb.append(suffix);
}
return sb.toString();
}
}
}
static String liveConnectSignature(Class[] argTypes)
{
int N = argTypes.length;
if (N == 0) { return "()"; }
StringBuffer sb = new StringBuffer();
sb.append('(');
for (int i = 0; i != N; ++i) {
if (i != 0) {
sb.append(',');
}
sb.append(javaSignature(argTypes[i]));
}
sb.append(')');
return sb.toString();
}
private MemberBox findExplicitFunction(String name, boolean isStatic)
{
int sigStart = name.indexOf('(');
if (sigStart < 0) { return null; }
Hashtable ht = isStatic ? staticMembers : members;
MemberBox[] methodsOrCtors = null;
boolean isCtor = (isStatic && sigStart == 0);
if (isCtor) {
// Explicit request for an overloaded constructor
methodsOrCtors = ctors;
} else {
// Explicit request for an overloaded method
String trueName = name.substring(0,sigStart);
Object obj = ht.get(trueName);
if (!isStatic && obj == null) {
// Try to get static member from instance (LC3)
obj = staticMembers.get(trueName);
}
if (obj instanceof NativeJavaMethod) {
NativeJavaMethod njm = (NativeJavaMethod)obj;
methodsOrCtors = njm.methods;
}
}
if (methodsOrCtors != null) {
for (int i = 0; i < methodsOrCtors.length; i++) {
Class[] type = methodsOrCtors[i].argTypes;
String sig = liveConnectSignature(type);
if (sigStart + sig.length() == name.length()
&& name.regionMatches(sigStart, sig, 0, sig.length()))
{
return methodsOrCtors[i];
}
}
}
return null;
}
private Object getExplicitFunction(Scriptable scope, String name,
Object javaObject, boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Object member = null;
MemberBox methodOrCtor = findExplicitFunction(name, isStatic);
if (methodOrCtor != null) {
Scriptable prototype =
ScriptableObject.getFunctionPrototype(scope);
if (methodOrCtor.isCtor()) {
NativeJavaConstructor fun =
new NativeJavaConstructor(methodOrCtor);
fun.setPrototype(prototype);
member = fun;
ht.put(name, fun);
} else {
String trueName = methodOrCtor.getName();
member = ht.get(trueName);
if (member instanceof NativeJavaMethod &&
((NativeJavaMethod)member).methods.length > 1 ) {
NativeJavaMethod fun =
new NativeJavaMethod(methodOrCtor, name);
fun.setPrototype(prototype);
ht.put(name, fun);
member = fun;
}
}
}
return member;
}
private void reflect(Scriptable scope)
{
// We reflect methods first, because we want overloaded field/method
// names to be allocated to the NativeJavaMethod before the field
// gets in the way.
reflectMethods(scope);
reflectFields(scope);
makeBeanProperties(scope, false);
makeBeanProperties(scope, true);
reflectCtors();
}
private void reflectMethods(Scriptable scope)
{
Method[] methods = cl.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
int mods = method.getModifiers();
if (!Modifier.isPublic(mods)) {
continue;
}
boolean isStatic = Modifier.isStatic(mods);
Hashtable ht = isStatic ? staticMembers : members;
String name = method.getName();
Object value = ht.get(name);
if (value == null) {
ht.put(name, method);
} else {
ObjArray overloadedMethods;
if (value instanceof ObjArray) {
overloadedMethods = (ObjArray)value;
} else {
if (!(value instanceof Method)) Context.codeBug();
// value should be instance of Method as reflectMethods is
// called when staticMembers and members are empty
overloadedMethods = new ObjArray();
overloadedMethods.add(value);
ht.put(name, overloadedMethods);
}
overloadedMethods.add(method);
}
}
initNativeMethods(staticMembers, scope);
initNativeMethods(members, scope);
}
private void reflectFields(Scriptable scope)
{
Field[] fields = cl.getFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
int mods = field.getModifiers();
if (!Modifier.isPublic(mods)) {
continue;
}
boolean isStatic = Modifier.isStatic(mods);
Hashtable ht = isStatic ? staticMembers : members;
String name = field.getName();
Object member = ht.get(name);
if (member == null) {
ht.put(name, field);
} else if (member instanceof NativeJavaMethod) {
NativeJavaMethod method = (NativeJavaMethod) member;
FieldAndMethods fam = new FieldAndMethods(method.methods,
field);
fam.setPrototype(ScriptableObject.getFunctionPrototype(scope));
getFieldAndMethodsTable(isStatic).put(name, fam);
ht.put(name, fam);
} else if (member instanceof Field) {
Field oldField = (Field) member;
// If this newly reflected field shadows an inherited field,
// then replace it. Otherwise, since access to the field
// would be ambiguous from Java, no field should be reflected.
// For now, the first field found wins, unless another field
// explicitly shadows it.
if (oldField.getDeclaringClass().
isAssignableFrom(field.getDeclaringClass()))
{
ht.put(name, field);
}
} else {
// "unknown member type"
Context.codeBug();
}
}
}
private void makeBeanProperties(Scriptable scope, boolean isStatic)
{
Hashtable ht = isStatic ? staticMembers : members;
Hashtable toAdd = new Hashtable();
// Now, For each member, make "bean" properties.
for (Enumeration e = ht.keys(); e.hasMoreElements(); ) {
// Is this a getter?
String name = (String) e.nextElement();
boolean memberIsGetMethod = name.startsWith("get");
boolean memberIsIsMethod = name.startsWith("is");
if (memberIsGetMethod || memberIsIsMethod) {
// Double check name component.
String nameComponent = name.substring(memberIsGetMethod ? 3 : 2);
if (nameComponent.length() == 0)
continue;
// Make the bean property name.
String beanPropertyName = nameComponent;
char ch0 = nameComponent.charAt(0);
if (Character.isUpperCase(ch0)) {
if (nameComponent.length() == 1) {
beanPropertyName = nameComponent.toLowerCase();
} else {
char ch1 = nameComponent.charAt(1);
if (!Character.isUpperCase(ch1)) {
beanPropertyName = Character.toLowerCase(ch0)
+nameComponent.substring(1);
}
}
}
// If we already have a member by this name, don't do this
// property.
if (ht.containsKey(beanPropertyName))
continue;
// Get the method by this name.
Object member = ht.get(name);
if (!(member instanceof NativeJavaMethod))
continue;
NativeJavaMethod njmGet = (NativeJavaMethod)member;
MemberBox getter = extractGetMethod(njmGet.methods, isStatic);
if (getter != null) {
// We have a getter. Now, do we have a setter?
NativeJavaMethod njmSet = null;
MemberBox setter = null;
String setterName = "set".concat(nameComponent);
if (ht.containsKey(setterName)) {
// Is this value a method?
member = ht.get(setterName);
if (member instanceof NativeJavaMethod) {
njmSet = (NativeJavaMethod)member;
Class type = getter.method().getReturnType();
setter = extractSetMethod(type, njmSet.methods,
isStatic);
}
}
// Make the property.
BeanProperty bp = new BeanProperty(getter, setter);
toAdd.put(beanPropertyName, bp);
}
}
}
// Add the new bean properties.
for (Enumeration e = toAdd.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
Object value = toAdd.get(key);
ht.put(key, value);
}
}
private void reflectCtors()
{
Constructor[] constructors = cl.getConstructors();
int N = constructors.length;
ctors = new MemberBox[N];
for (int i = 0; i != N; ++i) {
ctors[i] = new MemberBox(constructors[i]);
}
}
private static void initNativeMethods(Hashtable ht, Scriptable scope)
{
Enumeration e = ht.keys();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
MemberBox[] methods;
Object value = ht.get(name);
if (value instanceof Method) {
methods = new MemberBox[1];
methods[0] = new MemberBox((Method)value);
} else {
ObjArray overloadedMethods = (ObjArray)value;
int N = overloadedMethods.size();
if (N < 2) Context.codeBug();
methods = new MemberBox[N];
for (int i = 0; i != N; ++i) {
Method method = (Method)overloadedMethods.get(i);
methods[i] = new MemberBox(method);
}
}
NativeJavaMethod fun = new NativeJavaMethod(methods);
if (scope != null) {
fun.setPrototype(ScriptableObject.getFunctionPrototype(scope));
}
ht.put(name, fun);
}
}
private Hashtable getFieldAndMethodsTable(boolean isStatic)
{
Hashtable fmht = isStatic ? staticFieldAndMethods
: fieldAndMethods;
if (fmht == null) {
fmht = new Hashtable(11);
if (isStatic)
staticFieldAndMethods = fmht;
else
fieldAndMethods = fmht;
}
return fmht;
}
private static MemberBox extractGetMethod(MemberBox[] methods,
boolean isStatic)
{
// Grab and inspect the getter method; does it have an empty parameter
// list with a return value (eg. a getSomething() or isSomething())?
if (methods.length == 1) {
MemberBox method = methods[0];
// Make sure the method static-ness is preserved for this property.
if (!isStatic || method.isStatic()) {
if (method.argTypes.length == 0) {
Class type = method.method().getReturnType();
if (type != Void.TYPE) {
return method;
}
}
}
}
return null;
}
private static MemberBox extractSetMethod(Class type, MemberBox[] methods,
boolean isStatic)
{
//
// Note: it may be preferable to allow NativeJavaMethod.findFunction()
// to find the appropriate setter; unfortunately, it requires an
// instance of the target arg to determine that.
//
// Make two passes: one to find a method with direct type assignment,
// and one to find a widening conversion.
for (int pass = 1; pass <= 2; ++pass) {
for (int i = 0; i < methods.length; ++i) {
MemberBox method = methods[i];
if (!isStatic || method.isStatic()) {
if (method.method().getReturnType() == Void.TYPE) {
Class[] params = method.argTypes;
if (params.length == 1) {
if (pass == 1) {
if (params[0] == type) {
return method;
}
} else {
if (pass != 2) Context.codeBug();
if (params[0].isAssignableFrom(type)) {
return method;
}
}
}
}
}
}
}
return null;
}
Hashtable getFieldAndMethodsObjects(Scriptable scope, Object javaObject,
boolean isStatic)
{
Hashtable ht = isStatic ? staticFieldAndMethods : fieldAndMethods;
if (ht == null)
return null;
int len = ht.size();
Hashtable result = new Hashtable(len);
Enumeration e = ht.elements();
while (len-- > 0) {
FieldAndMethods fam = (FieldAndMethods) e.nextElement();
FieldAndMethods famNew = new FieldAndMethods(fam.methods,
fam.field);
famNew.javaObject = javaObject;
result.put(fam.field.getName(), famNew);
}
return result;
}
static JavaMembers lookupClass(Scriptable scope, Class dynamicType,
Class staticType)
{
Hashtable ct = classTable; // use local reference to avoid synchronize
JavaMembers members = (JavaMembers) ct.get(dynamicType);
if (members != null)
return members;
if (staticType == dynamicType) {
staticType = null;
}
Class cl = dynamicType;
if (!Modifier.isPublic(dynamicType.getModifiers())) {
if (staticType == null
|| !Modifier.isPublic(staticType.getModifiers()))
{
cl = getPublicSuperclass(dynamicType);
if (cl == null) {
// Can happen if dynamicType is interface
cl = dynamicType;
}
} else if (staticType.isInterface()) {
// If the static type is an interface, use it
cl = staticType;
} else {
// We can use the static type, and that is OK, but we'll trace
// back the java class chain here to look for public superclass
// comming before staticType
cl = getPublicSuperclass(dynamicType);
if (cl == null) {
// Can happen if dynamicType is interface
cl = dynamicType;
}
}
}
for (;;) {
try {
members = new JavaMembers(scope, cl);
break;
} catch (SecurityException e) {
// Reflection may fail for objects that are in a restricted
// access package (e.g. sun.*). If we get a security
// exception, try again with the static type if it is interface.
// Otherwise, try public superclass
if (staticType != null && staticType.isInterface()) {
cl = staticType;
staticType = null; // try staticType only once
continue;
}
Class parent = getPublicSuperclass(cl);
if (parent == null) {
if (cl.isInterface()) {
// last resort
parent = ScriptRuntime.ObjectClass;
} else {
throw e;
}
}
cl = parent;
}
}
if (Context.isCachingEnabled)
ct.put(cl, members);
return members;
}
private static Class getPublicSuperclass(Class cl)
{
if (cl == ScriptRuntime.ObjectClass) {
return null;
}
do {
cl = cl.getSuperclass();
if (cl == null || cl == ScriptRuntime.ObjectClass) {
break;
}
} while (!Modifier.isPublic(cl.getModifiers()));
return cl;
}
RuntimeException reportMemberNotFound(String memberName)
{
return Context.reportRuntimeError2(
"msg.java.member.not.found", cl.getName(), memberName);
}
static Hashtable classTable = new Hashtable();
private Class cl;
private Hashtable members;
private Hashtable fieldAndMethods;
private Hashtable staticMembers;
private Hashtable staticFieldAndMethods;
MemberBox[] ctors;
}
class BeanProperty
{
BeanProperty(MemberBox getter, MemberBox setter)
{
this.getter = getter;
this.setter = setter;
}
MemberBox getter;
MemberBox setter;
}
class FieldAndMethods extends NativeJavaMethod
{
FieldAndMethods(MemberBox[] methods, Field field)
{
super(methods);
this.field = field;
}
public Object getDefaultValue(Class hint)
{
if (hint == ScriptRuntime.FunctionClass)
return this;
Object rval;
Class type;
try {
rval = field.get(javaObject);
type = field.getType();
} catch (IllegalAccessException accEx) {
throw Context.reportRuntimeError1(
"msg.java.internal.private", field.getName());
}
Context cx = Context.getContext();
rval = cx.getWrapFactory().wrap(cx, this, rval, type);
if (rval instanceof Scriptable) {
rval = ((Scriptable) rval).getDefaultValue(hint);
}
return rval;
}
Field field;
Object javaObject;
}
| Fixing http://bugzilla.mozilla.org/show_bug.cgi?id=214608 :
The reason for the regression is that now JavaMembers.lookupClass never
attempts to reflect package-private classes. But this is wrong since even with
SecirutyManager installed JVM allows to call Class.getMethos()( and returns
list of all public methods in the class and its super classes.
The patch removes the restrictions while making JavaMembers.lookupClass much
simpler.
| src/org/mozilla/javascript/JavaMembers.java | Fixing http://bugzilla.mozilla.org/show_bug.cgi?id=214608 : |
|
Java | mpl-2.0 | error: pathspec 'qadevOOo/tests/java/ifc/util/_XNumberFormatter.java' did not match any file(s) known to git
| a9d5c3c572488477676766b3c10742cfeaed9f53 | 1 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*************************************************************************
*
* $RCSfile: _XNumberFormatter.java,v $
*
* $Revision: 1.2 $
*
* last change:$Date: 2003-09-08 11:31:02 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
package ifc.util;
import lib.MultiMethodTest;
import com.sun.star.util.XNumberFormatter;
/**
* Testing <code>com.sun.star.util.XNumberFormatter</code>
* interface methods :
* <ul>
* <li><code> attachNumberFormatsSupplier()</code></li>
* <li><code> convertNumberToString() </code></li>
* <li><code> convertStringToNumber() </code></li>
* <li><code> detectNumberFormat() </code></li>
* <li><code> formatString() </code></li>
* <li><code> getInputString() </code></li>
* <li><code> getNumberFormatsSupplier() </code></li>
* <li><code> queryColorForNumber() </code></li>
* <li><code> queryColorForString() </code></li>
* </ul> <p>
* Test is <b> NOT </b> multithread compilant. <p>
* @see com.sun.star.util.XNumberFormatter
*/
public class _XNumberFormatter extends MultiMethodTest {
public XNumberFormatter oObj = null;
/**
* Not implemented yet.
*/
public void _attachNumberFormatsSupplier() {
log.println("Not yet implemented");
}
/**
* Tries to convert a number to a string. <p>
* Has <b> OK </b> status if the method returns not
* <code>null</code> value.
*/
public void _convertNumberToString() {
double dValue = 1.56;
int key = 15;
String gString = oObj.convertNumberToString(key,dValue);
log.println("Getting: "+gString);
tRes.tested("convertNumberToString",gString!=null);
}
/**
* Not implemented yet.
*/
public void _convertStringToNumber() {
log.println("Not yet implemented");
}
/**
* Not implemented yet.
*/
public void _detectNumberFormat() {
log.println("Not yet implemented");
}
/**
* Not implemented yet.
*/
public void _formatString() {
log.println("Not yet implemented");
}
/**
* Not implemented yet.
*/
public void _getInputString() {
log.println("Not yet implemented");
}
/**
* Not implemented yet.
*/
public void _getNumberFormatsSupplier() {
log.println("Not yet implemented");
}
/**
* Not implemented yet.
*/
public void _queryColorForNumber() {
log.println("Not yet implemented");
}
/**
* Not implemented yet.
*/
public void _queryColorForString() {
log.println("Not yet implemented");
}
} // finish class _XNumberFormatter
| qadevOOo/tests/java/ifc/util/_XNumberFormatter.java | INTEGRATION: CWS qadev11 (1.1.2); FILE ADDED
2003/09/03 14:56:54 sw 1.1.2.1: #112049#
| qadevOOo/tests/java/ifc/util/_XNumberFormatter.java | INTEGRATION: CWS qadev11 (1.1.2); FILE ADDED 2003/09/03 14:56:54 sw 1.1.2.1: #112049# |
|
Java | mpl-2.0 | error: pathspec 'src/main/java/org/opengsi/comsci/exceptions/MismatchedSizeException.java' did not match any file(s) known to git
| 750e1f4d7904007e02502c7161a362d67823e6f1 | 1 | opengsi/java | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (C) 2014, youngmook.
*/
package org.opengsi.comsci.exceptions;
/**
*
* @author youngmook
*/
public class MismatchedSizeException extends Exception {
/**
* Creates a new instance of <code>MismatchedSizeException</code> without
* detail message.
*/
public MismatchedSizeException() {
}
/**
* Constructs an instance of <code>MismatchedSizeException</code> with the
* specified detail message.
*
* @param msg the detail message.
*/
public MismatchedSizeException(String msg) {
super(msg);
}
}
| src/main/java/org/opengsi/comsci/exceptions/MismatchedSizeException.java | Add MismatchedSizeException Class
1. Exception Type for mismatched size
2. package name : org.opengsi.comsci.exceptions
| src/main/java/org/opengsi/comsci/exceptions/MismatchedSizeException.java | Add MismatchedSizeException Class |
|
Java | agpl-3.0 | 3a5852efbfe8918b12a2fe55b3ec813dfb99570d | 0 | enviroCar/enviroCar-server,gotodeepak1122/enviroCar-server,Drifftr/enviroCar-server,enviroCar/enviroCar-server,autermann/enviroCar-server,enviroCar/enviroCar-server,autermann/enviroCar-server,autermann/enviroCar-server,Drifftr/enviroCar-server,gotodeepak1122/enviroCar-server | /**
* Copyright (C) 2013 Christian Autermann, Jan Alexander Wirwahn,
* Arne De Wall, Dustin Demuth, Saqib Rasheed
*
* 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 io.car.server.core;
import io.car.server.core.exception.ValidationException;
/**
* @author Christian Autermann <[email protected]>
*/
public interface Validator<T> {
void validateCreate(T t) throws ValidationException;
void validateUpdate(T t) throws ValidationException;
}
| core/src/main/java/io/car/server/core/Validator.java | /**
* Copyright (C) 2013 Christian Autermann, Jan Alexander Wirwahn,
* Arne De Wall, Dustin Demuth, Saqib Rasheed
*
* 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 io.car.server.core;
import io.car.server.core.exception.ValidationException;
/**
* @author Christian Autermann <[email protected]>
*/
public interface Validator<T> {
void validate(T t) throws ValidationException;
}
| different validation method for create and update
| core/src/main/java/io/car/server/core/Validator.java | different validation method for create and update |
|
Java | agpl-3.0 | error: pathspec 'src/main/java/org/kuali/kra/bo/KraUserRoles.java' did not match any file(s) known to git
| 77213dff41a121aa723606397839010bf1447e1c | 1 | geothomasp/kcmit,ColostateResearchServices/kc,jwillia/kc-old1,kuali/kc,kuali/kc,iu-uits-es/kc,UniversityOfHawaiiORS/kc,jwillia/kc-old1,UniversityOfHawaiiORS/kc,geothomasp/kcmit,geothomasp/kcmit,jwillia/kc-old1,ColostateResearchServices/kc,mukadder/kc,kuali/kc,jwillia/kc-old1,geothomasp/kcmit,iu-uits-es/kc,mukadder/kc,ColostateResearchServices/kc,geothomasp/kcmit,iu-uits-es/kc,mukadder/kc,UniversityOfHawaiiORS/kc | package org.kuali.kra.bo;
import java.util.LinkedHashMap;
public class KraUserRoles extends KraPersistableBusinessObjectBase {
private Integer roleId;
private String unitNumber;
private String userId;
private Boolean descendFlag;
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getUnitNumber() {
return unitNumber;
}
public void setUnitNumber(String unitNumber) {
this.unitNumber = unitNumber;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Boolean getDescendFlag() {
return descendFlag;
}
public void setDescendFlag(Boolean descendFlag) {
this.descendFlag = descendFlag;
}
@Override
protected LinkedHashMap toStringMapper() {
LinkedHashMap hashMap = new LinkedHashMap();
hashMap.put("roleId", getRoleId());
hashMap.put("unitNumber", getUnitNumber());
hashMap.put("userId", getUserId());
hashMap.put("descendFlag", getDescendFlag());
return hashMap;
}
}
| src/main/java/org/kuali/kra/bo/KraUserRoles.java | bo for user roles table - kra_user_roles
| src/main/java/org/kuali/kra/bo/KraUserRoles.java | bo for user roles table - kra_user_roles |
|
Java | agpl-3.0 | error: pathspec 'opennms-webapp/src/main/java/org/opennms/web/svclayer/ProgressMonitor.java' did not match any file(s) known to git
| 8da957c36eb5c45355ff546a3cf2ce7c07fe9d8c | 1 | roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,aihua/opennms,aihua/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,rdkgit/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github | package org.opennms.web.svclayer;
public class ProgressMonitor {
private int m_phaseCount = 1;
private int m_phase = 0;
private String m_phaseLabel = "Loading";
private Object m_result = null;
private Exception m_exception = null;
public int getPhaseCount() {
return m_phaseCount;
}
public void setPhaseCount(int phaseCount) {
m_phaseCount = phaseCount;
}
public String getPhaseLabel() {
return m_phaseLabel;
}
public int getPhase() {
return m_phase;
}
public void beginNextPhase(String phaseLabel) {
m_phaseLabel = phaseLabel;
m_phase++;
}
public void finished(Object result) {
m_result = result;
m_phaseLabel = "Done";
m_phase = m_phaseCount;
}
public boolean isFinished() {
return m_result != null;
}
public Object getResult() {
return m_result;
}
public boolean isError() {
return m_exception != null;
}
public Exception getException() {
return m_exception;
}
public void errorOccurred(Exception e) {
m_exception = e;
}
}
| opennms-webapp/src/main/java/org/opennms/web/svclayer/ProgressMonitor.java | Add progress bar to loading of Surveillence page
| opennms-webapp/src/main/java/org/opennms/web/svclayer/ProgressMonitor.java | Add progress bar to loading of Surveillence page |
|
Java | agpl-3.0 | error: pathspec 'inherit-service/inherit-service-activiti-engine/src/test/java/org/inheritsource/test/service/processengine/ActivitiServiceEngineTest.java' did not match any file(s) known to git
| fd7ba24b2da1abc52d65fe4368226880d9ddf60a | 1 | malmostad/eservices-platform,malmostad/eservices-platform,malmostad/eservices-platform,malmostad/eservices-platform | /*
* Process Aware Web Application Platform
*
* Copyright (C) 2011-2013 Inherit S AB
*
* 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/>.
*
* e-mail: info _at_ inherit.se
* mail: Inherit S AB, Långsjövägen 8, SE-131 33 NACKA, SWEDEN
* phone: +46 8 641 64 14
*/
package org.inheritsource.test.service.processengine;
import junit.framework.TestCase;
import org.inheritsource.service.processengine.ActivitiEngineService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ActivitiServiceEngineTest {
ActivitiEngineService activitiEngineService = null;
@Before
public void before() {
activitiEngineService = new ActivitiEngineService();
}
@After
public void after() {
activitiEngineService.close();
}
@Test
public void tags() {
System.out.println("TESTING TESTING...");
}
}
| inherit-service/inherit-service-activiti-engine/src/test/java/org/inheritsource/test/service/processengine/ActivitiServiceEngineTest.java | added junit testing
| inherit-service/inherit-service-activiti-engine/src/test/java/org/inheritsource/test/service/processengine/ActivitiServiceEngineTest.java | added junit testing |
|
Java | lgpl-2.1 | f9bc7352d56abf414be551889fc49fd9a80974c4 | 0 | trejkaz/swingx,trejkaz/swingx,krichter722/swingx,krichter722/swingx,tmyroadctfig/swingx | /*
* $Id$
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.UIManager;
import javax.swing.event.MouseInputAdapter;
import org.jdesktop.swingx.multislider.*;
import org.jdesktop.swingx.multislider.ThumbListener;
import org.jdesktop.swingx.multislider.ThumbRenderer;
import org.jdesktop.swingx.multislider.TrackRenderer;
import org.jdesktop.swingx.plaf.JXMultiThumbSliderAddon;
import org.jdesktop.swingx.plaf.LookAndFeelAddons;
import org.jdesktop.swingx.plaf.MultiThumbSliderUI;
/**
* <p>A slider which can have multiple control points or <i>Thumbs</i></p>
* <p>The thumbs each represent a value between the minimum and maximum values
* of the slider. Thumbs can pass each other when being dragged. Thumbs have
* no default visual representation. To customize the look of the thumbs and the
* track behind the thumbs you must provide a ThumbRenderer and a TrackRenderer
* implementation. To listen for changes to the thumbs you must provide an
* implemention of ThumbDataListener.
*
* TODOs:
* move public inner classes (interfaces, etc) to subpackage
* add min/maxvalue convenience methods to jxmultithumbslider
* add plafs for windows, mac, and basic (if necessary)
* make way to properly control the height.
* hide the inner thumb component
*
* @author joshy
*/
public class JXMultiThumbSlider<E> extends JComponent {
static {
LookAndFeelAddons.contribute(new JXMultiThumbSliderAddon());
}
public static final String uiClassID = "MultiThumbSliderUI";
/** Creates a new instance of JMultiThumbSlider */
public JXMultiThumbSlider() {
thumbs = new ArrayList();
setLayout(null);
tdl = new ThumbHandler();
setModel(new DefaultMultiThumbModel<E>());
MultiThumbMouseListener mia = new MultiThumbMouseListener(this);
addMouseListener(mia);
addMouseMotionListener(mia);
Dimension dim = new Dimension(60,16);
setPreferredSize(dim);
setSize(dim);
setMinimumSize(new Dimension(30,16));
updateUI();
}
public MultiThumbSliderUI getUI() {
return (MultiThumbSliderUI)ui;
}
public void setUI(MultiThumbSliderUI ui) {
super.setUI(ui);
}
public void updateUI() {
setUI((MultiThumbSliderUI)UIManager.getUI(this));
invalidate();
}
/**
* @inheritDoc
*/
@Override
public String getUIClassID() {
return uiClassID;
}
private ThumbDataListener tdl;
private List<ThumbComp> thumbs;
private ThumbRenderer thumbRenderer;
private TrackRenderer trackRenderer;
private MultiThumbModel<E> model;
private List<ThumbListener> listeners = new ArrayList();
private ThumbComp selected;
protected void paintComponent(Graphics g) {
if(isVisible()) {
if(trackRenderer != null) {
JComponent comp = trackRenderer.getRendererComponent(this);
add(comp);
comp.paint(g);
remove(comp);
} else {
paintRange((Graphics2D)g);
}
}
}
private void paintRange(Graphics2D g) {
g.setColor(Color.blue);
g.fillRect(0,0,getWidth(),getHeight());
}
private float getThumbValue(int thumbIndex) {
return getModel().getThumbAt(thumbIndex).getPosition();
}
private float getThumbValue(ThumbComp thumb) {
return getThumbValue(thumbs.indexOf(thumb));
}
private int getThumbIndex(ThumbComp thumb) {
return thumbs.indexOf(thumb);
}
private void clipThumbPosition(ThumbComp thumb) {
if(getThumbValue(thumb) < getModel().getMinimumValue()) {
getModel().getThumbAt(getThumbIndex(thumb)).setPosition(
getModel().getMinimumValue());
}
if(getThumbValue(thumb) > getModel().getMaximumValue()) {
getModel().getThumbAt(getThumbIndex(thumb)).setPosition(
getModel().getMaximumValue());
}
}
public ThumbRenderer getThumbRenderer() {
return thumbRenderer;
}
public void setThumbRenderer(ThumbRenderer thumbRenderer) {
this.thumbRenderer = thumbRenderer;
}
public TrackRenderer getTrackRenderer() {
return trackRenderer;
}
public void setTrackRenderer(TrackRenderer trackRenderer) {
this.trackRenderer = trackRenderer;
}
public float getMinimumValue() {
return getModel().getMinimumValue();
}
public void setMinimumValue(float minimumValue) {
getModel().setMinimumValue(minimumValue);
}
public float getMaximumValue() {
return getModel().getMaximumValue();
}
public void setMaximumValue(float maximumValue) {
getModel().setMaximumValue(maximumValue);
}
private void setThumbPositionByX(ThumbComp selected) {
float range = getModel().getMaximumValue()-getModel().getMinimumValue();
int x = selected.getX();
// adjust to the center of the thumb
x += selected.getWidth()/2;
// adjust for the leading space on the slider
x -= selected.getWidth()/2;
int w = getWidth();
// adjust for the leading and trailing space on the slider
w -= selected.getWidth();
float delta = ((float)x)/((float)w);
int thumb_index = getThumbIndex(selected);
float value = delta*range;
getModel().getThumbAt(thumb_index).setPosition(value);
//getModel().setPositionAt(thumb_index,value);
clipThumbPosition(selected);
}
private void setThumbXByPosition(ThumbComp thumb, float pos) {
float tu = pos;
float lp = getWidth()-thumb.getWidth();
float lu = getModel().getMaximumValue()-getModel().getMinimumValue();
float tp = (tu*lp)/lu;
thumb.setLocation((int)tp-thumb.getWidth()/2 + thumb.getWidth()/2, thumb.getY());
}
private void recalc() {
for(ThumbComp th : thumbs) {
setThumbXByPosition(th,getModel().getThumbAt(getThumbIndex(th)).getPosition());
//getPositionAt(getThumbIndex(th)));
}
}
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x,y,w,h);
recalc();
}
public JComponent getSelectedThumb() {
return selected;
}
public int getSelectedIndex() {
return getThumbIndex(selected);
}
public MultiThumbModel<E> getModel() {
return model;
}
public void setModel(MultiThumbModel<E> model) {
if(this.model != null) {
this.model.removeThumbDataListener(tdl);
}
this.model = model;
this.model.addThumbDataListener(tdl);
}
public void addMultiThumbListener(ThumbListener listener) {
listeners.add(listener);
}
private class MultiThumbMouseListener extends MouseInputAdapter {
private JXMultiThumbSlider slider;
public MultiThumbMouseListener(JXMultiThumbSlider slider) {
this.slider = slider;
}
public void mousePressed(MouseEvent evt) {
ThumbComp handle = findHandle(evt);
if(handle != null) {
selected = handle;
selected.setSelected(true);
int thumb_index = getThumbIndex(selected);
for(ThumbListener tl : listeners) {
tl.thumbSelected(thumb_index);
}
repaint();
} else {
selected = null;
for(ThumbListener tl : listeners) {
tl.thumbSelected(-1);
}
repaint();
}
for(ThumbListener tl : listeners) {
tl.mousePressed(evt);
}
}
public void mouseReleased(MouseEvent evt) {
if(selected != null) {
selected.setSelected(false);
}
}
public void mouseDragged(MouseEvent evt) {
if(selected != null) {
int nx = (int)evt.getPoint().getX()- selected.getWidth()/2;
if(nx < 0) {
nx = 0;
}
if(nx > getWidth()-selected.getWidth()) {
nx = getWidth()-selected.getWidth();
}
selected.setLocation(nx,(int)selected.getLocation().getY());
setThumbPositionByX(selected);
int thumb_index = getThumbIndex(selected);
//System.out.println("still dragging: " + thumb_index);
for(ThumbListener mtl : listeners) {
mtl.thumbMoved(thumb_index,getModel().getThumbAt(thumb_index).getPosition());
//getPositionAt(thumb_index));
}
repaint();
}
}
private ThumbComp findHandle(MouseEvent evt) {
for(ThumbComp hand : thumbs) {
Point p2 = new Point();
p2.setLocation(evt.getPoint().getX() - hand.getX(),
evt.getPoint().getY() - hand.getY());
if(hand.contains(p2)) {
return hand;
}
}
return null;
}
}
private class ThumbComp extends JComponent {
private JXMultiThumbSlider<E> slider;
public ThumbComp(JXMultiThumbSlider slider) {
this.slider = slider;
Dimension dim = new Dimension(10,10);//slider.getHeight());
/*if(slider.getThumbRenderer() != null) {
JComponent comp = getRenderer();
dim = comp.getPreferredSize();
}*/
setSize(dim);
setMinimumSize(dim);
setPreferredSize(dim);
setMaximumSize(dim);
setBackground(Color.white);
}
public void paintComponent(Graphics g) {
if(slider.getThumbRenderer() != null) {
JComponent comp = getRenderer();
comp.setSize(this.getSize());
comp.paint(g);
} else {
g.setColor(getBackground());
g.fillRect(0,0,getWidth(),getHeight());
if(isSelected()) {
g.setColor(Color.black);
g.drawRect(0,0,getWidth()-1,getHeight()-1);
}
}
}
private JComponent getRenderer() {
JComponent comp = slider.getThumbRenderer().
getThumbRendererComponent(slider,slider.getThumbIndex(this),isSelected());
return comp;
}
private boolean selected;
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
private class ThumbHandler implements ThumbDataListener {
public void positionChanged(ThumbDataEvent e) {
System.out.println("position changed");
}
public void thumbAdded(ThumbDataEvent evt) {
ThumbComp thumb = new ThumbComp(JXMultiThumbSlider.this);
thumb.setLocation(0, 0);
add(thumb);
thumbs.add(evt.getIndex(), thumb);
clipThumbPosition(thumb);
setThumbXByPosition(thumb, evt.getThumb().getPosition());
repaint();
}
public void thumbRemoved(ThumbDataEvent evt) {
ThumbComp thumb = thumbs.get(evt.getIndex());
remove(thumb);
thumbs.remove(thumb);
repaint();
}
public void valueChanged(ThumbDataEvent e) {
System.out.println("value changed");
}
}
}
| src/java/org/jdesktop/swingx/JXMultiThumbSlider.java | /*
* $Id$
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.UIManager;
import javax.swing.event.MouseInputAdapter;
import org.jdesktop.swingx.multislider.*;
import org.jdesktop.swingx.multislider.ThumbListener;
import org.jdesktop.swingx.multislider.ThumbRenderer;
import org.jdesktop.swingx.multislider.TrackRenderer;
import org.jdesktop.swingx.plaf.JXMultiThumbSliderAddon;
import org.jdesktop.swingx.plaf.LookAndFeelAddons;
import org.jdesktop.swingx.plaf.MultiThumbSliderUI;
/**
* <p>A slider which can have multiple control points or <i>Thumbs</i></p>
* <p>The thumbs each represent a value between the minimum and maximum values
* of the slider. Thumbs can pass each other when being dragged. Thumbs have
* no default visual representation. To customize the look of the thumbs and the
* track behind the thumbs you must provide a ThumbRenderer and a TrackRenderer
* implementation. To listen for changes to the thumbs you must provide an
* implemention of ThumbDataListener.
*
* TODOs:
* move public inner classes (interfaces, etc) to subpackage
* add min/maxvalue convenience methods to jxmultithumbslider
* add plafs for windows, mac, and basic (if necessary)
* make way to properly control the height.
* hide the inner thumb component
*
* @author joshy
*/
public class JXMultiThumbSlider<E> extends JComponent {
static {
LookAndFeelAddons.contribute(new JXMultiThumbSliderAddon());
}
public static final String uiClassID = "MultiThumbSliderUI";
/** Creates a new instance of JMultiThumbSlider */
public JXMultiThumbSlider() {
thumbs = new ArrayList();
setLayout(null);
tdl = new ThumbHandler();
setModel(new DefaultMultiThumbModel<E>());
MultiThumbMouseListener mia = new MultiThumbMouseListener(this);
addMouseListener(mia);
addMouseMotionListener(mia);
Dimension dim = new Dimension(60,16);
setPreferredSize(dim);
setSize(dim);
setMinimumSize(new Dimension(30,16));
updateUI();
}
public MultiThumbSliderUI getUI() {
return (MultiThumbSliderUI)ui;
}
public void setUI(MultiThumbSliderUI ui) {
super.setUI(ui);
}
public void updateUI() {
setUI((MultiThumbSliderUI)UIManager.getUI(this));
invalidate();
}
/**
* @inheritDoc
*/
@Override
public String getUIClassID() {
return uiClassID;
}
private ThumbDataListener tdl;
private List<ThumbComp> thumbs;
private ThumbRenderer thumbRenderer;
private TrackRenderer trackRenderer;
private MultiThumbModel<E> model;
private List<ThumbListener> listeners = new ArrayList();
private ThumbComp selected;
protected void paintComponent(Graphics g) {
if(isVisible()) {
if(trackRenderer != null) {
JComponent comp = trackRenderer.getRendererComponent(this);
add(comp);
comp.paint(g);
remove(comp);
} else {
paintRange((Graphics2D)g);
}
}
}
private void paintRange(Graphics2D g) {
g.setColor(Color.blue);
g.fillRect(0,0,getWidth(),getHeight());
}
private float getThumbValue(int thumbIndex) {
return getModel().getThumbAt(thumbIndex).getPosition();
}
private float getThumbValue(ThumbComp thumb) {
return getThumbValue(thumbs.indexOf(thumb));
}
private int getThumbIndex(ThumbComp thumb) {
return thumbs.indexOf(thumb);
}
private void clipThumbPosition(ThumbComp thumb) {
if(getThumbValue(thumb) < getModel().getMinimumValue()) {
getModel().getThumbAt(getThumbIndex(thumb)).setPosition(
getModel().getMinimumValue());
}
if(getThumbValue(thumb) > getModel().getMaximumValue()) {
getModel().getThumbAt(getThumbIndex(thumb)).setPosition(
getModel().getMaximumValue());
}
}
public ThumbRenderer getThumbRenderer() {
return thumbRenderer;
}
public void setThumbRenderer(ThumbRenderer thumbRenderer) {
this.thumbRenderer = thumbRenderer;
}
public TrackRenderer getTrackRenderer() {
return trackRenderer;
}
public void setTrackRenderer(TrackRenderer trackRenderer) {
this.trackRenderer = trackRenderer;
}
public float getMinimumValue() {
return getModel().getMinimumValue();
}
public void setMinimumValue(float minimumValue) {
getModel().setMinimumValue(minimumValue);
}
public float getMaximumValue() {
return getModel().getMaximumValue();
}
public void setMaximumValue(float maximumValue) {
getModel().setMaximumValue(maximumValue);
}
private void setThumbPositionByX(ThumbComp selected) {
float range = getModel().getMaximumValue()-getModel().getMinimumValue();
int x = selected.getX();
// adjust to the center of the thumb
x += selected.getWidth()/2;
// adjust for the leading space on the slider
x -= selected.getWidth()/2;
int w = getWidth();
// adjust for the leading and trailing space on the slider
w -= selected.getWidth();
float delta = ((float)x)/((float)w);
int thumb_index = getThumbIndex(selected);
float value = delta*range;
getModel().getThumbAt(thumb_index).setPosition(value);
//getModel().setPositionAt(thumb_index,value);
clipThumbPosition(selected);
}
private void setThumbXByPosition(ThumbComp thumb, float pos) {
float tu = pos;
float lp = getWidth()-thumb.getWidth();
float lu = getModel().getMaximumValue()-getModel().getMinimumValue();
float tp = (tu*lp)/lu;
thumb.setLocation((int)tp-thumb.getWidth()/2 + thumb.getWidth()/2, thumb.getY());
}
private void recalc() {
for(ThumbComp th : thumbs) {
setThumbXByPosition(th,getModel().getThumbAt(getThumbIndex(th)).getPosition());
//getPositionAt(getThumbIndex(th)));
}
}
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x,y,w,h);
recalc();
}
public JComponent getSelectedThumb() {
return selected;
}
public int getSelectedIndex() {
return getThumbIndex(selected);
}
public MultiThumbModel<E> getModel() {
return model;
}
public void setModel(MultiThumbModel<E> model) {
if(this.model != null) {
this.model.removeThumbDataListener(tdl);
}
this.model = model;
this.model.addThumbDataListener(tdl);
}
public void addMultiThumbListener(ThumbListener listener) {
listeners.add(listener);
}
private class MultiThumbMouseListener extends MouseInputAdapter {
private JXMultiThumbSlider slider;
public MultiThumbMouseListener(JXMultiThumbSlider slider) {
this.slider = slider;
}
public void mousePressed(MouseEvent evt) {
ThumbComp handle = findHandle(evt);
if(handle != null) {
selected = handle;
selected.setSelected(true);
int thumb_index = getThumbIndex(selected);
for(ThumbListener tl : listeners) {
tl.thumbSelected(thumb_index);
}
repaint();
} else {
selected = null;
for(ThumbListener tl : listeners) {
tl.thumbSelected(-1);
}
repaint();
}
for(ThumbListener tl : listeners) {
tl.mousePressed(evt);
}
}
public void mouseReleased(MouseEvent evt) {
if(selected != null) {
selected.setSelected(false);
}
}
public void mouseDragged(MouseEvent evt) {
if(selected != null) {
int nx = (int)evt.getPoint().getX()- selected.getWidth()/2;
if(nx < 0) {
nx = 0;
}
if(nx > getWidth()-selected.getWidth()) {
nx = getWidth()-selected.getWidth();
}
selected.setLocation(nx,(int)selected.getLocation().getY());
setThumbPositionByX(selected);
int thumb_index = getThumbIndex(selected);
//System.out.println("still dragging: " + thumb_index);
for(ThumbListener mtl : listeners) {
mtl.thumbMoved(thumb_index,getModel().getThumbAt(thumb_index).getPosition());
//getPositionAt(thumb_index));
}
repaint();
}
}
private ThumbComp findHandle(MouseEvent evt) {
for(ThumbComp hand : thumbs) {
Point p2 = new Point();
p2.setLocation(evt.getPoint().getX() - hand.getX(),
evt.getPoint().getY() - hand.getY());
if(hand.contains(p2)) {
return hand;
}
}
return null;
}
}
private class ThumbComp extends JComponent {
private JXMultiThumbSlider<E> slider;
public ThumbComp(JXMultiThumbSlider slider) {
this.slider = slider;
Dimension dim = new Dimension(10,10);//slider.getHeight());
if(slider.getThumbRenderer() != null) {
JComponent comp = getRenderer();
dim = comp.getPreferredSize();
}
setSize(dim);
setMinimumSize(dim);
setPreferredSize(dim);
setMaximumSize(dim);
setBackground(Color.white);
}
public void paintComponent(Graphics g) {
if(slider.getThumbRenderer() != null) {
JComponent comp = getRenderer();
comp.setSize(this.getSize());
comp.paint(g);
} else {
g.setColor(getBackground());
g.fillRect(0,0,getWidth(),getHeight());
if(isSelected()) {
g.setColor(Color.black);
g.drawRect(0,0,getWidth()-1,getHeight()-1);
}
}
}
private JComponent getRenderer() {
JComponent comp = slider.getThumbRenderer().
getThumbRendererComponent(slider,slider.getThumbIndex(this),isSelected());
return comp;
}
private boolean selected;
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
private class ThumbHandler implements ThumbDataListener {
public void positionChanged(ThumbDataEvent e) {
System.out.println("position changed");
}
public void thumbAdded(ThumbDataEvent evt) {
ThumbComp thumb = new ThumbComp(JXMultiThumbSlider.this);
thumb.setLocation(0, 0);
add(thumb);
thumbs.add(evt.getIndex(), thumb);
clipThumbPosition(thumb);
setThumbXByPosition(thumb, evt.getThumb().getPosition());
repaint();
}
public void thumbRemoved(ThumbDataEvent evt) {
ThumbComp thumb = thumbs.get(evt.getIndex());
remove(thumb);
thumbs.remove(thumb);
repaint();
}
public void valueChanged(ThumbDataEvent e) {
System.out.println("value changed");
}
}
}
| fixed an NPE
git-svn-id: 9c6ef37dfd7eaa5a3748af7ba0f8d9e7b67c2a4c@1261 1312f61e-266d-0410-97fa-c3b71232c9ac
| src/java/org/jdesktop/swingx/JXMultiThumbSlider.java | fixed an NPE |
|
Java | lgpl-2.1 | error: pathspec 'skyve-ee/src/skyve/modules/admin/Snapshot/SnapshotFactory.java' did not match any file(s) known to git
| 32adb65beae1a9824aa2abf7095dca4dd39397f6 | 1 | skyvers/skyve,skyvers/skyve,skyvers/skyve,skyvers/wildcat,skyvers/skyve,skyvers/wildcat,skyvers/skyve,skyvers/wildcat,skyvers/skyve,skyvers/wildcat,skyvers/skyve,skyvers/wildcat | package modules.admin.Snapshot;
import org.skyve.util.DataBuilder;
import org.skyve.util.test.SkyveFixture;
import org.skyve.util.test.SkyveFixture.FixtureType;
import modules.admin.domain.Snapshot;
public class SnapshotFactory {
@SkyveFixture(types = FixtureType.crud)
public Snapshot crudInstance() {
Snapshot bean = new DataBuilder()
.fixture(FixtureType.crud)
.domain(false)
.factoryBuild(Snapshot.MODULE_NAME, Snapshot.DOCUMENT_NAME);
bean.setQueryName("snapshot" + System.nanoTime());
return bean;
}
}
| skyve-ee/src/skyve/modules/admin/Snapshot/SnapshotFactory.java | Added SnapshotFactory to fix errors with dynamic domain values in automated unit tests
| skyve-ee/src/skyve/modules/admin/Snapshot/SnapshotFactory.java | Added SnapshotFactory to fix errors with dynamic domain values in automated unit tests |
|
Java | lgpl-2.1 | error: pathspec 'sipXconfig/web/src/org/sipfoundry/sipxconfig/site/permission/PermissionConverter.java' did not match any file(s) known to git
| dcbd8dd2edeeccf3f4f5c14c858590462451158f | 1 | sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror | /*
*
*
* Copyright (C) 2006 SIPfoundry Inc.
* Licensed by SIPfoundry under the LGPL license.
*
* Copyright (C) 2006 Pingtel Corp.
* Licensed to SIPfoundry under a Contributor Agreement.
*
* $
*/
package org.sipfoundry.sipxconfig.site.permission;
import org.apache.tapestry.components.IPrimaryKeyConverter;
import org.sipfoundry.sipxconfig.permission.Permission;
import org.sipfoundry.sipxconfig.permission.PermissionManager;
public class PermissionConverter implements IPrimaryKeyConverter {
private PermissionManager m_manager;
public void setManager(PermissionManager manager) {
m_manager = manager;
}
public Object getPrimaryKey(Object value) {
Permission permisison = (Permission) value;
return permisison.getName();
}
public Object getValue(Object primaryKey) {
return m_manager.getPermission((String) primaryKey);
}
}
| sipXconfig/web/src/org/sipfoundry/sipxconfig/site/permission/PermissionConverter.java | XCF-1121 missing file: permission UI CRUD
git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@7256 a612230a-c5fa-0310-af8b-88eea846685b
| sipXconfig/web/src/org/sipfoundry/sipxconfig/site/permission/PermissionConverter.java | XCF-1121 missing file: permission UI CRUD |
|
Java | unlicense | error: pathspec 'JAVA/UniquePalindromes.java' did not match any file(s) known to git
| 3aa0467f43848ab4c2b17b6b7d0f29927dea1b5c | 1 | lemming-life/Snippets,lemming-life/Snippets,lemming-life/Snippets,lemming-life/Snippets,lemming-life/Snippets,lemming-life/Snippets,lemming-life/Snippets,lemming-life/Snippets,lemming-life/Snippets |
// Author: http://lemming.life
// Language: Java
// Description: Given a string, identifies and counts the unique number of palindromes in the string's substrings.
// Build
// javac UniquePalindromes.java
// Run:
// java UniquePalindromes
// Example input: aabaa
// All strings:
// a, aa, ab, aab, aaba, aabaa
// a, ab, aba, abaa
// b, ba, baa
// a, aa
// a
// Unique palindromes: a, aa, aabaa, aba, b
// Count: 5
import java.util.Scanner;
class UniquePalindromes {
static int UniquePalindromesInStringCount(String s) {
int count = 0;
final int MAX_SIZE = 10000;
String[] uniqueStrings = new String[MAX_SIZE];
String[] allSubstrings = new String[MAX_SIZE];
int length = 1;
// Get all possible substrings
int subStringCount = 0;
for (int pos = 0; pos < s.length(); ++pos) {
for (int l = 0; l <= s.length() - pos; ++l) {
if (pos != pos+l) {
allSubstrings[subStringCount++] = s.substring(pos, pos+l);
}
}
}
// Determine if each substring is a palindrome, add if unique
for (int c = 0; c < subStringCount; ++c) {
// isPalidrome check
boolean isPalindrome = true;
String s1 = allSubstrings[c];
for (int i=0; i < s1.length() / 2; ++i) {
if (s1.charAt(i) != s1.charAt(s1.length()-(1+i))) {
isPalindrome = false;
break;
}
}
// Add if unique
if (isPalindrome) {
boolean found = false;
for (int j=0; j < count; ++j) {
if (s1.equals(uniqueStrings[j])) {
found = true;
break;
}
}
if (found == false) {
uniqueStrings[count++] = s1;
// System.out.println(s1); // Comment out to see the unique palindrome.
}
}
}
return count;
}
public static void main(String[] args) {
System.out.println("Unique palindrome count in substrings of string.");
System.out.print("Please, type the string: ");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("Count: " + UniquePalindromesInStringCount(s));
}
} | JAVA/UniquePalindromes.java | Added Java UniquePalindromes.java
| JAVA/UniquePalindromes.java | Added Java UniquePalindromes.java |
|
Java | unlicense | error: pathspec 'src/com/diguage/books/thinking/io/DirList2.java' did not match any file(s) known to git
| cb1e192401715df0bc8e71ef50cd28b18aeddf1d | 1 | diguage/ThinkingInJava | package com.diguage.books.thinking.io;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.regex.Pattern;
/**
* 使用内部类来完成文件名称的过滤
* <p/>
* Coder:D瓜哥,http://www.diguage.com/
* <p/>
* Date: 2014-07-09 15:25
*/
public class DirList2 {
public static FilenameFilter filter(final String regex) {
return new FilenameFilter() {
private Pattern pattern = Pattern.compile(regex);
@Override
public boolean accept(File dir, String name) {
return pattern.matcher(name).matches();
}
};
}
public static void main(String[] args) {
File path = new File(".");
String[] list = null;
if (args.length == 0) {
list = path.list();
} else {
list = path.list(filter(args[0]));
}
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for (String dirItem : list) {
System.out.println(dirItem);
}
}
}
| src/com/diguage/books/thinking/io/DirList2.java | io.DirLIst2
| src/com/diguage/books/thinking/io/DirList2.java | io.DirLIst2 |
|
Java | apache-2.0 | 3cf8db82f5807bc773f6b1b2ed92420202735e4c | 0 | mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,xfournet/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,allotria/intellij-community,asedunov/intellij-community,asedunov/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,da1z/intellij-community,asedunov/intellij-community,allotria/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,semonte/intellij-community,da1z/intellij-community,da1z/intellij-community,youdonghai/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,semonte/intellij-community,youdonghai/intellij-community,semonte/intellij-community,xfournet/intellij-community,ibinti/intellij-community,signed/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ibinti/intellij-community,allotria/intellij-community,signed/intellij-community,da1z/intellij-community,vvv1559/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,da1z/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,signed/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,apixandru/intellij-community,xfournet/intellij-community,signed/intellij-community,da1z/intellij-community,FHannes/intellij-community,semonte/intellij-community,semonte/intellij-community,ibinti/intellij-community,signed/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ibinti/intellij-community,signed/intellij-community,signed/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,allotria/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,apixandru/intellij-community,allotria/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,asedunov/intellij-community,FHannes/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,da1z/intellij-community,asedunov/intellij-community,allotria/intellij-community,asedunov/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,signed/intellij-community,semonte/intellij-community,da1z/intellij-community,xfournet/intellij-community,apixandru/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,signed/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,da1z/intellij-community,FHannes/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,allotria/intellij-community,asedunov/intellij-community,semonte/intellij-community,FHannes/intellij-community,youdonghai/intellij-community | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.customize;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.internal.statistic.ideSettings.IdeInitialConfigButtonUsages;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBCardLayout;
import com.intellij.ui.JBColor;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.labels.LinkLabel;
import com.intellij.ui.components.labels.LinkListener;
import com.intellij.util.ui.JBUI;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class CustomizePluginsStepPanel extends AbstractCustomizeWizardStep implements LinkListener<String> {
private static final String MAIN = "main";
private static final String CUSTOMIZE = "customize";
private static final int COLS = 3;
private static final TextProvider CUSTOMIZE_TEXT_PROVIDER = new TextProvider() {
@Override
public String getText() {
return "Customize...";
}
};
private static final String SWITCH_COMMAND = "Switch";
private static final String CUSTOMIZE_COMMAND = "Customize";
private final JBCardLayout myCardLayout;
private final IdSetPanel myCustomizePanel;
private final PluginGroups myPluginGroups;
public CustomizePluginsStepPanel(PluginGroups pluginGroups) {
myPluginGroups = pluginGroups;
myCardLayout = new JBCardLayout();
setLayout(myCardLayout);
JPanel gridPanel = new JPanel(new GridLayout(0, COLS));
myCustomizePanel = new IdSetPanel();
JBScrollPane scrollPane = createScrollPane(gridPanel);
add(scrollPane, MAIN);
add(myCustomizePanel, CUSTOMIZE);
Map<String, Pair<Icon, List<String>>> groups = pluginGroups.getTree();
for (final Map.Entry<String, Pair<Icon, List<String>>> entry : groups.entrySet()) {
final String group = entry.getKey();
if (PluginGroups.CORE.equals(group) || myPluginGroups.getSets(group).isEmpty()) continue;
JPanel groupPanel = new JPanel(new GridBagLayout()) {
@Override
public Color getBackground() {
Color color = UIManager.getColor("Panel.background");
return isGroupEnabled(group)? color : ColorUtil.darker(color, 1);
}
};
gridPanel.setOpaque(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
JLabel titleLabel = new JLabel("<html><body><h2 style=\"text-align:center;\">" + group + "</h2></body></html>", SwingConstants.CENTER) {
@Override
public boolean isEnabled() {
return isGroupEnabled(group);
}
};
groupPanel.add(new JLabel(entry.getValue().getFirst()), gbc);
//gbc.insets.bottom = 5;
groupPanel.add(titleLabel, gbc);
JLabel descriptionLabel = new JLabel(pluginGroups.getDescription(group), SwingConstants.CENTER) {
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.min(size.width, 200);
return size;
}
@Override
public boolean isEnabled() {
return isGroupEnabled(group);
}
@Override
public Color getForeground() {
return ColorUtil.withAlpha(UIManager.getColor("Label.foreground"), .75);
}
};
groupPanel.add(descriptionLabel, gbc);
gbc.weighty = 1;
groupPanel.add(Box.createVerticalGlue(), gbc);
gbc.weighty = 0;
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, SMALL_GAP, SMALL_GAP / 2));
buttonsPanel.setOpaque(false);
if (pluginGroups.getSets(group).size() == 1) {
buttonsPanel.add(createLink(SWITCH_COMMAND + ":" + group, getGroupSwitchTextProvider(group)));
}
else {
buttonsPanel.add(createLink(CUSTOMIZE_COMMAND + ":" + group, CUSTOMIZE_TEXT_PROVIDER));
buttonsPanel.add(createLink(SWITCH_COMMAND + ":" + group, getGroupSwitchTextProvider(group)));
}
groupPanel.add(buttonsPanel, gbc);
gridPanel.add(groupPanel);
}
int cursor = 0;
Component[] components = gridPanel.getComponents();
int rowCount = components.length / COLS;
if (components.length % COLS == 0) rowCount--;
for (Component component : components) {
((JComponent)component).setBorder(
new CompoundBorder(new CustomLineBorder(ColorUtil.withAlpha(JBColor.foreground(), .2), 0, 0, cursor / 3 <= rowCount - 1 ? 1 : 0,
cursor % COLS != COLS - 1 ? 1 : 0) {
@Override
protected Color getColor() {
return ColorUtil.withAlpha(JBColor.foreground(), .2);
}
}, BorderFactory.createEmptyBorder(SMALL_GAP, GAP, SMALL_GAP, GAP)));
cursor++;
}
}
static JBScrollPane createScrollPane(JPanel gridPanel) {
JBScrollPane scrollPane =
new JBScrollPane(gridPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(JBUI.Borders.empty()); // to disallow resetting border on LaF change
return scrollPane;
}
@Override
public void linkSelected(LinkLabel linkLabel, String command) {
if (command == null || !command.contains(":")) return;
int semicolonPosition = command.indexOf(":");
String group = command.substring(semicolonPosition + 1);
command = command.substring(0, semicolonPosition);
if (SWITCH_COMMAND.equals(command)) {
boolean enabled = isGroupEnabled(group);
List<IdSet> sets = myPluginGroups.getSets(group);
for (IdSet idSet : sets) {
String[] ids = idSet.getIds();
for (String id : ids) {
myPluginGroups.setPluginEnabledWithDependencies(id, !enabled);
}
}
repaint();
return;
}
if (CUSTOMIZE_COMMAND.equals(command)) {
myCustomizePanel.update(group);
myCardLayout.show(this, CUSTOMIZE);
setButtonsVisible(false);
}
}
private void setButtonsVisible(boolean visible) {
DialogWrapper window = DialogWrapper.findInstance(this);
if (window instanceof CustomizeIDEWizardDialog) {
((CustomizeIDEWizardDialog)window).setButtonsVisible(visible);
}
}
private LinkLabel createLink(String command, final TextProvider provider) {
return new LinkLabel<String>("", null, this, command) {
@Override
public String getText() {
return provider.getText();
}
};
}
TextProvider getGroupSwitchTextProvider(final String group) {
return new TextProvider() {
@Override
public String getText() {
return (isGroupEnabled(group) ? "Disable" : "Enable") +
(myPluginGroups.getSets(group).size() > 1 ? " All" : "");
}
};
}
private boolean isGroupEnabled(String group) {
List<IdSet> sets = myPluginGroups.getSets(group);
for (IdSet idSet : sets) {
String[] ids = idSet.getIds();
for (String id : ids) {
if (myPluginGroups.isPluginEnabled(id)) return true;
}
}
return false;
}
@Override
public String getTitle() {
return "Default plugins";
}
@Override
public String getHTMLHeader() {
return "<html><body><h2>Tune " +
ApplicationNamesInfo.getInstance().getProductName() +
" to your tasks</h2>" +
ApplicationNamesInfo.getInstance().getProductName() +
" has a lot of tools enabled by default. You can set only ones you need or leave them all." +
"</body></html>";
}
@Override
public boolean beforeOkAction() {
try {
PluginManager.saveDisabledPlugins(myPluginGroups.getDisabledPluginIds(), false);
IdeInitialConfigButtonUsages.setPredefinedDisabledPlugins(new HashSet<>(myPluginGroups.getDisabledPluginIds()));
}
catch (IOException ignored) {
}
return true;
}
private class IdSetPanel extends JPanel implements LinkListener<String> {
private JLabel myTitleLabel = new JLabel();
private JPanel myContentPanel = new JPanel(new GridLayout(0, 3, 5, 5));
private JButton mySaveButton = new JButton("Save Changes and Go Back");
private String myGroup;
private IdSetPanel() {
setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, GAP, true, false));
add(myTitleLabel);
add(myContentPanel);
JPanel buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.right = 25;
gbc.gridy = 0;
buttonPanel.add(mySaveButton, gbc);
buttonPanel.add(new LinkLabel<>("Enable All", null, this, "enable"), gbc);
buttonPanel.add(new LinkLabel<>("Disable All", null, this, "disable"), gbc);
gbc.weightx = 1;
buttonPanel.add(Box.createHorizontalGlue(), gbc);
add(buttonPanel);
mySaveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myCardLayout.show(CustomizePluginsStepPanel.this, MAIN);
setButtonsVisible(true);
}
});
}
@Override
public void linkSelected(LinkLabel aSource, String command) {
if (myGroup == null) return;
boolean enable = "enable".equals(command);
List<IdSet> idSets = myPluginGroups.getSets(myGroup);
for (IdSet set : idSets) {
myPluginGroups.setIdSetEnabled(set, enable);
}
CustomizePluginsStepPanel.this.repaint();
}
void update(String group) {
myGroup = group;
myTitleLabel.setText("<html><body><h2 style=\"text-align:left;\">" + group + "</h2></body></html>");
myContentPanel.removeAll();
List<IdSet> idSets = myPluginGroups.getSets(group);
for (final IdSet set : idSets) {
final JCheckBox checkBox = new JCheckBox(set.getTitle(), myPluginGroups.isIdSetAllEnabled(set));
checkBox.setModel(new JToggleButton.ToggleButtonModel() {
@Override
public boolean isSelected() {
return myPluginGroups.isIdSetAllEnabled(set);
}
});
checkBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myPluginGroups.setIdSetEnabled(set, !checkBox.isSelected());
CustomizePluginsStepPanel.this.repaint();
}
});
myContentPanel.add(checkBox);
}
}
}
private interface TextProvider {
String getText();
}
}
| platform/platform-impl/src/com/intellij/ide/customize/CustomizePluginsStepPanel.java | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.customize;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.internal.statistic.ideSettings.IdeInitialConfigButtonUsages;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBCardLayout;
import com.intellij.ui.JBColor;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.labels.LinkLabel;
import com.intellij.ui.components.labels.LinkListener;
import com.intellij.util.ui.JBUI;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class CustomizePluginsStepPanel extends AbstractCustomizeWizardStep implements LinkListener<String> {
private static final String MAIN = "main";
private static final String CUSTOMIZE = "customize";
private static final int COLS = 3;
private static final TextProvider CUSTOMIZE_TEXT_PROVIDER = new TextProvider() {
@Override
public String getText() {
return "Customize...";
}
};
private static final String SWITCH_COMMAND = "Switch";
private static final String CUSTOMIZE_COMMAND = "Customize";
private final JBCardLayout myCardLayout;
private final IdSetPanel myCustomizePanel;
private final PluginGroups myPluginGroups;
public CustomizePluginsStepPanel(PluginGroups pluginGroups) {
myPluginGroups = pluginGroups;
myCardLayout = new JBCardLayout();
setLayout(myCardLayout);
JPanel gridPanel = new JPanel(new GridLayout(0, COLS));
myCustomizePanel = new IdSetPanel();
JBScrollPane scrollPane = createScrollPane(gridPanel);
add(scrollPane, MAIN);
add(myCustomizePanel, CUSTOMIZE);
Map<String, Pair<Icon, List<String>>> groups = pluginGroups.getTree();
for (final Map.Entry<String, Pair<Icon, List<String>>> entry : groups.entrySet()) {
final String group = entry.getKey();
if (PluginGroups.CORE.equals(group) || myPluginGroups.getSets(group).isEmpty()) continue;
JPanel groupPanel = new JPanel(new GridBagLayout()) {
@Override
public Color getBackground() {
Color color = UIManager.getColor("Panel.background");
return isGroupEnabled(group)? color : ColorUtil.darker(color, 1);
}
};
gridPanel.setOpaque(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
JLabel titleLabel = new JLabel("<html><body><h2 style=\"text-align:center;\">" + group + "</h2></body></html>", SwingConstants.CENTER) {
@Override
public boolean isEnabled() {
return isGroupEnabled(group);
}
};
groupPanel.add(new JLabel(entry.getValue().getFirst()), gbc);
//gbc.insets.bottom = 5;
groupPanel.add(titleLabel, gbc);
JLabel descriptionLabel = new JLabel(pluginGroups.getDescription(group), SwingConstants.CENTER) {
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.min(size.width, 200);
return size;
}
@Override
public boolean isEnabled() {
return isGroupEnabled(group);
}
@Override
public Color getForeground() {
return ColorUtil.withAlpha(UIManager.getColor("Label.foreground"), .75);
}
};
groupPanel.add(descriptionLabel, gbc);
gbc.weighty = 1;
groupPanel.add(Box.createVerticalGlue(), gbc);
gbc.weighty = 0;
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, SMALL_GAP, SMALL_GAP / 2));
buttonsPanel.setOpaque(false);
if (pluginGroups.getSets(group).size() == 1) {
buttonsPanel.add(createLink(SWITCH_COMMAND + ":" + group, getGroupSwitchTextProvider(group)));
}
else {
buttonsPanel.add(createLink(CUSTOMIZE_COMMAND + ":" + group, CUSTOMIZE_TEXT_PROVIDER));
buttonsPanel.add(createLink(SWITCH_COMMAND + ":" + group, getGroupSwitchTextProvider(group)));
}
groupPanel.add(buttonsPanel, gbc);
gridPanel.add(groupPanel);
}
int cursor = 0;
Component[] components = gridPanel.getComponents();
int rowCount = components.length / COLS;
if (components.length % COLS == 0) rowCount--;
for (Component component : components) {
((JComponent)component).setBorder(
new CompoundBorder(new CustomLineBorder(ColorUtil.withAlpha(JBColor.foreground(), .2), 0, 0, cursor / 3 <= rowCount - 1 ? 1 : 0,
cursor % COLS != COLS - 1 ? 1 : 0) {
@Override
protected Color getColor() {
return ColorUtil.withAlpha(JBColor.foreground(), .2);
}
}, BorderFactory.createEmptyBorder(SMALL_GAP, GAP, SMALL_GAP, GAP)));
cursor++;
}
}
static JBScrollPane createScrollPane(JPanel gridPanel) {
JBScrollPane scrollPane =
new JBScrollPane(gridPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(JBUI.Borders.empty()); // to disallow resetting border on LaF change
return scrollPane;
}
@Override
public void linkSelected(LinkLabel linkLabel, String command) {
if (command == null || !command.contains(":")) return;
int semicolonPosition = command.indexOf(":");
String group = command.substring(semicolonPosition + 1);
command = command.substring(0, semicolonPosition);
if (SWITCH_COMMAND.equals(command)) {
boolean enabled = isGroupEnabled(group);
List<IdSet> sets = myPluginGroups.getSets(group);
for (IdSet idSet : sets) {
String[] ids = idSet.getIds();
for (String id : ids) {
myPluginGroups.setPluginEnabledWithDependencies(id, !enabled);
}
}
repaint();
return;
}
if (CUSTOMIZE_COMMAND.equals(command)) {
myCustomizePanel.update(group);
myCardLayout.show(this, CUSTOMIZE);
setButtonsVisible(false);
}
}
private void setButtonsVisible(boolean visible) {
DialogWrapper window = DialogWrapper.findInstance(this);
if (window instanceof CustomizeIDEWizardDialog) {
((CustomizeIDEWizardDialog)window).setButtonsVisible(visible);
}
}
private LinkLabel createLink(String command, final TextProvider provider) {
return new LinkLabel<String>("", null, this, command) {
@Override
public String getText() {
return provider.getText();
}
};
}
TextProvider getGroupSwitchTextProvider(final String group) {
return new TextProvider() {
@Override
public String getText() {
return (isGroupEnabled(group) ? "Disable" : "Enable") +
(myPluginGroups.getSets(group).size() > 1 ? " All" : "");
}
};
}
private boolean isGroupEnabled(String group) {
List<IdSet> sets = myPluginGroups.getSets(group);
for (IdSet idSet : sets) {
String[] ids = idSet.getIds();
for (String id : ids) {
if (myPluginGroups.isPluginEnabled(id)) return true;
}
}
return false;
}
@Override
public String getTitle() {
return "Default plugins";
}
@Override
public String getHTMLHeader() {
return "<html><body><h2>Tune " +
ApplicationNamesInfo.getInstance().getProductName() +
" to your tasks</h2>" +
ApplicationNamesInfo.getInstance().getProductName() +
" has a lot of tools enabled by default. You can set only ones you need or leave them all." +
"</body></html>";
}
@Override
public boolean beforeOkAction() {
try {
PluginManager.saveDisabledPlugins(myPluginGroups.getDisabledPluginIds(), false);
IdeInitialConfigButtonUsages.setPredefinedDisabledPlugins(new com.intellij.util.containers.HashSet<>(myPluginGroups.getDisabledPluginIds())/*
myPluginGroups.getTree().values().stream().flatMap(pair -> pair.getSecond().stream()).collect(Collectors.toSet())*/);
}
catch (IOException ignored) {
}
return true;
}
private class IdSetPanel extends JPanel implements LinkListener<String> {
private JLabel myTitleLabel = new JLabel();
private JPanel myContentPanel = new JPanel(new GridLayout(0, 3, 5, 5));
private JButton mySaveButton = new JButton("Save Changes and Go Back");
private String myGroup;
private IdSetPanel() {
setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, GAP, true, false));
add(myTitleLabel);
add(myContentPanel);
JPanel buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.right = 25;
gbc.gridy = 0;
buttonPanel.add(mySaveButton, gbc);
buttonPanel.add(new LinkLabel<>("Enable All", null, this, "enable"), gbc);
buttonPanel.add(new LinkLabel<>("Disable All", null, this, "disable"), gbc);
gbc.weightx = 1;
buttonPanel.add(Box.createHorizontalGlue(), gbc);
add(buttonPanel);
mySaveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myCardLayout.show(CustomizePluginsStepPanel.this, MAIN);
setButtonsVisible(true);
}
});
}
@Override
public void linkSelected(LinkLabel aSource, String command) {
if (myGroup == null) return;
boolean enable = "enable".equals(command);
List<IdSet> idSets = myPluginGroups.getSets(myGroup);
for (IdSet set : idSets) {
myPluginGroups.setIdSetEnabled(set, enable);
}
CustomizePluginsStepPanel.this.repaint();
}
void update(String group) {
myGroup = group;
myTitleLabel.setText("<html><body><h2 style=\"text-align:left;\">" + group + "</h2></body></html>");
myContentPanel.removeAll();
List<IdSet> idSets = myPluginGroups.getSets(group);
for (final IdSet set : idSets) {
final JCheckBox checkBox = new JCheckBox(set.getTitle(), myPluginGroups.isIdSetAllEnabled(set));
checkBox.setModel(new JToggleButton.ToggleButtonModel() {
@Override
public boolean isSelected() {
return myPluginGroups.isIdSetAllEnabled(set);
}
});
checkBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myPluginGroups.setIdSetEnabled(set, !checkBox.isSelected());
CustomizePluginsStepPanel.this.repaint();
}
});
myContentPanel.add(checkBox);
}
}
}
private interface TextProvider {
String getText();
}
}
| cleanup
| platform/platform-impl/src/com/intellij/ide/customize/CustomizePluginsStepPanel.java | cleanup |
|
Java | apache-2.0 | 895de81029c76ec602d4c16dce467d77b0f78f41 | 0 | mwringe/hawkular-metrics,spadgett/hawkular-metrics,jshaughn/hawkular-metrics,spadgett/hawkular-metrics,jotak/hawkular-metrics,burmanm/hawkular-metrics,mwringe/hawkular-metrics,pilhuhn/rhq-metrics,ppalaga/hawkular-metrics,jotak/hawkular-metrics,pilhuhn/rhq-metrics,ppalaga/hawkular-metrics,140293816/Hawkular-fork,spadgett/hawkular-metrics,ppalaga/hawkular-metrics,jshaughn/hawkular-metrics,pilhuhn/rhq-metrics,tsegismont/hawkular-metrics,jotak/hawkular-metrics,tsegismont/hawkular-metrics,mwringe/hawkular-metrics,hawkular/hawkular-metrics,burmanm/hawkular-metrics,spadgett/hawkular-metrics,140293816/Hawkular-fork,140293816/Hawkular-fork,jotak/hawkular-metrics,hawkular/hawkular-metrics,ppalaga/hawkular-metrics,pilhuhn/rhq-metrics,burmanm/hawkular-metrics,tsegismont/hawkular-metrics,jshaughn/hawkular-metrics,tsegismont/hawkular-metrics,jshaughn/hawkular-metrics,spadgett/hawkular-metrics,hawkular/hawkular-metrics,mwringe/hawkular-metrics,140293816/Hawkular-fork,hawkular/hawkular-metrics,burmanm/hawkular-metrics | /*
* Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.metrics.api.jaxrs;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.hawkular.metrics.core.api.MetricsService.DEFAULT_TENANT_ID;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import com.google.common.base.Function;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.hawkular.metrics.api.jaxrs.callback.MetricCreatedCallback;
import org.hawkular.metrics.api.jaxrs.callback.NoDataCallback;
import org.hawkular.metrics.api.jaxrs.callback.SimpleDataCallback;
import org.hawkular.metrics.api.jaxrs.param.Duration;
import org.hawkular.metrics.core.api.Availability;
import org.hawkular.metrics.core.api.AvailabilityMetric;
import org.hawkular.metrics.core.api.BucketDataPoint;
import org.hawkular.metrics.core.api.BucketedOutput;
import org.hawkular.metrics.core.api.Buckets;
import org.hawkular.metrics.core.api.Counter;
import org.hawkular.metrics.core.api.Metric;
import org.hawkular.metrics.core.api.MetricId;
import org.hawkular.metrics.core.api.MetricType;
import org.hawkular.metrics.core.api.MetricsService;
import org.hawkular.metrics.core.api.NumericData;
import org.hawkular.metrics.core.api.NumericMetric;
import org.hawkular.metrics.core.impl.cassandra.MetricUtils;
import org.hawkular.metrics.core.impl.request.TagRequest;
/**
* Interface to deal with metrics
* @author Heiko W. Rupp
*/
@Path("/")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Api(value = "/", description = "Metrics related REST interface")
public class MetricHandler {
private static final long EIGHT_HOURS = MILLISECONDS.convert(8, HOURS);
@Inject
private MetricsService metricsService;
@POST
@Path("/{tenantId}/metrics/numeric")
@ApiOperation(value = "Create numeric metric definition.", notes = "Clients are not required to explicitly create "
+ "a metric before storing data. Doing so however allows clients to prevent naming collisions and to "
+ "specify tags and data retention.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Metric definition created successfully"),
@ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class),
@ApiResponse(code = 409, message = "Numeric metric with given id already exists",
response = ApiError.class),
@ApiResponse(code = 500, message = "Metric definition creation failed due to an unexpected error",
response = ApiError.class)
})
public void createNumericMetric(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(required = true) NumericMetric metric,
@Context UriInfo uriInfo
) {
if (metric == null) {
Response response = Response.status(Status.BAD_REQUEST).entity(new ApiError("Payload is empty")).build();
asyncResponse.resume(response);
return;
}
metric.setTenantId(tenantId);
ListenableFuture<Void> future = metricsService.createMetric(metric);
URI created = uriInfo.getBaseUriBuilder()
.path("/{tenantId}/metrics/numeric/{id}")
.build(tenantId, metric.getId().getName());
MetricCreatedCallback metricCreatedCallback = new MetricCreatedCallback(asyncResponse, created);
Futures.addCallback(future, metricCreatedCallback);
}
@POST
@Path("/{tenantId}/metrics/availability")
@ApiOperation(value = "Create availability metric definition. Same notes as creating numeric metric apply.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Metric definition created successfully"),
@ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class),
@ApiResponse(code = 409, message = "Numeric metric with given id already exists",
response = ApiError.class),
@ApiResponse(code = 500, message = "Metric definition creation failed due to an unexpected error",
response = ApiError.class)
})
public void createAvailabilityMetric(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(required = true) AvailabilityMetric metric,
@Context UriInfo uriInfo) {
if (metric == null) {
Response response = Response.status(Status.BAD_REQUEST).entity(new ApiError("Payload is empty")).build();
asyncResponse.resume(response);
return;
}
metric.setTenantId(tenantId);
ListenableFuture<Void> future = metricsService.createMetric(metric);
URI created = uriInfo.getBaseUriBuilder()
.path("/{tenantId}/metrics/availability/{id}")
.build(tenantId, metric.getId().getName());
MetricCreatedCallback metricCreatedCallback = new MetricCreatedCallback(asyncResponse, created);
Futures.addCallback(future, metricCreatedCallback);
}
@GET
@Path("/{tenantId}/metrics/numeric/{id}/tags")
@ApiOperation(value = "Retrieve tags associated with the metric definition.", response = Metric.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully retrieved."),
@ApiResponse(code = 204, message = "Query was successful, but no metrics were found."),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric's tags.",
response = ApiError.class)
})
public void getNumericMetricTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id) {
ListenableFuture<Metric<?>> future = metricsService.findMetric(tenantId, MetricType.NUMERIC,
new MetricId(id));
Futures.addCallback(future, new SimpleDataCallback<Metric<?>>(asyncResponse));
}
@PUT
@Path("/{tenantId}/metrics/numeric/{id}/tags")
@ApiOperation(value = "Update tags associated with the metric definition.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully updated."),
@ApiResponse(code = 500, message = "Unexpected error occurred while updating metric's tags.",
response = ApiError.class)
})
public void updateNumericMetricTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id,
@ApiParam(required = true) Map<String, String> tags) {
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
ListenableFuture<Void> future = metricsService.addTags(metric, tags);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@DELETE
@Path("/{tenantId}/metrics/numeric/{id}/tags/{tags}")
@ApiOperation(value = "Delete tags associated with the metric definition.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully deleted."),
@ApiResponse(code = 500, message = "Unexpected error occurred while trying to delete metric's tags.",
response = ApiError.class)
})
public void deleteNumericMetricTags(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@PathParam("id") String id,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@PathParam("tags") String encodedTags) {
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
ListenableFuture<Void> future = metricsService.deleteTags(metric, MetricUtils.decodeTags(encodedTags));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@GET
@Path("/{tenantId}/metrics/availability/{id}/tags")
@ApiOperation(value = "Retrieve tags associated with the metric definition.", response = Map.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully retrieved."),
@ApiResponse(code = 204, message = "Query was successful, but no metrics were found."),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric's tags.",
response = ApiError.class)
})
public void getAvailabilityMetricTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id) {
ListenableFuture<Metric<?>> future = metricsService.findMetric(tenantId, MetricType.AVAILABILITY,
new MetricId(id));
Futures.addCallback(future, new SimpleDataCallback<Metric<?>>(asyncResponse));
}
@PUT
@Path("/{tenantId}/metrics/availability/{id}/tags")
@ApiOperation(value = "Update tags associated with the metric definition.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully updated."),
@ApiResponse(code = 500, message = "Unexpected error occurred while updating metric's tags.",
response = ApiError.class)
})
public void updateAvailabilityMetricTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id,
@ApiParam(required = true) Map<String, String> tags) {
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
ListenableFuture<Void> future = metricsService.addTags(metric, tags);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@DELETE
@Path("/{tenantId}/metrics/availability/{id}/tags/{tags}")
@ApiOperation(value = "Delete tags associated with the metric definition.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully deleted."),
@ApiResponse(code = 500, message = "Unexpected error occurred while trying to delete metric's tags.",
response = ApiError.class)
})
public void deleteAvailabilityMetricTags(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@PathParam("tags") String encodedTags) {
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
ListenableFuture<Void> future = metricsService.deleteTags(metric, MetricUtils.decodeTags(encodedTags));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/numeric/{id}/data")
@ApiOperation(value = "Add data for a single numeric metric.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 400, message = "Missing or invalid payload",
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class),
})
public void addDataForMetric(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") final String tenantId, @PathParam("id") String id,
@ApiParam(value = "List of datapoints containing timestamp and value", required = true)
List<NumericData> data
) {
if (data == null) {
Response response = Response.status(Status.BAD_REQUEST).entity(new ApiError("Payload is empty")).build();
asyncResponse.resume(response);
return;
}
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
data.forEach(metric::addData);
ListenableFuture<Void> future = metricsService.addNumericData(Collections.singletonList(metric));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/availability/{id}/data")
@ApiOperation(value = "Add data for a single availability metric.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 400, message = "Missing or invalid payload",
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class)
})
public void addAvailabilityForMetric(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") final String tenantId, @PathParam("id") String id,
@ApiParam(value = "List of availability datapoints", required = true) List<Availability> data
) {
if (data == null) {
Response response = Response.status(Status.BAD_REQUEST).entity(new ApiError("Payload is empty")).build();
asyncResponse.resume(response);
return;
}
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
data.forEach(metric::addData);
ListenableFuture<Void> future = metricsService.addAvailabilityData(Collections.singletonList(metric));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/numeric/data")
@ApiOperation(value = "Add metric data for multiple numeric metrics in a single call.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class)
})
public void addNumericData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(value = "List of metrics", required = true)
List<NumericMetric> metrics) {
if (metrics.isEmpty()) {
asyncResponse.resume(Response.ok().build());
}
for (NumericMetric metric : metrics) {
metric.setTenantId(tenantId);
}
ListenableFuture<Void> future = metricsService.addNumericData(metrics);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/availability/data")
@ApiOperation(value = "Add metric data for multiple availability metrics in a single call.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class)
})
public void addAvailabilityData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @ApiParam(value = "List of availability metrics", required = true)
List<AvailabilityMetric> metrics) {
if (metrics.isEmpty()) {
asyncResponse.resume(Response.ok().build());
}
for (AvailabilityMetric metric : metrics) {
metric.setTenantId(tenantId);
}
ListenableFuture<Void> future = metricsService.addAvailabilityData(metrics);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@GET
@Path("/{tenantId}/numeric")
@ApiOperation(value = "Find numeric metrics data by their tags.", response = Map.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = ""),
@ApiResponse(code = 500, message = "Any error in the query.", response = ApiError.class)
})
public void findNumericDataByTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@QueryParam("tags") String encodedTags) {
ListenableFuture<Map<MetricId, Set<NumericData>>> queryFuture = metricsService.findNumericDataByTags(
tenantId, MetricUtils.decodeTags(encodedTags));
Futures.addCallback(queryFuture, new SimpleDataCallback<Map<MetricId, Set<NumericData>>>(asyncResponse));
}
@GET
@Path("/{tenantId}/availability")
@ApiOperation(value = "Find availabilities metrics data by their tags.", response = Map.class,
responseContainer = "List")
// See above method and HWKMETRICS-26 for fixes.
@ApiResponses(value = { @ApiResponse(code = 200, message = ""),
@ApiResponse(code = 204, message = "No matching availability metrics were found."),
@ApiResponse(code = 500, message = "Any error in the query.", response = ApiError.class)
})
public void findAvailabilityDataByTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@QueryParam("tags") String encodedTags) {
ListenableFuture<Map<MetricId, Set<Availability>>> queryFuture = metricsService.findAvailabilityByTags(
tenantId, MetricUtils.decodeTags(encodedTags));
Futures.addCallback(queryFuture, new SimpleDataCallback<Map<MetricId, Set<Availability>>>(asyncResponse));
}
@GET
@Path("/{tenantId}/metrics/numeric/{id}/data")
@ApiOperation(value = "Retrieve numeric data. When buckets or bucketDuration query parameter is used, the time "
+ "range between start and end will be divided in buckets of equal duration, and metric "
+ "statistics will be computed for each bucket.", response = List.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully fetched numeric data."),
@ApiResponse(code = 204, message = "No numeric data was found."),
@ApiResponse(code = 400, message = "buckets or bucketDuration parameter is invalid, or both are used.",
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching numeric data.",
response = ApiError.class)
})
public void findNumericData(
@Suspended AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") Long start,
@ApiParam(value = "Defaults to now") @QueryParam("end") Long end,
@ApiParam(value = "Total number of buckets") @QueryParam("buckets") Integer bucketsCount,
@ApiParam(value = "Bucket duration") @QueryParam("bucketDuration") Duration bucketDuration
) {
long now = System.currentTimeMillis();
start = start == null ? now - EIGHT_HOURS : start;
end = end == null ? now : end;
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
if (bucketsCount == null && bucketDuration == null) {
ListenableFuture<NumericMetric> dataFuture = metricsService.findNumericData(metric, start, end);
ListenableFuture<List<NumericData>> outputFuture = Futures.transform(
dataFuture, new Function<NumericMetric, List<NumericData>>() {
@Override
public List<NumericData> apply(NumericMetric input) {
if (input == null) {
return null;
}
return input.getData();
}
}
);
Futures.addCallback(outputFuture, new SimpleDataCallback<Object>(asyncResponse));
return;
}
if (bucketsCount != null && bucketDuration != null) {
ApiError apiError = new ApiError("Both buckets and bucketDuration parameters are used");
Response response = Response.status(Status.BAD_REQUEST).entity(apiError).build();
asyncResponse.resume(response);
return;
}
Buckets buckets;
try {
if (bucketsCount != null) {
buckets = Buckets.fromCount(start, end, bucketsCount);
} else {
buckets = Buckets.fromStep(start, end, bucketDuration.toMillis());
}
} catch (IllegalArgumentException e) {
ApiError apiError = new ApiError("Bucket: " + e.getMessage());
Response response = Response.status(Status.BAD_REQUEST).entity(apiError).build();
asyncResponse.resume(response);
return;
}
ListenableFuture<BucketedOutput> dataFuture = metricsService.findNumericStats(metric, start, end, buckets);
ListenableFuture<List<BucketDataPoint>> outputFuture = Futures.transform(
dataFuture, new Function<BucketedOutput, List<BucketDataPoint>>() {
@Override
public List<BucketDataPoint> apply(BucketedOutput input) {
if (input == null) {
return null;
}
return input.getData();
}
}
);
Futures.addCallback(outputFuture, new SimpleDataCallback<Object>(asyncResponse));
}
@GET
@Path("/{tenantId}/metrics/numeric/{id}/periods")
@ApiOperation(value = "Retrieve periods for which the condition holds true for each consecutive data point.",
response = List.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully fetched periods."),
@ApiResponse(code = 204, message = "No numeric data was found."),
@ApiResponse(code = 400, message = "Missing or invalid query parameters")})
public void findPeriods(
@Suspended final AsyncResponse response, @PathParam("tenantId") String tenantId,
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours", required = false) @QueryParam("start") Long start,
@ApiParam(value = "Defaults to now", required = false) @QueryParam("end") Long end,
@ApiParam(value = "A threshold against which values are compared", required = true) @QueryParam("threshold")
double threshold,
@ApiParam(value = "A comparison operation to perform between values and the threshold. Supported operations " +
"include ge, gte, lt, lte, and eq", required = true) @QueryParam("op") String operator) {
long now = System.currentTimeMillis();
if (start == null) {
start = now - EIGHT_HOURS;
}
if (end == null) {
end = now;
}
Predicate<Double> predicate;
switch (operator) {
case "lt":
predicate = d -> d < threshold;
break;
case "lte":
predicate = d -> d <= threshold;
break;
case "eq":
predicate = d -> d == threshold;
break;
case "neq":
predicate = d -> d != threshold;
break;
case "gt":
predicate = d -> d > threshold;
break;
case "gte":
predicate = d -> d >= threshold;
break;
default:
predicate = null;
}
if (predicate == null) {
response.resume(Response.status(Status.BAD_REQUEST).entity(new ApiError("Invalid value for op parameter. "
+ "Supported values are lt, lte, eq, gt, gte")).build());
} else {
ListenableFuture<List<long[]>> future = metricsService.getPeriods(tenantId, new MetricId(id), predicate,
start, end);
// We need to transform empty results to null because SimpleDataCallback returns a 204 status for null
// data.
future = Futures.transform(future, (List<long[]> periods) -> periods.isEmpty() ? null : periods);
Futures.addCallback(future, new SimpleDataCallback<>(response));
}
}
@GET
@Path("/{tenantId}/metrics/availability/{id}/data")
@ApiOperation(
value = "Retrieve availability data. When buckets or bucketDuration query parameter is used, the time "
+ "range between start and end will be divided in buckets of equal duration, and availability "
+ "statistics will be computed for each bucket.", response = List.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully fetched availability data."),
@ApiResponse(code = 204, message = "No availability data was found."),
@ApiResponse(code = 400, message = "buckets or bucketDuration parameter is invalid, or both are used.",
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching availability data.",
response = ApiError.class),
})
public void findAvailabilityData(
@Suspended AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") Long start,
@ApiParam(value = "Defaults to now") @QueryParam("end") Long end,
@ApiParam(value = "Total number of buckets") @QueryParam("buckets") Integer bucketsCount,
@ApiParam(value = "Bucket duration") @QueryParam("bucketDuration") Duration bucketDuration
) {
long now = System.currentTimeMillis();
start = start == null ? now - EIGHT_HOURS : start;
end = end == null ? now : end;
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
ListenableFuture<AvailabilityMetric> future = metricsService.findAvailabilityData(metric, start, end);
ListenableFuture<List<Availability>> outputfuture = Futures.transform(future,
new Function<AvailabilityMetric, List<Availability>>() {
@Override
public List<Availability> apply(AvailabilityMetric input) {
if (input == null) {
return null;
}
return input.getData();
}
});
Futures.addCallback(outputfuture, new SimpleDataCallback<List<Availability>>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/numeric/{id}/tag")
@ApiOperation(value = "Add or update numeric metric's tags.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Tags were modified successfully.")})
public void tagNumericData(@Suspended final AsyncResponse asyncResponse, @PathParam("tenantId") String tenantId,
@PathParam("id") final String id, @ApiParam(required = true) TagRequest params) {
ListenableFuture<List<NumericData>> future;
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
if (params.getTimestamp() != null) {
future = metricsService.tagNumericData(metric, params.getTags(), params.getTimestamp());
} else {
future = metricsService.tagNumericData(metric, params.getTags(), params.getStart(), params.getEnd());
}
Futures.addCallback(future, new NoDataCallback<List<NumericData>>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/availability/{id}/tag")
@ApiOperation(value = "Add or update availability metric's tags.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Tags were modified successfully.")})
public void tagAvailabilityData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") final String id,
@ApiParam(required = true) TagRequest params) {
ListenableFuture<List<Availability>> future;
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
if (params.getTimestamp() != null) {
future = metricsService.tagAvailabilityData(metric, params.getTags(), params.getTimestamp());
} else {
future = metricsService.tagAvailabilityData(metric, params.getTags(), params.getStart(), params.getEnd());
}
Futures.addCallback(future, new NoDataCallback<List<Availability>>(asyncResponse));
}
@GET
@Path("/{tenantId}/tags/numeric/{tag}")
@ApiOperation(value = "Find numeric metric data with given tags.", response = Map.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Numeric values fetched successfully"),
@ApiResponse(code = 500, message = "Any error while fetching data.",
response = ApiError.class)
})
public void findTaggedNumericData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@PathParam("tag") String encodedTag) {
ListenableFuture<Map<MetricId, Set<NumericData>>> queryFuture = metricsService.findNumericDataByTags(
tenantId, MetricUtils.decodeTags(encodedTag));
ListenableFuture<Map<String, Set<NumericData>>> resultFuture = Futures.transform(
queryFuture,
new Function<Map<MetricId, Set<NumericData>>, Map<String, Set<NumericData>>>() {
@Override
public Map<String, Set<NumericData>> apply(Map<MetricId, Set<NumericData>> input) {
Map<String, Set<NumericData>> result = new HashMap<String, Set<NumericData>>(input.size());
for (Map.Entry<MetricId, Set<NumericData>> entry : input.entrySet()) {
result.put(entry.getKey().getName(), entry.getValue());
}
return result;
}
}
);
Futures.addCallback(resultFuture, new SimpleDataCallback<Map<String, Set<NumericData>>>(asyncResponse));
}
@GET
@Path("/{tenantId}/tags/availability/{tag}")
@ApiOperation(value = "Find availability metric data with given tags.", response = Map.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Availability values fetched successfully"),
@ApiResponse(code = 500, message = "Any error while fetching data.",
response = ApiError.class)
})
public void findTaggedAvailabilityData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@PathParam("tag") String encodedTag) {
ListenableFuture<Map<MetricId, Set<Availability>>> queryFuture = metricsService.findAvailabilityByTags(tenantId,
MetricUtils.decodeTags(encodedTag));
Futures.addCallback(queryFuture, new SimpleDataCallback<Map<MetricId, Set<Availability>>>(asyncResponse));
}
@POST
@Path("/counters")
@ApiOperation(value = "List of counter definitions", hidden = true)
public void updateCountersForGroups(@Suspended final AsyncResponse asyncResponse, Collection<Counter> counters) {
ListenableFuture<Void> future = metricsService.updateCounters(counters);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/counters/{group}")
@ApiOperation(value = "Update multiple counters in a single counter group", hidden = true)
public void updateCounterForGroup(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group,
Collection<Counter> counters) {
for (Counter counter : counters) {
counter.setGroup(group);
}
ListenableFuture<Void> future = metricsService.updateCounters(counters);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/counters/{group}/{counter}")
@ApiOperation(value = "Increase value of a counter", hidden = true)
public void updateCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group,
@PathParam("counter") String counter) {
ListenableFuture<Void> future = metricsService
.updateCounter(new Counter(DEFAULT_TENANT_ID, group, counter, 1L));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/counters/{group}/{counter}/{value}")
@ApiOperation(value = "Update value of a counter", hidden = true)
public void updateCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group,
@PathParam("counter") String counter, @PathParam("value") Long value) {
ListenableFuture<Void> future = metricsService.updateCounter(new Counter(DEFAULT_TENANT_ID, group, counter,
value));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@GET
@Path("/counters/{group}")
@ApiOperation(value = "Retrieve a list of counter values in this group", hidden = true, response = Counter.class,
responseContainer = "List")
@Produces({ APPLICATION_JSON })
public void getCountersForGroup(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group) {
ListenableFuture<List<Counter>> future = metricsService.findCounters(group);
Futures.addCallback(future, new SimpleDataCallback<List<Counter>>(asyncResponse));
}
@GET
@Path("/counters/{group}/{counter}")
@ApiOperation(value = "Retrieve value of a counter", hidden = true, response = Counter.class,
responseContainer = "List")
public void getCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("group") final String group,
@PathParam("counter") final String counter) {
ListenableFuture<List<Counter>> future = metricsService.findCounters(group, Collections.singletonList(counter));
Futures.addCallback(future, new FutureCallback<List<Counter>>() {
@Override
public void onSuccess(List<Counter> counters) {
if (counters.isEmpty()) {
asyncResponse.resume(Response.status(404).entity("Counter[group: " + group + ", name: " +
counter + "] not found").build());
} else {
Response jaxrs = Response.ok(counters.get(0)).build();
asyncResponse.resume(jaxrs);
}
}
@Override
public void onFailure(Throwable t) {
asyncResponse.resume(t);
}
});
}
@GET
@Path("/{tenantId}/metrics")
@ApiOperation(value = "Find tenant's metric definitions.", notes = "Does not include any metric values. ",
response = List.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved at least one metric "
+ "definition."),
@ApiResponse(code = 204, message = "No metrics found."),
@ApiResponse(code = 400, message = "Given type is not a valid type.", response = ApiError.class),
@ApiResponse(code = 500, message = "Failed to retrieve metrics due to unexpected error.",
response = ApiError.class)
})
public void findMetrics(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") final String tenantId,
@ApiParam(value = "Queried metric type", required = true, allowableValues = "[num, avail, log]")
@QueryParam("type") String type) {
MetricType metricType = null;
try {
metricType = MetricType.fromTextCode(type);
} catch (IllegalArgumentException e) {
ApiError errors = new ApiError("[" + type + "] is not a valid type. Accepted values are num|avail|log");
asyncResponse.resume(Response.status(Status.BAD_REQUEST).entity(errors).build());
}
ListenableFuture<List<Metric<?>>> future = metricsService.findMetrics(tenantId, metricType);
Futures.addCallback(future, new SimpleDataCallback<List<Metric<?>>>(asyncResponse));
}
}
| api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/MetricHandler.java | /*
* Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.metrics.api.jaxrs;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.hawkular.metrics.core.api.MetricsService.DEFAULT_TENANT_ID;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import com.google.common.base.Function;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.hawkular.metrics.api.jaxrs.callback.MetricCreatedCallback;
import org.hawkular.metrics.api.jaxrs.callback.NoDataCallback;
import org.hawkular.metrics.api.jaxrs.callback.SimpleDataCallback;
import org.hawkular.metrics.api.jaxrs.param.Duration;
import org.hawkular.metrics.core.api.Availability;
import org.hawkular.metrics.core.api.AvailabilityMetric;
import org.hawkular.metrics.core.api.BucketDataPoint;
import org.hawkular.metrics.core.api.BucketedOutput;
import org.hawkular.metrics.core.api.Buckets;
import org.hawkular.metrics.core.api.Counter;
import org.hawkular.metrics.core.api.Metric;
import org.hawkular.metrics.core.api.MetricId;
import org.hawkular.metrics.core.api.MetricType;
import org.hawkular.metrics.core.api.MetricsService;
import org.hawkular.metrics.core.api.NumericData;
import org.hawkular.metrics.core.api.NumericMetric;
import org.hawkular.metrics.core.impl.cassandra.MetricUtils;
import org.hawkular.metrics.core.impl.request.TagRequest;
/**
* Interface to deal with metrics
* @author Heiko W. Rupp
*/
@Path("/")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Api(value = "/", description = "Metrics related REST interface")
public class MetricHandler {
private static final long EIGHT_HOURS = MILLISECONDS.convert(8, HOURS);
@Inject
private MetricsService metricsService;
@POST
@Path("/{tenantId}/metrics/numeric")
@ApiOperation(value = "Create numeric metric definition.", notes = "Clients are not required to explicitly create "
+ "a metric before storing data. Doing so however allows clients to prevent naming collisions and to "
+ "specify tags and data retention.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Metric definition created successfully"),
@ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class),
@ApiResponse(code = 409, message = "Numeric metric with given id already exists",
response = ApiError.class),
@ApiResponse(code = 500, message = "Metric definition creation failed due to an unexpected error",
response = ApiError.class)
})
public void createNumericMetric(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(required = true) NumericMetric metric,
@Context UriInfo uriInfo
) {
if (metric == null) {
Response response = Response.status(Status.BAD_REQUEST).entity(new ApiError("Payload is empty")).build();
asyncResponse.resume(response);
return;
}
metric.setTenantId(tenantId);
ListenableFuture<Void> future = metricsService.createMetric(metric);
URI created = uriInfo.getBaseUriBuilder()
.path("/{tenantId}/metrics/numeric/{id}")
.build(tenantId, metric.getId().getName());
MetricCreatedCallback metricCreatedCallback = new MetricCreatedCallback(asyncResponse, created);
Futures.addCallback(future, metricCreatedCallback);
}
@POST
@Path("/{tenantId}/metrics/availability")
@ApiOperation(value = "Create availability metric definition. Same notes as creating numeric metric apply.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Metric definition created successfully"),
@ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class),
@ApiResponse(code = 409, message = "Numeric metric with given id already exists",
response = ApiError.class),
@ApiResponse(code = 500, message = "Metric definition creation failed due to an unexpected error",
response = ApiError.class)
})
public void createAvailabilityMetric(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(required = true) AvailabilityMetric metric,
@Context UriInfo uriInfo) {
if (metric == null) {
Response response = Response.status(Status.BAD_REQUEST).entity(new ApiError("Payload is empty")).build();
asyncResponse.resume(response);
return;
}
metric.setTenantId(tenantId);
ListenableFuture<Void> future = metricsService.createMetric(metric);
URI created = uriInfo.getBaseUriBuilder()
.path("/{tenantId}/metrics/availability/{id}")
.build(tenantId, metric.getId().getName());
MetricCreatedCallback metricCreatedCallback = new MetricCreatedCallback(asyncResponse, created);
Futures.addCallback(future, metricCreatedCallback);
}
@GET
@Path("/{tenantId}/metrics/numeric/{id}/tags")
@ApiOperation(value = "Retrieve tags associated with the metric definition.", response = Metric.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully retrieved."),
@ApiResponse(code = 204, message = "Query was successful, but no metrics were found."),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric's tags.",
response = ApiError.class)
})
public void getNumericMetricTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id) {
ListenableFuture<Metric<?>> future = metricsService.findMetric(tenantId, MetricType.NUMERIC,
new MetricId(id));
Futures.addCallback(future, new SimpleDataCallback<Metric<?>>(asyncResponse));
}
@PUT
@Path("/{tenantId}/metrics/numeric/{id}/tags")
@ApiOperation(value = "Update tags associated with the metric definition.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully updated."),
@ApiResponse(code = 500, message = "Unexpected error occurred while updating metric's tags.",
response = ApiError.class)
})
public void updateNumericMetricTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id,
@ApiParam(required = true) Map<String, String> tags) {
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
ListenableFuture<Void> future = metricsService.addTags(metric, tags);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@DELETE
@Path("/{tenantId}/metrics/numeric/{id}/tags/{tags}")
@ApiOperation(value = "Delete tags associated with the metric definition.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully deleted."),
@ApiResponse(code = 500, message = "Unexpected error occurred while trying to delete metric's tags.",
response = ApiError.class)
})
public void deleteNumericMetricTags(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@PathParam("id") String id,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@PathParam("tags") String encodedTags) {
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
ListenableFuture<Void> future = metricsService.deleteTags(metric, MetricUtils.decodeTags(encodedTags));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@GET
@Path("/{tenantId}/metrics/availability/{id}/tags")
@ApiOperation(value = "Retrieve tags associated with the metric definition.", response = Map.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully retrieved."),
@ApiResponse(code = 204, message = "Query was successful, but no metrics were found."),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric's tags.",
response = ApiError.class)
})
public void getAvailabilityMetricTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id) {
ListenableFuture<Metric<?>> future = metricsService.findMetric(tenantId, MetricType.AVAILABILITY,
new MetricId(id));
Futures.addCallback(future, new SimpleDataCallback<Metric<?>>(asyncResponse));
}
@PUT
@Path("/{tenantId}/metrics/availability/{id}/tags")
@ApiOperation(value = "Update tags associated with the metric definition.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully updated."),
@ApiResponse(code = 500, message = "Unexpected error occurred while updating metric's tags.",
response = ApiError.class)
})
public void updateAvailabilityMetricTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id,
@ApiParam(required = true) Map<String, String> tags) {
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
ListenableFuture<Void> future = metricsService.addTags(metric, tags);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@DELETE
@Path("/{tenantId}/metrics/availability/{id}/tags/{tags}")
@ApiOperation(value = "Delete tags associated with the metric definition.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's tags were successfully deleted."),
@ApiResponse(code = 500, message = "Unexpected error occurred while trying to delete metric's tags.",
response = ApiError.class)
})
public void deleteAvailabilityMetricTags(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") String id,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@PathParam("tags") String encodedTags) {
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
ListenableFuture<Void> future = metricsService.deleteTags(metric, MetricUtils.decodeTags(encodedTags));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/numeric/{id}/data")
@ApiOperation(value = "Add data for a single numeric metric.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 400, message = "Missing or invalid payload",
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class),
})
public void addDataForMetric(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") final String tenantId, @PathParam("id") String id,
@ApiParam(value = "List of datapoints containing timestamp and value", required = true)
List<NumericData> data
) {
if (data == null) {
Response response = Response.status(Status.BAD_REQUEST).entity(new ApiError("Payload is empty")).build();
asyncResponse.resume(response);
return;
}
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
data.forEach(metric::addData);
ListenableFuture<Void> future = metricsService.addNumericData(Collections.singletonList(metric));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/availability/{id}/data")
@ApiOperation(value = "Add data for a single availability metric.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 400, message = "Missing or invalid payload",
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class)
})
public void addAvailabilityForMetric(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") final String tenantId, @PathParam("id") String id,
@ApiParam(value = "List of availability datapoints", required = true) List<Availability> data
) {
if (data == null) {
Response response = Response.status(Status.BAD_REQUEST).entity(new ApiError("Payload is empty")).build();
asyncResponse.resume(response);
return;
}
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
data.forEach(metric::addData);
ListenableFuture<Void> future = metricsService.addAvailabilityData(Collections.singletonList(metric));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/numeric/data")
@ApiOperation(value = "Add metric data for multiple numeric metrics in a single call.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class)
})
public void addNumericData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(value = "List of metrics", required = true)
List<NumericMetric> metrics) {
if (metrics.isEmpty()) {
asyncResponse.resume(Response.ok().build());
}
for (NumericMetric metric : metrics) {
metric.setTenantId(tenantId);
}
ListenableFuture<Void> future = metricsService.addNumericData(metrics);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/availability/data")
@ApiOperation(value = "Add metric data for multiple availability metrics in a single call.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class)
})
public void addAvailabilityData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @ApiParam(value = "List of availability metrics", required = true)
List<AvailabilityMetric> metrics) {
if (metrics.isEmpty()) {
asyncResponse.resume(Response.ok().build());
}
for (AvailabilityMetric metric : metrics) {
metric.setTenantId(tenantId);
}
ListenableFuture<Void> future = metricsService.addAvailabilityData(metrics);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@GET
@Path("/{tenantId}/numeric")
@ApiOperation(value = "Find numeric metrics data by their tags.", response = Map.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = ""),
@ApiResponse(code = 500, message = "Any error in the query.", response = ApiError.class)
})
public void findNumericDataByTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@QueryParam("tags") String encodedTags) {
ListenableFuture<Map<MetricId, Set<NumericData>>> queryFuture = metricsService.findNumericDataByTags(
tenantId, MetricUtils.decodeTags(encodedTags));
Futures.addCallback(queryFuture, new SimpleDataCallback<Map<MetricId, Set<NumericData>>>(asyncResponse));
}
@GET
@Path("/{tenantId}/availability")
@ApiOperation(value = "Find availabilities metrics data by their tags.", response = Map.class,
responseContainer = "List")
// See above method and HWKMETRICS-26 for fixes.
@ApiResponses(value = { @ApiResponse(code = 200, message = ""),
@ApiResponse(code = 204, message = "No matching availability metrics were found."),
@ApiResponse(code = 500, message = "Any error in the query.", response = ApiError.class)
})
public void findAvailabilityDataByTags(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@QueryParam("tags") String encodedTags) {
ListenableFuture<Map<MetricId, Set<Availability>>> queryFuture = metricsService.findAvailabilityByTags(
tenantId, MetricUtils.decodeTags(encodedTags));
Futures.addCallback(queryFuture, new SimpleDataCallback<Map<MetricId, Set<Availability>>>(asyncResponse));
}
@GET
@Path("/{tenantId}/metrics/numeric/{id}/data")
@ApiOperation(value = "Retrieve numeric data. When buckets or bucketDuration query parameter is used, the time "
+ "range between start and end will be divided in buckets of equal duration, and metric "
+ "statistics will be computed for each bucket.", response = List.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully fetched numeric data."),
@ApiResponse(code = 204, message = "No numeric data was found."),
@ApiResponse(code = 400, message = "buckets or bucketDuration parameter is invalid, or both are used.",
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching numeric data.",
response = ApiError.class)
})
public void findNumericData(
@Suspended AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") Long start,
@ApiParam(value = "Defaults to now") @QueryParam("end") Long end,
@ApiParam(value = "Total number of buckets") @QueryParam("buckets") Integer bucketsCount,
@ApiParam(value = "Bucket duration") @QueryParam("bucketDuration") Duration bucketDuration
) {
long now = System.currentTimeMillis();
start = start == null ? now - EIGHT_HOURS : start;
end = end == null ? now : end;
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
if (bucketsCount == null && bucketDuration == null) {
ListenableFuture<NumericMetric> dataFuture = metricsService.findNumericData(metric, start, end);
ListenableFuture<List<NumericData>> outputFuture = Futures.transform(
dataFuture, new Function<NumericMetric, List<NumericData>>() {
@Override
public List<NumericData> apply(NumericMetric input) {
if (input == null) {
return null;
}
return input.getData();
}
}
);
Futures.addCallback(outputFuture, new SimpleDataCallback<Object>(asyncResponse));
return;
}
if (bucketsCount != null && bucketDuration != null) {
ApiError apiError = new ApiError("Both buckets and bucketDuration parameters are used");
Response response = Response.status(Status.BAD_REQUEST).entity(apiError).build();
asyncResponse.resume(response);
return;
}
Buckets buckets;
try {
if (bucketsCount != null) {
buckets = Buckets.fromCount(start, end, bucketsCount);
} else {
buckets = Buckets.fromStep(start, end, bucketDuration.toMillis());
}
} catch (IllegalArgumentException e) {
ApiError apiError = new ApiError("Bucket: " + e.getMessage());
Response response = Response.status(Status.BAD_REQUEST).entity(apiError).build();
asyncResponse.resume(response);
return;
}
ListenableFuture<BucketedOutput> dataFuture = metricsService.findNumericStats(metric, start, end, buckets);
ListenableFuture<List<BucketDataPoint>> outputFuture = Futures.transform(
dataFuture, new Function<BucketedOutput, List<BucketDataPoint>>() {
@Override
public List<BucketDataPoint> apply(BucketedOutput input) {
if (input == null) {
return null;
}
return input.getData();
}
}
);
Futures.addCallback(outputFuture, new SimpleDataCallback<Object>(asyncResponse));
}
@GET
@Path("/{tenantId}/metrics/numeric/{id}/periods")
@ApiOperation(value = "Retrieve periods for which the condition holds true for each consecutive data point.",
response = List.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully fetched periods."),
@ApiResponse(code = 204, message = "No numeric data was found."),
@ApiResponse(code = 400, message = "Missing or invalid query parameters")})
public void findPeriods(
@Suspended final AsyncResponse response, @PathParam("tenantId") String tenantId,
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours", required = false) @QueryParam("start") Long start,
@ApiParam(value = "Defaults to now", required = false) @QueryParam("end") Long end,
@ApiParam(value = "A threshold against which values are compared", required = true) @QueryParam("threshold")
double threshold,
@ApiParam(value = "A comparison operation to perform between values and the threshold. Supported operations " +
"include ge, gte, lt, lte, and eq", required = true) @QueryParam("op") String operator) {
long now = System.currentTimeMillis();
if (start == null) {
start = now - EIGHT_HOURS;
}
if (end == null) {
end = now;
}
Predicate<Double> predicate;
switch (operator) {
case "lt":
predicate = d -> d < threshold;
break;
case "lte":
predicate = d -> d <= threshold;
break;
case "eq":
predicate = d -> d == threshold;
break;
case "neq":
predicate = d -> d != threshold;
break;
case "gt":
predicate = d -> d > threshold;
break;
case "gte":
predicate = d -> d >= threshold;
break;
default:
predicate = null;
}
if (predicate == null) {
response.resume(Response.status(Status.BAD_REQUEST).entity(new ApiError("Invalid value for op parameter. "
+ "Supported values are lt, lte, eq, gt, gte")).build());
} else {
ListenableFuture<List<long[]>> future = metricsService.getPeriods(tenantId, new MetricId(id), predicate,
start, end);
// We need to transform empty results to null because SimpleDataCallback returns a 204 status for null
// data.
future = Futures.transform(future, (List<long[]> periods) -> periods.isEmpty() ? null : periods);
Futures.addCallback(future, new SimpleDataCallback<>(response));
}
}
@GET
@Path("/{tenantId}/metrics/availability/{id}/data")
@ApiOperation(value = "Retrieve availability data.", response = Availability.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully fetched availability data."),
@ApiResponse(code = 204, message = "No availability data was found.")})
public void findAvailabilityData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") final String id,
@ApiParam(value = "Defaults to now - 8 hours", required = false) @QueryParam("start") Long start,
@ApiParam(value = "Defaults to now", required = false) @QueryParam("end") Long end) {
long now = System.currentTimeMillis();
if (start == null) {
start = now - EIGHT_HOURS;
}
if (end == null) {
end = now;
}
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
ListenableFuture<AvailabilityMetric> future = metricsService.findAvailabilityData(metric, start, end);
ListenableFuture<List<Availability>> outputfuture = Futures.transform(future,
new Function<AvailabilityMetric, List<Availability>>() {
@Override
public List<Availability> apply(AvailabilityMetric input) {
if (input == null) {
return null;
}
return input.getData();
}
});
Futures.addCallback(outputfuture, new SimpleDataCallback<List<Availability>>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/numeric/{id}/tag")
@ApiOperation(value = "Add or update numeric metric's tags.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Tags were modified successfully.")})
public void tagNumericData(@Suspended final AsyncResponse asyncResponse, @PathParam("tenantId") String tenantId,
@PathParam("id") final String id, @ApiParam(required = true) TagRequest params) {
ListenableFuture<List<NumericData>> future;
NumericMetric metric = new NumericMetric(tenantId, new MetricId(id));
if (params.getTimestamp() != null) {
future = metricsService.tagNumericData(metric, params.getTags(), params.getTimestamp());
} else {
future = metricsService.tagNumericData(metric, params.getTags(), params.getStart(), params.getEnd());
}
Futures.addCallback(future, new NoDataCallback<List<NumericData>>(asyncResponse));
}
@POST
@Path("/{tenantId}/metrics/availability/{id}/tag")
@ApiOperation(value = "Add or update availability metric's tags.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Tags were modified successfully.")})
public void tagAvailabilityData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId, @PathParam("id") final String id,
@ApiParam(required = true) TagRequest params) {
ListenableFuture<List<Availability>> future;
AvailabilityMetric metric = new AvailabilityMetric(tenantId, new MetricId(id));
if (params.getTimestamp() != null) {
future = metricsService.tagAvailabilityData(metric, params.getTags(), params.getTimestamp());
} else {
future = metricsService.tagAvailabilityData(metric, params.getTags(), params.getStart(), params.getEnd());
}
Futures.addCallback(future, new NoDataCallback<List<Availability>>(asyncResponse));
}
@GET
@Path("/{tenantId}/tags/numeric/{tag}")
@ApiOperation(value = "Find numeric metric data with given tags.", response = Map.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Numeric values fetched successfully"),
@ApiResponse(code = 500, message = "Any error while fetching data.",
response = ApiError.class)
})
public void findTaggedNumericData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@PathParam("tag") String encodedTag) {
ListenableFuture<Map<MetricId, Set<NumericData>>> queryFuture = metricsService.findNumericDataByTags(
tenantId, MetricUtils.decodeTags(encodedTag));
ListenableFuture<Map<String, Set<NumericData>>> resultFuture = Futures.transform(
queryFuture,
new Function<Map<MetricId, Set<NumericData>>, Map<String, Set<NumericData>>>() {
@Override
public Map<String, Set<NumericData>> apply(Map<MetricId, Set<NumericData>> input) {
Map<String, Set<NumericData>> result = new HashMap<String, Set<NumericData>>(input.size());
for (Map.Entry<MetricId, Set<NumericData>> entry : input.entrySet()) {
result.put(entry.getKey().getName(), entry.getValue());
}
return result;
}
}
);
Futures.addCallback(resultFuture, new SimpleDataCallback<Map<String, Set<NumericData>>>(asyncResponse));
}
@GET
@Path("/{tenantId}/tags/availability/{tag}")
@ApiOperation(value = "Find availability metric data with given tags.", response = Map.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Availability values fetched successfully"),
@ApiResponse(code = 500, message = "Any error while fetching data.",
response = ApiError.class)
})
public void findTaggedAvailabilityData(@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") String tenantId,
@ApiParam(allowMultiple = true, required = true, value = "A list of tags in the format of name:value")
@PathParam("tag") String encodedTag) {
ListenableFuture<Map<MetricId, Set<Availability>>> queryFuture = metricsService.findAvailabilityByTags(tenantId,
MetricUtils.decodeTags(encodedTag));
Futures.addCallback(queryFuture, new SimpleDataCallback<Map<MetricId, Set<Availability>>>(asyncResponse));
}
@POST
@Path("/counters")
@ApiOperation(value = "List of counter definitions", hidden = true)
public void updateCountersForGroups(@Suspended final AsyncResponse asyncResponse, Collection<Counter> counters) {
ListenableFuture<Void> future = metricsService.updateCounters(counters);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/counters/{group}")
@ApiOperation(value = "Update multiple counters in a single counter group", hidden = true)
public void updateCounterForGroup(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group,
Collection<Counter> counters) {
for (Counter counter : counters) {
counter.setGroup(group);
}
ListenableFuture<Void> future = metricsService.updateCounters(counters);
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/counters/{group}/{counter}")
@ApiOperation(value = "Increase value of a counter", hidden = true)
public void updateCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group,
@PathParam("counter") String counter) {
ListenableFuture<Void> future = metricsService
.updateCounter(new Counter(DEFAULT_TENANT_ID, group, counter, 1L));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@POST
@Path("/counters/{group}/{counter}/{value}")
@ApiOperation(value = "Update value of a counter", hidden = true)
public void updateCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group,
@PathParam("counter") String counter, @PathParam("value") Long value) {
ListenableFuture<Void> future = metricsService.updateCounter(new Counter(DEFAULT_TENANT_ID, group, counter,
value));
Futures.addCallback(future, new NoDataCallback<Void>(asyncResponse));
}
@GET
@Path("/counters/{group}")
@ApiOperation(value = "Retrieve a list of counter values in this group", hidden = true, response = Counter.class,
responseContainer = "List")
@Produces({ APPLICATION_JSON })
public void getCountersForGroup(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group) {
ListenableFuture<List<Counter>> future = metricsService.findCounters(group);
Futures.addCallback(future, new SimpleDataCallback<List<Counter>>(asyncResponse));
}
@GET
@Path("/counters/{group}/{counter}")
@ApiOperation(value = "Retrieve value of a counter", hidden = true, response = Counter.class,
responseContainer = "List")
public void getCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("group") final String group,
@PathParam("counter") final String counter) {
ListenableFuture<List<Counter>> future = metricsService.findCounters(group, Collections.singletonList(counter));
Futures.addCallback(future, new FutureCallback<List<Counter>>() {
@Override
public void onSuccess(List<Counter> counters) {
if (counters.isEmpty()) {
asyncResponse.resume(Response.status(404).entity("Counter[group: " + group + ", name: " +
counter + "] not found").build());
} else {
Response jaxrs = Response.ok(counters.get(0)).build();
asyncResponse.resume(jaxrs);
}
}
@Override
public void onFailure(Throwable t) {
asyncResponse.resume(t);
}
});
}
@GET
@Path("/{tenantId}/metrics")
@ApiOperation(value = "Find tenant's metric definitions.", notes = "Does not include any metric values. ",
response = List.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved at least one metric "
+ "definition."),
@ApiResponse(code = 204, message = "No metrics found."),
@ApiResponse(code = 400, message = "Given type is not a valid type.", response = ApiError.class),
@ApiResponse(code = 500, message = "Failed to retrieve metrics due to unexpected error.",
response = ApiError.class)
})
public void findMetrics(
@Suspended final AsyncResponse asyncResponse,
@PathParam("tenantId") final String tenantId,
@ApiParam(value = "Queried metric type", required = true, allowableValues = "[num, avail, log]")
@QueryParam("type") String type) {
MetricType metricType = null;
try {
metricType = MetricType.fromTextCode(type);
} catch (IllegalArgumentException e) {
ApiError errors = new ApiError("[" + type + "] is not a valid type. Accepted values are num|avail|log");
asyncResponse.resume(Response.status(Status.BAD_REQUEST).entity(errors).build());
}
ListenableFuture<List<Metric<?>>> future = metricsService.findMetrics(tenantId, metricType);
Futures.addCallback(future, new SimpleDataCallback<List<Metric<?>>>(asyncResponse));
}
}
| First, a Javadoc update and minor code changes
| api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/MetricHandler.java | First, a Javadoc update and minor code changes |
|
Java | apache-2.0 | a695533a24f634f0652da11836a7359c26bc8a15 | 0 | FHannes/intellij-community,signed/intellij-community,semonte/intellij-community,semonte/intellij-community,FHannes/intellij-community,da1z/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,asedunov/intellij-community,signed/intellij-community,da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,signed/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,signed/intellij-community,apixandru/intellij-community,xfournet/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,semonte/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,signed/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,ibinti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,signed/intellij-community,suncycheng/intellij-community,semonte/intellij-community,signed/intellij-community,asedunov/intellij-community,da1z/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,ibinti/intellij-community,FHannes/intellij-community,xfournet/intellij-community,apixandru/intellij-community,FHannes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vvv1559/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,da1z/intellij-community,allotria/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,apixandru/intellij-community,signed/intellij-community,allotria/intellij-community,asedunov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,semonte/intellij-community,signed/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,asedunov/intellij-community,semonte/intellij-community,xfournet/intellij-community,semonte/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,signed/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,allotria/intellij-community,asedunov/intellij-community,FHannes/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community | package com.jetbrains.jsonSchema;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.xmlb.annotations.Transient;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* @author Irina.Chernushina on 2/2/2016.
*/
@State(
name = "JsonSchemaMappingsProjectConfiguration",
storages = {
@Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/jsonSchemas.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class JsonSchemaMappingsProjectConfiguration extends JsonSchemaMappingsConfigurationBase {
private Project myProject;
@Transient
private final Map<VirtualFile, SchemaInfo> mySchemaFiles = new HashMap<>();
public static JsonSchemaMappingsProjectConfiguration getInstance(@NotNull final Project project) {
return ServiceManager.getService(project, JsonSchemaMappingsProjectConfiguration.class);
}
public JsonSchemaMappingsProjectConfiguration(Project project) {
myProject = project;
}
public JsonSchemaMappingsProjectConfiguration() {
}
@Override
public File convertToAbsoluteFile(@NotNull String path) {
return myProject.getBasePath() == null ? new File(path) : new File(myProject.getBasePath(), path);
}
public boolean isRegisteredSchemaFile(@NotNull VirtualFile file) {
return mySchemaFiles.containsKey(file);
}
@Override
public void setState(@NotNull Map<String, SchemaInfo> state) {
super.setState(state);
recalculateSchemaFiles();
}
@Override
public void addSchema(@NotNull SchemaInfo info) {
super.addSchema(info);
recalculateSchemaFiles();
}
@Override
public void removeSchema(@NotNull SchemaInfo info) {
super.removeSchema(info);
recalculateSchemaFiles();
}
@Override
public void loadState(JsonSchemaMappingsConfigurationBase state) {
super.loadState(state);
recalculateSchemaFiles();
}
private void recalculateSchemaFiles() {
ApplicationManager.getApplication().invokeLater(() -> {
ApplicationManager.getApplication().runWriteAction(() -> FileTypeManagerEx.getInstanceEx().fireFileTypesChanged());
}, o -> !myProject.isDisposed());
mySchemaFiles.clear();
if (myProject == null || myProject.getBaseDir() == null) return;
for (JsonSchemaMappingsConfigurationBase.SchemaInfo info : myState.values()) {
final VirtualFile schemaFile = info.getSchemaFile(myProject);
if (schemaFile != null) mySchemaFiles.put(schemaFile, info);
}
}
@Nullable
public SchemaInfo getSchemaBySchemaFile(@NotNull final VirtualFile file) {
return mySchemaFiles.get(file);
}
}
| json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsProjectConfiguration.java | package com.jetbrains.jsonSchema;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.xmlb.annotations.Transient;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* @author Irina.Chernushina on 2/2/2016.
*/
@State(
name = "JsonSchemaMappingsProjectConfiguration",
storages = {
@Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/jsonSchemas.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class JsonSchemaMappingsProjectConfiguration extends JsonSchemaMappingsConfigurationBase {
private Project myProject;
@Transient
private final Map<VirtualFile, SchemaInfo> mySchemaFiles = new HashMap<>();
public static JsonSchemaMappingsProjectConfiguration getInstance(@NotNull final Project project) {
return ServiceManager.getService(project, JsonSchemaMappingsProjectConfiguration.class);
}
public JsonSchemaMappingsProjectConfiguration(Project project) {
myProject = project;
}
public JsonSchemaMappingsProjectConfiguration() {
}
@Override
public File convertToAbsoluteFile(@NotNull String path) {
return myProject.getBasePath() == null ? new File(path) : new File(myProject.getBasePath(), path);
}
public boolean isRegisteredSchemaFile(@NotNull VirtualFile file) {
return mySchemaFiles.containsKey(file);
}
@Override
public void setState(@NotNull Map<String, SchemaInfo> state) {
super.setState(state);
recalculateSchemaFiles();
}
@Override
public void addSchema(@NotNull SchemaInfo info) {
super.addSchema(info);
recalculateSchemaFiles();
}
@Override
public void removeSchema(@NotNull SchemaInfo info) {
super.removeSchema(info);
recalculateSchemaFiles();
}
@Override
public void loadState(JsonSchemaMappingsConfigurationBase state) {
super.loadState(state);
recalculateSchemaFiles();
}
private void recalculateSchemaFiles() {
ApplicationManager
.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> FileTypeManagerEx.getInstanceEx().fireFileTypesChanged()));
mySchemaFiles.clear();
if (myProject == null || myProject.getBaseDir() == null) return;
for (JsonSchemaMappingsConfigurationBase.SchemaInfo info : myState.values()) {
final VirtualFile schemaFile = info.getSchemaFile(myProject);
if (schemaFile != null) mySchemaFiles.put(schemaFile, info);
}
}
@Nullable
public SchemaInfo getSchemaBySchemaFile(@NotNull final VirtualFile file) {
return mySchemaFiles.get(file);
}
}
| json schema listener, do not process events after the project is closed
| json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsProjectConfiguration.java | json schema listener, do not process events after the project is closed |
|
Java | apache-2.0 | d963359df4c2be1304febc5d27bc83bc1dbbc358 | 0 | vvv1559/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,holmes/intellij-community,ryano144/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,da1z/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,fnouama/intellij-community,signed/intellij-community,kool79/intellij-community,semonte/intellij-community,FHannes/intellij-community,apixandru/intellij-community,dslomov/intellij-community,amith01994/intellij-community,slisson/intellij-community,semonte/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,apixandru/intellij-community,xfournet/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ibinti/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,blademainer/intellij-community,petteyg/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,kool79/intellij-community,kool79/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,caot/intellij-community,retomerz/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,hurricup/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,tmpgit/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,holmes/intellij-community,hurricup/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,clumsy/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,supersven/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,diorcety/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,clumsy/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,ibinti/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,FHannes/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,semonte/intellij-community,tmpgit/intellij-community,kool79/intellij-community,dslomov/intellij-community,semonte/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,hurricup/intellij-community,semonte/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,kdwink/intellij-community,diorcety/intellij-community,asedunov/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,kool79/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,retomerz/intellij-community,jagguli/intellij-community,fitermay/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,samthor/intellij-community,fitermay/intellij-community,vladmm/intellij-community,allotria/intellij-community,jagguli/intellij-community,slisson/intellij-community,slisson/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,semonte/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,holmes/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,signed/intellij-community,da1z/intellij-community,fitermay/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,suncycheng/intellij-community,allotria/intellij-community,asedunov/intellij-community,ryano144/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,caot/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,allotria/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,retomerz/intellij-community,samthor/intellij-community,ibinti/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,izonder/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,vladmm/intellij-community,ryano144/intellij-community,apixandru/intellij-community,FHannes/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,amith01994/intellij-community,caot/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,caot/intellij-community,signed/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,wreckJ/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,petteyg/intellij-community,semonte/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,kool79/intellij-community,retomerz/intellij-community,jagguli/intellij-community,kool79/intellij-community,holmes/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,caot/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,robovm/robovm-studio,asedunov/intellij-community,dslomov/intellij-community,izonder/intellij-community,holmes/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,amith01994/intellij-community,supersven/intellij-community,da1z/intellij-community,samthor/intellij-community,fnouama/intellij-community,da1z/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,kool79/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,retomerz/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,ryano144/intellij-community,slisson/intellij-community,dslomov/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,ibinti/intellij-community,robovm/robovm-studio,kdwink/intellij-community,allotria/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,caot/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,allotria/intellij-community,blademainer/intellij-community,slisson/intellij-community,signed/intellij-community,slisson/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,diorcety/intellij-community,slisson/intellij-community,slisson/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,signed/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,signed/intellij-community,vladmm/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,da1z/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,FHannes/intellij-community,supersven/intellij-community,suncycheng/intellij-community,izonder/intellij-community,holmes/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,asedunov/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,allotria/intellij-community,fnouama/intellij-community,ibinti/intellij-community,samthor/intellij-community,adedayo/intellij-community,supersven/intellij-community,allotria/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,caot/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,izonder/intellij-community,jagguli/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,vladmm/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,signed/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,semonte/intellij-community,vladmm/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,hurricup/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,da1z/intellij-community,robovm/robovm-studio,da1z/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,izonder/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,dslomov/intellij-community,caot/intellij-community,amith01994/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,allotria/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,blademainer/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,kdwink/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,adedayo/intellij-community,robovm/robovm-studio,signed/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,ryano144/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,supersven/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community | /*
* 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.openapi.components.impl.stores;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.impl.ProjectManagerImpl;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
abstract class BaseFileConfigurableStoreImpl extends ComponentStoreImpl {
@NonNls protected static final String VERSION_OPTION = "version";
@NonNls public static final String ATTRIBUTE_NAME = "name";
private final ComponentManager myComponentManager;
private static final ArrayList<String> ourConversionProblemsStorage = new ArrayList<String>();
private final DefaultsStateStorage myDefaultsStateStorage;
private StateStorageManager myStateStorageManager;
protected BaseFileConfigurableStoreImpl(final ComponentManager componentManager) {
myComponentManager = componentManager;
final PathMacroManager pathMacroManager = PathMacroManager.getInstance(myComponentManager);
myDefaultsStateStorage = new DefaultsStateStorage(pathMacroManager);
}
public synchronized ComponentManager getComponentManager() {
return myComponentManager;
}
protected static class BaseStorageData extends FileBasedStorage.FileStorageData {
protected int myVersion;
public BaseStorageData(final String rootElementName) {
super(rootElementName);
}
protected BaseStorageData(BaseStorageData storageData) {
super(storageData);
myVersion = ProjectManagerImpl.CURRENT_FORMAT_VERSION;
}
@Override
public void load(@NotNull final Element rootElement) throws IOException {
super.load(rootElement);
final String v = rootElement.getAttributeValue(VERSION_OPTION);
if (v != null) {
myVersion = Integer.parseInt(v);
}
else {
myVersion = ProjectManagerImpl.CURRENT_FORMAT_VERSION;
}
}
@Override
@NotNull
protected Element save() {
final Element root = super.save();
root.setAttribute(VERSION_OPTION, Integer.toString(myVersion));
return root;
}
@Override
public StorageData clone() {
return new BaseStorageData(this);
}
@Override
protected int computeHash() {
int result = super.computeHash();
result = result * 31 + myVersion;
return result;
}
@Override
@Nullable
public Set<String> getDifference(final StorageData storageData, PathMacroSubstitutor substitutor) {
final BaseStorageData data = (BaseStorageData)storageData;
if (myVersion != data.myVersion) return null;
return super.getDifference(storageData, substitutor);
}
}
protected abstract XmlElementStorage getMainStorage();
@Nullable
static ArrayList<String> getConversionProblemsStorage() {
return ourConversionProblemsStorage;
}
@Override
public void load() throws IOException, StateStorageException {
getMainStorageData(); //load it
}
public BaseStorageData getMainStorageData() throws StateStorageException {
return (BaseStorageData) getMainStorage().getStorageData(false);
}
@Override
protected StateStorage getDefaultsStorage() {
return myDefaultsStateStorage;
}
@NotNull
@Override
public StateStorageManager getStateStorageManager() {
if (myStateStorageManager == null) {
myStateStorageManager = createStateStorageManager();
}
return myStateStorageManager;
}
@NotNull
protected abstract StateStorageManager createStateStorageManager();
}
| platform/platform-impl/src/com/intellij/openapi/components/impl/stores/BaseFileConfigurableStoreImpl.java | /*
* 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.openapi.components.impl.stores;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.impl.ProjectManagerImpl;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
abstract class BaseFileConfigurableStoreImpl extends ComponentStoreImpl {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.components.impl.stores.BaseFileConfigurableStoreImpl");
@NonNls protected static final String VERSION_OPTION = "version";
@NonNls public static final String ATTRIBUTE_NAME = "name";
private final ComponentManager myComponentManager;
private static final ArrayList<String> ourConversionProblemsStorage = new ArrayList<String>();
private final DefaultsStateStorage myDefaultsStateStorage;
private StateStorageManager myStateStorageManager;
protected BaseFileConfigurableStoreImpl(final ComponentManager componentManager) {
myComponentManager = componentManager;
final PathMacroManager pathMacroManager = PathMacroManager.getInstance(myComponentManager);
myDefaultsStateStorage = new DefaultsStateStorage(pathMacroManager);
}
public synchronized ComponentManager getComponentManager() {
return myComponentManager;
}
protected static class BaseStorageData extends FileBasedStorage.FileStorageData {
protected int myVersion;
public BaseStorageData(final String rootElementName) {
super(rootElementName);
}
protected BaseStorageData(BaseStorageData storageData) {
super(storageData);
myVersion = ProjectManagerImpl.CURRENT_FORMAT_VERSION;
}
@Override
public void load(@NotNull final Element rootElement) throws IOException {
super.load(rootElement);
final String v = rootElement.getAttributeValue(VERSION_OPTION);
if (v != null) {
myVersion = Integer.parseInt(v);
}
else {
myVersion = ProjectManagerImpl.CURRENT_FORMAT_VERSION;
}
}
@Override
@NotNull
protected Element save() {
final Element root = super.save();
root.setAttribute(VERSION_OPTION, Integer.toString(myVersion));
return root;
}
@Override
public StorageData clone() {
return new BaseStorageData(this);
}
@Override
protected int computeHash() {
int result = super.computeHash();
result = result * 31 + myVersion;
return result;
}
@Override
@Nullable
public Set<String> getDifference(final StorageData storageData, PathMacroSubstitutor substitutor) {
final BaseStorageData data = (BaseStorageData)storageData;
if (myVersion != data.myVersion) return null;
return super.getDifference(storageData, substitutor);
}
}
protected abstract XmlElementStorage getMainStorage();
@Nullable
static ArrayList<String> getConversionProblemsStorage() {
return ourConversionProblemsStorage;
}
@Override
public void load() throws IOException, StateStorageException {
getMainStorageData(); //load it
}
public BaseStorageData getMainStorageData() throws StateStorageException {
return (BaseStorageData) getMainStorage().getStorageData(false);
}
@Override
protected StateStorage getDefaultsStorage() {
return myDefaultsStateStorage;
}
@NotNull
@Override
public StateStorageManager getStateStorageManager() {
if (myStateStorageManager == null) {
myStateStorageManager = createStateStorageManager();
}
return myStateStorageManager;
}
@NotNull
protected abstract StateStorageManager createStateStorageManager();
}
| cleanup
| platform/platform-impl/src/com/intellij/openapi/components/impl/stores/BaseFileConfigurableStoreImpl.java | cleanup |
|
Java | apache-2.0 | 416f7bb83b38dda5bb6e7f8b5594458b1ae3a6bd | 0 | jgaupp/arx,kbabioch/arx,TheRealRasu/arx,bitraten/arx,COWYARD/arx,jgaupp/arx,fstahnke/arx,RaffaelBild/arx,kbabioch/arx,COWYARD/arx,tijanat/arx,bitraten/arx,kentoa/arx,kentoa/arx,arx-deidentifier/arx,TheRealRasu/arx,fstahnke/arx,arx-deidentifier/arx,tijanat/arx,RaffaelBild/arx | /*
* ARX: Powerful Data Anonymization
* Copyright (C) 2012 - 2014 Florian Kohlmayer, Fabian Prasser
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.deidentifier.arx.framework.lattice;
import java.util.Arrays;
import org.deidentifier.arx.metric.InformationLoss;
/**
* The Class Node.
*
* @author Fabian Prasser
* @author Florian Kohlmayer
*/
public class Node {
/**
* All privacy criteria are fulfilled
*/
public static final int PROPERTY_ANONYMOUS = 1 << 0;
/**
* Not all privacy criteria are fulfilled
*/
public static final int PROPERTY_NOT_ANONYMOUS = 1 << 1;
/**
* A k-anonymity sub-criterion is fulfilled
*/
public static final int PROPERTY_K_ANONYMOUS = 1 << 2;
/**
* A k-anonymity sub-criterion is not fulfilled
*/
public static final int PROPERTY_NOT_K_ANONYMOUS = 1 << 3;
/**
* The transformation results in insufficient utility
*/
public static final int PROPERTY_INSUFFICIENT_UTILITY = 1 << 4;
/**
* The transformation has been checked explicitly
*/
public static final int PROPERTY_CHECKED = 1 << 5;
/**
* A snapshot for this transformation must be created if it fits the size
* limits, regardless of whether it triggers the storage condition
*/
public static final int PROPERTY_FORCE_SNAPSHOT = 1 << 6;
/**
* This node has already been visited during the second phase
*/
public static final int PROPERTY_VISITED = 1 << 7;
/**
* Marks nodes for which the search algorithm guarantees to never check any
* of its successors
*/
public static final int PROPERTY_SUCCESSORS_PRUNED = 1 << 8;
/**
* We have already fired an event for this node
*/
public static final int PROPERTY_EVENT_FIRED = 1 << 9;
/** The id. */
public final int id;
/** Set of properties */
private int properties;
/** The predecessors. */
private Node[] predecessors;
/** The level. */
private int level;
/** The information loss. */
private InformationLoss<?> informationLoss;
/** The lower bound. */
private InformationLoss<?> lowerBound;
/** The transformation. */
private int[] transformation;
/** The upwards. */
private Node[] successors;
/** The down index. */
private int preIndex;
/** The up index. */
private int sucIndex;
/** Associated data */
private Object data;
/**
* Instantiates a new node.
*/
public Node(int id) {
this.id = id;
this.informationLoss = null;
this.preIndex = 0;
this.sucIndex = 0;
this.properties = 0;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) { return true; }
if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; }
final Node other = (Node) obj;
if (!Arrays.equals(transformation, other.transformation)) { return false; }
return true;
}
/** Associated data*/
public Object getData() {
return data;
}
/**
* Returns the information loss
*
* @return
*/
public InformationLoss<?> getInformationLoss() {
return informationLoss;
}
/**
* Returns the level
*
* @return
*/
public int getLevel() {
return level;
}
/**
* @return the lowerBound
*/
public InformationLoss<?> getLowerBound() {
return lowerBound;
}
/**
* Returns the predecessors
*
* @return
*/
public Node[] getPredecessors() {
return predecessors;
}
/**
* Returns the successors
*
* @return
*/
public Node[] getSuccessors() {
return successors;
}
/**
* Returns the transformation
*
* @return
*/
public int[] getTransformation() {
return transformation;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Arrays.hashCode(transformation);
}
/**
* Returns whether the node has the given property
* @param property
* @return
*/
public boolean hasProperty(int property){
return (properties & property) == property;
}
/** Associated data*/
public void setData(Object data) {
this.data = data;
}
/**
* Sets the transformation
*
* @param transformation
*/
public void setTransformation(int[] transformation, int level) {
this.transformation = transformation;
this.level = level;
}
/**
* Sets the information loss
*
* @param informationLoss
*/
protected void setInformationLoss(final InformationLoss<?> informationLoss) {
if (this.informationLoss == null) {
this.informationLoss = informationLoss;
}
}
/**
* Sets the information loss
*
* @param informationLoss
*/
protected void setLowerBound(final InformationLoss<?> lowerBound) {
if (this.lowerBound == null) {
this.lowerBound = lowerBound;
}
}
/**
* Sets the predecessors
*
* @param nodes
*/
protected void setPredecessors(Node[] nodes) {
predecessors = nodes;
}
/**
* Sets the given property
* @param property
* @return
*/
protected void setProperty(int property){
properties |= property;
}
/**
* Sets the successors
*
* @param nodes
*/
protected void setSuccessors(Node[] nodes) {
successors = nodes;
}
/**
* Adds a predecessor
*
* @param predecessor
*/
void addPredecessor(Node predecessor) {
predecessors[preIndex++] = predecessor;
}
/**
* Adds a successor
*
* @param successor
*/
void addSuccessor(Node successor) {
successors[sucIndex++] = successor;
}
}
| src/main/org/deidentifier/arx/framework/lattice/Node.java | /*
* ARX: Powerful Data Anonymization
* Copyright (C) 2012 - 2014 Florian Kohlmayer, Fabian Prasser
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.deidentifier.arx.framework.lattice;
import java.util.Arrays;
import org.deidentifier.arx.metric.InformationLoss;
/**
* The Class Node.
*
* @author Fabian Prasser
* @author Florian Kohlmayer
*/
public class Node {
/**
* All privacy criteria are fulfilled
*/
public static final int PROPERTY_ANONYMOUS = 1 << 0;
/**
* Not all privacy criteria are fulfilled
*/
public static final int PROPERTY_NOT_ANONYMOUS = 1 << 1;
/**
* A k-anonymity sub-criterion is fulfilled
*/
public static final int PROPERTY_K_ANONYMOUS = 1 << 2;
/**
* A k-anonymity sub-criterion is not fulfilled
*/
public static final int PROPERTY_NOT_K_ANONYMOUS = 1 << 3;
/**
* The transformation results in insufficient utility
*/
public static final int PROPERTY_INSUFFICIENT_UTILITY = 1 << 4;
/**
* The transformation has been checked explicitly
*/
public static final int PROPERTY_CHECKED = 1 << 5;
/**
* A snapshot for this transformation must be created if it fits the size
* limits, regardless of whether it triggers the storage condition
*/
public static final int PROPERTY_FORCE_SNAPSHOT = 1 << 6;
/**
* This node has already been visited during the second phase
*/
public static final int PROPERTY_VISITED = 1 << 7;
/**
* Marks nodes for which the search algorithm guarantees to never check any
* of its successors
*/
public static final int PROPERTY_SUCCESSORS_PRUNED = 1 << 8;
/**
* We have already fired an event for this node
*/
public static final int PROPERTY_EVENT_FIRED = 1 << 9;
/** The id. */
public final int id;
/** Set of properties */
private int properties;
/** The predecessors. */
private Node[] predecessors;
/** The level. */
private int level;
/** The information loss. */
private InformationLoss<?> informationLoss;
/** The lower bound. */
private InformationLoss<?> lowerBound;
/** The transformation. */
private int[] transformation;
/** The upwards. */
private Node[] successors;
/** The down index. */
private int preIndex;
/** The up index. */
private int sucIndex;
/** Associated data */
private Object data;
/**
* Instantiates a new node.
*/
public Node(int id) {
this.id = id;
this.informationLoss = null;
this.preIndex = 0;
this.sucIndex = 0;
this.properties = 0;
}
/**
* Adds a predecessor
*
* @param predecessor
*/
public void addPredecessor(Node predecessor) {
predecessors[preIndex++] = predecessor;
}
/**
* Adds a successor
*
* @param successor
*/
public void addSuccessor(Node successor) {
successors[sucIndex++] = successor;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) { return true; }
if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; }
final Node other = (Node) obj;
if (!Arrays.equals(transformation, other.transformation)) { return false; }
return true;
}
/** Associated data*/
public Object getData() {
return data;
}
/**
* Returns the information loss
*
* @return
*/
public InformationLoss<?> getInformationLoss() {
return informationLoss;
}
/**
* Returns the level
*
* @return
*/
public int getLevel() {
return level;
}
/**
* @return the lowerBound
*/
public InformationLoss<?> getLowerBound() {
return lowerBound;
}
/**
* Returns the predecessors
*
* @return
*/
public Node[] getPredecessors() {
return predecessors;
}
/**
* Returns the successors
*
* @return
*/
public Node[] getSuccessors() {
return successors;
}
/**
* Returns the transformation
*
* @return
*/
public int[] getTransformation() {
return transformation;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + Arrays.hashCode(transformation);
return result;
}
/**
* Returns whether the node has the given property
* @param property
* @return
*/
public boolean hasProperty(int property){
return (properties & property) == property;
}
/** Associated data*/
public void setData(Object data) {
this.data = data;
}
/**
* Sets the transformation
*
* @param transformation
*/
public void setTransformation(int[] transformation, int level) {
this.transformation = transformation;
this.level = level;
}
/**
* Sets the information loss
*
* @param informationLoss
*/
protected void setInformationLoss(final InformationLoss<?> informationLoss) {
if (this.informationLoss == null) {
this.informationLoss = informationLoss;
}
}
/**
* Sets the information loss
*
* @param informationLoss
*/
protected void setLowerBound(final InformationLoss<?> lowerBound) {
if (this.lowerBound == null) {
this.lowerBound = lowerBound;
}
}
/**
* Sets the predecessors
*
* @param nodes
*/
protected void setPredecessors(Node[] nodes) {
predecessors = nodes;
}
/**
* Sets the given property
* @param property
* @return
*/
protected void setProperty(int property){
properties |= property;
}
/**
* Sets the successors
*
* @param nodes
*/
protected void setSuccessors(Node[] nodes) {
successors = nodes;
}
}
| Improve class Node | src/main/org/deidentifier/arx/framework/lattice/Node.java | Improve class Node |
|
Java | apache-2.0 | 3bf9743d5954781d5b10132059029a48648fde13 | 0 | ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,vvv1559/intellij-community,signed/intellij-community,semonte/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,apixandru/intellij-community,allotria/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,da1z/intellij-community,xfournet/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,allotria/intellij-community,xfournet/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ibinti/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,allotria/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,FHannes/intellij-community,allotria/intellij-community,ibinti/intellij-community,da1z/intellij-community,signed/intellij-community,youdonghai/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,asedunov/intellij-community,FHannes/intellij-community,da1z/intellij-community,vvv1559/intellij-community,allotria/intellij-community,da1z/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,signed/intellij-community,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,allotria/intellij-community,xfournet/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,FHannes/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,signed/intellij-community,da1z/intellij-community,da1z/intellij-community,vvv1559/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ibinti/intellij-community,FHannes/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,signed/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,signed/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,xfournet/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,FHannes/intellij-community,semonte/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,da1z/intellij-community,semonte/intellij-community,xfournet/intellij-community,semonte/intellij-community,suncycheng/intellij-community,allotria/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,signed/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,semonte/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,signed/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ibinti/intellij-community,semonte/intellij-community,FHannes/intellij-community,semonte/intellij-community | package com.intellij.remoteServer.util;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.remoteServer.agent.util.CloudAgentLoggingHandler;
import com.intellij.remoteServer.agent.util.CloudGitApplication;
import com.intellij.remoteServer.configuration.deployment.DeploymentSource;
import com.intellij.remoteServer.runtime.deployment.DeploymentLogManager;
import com.intellij.remoteServer.runtime.deployment.DeploymentTask;
import com.intellij.util.ArrayUtil;
import com.intellij.util.concurrency.Semaphore;
import git4idea.GitUtil;
import git4idea.actions.GitInit;
import git4idea.commands.*;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import git4idea.util.GitFileUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author michael.golubev
*/
public class CloudGitDeploymentRuntime extends CloudDeploymentRuntime {
private static final Logger LOG = Logger.getInstance("#" + CloudGitDeploymentRuntime.class.getName());
private static final String COMMIT_MESSAGE = "Deploy";
private static final CommitSession NO_COMMIT = new CommitSession() {
@Nullable
@Override
public JComponent getAdditionalConfigurationUI() {
return null;
}
@Nullable
@Override
public JComponent getAdditionalConfigurationUI(Collection<Change> changes, String commitMessage) {
return null;
}
@Override
public boolean canExecute(Collection<Change> changes, String commitMessage) {
return true;
}
@Override
public void execute(Collection<Change> changes, String commitMessage) {
}
@Override
public void executionCanceled() {
}
@Override
public String getHelpId() {
return null;
}
};
private static final List<CommitExecutor> ourCommitExecutors = Arrays.asList(
new CommitExecutor() {
@Nls
@Override
public String getActionText() {
return "Commit and Push";
}
@NotNull
@Override
public CommitSession createCommitSession() {
return CommitSession.VCS_COMMIT;
}
},
new CommitExecutorBase() {
@Nls
@Override
public String getActionText() {
return "Push without Commit";
}
@NotNull
@Override
public CommitSession createCommitSession() {
return NO_COMMIT;
}
@Override
public boolean areChangesRequired() {
return false;
}
}
);
private final GitRepositoryManager myGitRepositoryManager;
private final Git myGit;
private final VirtualFile myContentRoot;
private final File myRepositoryRootFile;
private final String myDefaultRemoteName;
private final ChangeListManagerEx myChangeListManager;
private String myRemoteName;
private final String myCloudName;
private GitRepository myRepository;
public CloudGitDeploymentRuntime(CloudMultiSourceServerRuntimeInstance serverRuntime,
DeploymentSource source,
File repositoryRoot,
DeploymentTask<? extends CloudDeploymentNameConfiguration> task,
DeploymentLogManager logManager,
String defaultRemoteName,
String cloudName) throws ServerRuntimeException {
super(serverRuntime, source, task, logManager);
myDefaultRemoteName = defaultRemoteName;
myCloudName = cloudName;
myRepositoryRootFile = repositoryRoot;
VirtualFile contentRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(myRepositoryRootFile);
LOG.assertTrue(contentRoot != null, "Repository root is not found");
myContentRoot = contentRoot;
Project project = getProject();
myGitRepositoryManager = GitUtil.getRepositoryManager(project);
myGit = ServiceManager.getService(Git.class);
if (myGit == null) {
throw new ServerRuntimeException("Can't initialize GIT");
}
myChangeListManager = ChangeListManagerImpl.getInstanceImpl(project);
}
@Override
public CloudGitApplication deploy() throws ServerRuntimeException {
CloudGitApplication application = findOrCreateApplication();
deployApplication(application);
return application;
}
private void deployApplication(CloudGitApplication application) throws ServerRuntimeException {
boolean firstDeploy = findRepository() == null;
GitRepository repository = findOrCreateRepository();
addOrResetGitRemote(application, repository);
final LocalChangeList activeChangeList = myChangeListManager.getDefaultChangeList();
if (activeChangeList != null && !firstDeploy) {
commitWithChangesDialog(activeChangeList);
}
else {
add();
commit();
}
repository.update();
pushApplication(application);
}
protected void commitWithChangesDialog(final @NotNull LocalChangeList activeChangeList)
throws ServerRuntimeException {
Collection<Change> changes = activeChangeList.getChanges();
final List<Change> relevantChanges = new ArrayList<>();
for (Change change : changes) {
if (isRelevant(change.getBeforeRevision()) || isRelevant(change.getAfterRevision())) {
relevantChanges.add(change);
}
}
final Semaphore commitSemaphore = new Semaphore();
commitSemaphore.down();
final Ref<Boolean> commitSucceeded = new Ref<>(false);
Boolean commitStarted = runOnEdt(() -> CommitChangeListDialog.commitChanges(getProject(),
relevantChanges,
activeChangeList,
ourCommitExecutors,
false,
COMMIT_MESSAGE,
new CommitResultHandler() {
@Override
public void onSuccess(@NotNull String commitMessage) {
commitSucceeded.set(true);
commitSemaphore.up();
}
@Override
public void onFailure() {
commitSemaphore.up();
}
},
false));
if (commitStarted != null && commitStarted) {
commitSemaphore.waitFor();
if (!commitSucceeded.get()) {
getRepository().update();
throw new ServerRuntimeException("Commit failed");
}
}
else {
throw new ServerRuntimeException("Deploy interrupted");
}
}
private boolean isRelevant(ContentRevision contentRevision) throws ServerRuntimeException {
if (contentRevision == null) {
return false;
}
GitRepository repository = getRepository();
VirtualFile affectedFile = contentRevision.getFile().getVirtualFile();
return affectedFile != null && VfsUtilCore.isAncestor(repository.getRoot(), affectedFile, false);
}
private static <T> T runOnEdt(final Computable<T> computable) {
final Ref<T> result = new Ref<>();
ApplicationManager.getApplication().invokeAndWait(() -> result.set(computable.compute()));
return result.get();
}
public boolean isDeployed() throws ServerRuntimeException {
return findApplication() != null;
}
public CloudGitApplication findOrCreateApplication() throws ServerRuntimeException {
CloudGitApplication application = findApplication();
if (application == null) {
application = createApplication();
}
return application;
}
public void addOrResetGitRemote(CloudGitApplication application, GitRepository repository) throws ServerRuntimeException {
String gitUrl = application.getGitUrl();
if (myRemoteName == null) {
for (GitRemote gitRemote : repository.getRemotes()) {
if (gitRemote.getUrls().contains(gitUrl)) {
myRemoteName = gitRemote.getName();
return;
}
}
}
GitRemote gitRemote = GitUtil.findRemoteByName(repository, getRemoteName());
if (gitRemote == null) {
addGitRemote(application);
}
else if (!gitRemote.getUrls().contains(gitUrl)) {
resetGitRemote(application);
}
}
public GitRepository findOrCreateRepository() throws ServerRuntimeException {
GitRepository repository = findRepository();
if (repository == null) {
getLoggingHandler().println("Initializing git repository...");
GitCommandResult gitInitResult = getGit().init(getProject(), getRepositoryRoot(), createGitLineHandlerListener());
checkGitResult(gitInitResult);
refreshApplicationRepository();
repository = getRepository();
}
return repository;
}
public void downloadExistingApplication() throws ServerRuntimeException {
new CloneJobWithRemote().cloneToModule(getApplication().getGitUrl());
getRepository().update();
refreshContentRoot();
}
protected Git getGit() {
return myGit;
}
protected VirtualFile getRepositoryRoot() {
return myContentRoot;
}
protected File getRepositoryRootFile() {
return myRepositoryRootFile;
}
protected static void checkGitResult(GitCommandResult commandResult) throws ServerRuntimeException {
if (!commandResult.success()) {
Throwable exception = commandResult.getException();
if (exception != null) {
LOG.info(exception);
throw new ServerRuntimeException(exception);
}
else {
throw new ServerRuntimeException(commandResult.getErrorOutputAsJoinedString());
}
}
}
protected GitLineHandlerListener createGitLineHandlerListener() {
return new GitLineHandlerAdapter() {
@Override
public void onLineAvailable(String line, Key outputType) {
getLoggingHandler().println(line);
}
};
}
@Override
protected CloudAgentLoggingHandler getLoggingHandler() {
return super.getLoggingHandler();
}
protected void addGitRemote(CloudGitApplication application) throws ServerRuntimeException {
doGitRemote(getRemoteName(), application, "add", CloudBundle.getText("failed.add.remote", getRemoteName()));
}
protected void resetGitRemote(CloudGitApplication application) throws ServerRuntimeException {
doGitRemote(getRemoteName(), application, "set-url", CloudBundle.getText("failed.reset.remote", getRemoteName()));
}
protected void doGitRemote(String remoteName,
CloudGitApplication application,
String subCommand,
String failMessage)
throws ServerRuntimeException {
try {
final GitSimpleHandler handler = new GitSimpleHandler(getProject(), myContentRoot, GitCommand.REMOTE);
handler.setSilent(false);
handler.addParameters(subCommand, remoteName, application.getGitUrl());
handler.run();
getRepository().update();
if (handler.getExitCode() != 0) {
throw new ServerRuntimeException(failMessage);
}
}
catch (VcsException e) {
throw new ServerRuntimeException(e);
}
}
@Nullable
protected GitRepository findRepository() {
if (myRepository != null) {
return myRepository;
}
myRepository = myGitRepositoryManager.getRepositoryForRoot(myContentRoot);
return myRepository;
}
protected void refreshApplicationRepository() {
GitInit.refreshAndConfigureVcsMappings(getProject(), getRepositoryRoot(), getRepositoryRootFile().getAbsolutePath());
}
protected void pushApplication(@NotNull CloudGitApplication application) throws ServerRuntimeException {
push(application, getRepository(), getRemoteName());
}
protected void push(@NotNull CloudGitApplication application, @NotNull GitRepository repository, @NotNull String remote)
throws ServerRuntimeException {
GitCommandResult gitPushResult
= getGit().push(repository, remote, application.getGitUrl(), "master:master", false, createGitLineHandlerListener());
checkGitResult(gitPushResult);
}
@NotNull
protected GitRepository getRepository() throws ServerRuntimeException {
GitRepository repository = findRepository();
if (repository == null) {
throw new ServerRuntimeException("Unable to find GIT repository for module root: " + myContentRoot);
}
return repository;
}
protected void fetch() throws ServerRuntimeException {
final VirtualFile contentRoot = getRepositoryRoot();
GitRepository repository = getRepository();
final GitLineHandler fetchHandler = new GitLineHandler(getProject(), contentRoot, GitCommand.FETCH);
fetchHandler.setUrl(getApplication().getGitUrl());
fetchHandler.setSilent(false);
fetchHandler.addParameters(getRemoteName());
fetchHandler.addLineListener(createGitLineHandlerListener());
performRemoteGitTask(fetchHandler, CloudBundle.getText("fetching.application", getCloudName()));
repository.update();
}
protected void add() throws ServerRuntimeException {
try {
GitFileUtils.addFiles(getProject(), myContentRoot, myContentRoot);
}
catch (VcsException e) {
throw new ServerRuntimeException(e);
}
}
protected void commit() throws ServerRuntimeException {
commit(COMMIT_MESSAGE);
}
protected void commit(String message) throws ServerRuntimeException {
try {
if (GitUtil.hasLocalChanges(true, getProject(), myContentRoot)) {
GitSimpleHandler handler = new GitSimpleHandler(getProject(), myContentRoot, GitCommand.COMMIT);
handler.setSilent(false);
handler.setStdoutSuppressed(false);
handler.addParameters("-m", message);
handler.endOptions();
handler.run();
}
}
catch (VcsException e) {
throw new ServerRuntimeException(e);
}
}
protected void performRemoteGitTask(final GitLineHandler handler, String title) throws ServerRuntimeException {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText(title);
handler.addLineListener(GitStandardProgressAnalyzer.createListener(indicator));
}
GitCommandResult result = myGit.runCommand(handler);
if (!result.success()) {
getLoggingHandler().println(result.getErrorOutputAsJoinedString());
if (result.getException() != null) {
throw new ServerRuntimeException(result.getException());
}
throw new ServerRuntimeException(result.getErrorOutputAsJoinedString());
}
}
protected void refreshContentRoot() {
ApplicationManager.getApplication().invokeLater(() -> getRepositoryRoot().refresh(false, true));
}
public void fetchAndRefresh() throws ServerRuntimeException {
fetch();
refreshContentRoot();
}
private String getRemoteName() {
if (myRemoteName == null) {
myRemoteName = myDefaultRemoteName;
}
return myRemoteName;
}
private String getCloudName() {
return myCloudName;
}
protected CloudGitApplication findApplication() throws ServerRuntimeException {
return getAgentTaskExecutor().execute(() -> getDeployment().findApplication());
}
protected CloudGitApplication getApplication() throws ServerRuntimeException {
CloudGitApplication application = findApplication();
if (application == null) {
throw new ServerRuntimeException("Can't find the application: " + getApplicationName());
}
return application;
}
protected CloudGitApplication createApplication() throws ServerRuntimeException {
return getAgentTaskExecutor().execute(() -> getDeployment().createApplication());
}
public CloudGitApplication findApplication4Repository() throws ServerRuntimeException {
final List<String> repositoryUrls = new ArrayList<>();
for (GitRemote remote : getRepository().getRemotes()) {
for (String url : remote.getUrls()) {
repositoryUrls.add(url);
}
}
return getAgentTaskExecutor().execute(() -> getDeployment().findApplication4Repository(ArrayUtil.toStringArray(repositoryUrls)));
}
public class CloneJob {
public File cloneToTemp(String gitUrl) throws ServerRuntimeException {
File cloneDir;
try {
cloneDir = FileUtil.createTempDirectory("cloud", "clone");
}
catch (IOException e) {
throw new ServerRuntimeException(e);
}
File cloneDirParent = cloneDir.getParentFile();
String cloneDirName = cloneDir.getName();
doClone(cloneDirParent, cloneDirName, gitUrl);
return cloneDir;
}
public void cloneToModule(String gitUrl) throws ServerRuntimeException {
File cloneDir = cloneToTemp(gitUrl);
try {
FileUtil.copyDir(cloneDir, getRepositoryRootFile());
}
catch (IOException e) {
throw new ServerRuntimeException(e);
}
refreshApplicationRepository();
}
public void doClone(File cloneDirParent, String cloneDirName, String gitUrl) throws ServerRuntimeException {
GitCommandResult gitCloneResult
= getGit().clone(getProject(), cloneDirParent, gitUrl, cloneDirName, createGitLineHandlerListener());
checkGitResult(gitCloneResult);
}
}
public class CloneJobWithRemote extends CloneJob {
public void doClone(File cloneDirParent, String cloneDirName, String gitUrl) throws ServerRuntimeException {
final GitLineHandler handler = new GitLineHandler(getProject(), cloneDirParent, GitCommand.CLONE);
handler.setSilent(false);
handler.setStdoutSuppressed(false);
handler.setUrl(gitUrl);
handler.addParameters("--progress");
handler.addParameters(gitUrl);
handler.addParameters(cloneDirName);
handler.addParameters("-o");
handler.addParameters(getRemoteName());
handler.addLineListener(createGitLineHandlerListener());
performRemoteGitTask(handler, CloudBundle.getText("cloning.existing.application", getCloudName()));
}
}
}
| plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java | package com.intellij.remoteServer.util;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.remoteServer.agent.util.CloudAgentLoggingHandler;
import com.intellij.remoteServer.agent.util.CloudGitApplication;
import com.intellij.remoteServer.configuration.deployment.DeploymentSource;
import com.intellij.remoteServer.runtime.deployment.DeploymentLogManager;
import com.intellij.remoteServer.runtime.deployment.DeploymentTask;
import com.intellij.util.ArrayUtil;
import com.intellij.util.concurrency.Semaphore;
import git4idea.GitUtil;
import git4idea.actions.GitInit;
import git4idea.commands.*;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import git4idea.util.GitFileUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author michael.golubev
*/
public class CloudGitDeploymentRuntime extends CloudDeploymentRuntime {
private static final Logger LOG = Logger.getInstance("#" + CloudGitDeploymentRuntime.class.getName());
private static final String COMMIT_MESSAGE = "Deploy";
private static final CommitSession NO_COMMIT = new CommitSession() {
@Nullable
@Override
public JComponent getAdditionalConfigurationUI() {
return null;
}
@Nullable
@Override
public JComponent getAdditionalConfigurationUI(Collection<Change> changes, String commitMessage) {
return null;
}
@Override
public boolean canExecute(Collection<Change> changes, String commitMessage) {
return true;
}
@Override
public void execute(Collection<Change> changes, String commitMessage) {
}
@Override
public void executionCanceled() {
}
@Override
public String getHelpId() {
return null;
}
};
private static final List<CommitExecutor> ourCommitExecutors = Arrays.asList(
new CommitExecutor() {
@Nls
@Override
public String getActionText() {
return "Commit and Push";
}
@NotNull
@Override
public CommitSession createCommitSession() {
return CommitSession.VCS_COMMIT;
}
},
new CommitExecutorBase() {
@Nls
@Override
public String getActionText() {
return "Push without Commit";
}
@NotNull
@Override
public CommitSession createCommitSession() {
return NO_COMMIT;
}
@Override
public boolean areChangesRequired() {
return false;
}
}
);
private final GitRepositoryManager myGitRepositoryManager;
private final Git myGit;
private final VirtualFile myContentRoot;
private final File myRepositoryRootFile;
private final String myDefaultRemoteName;
private final ChangeListManagerEx myChangeListManager;
private String myRemoteName;
private final String myCloudName;
private GitRepository myRepository;
public CloudGitDeploymentRuntime(CloudMultiSourceServerRuntimeInstance serverRuntime,
DeploymentSource source,
File repositoryRoot,
DeploymentTask<? extends CloudDeploymentNameConfiguration> task,
DeploymentLogManager logManager,
String defaultRemoteName,
String cloudName) throws ServerRuntimeException {
super(serverRuntime, source, task, logManager);
myDefaultRemoteName = defaultRemoteName;
myCloudName = cloudName;
myRepositoryRootFile = repositoryRoot;
VirtualFile contentRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(myRepositoryRootFile);
LOG.assertTrue(contentRoot != null, "Repository root is not found");
myContentRoot = contentRoot;
Project project = getProject();
myGitRepositoryManager = GitUtil.getRepositoryManager(project);
myGit = ServiceManager.getService(Git.class);
if (myGit == null) {
throw new ServerRuntimeException("Can't initialize GIT");
}
myChangeListManager = ChangeListManagerImpl.getInstanceImpl(project);
}
@Override
public CloudGitApplication deploy() throws ServerRuntimeException {
CloudGitApplication application = findOrCreateApplication();
deployApplication(application);
return application;
}
private void deployApplication(CloudGitApplication application) throws ServerRuntimeException {
boolean firstDeploy = findRepository() == null;
GitRepository repository = findOrCreateRepository();
addOrResetGitRemote(application, repository);
final LocalChangeList activeChangeList = myChangeListManager.getDefaultChangeList();
if (activeChangeList != null && !firstDeploy) {
commitWithChangesDialog(activeChangeList);
}
else {
add();
commit();
}
repository.update();
pushApplication(application);
}
protected void commitWithChangesDialog(final @NotNull LocalChangeList activeChangeList)
throws ServerRuntimeException {
Collection<Change> changes = activeChangeList.getChanges();
final List<Change> relevantChanges = new ArrayList<>();
for (Change change : changes) {
if (isRelevant(change.getBeforeRevision()) || isRelevant(change.getAfterRevision())) {
relevantChanges.add(change);
}
}
final Semaphore commitSemaphore = new Semaphore();
commitSemaphore.down();
final Ref<Boolean> commitSucceeded = new Ref<>(false);
Boolean commitStarted = runOnEdt(() -> CommitChangeListDialog.commitChanges(getProject(),
relevantChanges,
activeChangeList,
ourCommitExecutors,
false,
COMMIT_MESSAGE,
new CommitResultHandler() {
@Override
public void onSuccess(@NotNull String commitMessage) {
commitSucceeded.set(true);
commitSemaphore.up();
}
@Override
public void onFailure() {
commitSemaphore.up();
}
},
false));
if (commitStarted != null && commitStarted) {
commitSemaphore.waitFor();
if (!commitSucceeded.get()) {
getRepository().update();
throw new ServerRuntimeException("Commit failed");
}
}
else {
throw new ServerRuntimeException("Deploy interrupted");
}
}
private boolean isRelevant(ContentRevision contentRevision) throws ServerRuntimeException {
if (contentRevision == null) {
return false;
}
GitRepository repository = getRepository();
VirtualFile affectedFile = contentRevision.getFile().getVirtualFile();
return affectedFile != null && VfsUtilCore.isAncestor(repository.getRoot(), affectedFile, false);
}
private static <T> T runOnEdt(final Computable<T> computable) {
final Ref<T> result = new Ref<>();
ApplicationManager.getApplication().invokeAndWait(() -> result.set(computable.compute()), ModalityState.any());
return result.get();
}
public boolean isDeployed() throws ServerRuntimeException {
return findApplication() != null;
}
public CloudGitApplication findOrCreateApplication() throws ServerRuntimeException {
CloudGitApplication application = findApplication();
if (application == null) {
application = createApplication();
}
return application;
}
public void addOrResetGitRemote(CloudGitApplication application, GitRepository repository) throws ServerRuntimeException {
String gitUrl = application.getGitUrl();
if (myRemoteName == null) {
for (GitRemote gitRemote : repository.getRemotes()) {
if (gitRemote.getUrls().contains(gitUrl)) {
myRemoteName = gitRemote.getName();
return;
}
}
}
GitRemote gitRemote = GitUtil.findRemoteByName(repository, getRemoteName());
if (gitRemote == null) {
addGitRemote(application);
}
else if (!gitRemote.getUrls().contains(gitUrl)) {
resetGitRemote(application);
}
}
public GitRepository findOrCreateRepository() throws ServerRuntimeException {
GitRepository repository = findRepository();
if (repository == null) {
getLoggingHandler().println("Initializing git repository...");
GitCommandResult gitInitResult = getGit().init(getProject(), getRepositoryRoot(), createGitLineHandlerListener());
checkGitResult(gitInitResult);
refreshApplicationRepository();
repository = getRepository();
}
return repository;
}
public void downloadExistingApplication() throws ServerRuntimeException {
new CloneJobWithRemote().cloneToModule(getApplication().getGitUrl());
getRepository().update();
refreshContentRoot();
}
protected Git getGit() {
return myGit;
}
protected VirtualFile getRepositoryRoot() {
return myContentRoot;
}
protected File getRepositoryRootFile() {
return myRepositoryRootFile;
}
protected static void checkGitResult(GitCommandResult commandResult) throws ServerRuntimeException {
if (!commandResult.success()) {
Throwable exception = commandResult.getException();
if (exception != null) {
LOG.info(exception);
throw new ServerRuntimeException(exception);
}
else {
throw new ServerRuntimeException(commandResult.getErrorOutputAsJoinedString());
}
}
}
protected GitLineHandlerListener createGitLineHandlerListener() {
return new GitLineHandlerAdapter() {
@Override
public void onLineAvailable(String line, Key outputType) {
getLoggingHandler().println(line);
}
};
}
@Override
protected CloudAgentLoggingHandler getLoggingHandler() {
return super.getLoggingHandler();
}
protected void addGitRemote(CloudGitApplication application) throws ServerRuntimeException {
doGitRemote(getRemoteName(), application, "add", CloudBundle.getText("failed.add.remote", getRemoteName()));
}
protected void resetGitRemote(CloudGitApplication application) throws ServerRuntimeException {
doGitRemote(getRemoteName(), application, "set-url", CloudBundle.getText("failed.reset.remote", getRemoteName()));
}
protected void doGitRemote(String remoteName,
CloudGitApplication application,
String subCommand,
String failMessage)
throws ServerRuntimeException {
try {
final GitSimpleHandler handler = new GitSimpleHandler(getProject(), myContentRoot, GitCommand.REMOTE);
handler.setSilent(false);
handler.addParameters(subCommand, remoteName, application.getGitUrl());
handler.run();
getRepository().update();
if (handler.getExitCode() != 0) {
throw new ServerRuntimeException(failMessage);
}
}
catch (VcsException e) {
throw new ServerRuntimeException(e);
}
}
@Nullable
protected GitRepository findRepository() {
if (myRepository != null) {
return myRepository;
}
myRepository = myGitRepositoryManager.getRepositoryForRoot(myContentRoot);
return myRepository;
}
protected void refreshApplicationRepository() {
GitInit.refreshAndConfigureVcsMappings(getProject(), getRepositoryRoot(), getRepositoryRootFile().getAbsolutePath());
}
protected void pushApplication(@NotNull CloudGitApplication application) throws ServerRuntimeException {
push(application, getRepository(), getRemoteName());
}
protected void push(@NotNull CloudGitApplication application, @NotNull GitRepository repository, @NotNull String remote)
throws ServerRuntimeException {
GitCommandResult gitPushResult
= getGit().push(repository, remote, application.getGitUrl(), "master:master", false, createGitLineHandlerListener());
checkGitResult(gitPushResult);
}
@NotNull
protected GitRepository getRepository() throws ServerRuntimeException {
GitRepository repository = findRepository();
if (repository == null) {
throw new ServerRuntimeException("Unable to find GIT repository for module root: " + myContentRoot);
}
return repository;
}
protected void fetch() throws ServerRuntimeException {
final VirtualFile contentRoot = getRepositoryRoot();
GitRepository repository = getRepository();
final GitLineHandler fetchHandler = new GitLineHandler(getProject(), contentRoot, GitCommand.FETCH);
fetchHandler.setUrl(getApplication().getGitUrl());
fetchHandler.setSilent(false);
fetchHandler.addParameters(getRemoteName());
fetchHandler.addLineListener(createGitLineHandlerListener());
performRemoteGitTask(fetchHandler, CloudBundle.getText("fetching.application", getCloudName()));
repository.update();
}
protected void add() throws ServerRuntimeException {
try {
GitFileUtils.addFiles(getProject(), myContentRoot, myContentRoot);
}
catch (VcsException e) {
throw new ServerRuntimeException(e);
}
}
protected void commit() throws ServerRuntimeException {
commit(COMMIT_MESSAGE);
}
protected void commit(String message) throws ServerRuntimeException {
try {
if (GitUtil.hasLocalChanges(true, getProject(), myContentRoot)) {
GitSimpleHandler handler = new GitSimpleHandler(getProject(), myContentRoot, GitCommand.COMMIT);
handler.setSilent(false);
handler.setStdoutSuppressed(false);
handler.addParameters("-m", message);
handler.endOptions();
handler.run();
}
}
catch (VcsException e) {
throw new ServerRuntimeException(e);
}
}
protected void performRemoteGitTask(final GitLineHandler handler, String title) throws ServerRuntimeException {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText(title);
handler.addLineListener(GitStandardProgressAnalyzer.createListener(indicator));
}
GitCommandResult result = myGit.runCommand(handler);
if (!result.success()) {
getLoggingHandler().println(result.getErrorOutputAsJoinedString());
if (result.getException() != null) {
throw new ServerRuntimeException(result.getException());
}
throw new ServerRuntimeException(result.getErrorOutputAsJoinedString());
}
}
protected void refreshContentRoot() {
ApplicationManager.getApplication().invokeLater(() -> getRepositoryRoot().refresh(false, true));
}
public void fetchAndRefresh() throws ServerRuntimeException {
fetch();
refreshContentRoot();
}
private String getRemoteName() {
if (myRemoteName == null) {
myRemoteName = myDefaultRemoteName;
}
return myRemoteName;
}
private String getCloudName() {
return myCloudName;
}
protected CloudGitApplication findApplication() throws ServerRuntimeException {
return getAgentTaskExecutor().execute(() -> getDeployment().findApplication());
}
protected CloudGitApplication getApplication() throws ServerRuntimeException {
CloudGitApplication application = findApplication();
if (application == null) {
throw new ServerRuntimeException("Can't find the application: " + getApplicationName());
}
return application;
}
protected CloudGitApplication createApplication() throws ServerRuntimeException {
return getAgentTaskExecutor().execute(() -> getDeployment().createApplication());
}
public CloudGitApplication findApplication4Repository() throws ServerRuntimeException {
final List<String> repositoryUrls = new ArrayList<>();
for (GitRemote remote : getRepository().getRemotes()) {
for (String url : remote.getUrls()) {
repositoryUrls.add(url);
}
}
return getAgentTaskExecutor().execute(() -> getDeployment().findApplication4Repository(ArrayUtil.toStringArray(repositoryUrls)));
}
public class CloneJob {
public File cloneToTemp(String gitUrl) throws ServerRuntimeException {
File cloneDir;
try {
cloneDir = FileUtil.createTempDirectory("cloud", "clone");
}
catch (IOException e) {
throw new ServerRuntimeException(e);
}
File cloneDirParent = cloneDir.getParentFile();
String cloneDirName = cloneDir.getName();
doClone(cloneDirParent, cloneDirName, gitUrl);
return cloneDir;
}
public void cloneToModule(String gitUrl) throws ServerRuntimeException {
File cloneDir = cloneToTemp(gitUrl);
try {
FileUtil.copyDir(cloneDir, getRepositoryRootFile());
}
catch (IOException e) {
throw new ServerRuntimeException(e);
}
refreshApplicationRepository();
}
public void doClone(File cloneDirParent, String cloneDirName, String gitUrl) throws ServerRuntimeException {
GitCommandResult gitCloneResult
= getGit().clone(getProject(), cloneDirParent, gitUrl, cloneDirName, createGitLineHandlerListener());
checkGitResult(gitCloneResult);
}
}
public class CloneJobWithRemote extends CloneJob {
public void doClone(File cloneDirParent, String cloneDirName, String gitUrl) throws ServerRuntimeException {
final GitLineHandler handler = new GitLineHandler(getProject(), cloneDirParent, GitCommand.CLONE);
handler.setSilent(false);
handler.setStdoutSuppressed(false);
handler.setUrl(gitUrl);
handler.addParameters("--progress");
handler.addParameters(gitUrl);
handler.addParameters(cloneDirName);
handler.addParameters("-o");
handler.addParameters(getRemoteName());
handler.addLineListener(createGitLineHandlerListener());
performRemoteGitTask(handler, CloudBundle.getText("cloning.existing.application", getCloudName()));
}
}
}
| show cloudgit commit dialog in a write-safe context (EA-89532 - assert: FileDocumentManagerImpl.saveAllDocuments)
| plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java | show cloudgit commit dialog in a write-safe context (EA-89532 - assert: FileDocumentManagerImpl.saveAllDocuments) |
|
Java | apache-2.0 | 26c3ad065b1001138b8ce1011fd61d787195730b | 0 | cthiebaud/jaxrs-analyzer,cthiebaud/jaxrs-analyzer,sdaschner/jaxrs-analyzer | /*
* Copyright (C) 2015 Sebastian Daschner, sebastian-daschner.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE2.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.sebastian_daschner.jaxrs_analyzer.analysis.bytecode;
import com.sebastian_daschner.jaxrs_analyzer.analysis.bytecode.simulation.MethodPool;
import com.sebastian_daschner.jaxrs_analyzer.analysis.bytecode.simulation.MethodSimulator;
import com.sebastian_daschner.jaxrs_analyzer.model.JavaUtils;
import com.sebastian_daschner.jaxrs_analyzer.model.Types;
import com.sebastian_daschner.jaxrs_analyzer.model.elements.Element;
import com.sebastian_daschner.jaxrs_analyzer.model.elements.HttpResponse;
import com.sebastian_daschner.jaxrs_analyzer.model.elements.JsonValue;
import com.sebastian_daschner.jaxrs_analyzer.model.instructions.Instruction;
import com.sebastian_daschner.jaxrs_analyzer.model.methods.ProjectMethod;
import com.sebastian_daschner.jaxrs_analyzer.model.results.MethodResult;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
/**
* Analyzes JAX-RS resource methods. This class is thread-safe.
*
* @author Sebastian Daschner
*/
class ResourceMethodContentAnalyzer extends MethodContentAnalyzer {
private final Lock lock = new ReentrantLock();
/**
* Analyzes the method (including own project methods).
*
* @param methodResult The method result
*/
void analyze(final MethodResult methodResult) {
lock.lock();
try {
buildPackagePrefix(methodResult.getParentResource().getOriginalClass());
final List<Instruction> visitedInstructions = interpretRelevantInstructions(methodResult.getInstructions());
// find project defined methods in invoke occurrences
final Set<ProjectMethod> projectMethods = findProjectMethods(visitedInstructions);
// add project methods to global method pool
projectMethods.stream().forEach(MethodPool.getInstance()::addProjectMethod);
Element returnedElement = new MethodSimulator().simulate(visitedInstructions);
final String returnType = JavaUtils.getReturnType(methodResult.getOriginalMethodSignature());
// void resource methods are interpreted later; stop analyzing on error
if (Types.PRIMITIVE_VOID.equals(returnType)) {
return;
}
if (returnedElement == null) {
// LogProvider.debug("Non-void method, but no return element returned after analysis");
// happens for abstract methods
return;
// returnedElement = new Element(returnType);
}
final Set<Object> possibleObjects = returnedElement.getPossibleValues().stream().filter(o -> !(o instanceof HttpResponse))
.collect(Collectors.toSet());
// for non-Response methods add a default if there are non-Response objects or none objects at all
if (!Types.RESPONSE.equals(returnType)) {
final HttpResponse defaultResponse = new HttpResponse();
if (Types.OBJECT.equals(returnType))
defaultResponse.getEntityTypes().addAll(returnedElement.getTypes());
else
defaultResponse.getEntityTypes().add(returnType);
possibleObjects.stream().filter(o -> o instanceof JsonValue).map(o -> (JsonValue) o).forEach(defaultResponse.getInlineEntities()::add);
methodResult.getResponses().add(defaultResponse);
}
// add Response results as well
returnedElement.getPossibleValues().stream().filter(o -> o instanceof HttpResponse).map(o -> (HttpResponse) o).forEach(methodResult.getResponses()::add);
} finally {
lock.unlock();
}
}
}
| src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/bytecode/ResourceMethodContentAnalyzer.java | /*
* Copyright (C) 2015 Sebastian Daschner, sebastian-daschner.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE2.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.sebastian_daschner.jaxrs_analyzer.analysis.bytecode;
import com.sebastian_daschner.jaxrs_analyzer.analysis.bytecode.simulation.MethodPool;
import com.sebastian_daschner.jaxrs_analyzer.analysis.bytecode.simulation.MethodSimulator;
import com.sebastian_daschner.jaxrs_analyzer.model.JavaUtils;
import com.sebastian_daschner.jaxrs_analyzer.model.Types;
import com.sebastian_daschner.jaxrs_analyzer.model.elements.Element;
import com.sebastian_daschner.jaxrs_analyzer.model.elements.HttpResponse;
import com.sebastian_daschner.jaxrs_analyzer.model.elements.JsonValue;
import com.sebastian_daschner.jaxrs_analyzer.model.instructions.Instruction;
import com.sebastian_daschner.jaxrs_analyzer.model.methods.ProjectMethod;
import com.sebastian_daschner.jaxrs_analyzer.model.results.MethodResult;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
/**
* Analyzes JAX-RS resource methods. This class is thread-safe.
*
* @author Sebastian Daschner
*/
class ResourceMethodContentAnalyzer extends MethodContentAnalyzer {
private final Lock lock = new ReentrantLock();
private final MethodSimulator methodSimulator = new MethodSimulator();
/**
* Analyzes the method (including own project methods).
*
* @param methodResult The method result
*/
void analyze(final MethodResult methodResult) {
lock.lock();
try {
buildPackagePrefix(methodResult.getParentResource().getOriginalClass());
final List<Instruction> visitedInstructions = interpretRelevantInstructions(methodResult.getInstructions());
// find project defined methods in invoke occurrences
final Set<ProjectMethod> projectMethods = findProjectMethods(visitedInstructions);
// add project methods to global method pool
projectMethods.stream().forEach(MethodPool.getInstance()::addProjectMethod);
Element returnedElement = methodSimulator.simulate(visitedInstructions);
final String returnType = JavaUtils.getReturnType(methodResult.getOriginalMethodSignature());
// void resource methods are interpreted later; stop analyzing on error
if (Types.PRIMITIVE_VOID.equals(returnType)) {
return;
}
if (returnedElement == null) {
// LogProvider.debug("Non-void method, but no return element returned after analysis");
// happens for abstract methods
return;
// returnedElement = new Element(returnType);
}
final Set<Object> possibleObjects = returnedElement.getPossibleValues().stream().filter(o -> !(o instanceof HttpResponse))
.collect(Collectors.toSet());
// for non-Response methods add a default if there are non-Response objects or none objects at all
if (!Types.RESPONSE.equals(returnType)) {
final HttpResponse defaultResponse = new HttpResponse();
if (Types.OBJECT.equals(returnType))
defaultResponse.getEntityTypes().addAll(returnedElement.getTypes());
else
defaultResponse.getEntityTypes().add(returnType);
possibleObjects.stream().filter(o -> o instanceof JsonValue).map(o -> (JsonValue) o).forEach(defaultResponse.getInlineEntities()::add);
methodResult.getResponses().add(defaultResponse);
}
// add Response results as well
returnedElement.getPossibleValues().stream().filter(o -> o instanceof HttpResponse).map(o -> (HttpResponse) o).forEach(methodResult.getResponses()::add);
} finally {
lock.unlock();
}
}
}
| fixed minor merge-bug
| src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/bytecode/ResourceMethodContentAnalyzer.java | fixed minor merge-bug |
|
Java | apache-2.0 | b79c0aa5bec3cf294dbc58ff66dbaa8686229654 | 0 | peterl1084/framework,Flamenco/vaadin,Darsstar/framework,magi42/vaadin,jdahlstrom/vaadin.react,magi42/vaadin,mittop/vaadin,cbmeeks/vaadin,bmitc/vaadin,synes/vaadin,shahrzadmn/vaadin,Scarlethue/vaadin,travisfw/vaadin,kironapublic/vaadin,mstahv/framework,Peppe/vaadin,cbmeeks/vaadin,Peppe/vaadin,Peppe/vaadin,asashour/framework,Darsstar/framework,peterl1084/framework,Darsstar/framework,oalles/vaadin,kironapublic/vaadin,bmitc/vaadin,fireflyc/vaadin,jdahlstrom/vaadin.react,magi42/vaadin,synes/vaadin,synes/vaadin,Legioth/vaadin,synes/vaadin,jdahlstrom/vaadin.react,Darsstar/framework,mstahv/framework,oalles/vaadin,sitexa/vaadin,carrchang/vaadin,fireflyc/vaadin,jdahlstrom/vaadin.react,travisfw/vaadin,mstahv/framework,magi42/vaadin,fireflyc/vaadin,asashour/framework,travisfw/vaadin,oalles/vaadin,carrchang/vaadin,Flamenco/vaadin,travisfw/vaadin,mstahv/framework,Scarlethue/vaadin,cbmeeks/vaadin,udayinfy/vaadin,Scarlethue/vaadin,magi42/vaadin,Legioth/vaadin,travisfw/vaadin,Scarlethue/vaadin,asashour/framework,bmitc/vaadin,cbmeeks/vaadin,sitexa/vaadin,Flamenco/vaadin,mittop/vaadin,oalles/vaadin,Legioth/vaadin,Darsstar/framework,Peppe/vaadin,Peppe/vaadin,synes/vaadin,shahrzadmn/vaadin,udayinfy/vaadin,mstahv/framework,kironapublic/vaadin,sitexa/vaadin,kironapublic/vaadin,carrchang/vaadin,Legioth/vaadin,oalles/vaadin,fireflyc/vaadin,mittop/vaadin,shahrzadmn/vaadin,Flamenco/vaadin,kironapublic/vaadin,asashour/framework,peterl1084/framework,shahrzadmn/vaadin,peterl1084/framework,udayinfy/vaadin,asashour/framework,peterl1084/framework,mittop/vaadin,Legioth/vaadin,Scarlethue/vaadin,udayinfy/vaadin,udayinfy/vaadin,jdahlstrom/vaadin.react,fireflyc/vaadin,bmitc/vaadin,sitexa/vaadin,sitexa/vaadin,carrchang/vaadin,shahrzadmn/vaadin | /*
* Copyright 2000-2013 Vaadin Ltd.
*
* 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.vaadin.client;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.gwt.core.client.Duration;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ClosingEvent;
import com.google.gwt.user.client.Window.ClosingHandler;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.ApplicationConfiguration.ErrorMessage;
import com.vaadin.client.ResourceLoader.ResourceLoadEvent;
import com.vaadin.client.ResourceLoader.ResourceLoadListener;
import com.vaadin.client.communication.HasJavaScriptConnectorHelper;
import com.vaadin.client.communication.JavaScriptMethodInvocation;
import com.vaadin.client.communication.JsonDecoder;
import com.vaadin.client.communication.JsonEncoder;
import com.vaadin.client.communication.PushConnection;
import com.vaadin.client.communication.RpcManager;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.extensions.AbstractExtensionConnector;
import com.vaadin.client.metadata.ConnectorBundleLoader;
import com.vaadin.client.metadata.Method;
import com.vaadin.client.metadata.NoDataException;
import com.vaadin.client.metadata.Property;
import com.vaadin.client.metadata.Type;
import com.vaadin.client.metadata.TypeData;
import com.vaadin.client.ui.AbstractComponentConnector;
import com.vaadin.client.ui.AbstractConnector;
import com.vaadin.client.ui.VContextMenu;
import com.vaadin.client.ui.VNotification;
import com.vaadin.client.ui.VNotification.HideEvent;
import com.vaadin.client.ui.dd.VDragAndDropManager;
import com.vaadin.client.ui.ui.UIConnector;
import com.vaadin.client.ui.window.WindowConnector;
import com.vaadin.shared.AbstractComponentState;
import com.vaadin.shared.ApplicationConstants;
import com.vaadin.shared.Version;
import com.vaadin.shared.communication.LegacyChangeVariablesInvocation;
import com.vaadin.shared.communication.MethodInvocation;
import com.vaadin.shared.communication.SharedState;
import com.vaadin.shared.ui.ui.UIConstants;
/**
* This is the client side communication "engine", managing client-server
* communication with its server side counterpart
* com.vaadin.server.VaadinService.
*
* Client-side connectors receive updates from the corresponding server-side
* connector (typically component) as state updates or RPC calls. The connector
* has the possibility to communicate back with its server side counter part
* through RPC calls.
*
* TODO document better
*
* Entry point classes (widgetsets) define <code>onModuleLoad()</code>.
*/
public class ApplicationConnection {
/**
* Helper used to return two values when updating the connector hierarchy.
*/
private static class ConnectorHierarchyUpdateResult {
/**
* Needed at a later point when the created events are fired
*/
private JsArrayObject<ConnectorHierarchyChangeEvent> events = JavaScriptObject
.createArray().cast();
/**
* Needed to know where captions might need to get updated
*/
private FastStringSet parentChangedIds = FastStringSet.create();
}
public static final String MODIFIED_CLASSNAME = "v-modified";
public static final String DISABLED_CLASSNAME = "v-disabled";
public static final String REQUIRED_CLASSNAME_EXT = "-required";
public static final String ERROR_CLASSNAME_EXT = "-error";
public static final char VAR_BURST_SEPARATOR = '\u001d';
public static final char VAR_ESCAPE_CHARACTER = '\u001b';
/**
* A string that, if found in a non-JSON response to a UIDL request, will
* cause the browser to refresh the page. If followed by a colon, optional
* whitespace, and a URI, causes the browser to synchronously load the URI.
*
* <p>
* This allows, for instance, a servlet filter to redirect the application
* to a custom login page when the session expires. For example:
* </p>
*
* <pre>
* if (sessionExpired) {
* response.setHeader("Content-Type", "text/html");
* response.getWriter().write(
* myLoginPageHtml + "<!-- Vaadin-Refresh: "
* + request.getContextPath() + " -->");
* }
* </pre>
*/
public static final String UIDL_REFRESH_TOKEN = "Vaadin-Refresh";
// will hold the CSRF token once received
private String csrfToken = "init";
private final HashMap<String, String> resourcesMap = new HashMap<String, String>();
/**
* The pending method invocations that will be send to the server by
* {@link #sendPendingCommand}. The key is defined differently based on
* whether the method invocation is enqueued with lastonly. With lastonly
* enabled, the method signature ( {@link MethodInvocation#getLastOnlyTag()}
* ) is used as the key to make enable removing a previously enqueued
* invocation. Without lastonly, an incremental id based on
* {@link #lastInvocationTag} is used to get unique values.
*/
private LinkedHashMap<String, MethodInvocation> pendingInvocations = new LinkedHashMap<String, MethodInvocation>();
private int lastInvocationTag = 0;
private WidgetSet widgetSet;
private VContextMenu contextMenu = null;
private final UIConnector uIConnector;
protected boolean applicationRunning = false;
private boolean hasActiveRequest = false;
/**
* Some browsers cancel pending XHR requests when a request that might
* navigate away from the page starts (indicated by a beforeunload event).
* In that case, we should just send the request again without displaying
* any error.
*/
private boolean retryCanceledActiveRequest = false;
/**
* Webkit will ignore outgoing requests while waiting for a response to a
* navigation event (indicated by a beforeunload event). When this happens,
* we should keep trying to send the request every now and then until there
* is a response or until it throws an exception saying that it is already
* being sent.
*/
private boolean webkitMaybeIgnoringRequests = false;
protected boolean cssLoaded = false;
/** Parameters for this application connection loaded from the web-page */
private ApplicationConfiguration configuration;
/** List of pending variable change bursts that must be submitted in order */
private final ArrayList<LinkedHashMap<String, MethodInvocation>> pendingBursts = new ArrayList<LinkedHashMap<String, MethodInvocation>>();
/** Timer for automatic refirect to SessionExpiredURL */
private Timer redirectTimer;
/** redirectTimer scheduling interval in seconds */
private int sessionExpirationInterval;
private Date requestStartTime;
private boolean validatingLayouts = false;
private final LayoutManager layoutManager;
private final RpcManager rpcManager;
private PushConnection push;
/**
* If responseHandlingLocks contains any objects, response handling is
* suspended until the collection is empty or a timeout has occurred.
*/
private Set<Object> responseHandlingLocks = new HashSet<Object>();
/**
* Data structure holding information about pending UIDL messages.
*/
private class PendingUIDLMessage {
private Date start;
private String jsonText;
private ValueMap json;
public PendingUIDLMessage(Date start, String jsonText, ValueMap json) {
this.start = start;
this.jsonText = jsonText;
this.json = json;
}
public Date getStart() {
return start;
}
public String getJsonText() {
return jsonText;
}
public ValueMap getJson() {
return json;
}
}
/** Contains all UIDL messages received while response handling is suspended */
private List<PendingUIDLMessage> pendingUIDLMessages = new ArrayList<PendingUIDLMessage>();
/** The max timeout that response handling may be suspended */
private static final int MAX_SUSPENDED_TIMEOUT = 5000;
/** Event bus for communication events */
private EventBus eventBus = GWT.create(SimpleEventBus.class);
private int lastResponseId = -1;
/**
* The communication handler methods are called at certain points during
* communication with the server. This allows for making add-ons that keep
* track of different aspects of the communication.
*/
public interface CommunicationHandler extends EventHandler {
void onRequestStarting(RequestStartingEvent e);
void onResponseHandlingStarted(ResponseHandlingStartedEvent e);
void onResponseHandlingEnded(ResponseHandlingEndedEvent e);
}
public static class RequestStartingEvent extends ApplicationConnectionEvent {
public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
public RequestStartingEvent(ApplicationConnection connection) {
super(connection);
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<CommunicationHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(CommunicationHandler handler) {
handler.onRequestStarting(this);
}
}
public static class ResponseHandlingEndedEvent extends
ApplicationConnectionEvent {
public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
public ResponseHandlingEndedEvent(ApplicationConnection connection) {
super(connection);
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<CommunicationHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(CommunicationHandler handler) {
handler.onResponseHandlingEnded(this);
}
}
public static abstract class ApplicationConnectionEvent extends
GwtEvent<CommunicationHandler> {
private ApplicationConnection connection;
protected ApplicationConnectionEvent(ApplicationConnection connection) {
this.connection = connection;
}
public ApplicationConnection getConnection() {
return connection;
}
}
public static class ResponseHandlingStartedEvent extends
ApplicationConnectionEvent {
public ResponseHandlingStartedEvent(ApplicationConnection connection) {
super(connection);
}
public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
@Override
public com.google.gwt.event.shared.GwtEvent.Type<CommunicationHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(CommunicationHandler handler) {
handler.onResponseHandlingStarted(this);
}
}
/**
* Allows custom handling of communication errors.
*/
public interface CommunicationErrorHandler {
/**
* Called when a communication error has occurred. Returning
* <code>true</code> from this method suppresses error handling.
*
* @param details
* A string describing the error.
* @param statusCode
* The HTTP status code (e.g. 404, etc).
* @return true if the error reporting should be suppressed, false to
* perform normal error reporting.
*/
public boolean onError(String details, int statusCode);
}
private CommunicationErrorHandler communicationErrorDelegate = null;
private VLoadingIndicator loadingIndicator;
public static class MultiStepDuration extends Duration {
private int previousStep = elapsedMillis();
public void logDuration(String message) {
logDuration(message, 0);
}
public void logDuration(String message, int minDuration) {
int currentTime = elapsedMillis();
int stepDuration = currentTime - previousStep;
if (stepDuration >= minDuration) {
VConsole.log(message + ": " + stepDuration + " ms");
}
previousStep = currentTime;
}
}
public ApplicationConnection() {
// Assuming UI data is eagerly loaded
ConnectorBundleLoader.get().loadBundle(
ConnectorBundleLoader.EAGER_BUNDLE_NAME, null);
uIConnector = GWT.create(UIConnector.class);
rpcManager = GWT.create(RpcManager.class);
layoutManager = GWT.create(LayoutManager.class);
layoutManager.setConnection(this);
tooltip = GWT.create(VTooltip.class);
loadingIndicator = GWT.create(VLoadingIndicator.class);
loadingIndicator.setConnection(this);
}
public void init(WidgetSet widgetSet, ApplicationConfiguration cnf) {
VConsole.log("Starting application " + cnf.getRootPanelId());
VConsole.log("Using theme: " + cnf.getThemeName());
VConsole.log("Vaadin application servlet version: "
+ cnf.getServletVersion());
if (!cnf.getServletVersion().equals(Version.getFullVersion())) {
VConsole.error("Warning: your widget set seems to be built with a different "
+ "version than the one used on server. Unexpected "
+ "behavior may occur.");
}
this.widgetSet = widgetSet;
configuration = cnf;
ComponentLocator componentLocator = new ComponentLocator(this);
String appRootPanelName = cnf.getRootPanelId();
// remove the end (window name) of autogenerated rootpanel id
appRootPanelName = appRootPanelName.replaceFirst("-\\d+$", "");
initializeTestbenchHooks(componentLocator, appRootPanelName);
initializeClientHooks();
uIConnector.init(cnf.getRootPanelId(), this);
tooltip.setOwner(uIConnector.getWidget());
getLoadingIndicator().show();
scheduleHeartbeat();
Window.addWindowClosingHandler(new ClosingHandler() {
@Override
public void onWindowClosing(ClosingEvent event) {
/*
* Set some flags to avoid potential problems with XHR requests,
* see javadocs of the flags for details
*/
if (hasActiveRequest()) {
retryCanceledActiveRequest = true;
}
webkitMaybeIgnoringRequests = true;
}
});
}
/**
* Starts this application. Don't call this method directly - it's called by
* {@link ApplicationConfiguration#startNextApplication()}, which should be
* called once this application has started (first response received) or
* failed to start. This ensures that the applications are started in order,
* to avoid session-id problems.
*
*/
public void start() {
String jsonText = configuration.getUIDL();
if (jsonText == null) {
// inital UIDL not in DOM, request later
repaintAll();
} else {
// Update counter so TestBench knows something is still going on
hasActiveRequest = true;
// initial UIDL provided in DOM, continue as if returned by request
handleJSONText(jsonText, -1);
}
}
private native void initializeTestbenchHooks(
ComponentLocator componentLocator, String TTAppId)
/*-{
var ap = this;
var client = {};
client.isActive = $entry(function() {
return [email protected]::hasActiveRequest()()
|| [email protected]::isExecutingDeferredCommands()();
});
var vi = [email protected]::getVersionInfo()();
if (vi) {
client.getVersionInfo = function() {
return vi;
}
}
client.getProfilingData = $entry(function() {
var pd = [
[email protected]::lastProcessingTime,
[email protected]::totalProcessingTime
];
pd = pd.concat([email protected]::serverTimingInfo);
pd[pd.length] = [email protected]::bootstrapTime;
return pd;
});
client.getElementByPath = $entry(function(id) {
return [email protected]::getElementByPath(Ljava/lang/String;)(id);
});
client.getPathForElement = $entry(function(element) {
return [email protected]::getPathForElement(Lcom/google/gwt/user/client/Element;)(element);
});
client.initializing = false;
$wnd.vaadin.clients[TTAppId] = client;
}-*/;
private static native final int calculateBootstrapTime()
/*-{
if ($wnd.performance && $wnd.performance.timing) {
return (new Date).getTime() - $wnd.performance.timing.responseStart;
} else {
// performance.timing not supported
return -1;
}
}-*/;
/**
* Helper for tt initialization
*/
private JavaScriptObject getVersionInfo() {
return configuration.getVersionInfoJSObject();
}
/**
* Publishes a JavaScript API for mash-up applications.
* <ul>
* <li><code>vaadin.forceSync()</code> sends pending variable changes, in
* effect synchronizing the server and client state. This is done for all
* applications on host page.</li>
* <li><code>vaadin.postRequestHooks</code> is a map of functions which gets
* called after each XHR made by vaadin application. Note, that it is
* attaching js functions responsibility to create the variable like this:
*
* <code><pre>
* if(!vaadin.postRequestHooks) {vaadin.postRequestHooks = new Object();}
* postRequestHooks.myHook = function(appId) {
* if(appId == "MyAppOfInterest") {
* // do the staff you need on xhr activity
* }
* }
* </pre></code> First parameter passed to these functions is the identifier
* of Vaadin application that made the request.
* </ul>
*
* TODO make this multi-app aware
*/
private native void initializeClientHooks()
/*-{
var app = this;
var oldSync;
if ($wnd.vaadin.forceSync) {
oldSync = $wnd.vaadin.forceSync;
}
$wnd.vaadin.forceSync = $entry(function() {
if (oldSync) {
oldSync();
}
[email protected]::sendPendingVariableChanges()();
});
var oldForceLayout;
if ($wnd.vaadin.forceLayout) {
oldForceLayout = $wnd.vaadin.forceLayout;
}
$wnd.vaadin.forceLayout = $entry(function() {
if (oldForceLayout) {
oldForceLayout();
}
[email protected]::forceLayout()();
});
}-*/;
/**
* Runs possibly registered client side post request hooks. This is expected
* to be run after each uidl request made by Vaadin application.
*
* @param appId
*/
private static native void runPostRequestHooks(String appId)
/*-{
if ($wnd.vaadin.postRequestHooks) {
for ( var hook in $wnd.vaadin.postRequestHooks) {
if (typeof ($wnd.vaadin.postRequestHooks[hook]) == "function") {
try {
$wnd.vaadin.postRequestHooks[hook](appId);
} catch (e) {
}
}
}
}
}-*/;
/**
* If on Liferay and logged in, ask the client side session management
* JavaScript to extend the session duration.
*
* Otherwise, Liferay client side JavaScript will explicitly expire the
* session even though the server side considers the session to be active.
* See ticket #8305 for more information.
*/
protected native void extendLiferaySession()
/*-{
if ($wnd.Liferay && $wnd.Liferay.Session) {
$wnd.Liferay.Session.extend();
// if the extend banner is visible, hide it
if ($wnd.Liferay.Session.banner) {
$wnd.Liferay.Session.banner.remove();
}
}
}-*/;
/**
* Indicates whether or not there are currently active UIDL requests. Used
* internally to sequence requests properly, seldom needed in Widgets.
*
* @return true if there are active requests
*/
public boolean hasActiveRequest() {
return hasActiveRequest;
}
private String getRepaintAllParameters() {
// collect some client side data that will be sent to server on
// initial uidl request
String nativeBootstrapParameters = getNativeBrowserDetailsParameters(getConfiguration()
.getRootPanelId());
// TODO figure out how client and view size could be used better on
// server. screen size can be accessed via Browser object, but other
// values currently only via transaction listener.
String parameters = ApplicationConstants.URL_PARAMETER_REPAINT_ALL
+ "=1&" + nativeBootstrapParameters;
return parameters;
}
/**
* Gets the browser detail parameters that are sent by the bootstrap
* javascript for two-request initialization.
*
* @param parentElementId
* @return
*/
private static native String getNativeBrowserDetailsParameters(
String parentElementId)
/*-{
return $wnd.vaadin.getBrowserDetailsParameters(parentElementId);
}-*/;
protected void repaintAll() {
makeUidlRequest("", getRepaintAllParameters());
}
/**
* Requests an analyze of layouts, to find inconsistencies. Exclusively used
* for debugging during development.
*/
public void analyzeLayouts() {
String params = getRepaintAllParameters() + "&"
+ ApplicationConstants.PARAM_ANALYZE_LAYOUTS + "=1";
makeUidlRequest("", params);
}
/**
* Sends a request to the server to print details to console that will help
* the developer to locate the corresponding server-side connector in the
* source code.
*
* @param serverConnector
*/
void highlightConnector(ServerConnector serverConnector) {
String params = getRepaintAllParameters() + "&"
+ ApplicationConstants.PARAM_HIGHLIGHT_CONNECTOR + "="
+ serverConnector.getConnectorId();
makeUidlRequest("", params);
}
/**
* Makes an UIDL request to the server.
*
* @param requestData
* Data that is passed to the server.
* @param extraParams
* Parameters that are added as GET parameters to the url.
* Contains key=value pairs joined by & characters or is empty if
* no parameters should be added. Should not start with any
* special character.
*/
protected void makeUidlRequest(final String requestData,
final String extraParams) {
startRequest();
// Security: double cookie submission pattern
final String payload = getCsrfToken() + VAR_BURST_SEPARATOR
+ requestData;
VConsole.log("Making UIDL Request with params: " + payload);
String uri = translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
+ ApplicationConstants.UIDL_PATH + '/');
if (extraParams != null && extraParams.length() > 0) {
uri = addGetParameters(uri, extraParams);
}
uri = addGetParameters(uri, UIConstants.UI_ID_PARAMETER + "="
+ configuration.getUIId());
doUidlRequest(uri, payload);
}
/**
* Sends an asynchronous or synchronous UIDL request to the server using the
* given URI.
*
* @param uri
* The URI to use for the request. May includes GET parameters
* @param payload
* The contents of the request to send
*/
protected void doUidlRequest(final String uri, final String payload) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onError(Request request, Throwable exception) {
handleCommunicationError(exception.getMessage(), -1);
}
private void handleCommunicationError(String details, int statusCode) {
if (!handleErrorInDelegate(details, statusCode)) {
showCommunicationError(details, statusCode);
}
endRequest();
}
@Override
public void onResponseReceived(Request request, Response response) {
VConsole.log("Server visit took "
+ String.valueOf((new Date()).getTime()
- requestStartTime.getTime()) + "ms");
int statusCode = response.getStatusCode();
switch (statusCode) {
case 0:
if (retryCanceledActiveRequest) {
/*
* Request was most likely canceled because the browser
* is maybe navigating away from the page. Just send the
* request again without displaying any error in case
* the navigation isn't carried through.
*/
retryCanceledActiveRequest = false;
doUidlRequest(uri, payload);
} else {
handleCommunicationError(
"Invalid status code 0 (server down?)",
statusCode);
}
return;
case 401:
/*
* Authorization has failed. Could be that the session has
* timed out and the container is redirecting to a login
* page.
*/
showAuthenticationError("");
endRequest();
return;
case 503:
/*
* We'll assume msec instead of the usual seconds. If
* there's no Retry-After header, handle the error like a
* 500, as per RFC 2616 section 10.5.4.
*/
String delay = response.getHeader("Retry-After");
if (delay != null) {
VConsole.log("503, retrying in " + delay + "msec");
(new Timer() {
@Override
public void run() {
doUidlRequest(uri, payload);
}
}).schedule(Integer.parseInt(delay));
return;
}
}
if ((statusCode / 100) == 4) {
// Handle all 4xx errors the same way as (they are
// all permanent errors)
showCommunicationError(
"UIDL could not be read from server. Check servlets mappings. Error code: "
+ statusCode, statusCode);
endRequest();
return;
} else if ((statusCode / 100) == 5) {
// Something's wrong on the server, there's nothing the
// client can do except maybe try again.
handleCommunicationError("Server error. Error code: "
+ statusCode, statusCode);
return;
}
String contentType = response.getHeader("Content-Type");
if (contentType == null
|| !contentType.startsWith("application/json")) {
/*
* A servlet filter or equivalent may have intercepted the
* request and served non-UIDL content (for instance, a
* login page if the session has expired.) If the response
* contains a magic substring, do a synchronous refresh. See
* #8241.
*/
MatchResult refreshToken = RegExp.compile(
UIDL_REFRESH_TOKEN + "(:\\s*(.*?))?(\\s|$)").exec(
response.getText());
if (refreshToken != null) {
redirect(refreshToken.getGroup(2));
return;
}
}
// for(;;);[realjson]
final String jsonText = response.getText().substring(9,
response.getText().length() - 1);
handleJSONText(jsonText, statusCode);
}
};
if (push != null) {
push.push(payload);
} else {
try {
doAjaxRequest(uri, payload, requestCallback);
} catch (RequestException e) {
VConsole.error(e);
endRequest();
}
}
}
/**
* Handles received UIDL JSON text, parsing it, and passing it on to the
* appropriate handlers, while logging timing information.
*
* @param jsonText
* @param statusCode
*/
private void handleJSONText(String jsonText, int statusCode) {
final Date start = new Date();
final ValueMap json;
try {
json = parseJSONResponse(jsonText);
} catch (final Exception e) {
endRequest();
showCommunicationError(e.getMessage() + " - Original JSON-text:"
+ jsonText, statusCode);
return;
}
VConsole.log("JSON parsing took "
+ (new Date().getTime() - start.getTime()) + "ms");
if (applicationRunning) {
handleReceivedJSONMessage(start, jsonText, json);
} else {
applicationRunning = true;
handleWhenCSSLoaded(jsonText, json);
}
}
/**
* Sends an asynchronous UIDL request to the server using the given URI.
*
* @param uri
* The URI to use for the request. May includes GET parameters
* @param payload
* The contents of the request to send
* @param requestCallback
* The handler for the response
* @throws RequestException
* if the request could not be sent
*/
protected void doAjaxRequest(String uri, String payload,
RequestCallback requestCallback) throws RequestException {
RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
// TODO enable timeout
// rb.setTimeoutMillis(timeoutMillis);
// TODO this should be configurable
rb.setHeader("Content-Type", "text/plain;charset=utf-8");
rb.setRequestData(payload);
rb.setCallback(requestCallback);
final Request request = rb.send();
if (webkitMaybeIgnoringRequests && BrowserInfo.get().isWebkit()) {
final int retryTimeout = 250;
new Timer() {
@Override
public void run() {
// Use native js to access private field in Request
if (resendRequest(request) && webkitMaybeIgnoringRequests) {
// Schedule retry if still needed
schedule(retryTimeout);
}
}
}.schedule(retryTimeout);
}
}
private static native boolean resendRequest(Request request)
/*-{
var xhr = [email protected]::xmlHttpRequest
if (xhr.readyState != 1) {
// Progressed to some other readyState -> no longer blocked
return false;
}
try {
xhr.send();
return true;
} catch (e) {
// send throws exception if it is running for real
return false;
}
}-*/;
int cssWaits = 0;
/**
* Holds the time spent rendering the last request
*/
protected int lastProcessingTime;
/**
* Holds the total time spent rendering requests during the lifetime of the
* session.
*/
protected int totalProcessingTime;
/**
* Holds the time it took to load the page and render the first view. 0
* means that this value has not yet been calculated because the first view
* has not yet been rendered (or that your browser is very fast). -1 means
* that the browser does not support the performance.timing feature used to
* get this measurement.
*/
private int bootstrapTime;
/**
* Holds the timing information from the server-side. How much time was
* spent servicing the last request and how much time has been spent
* servicing the session so far. These values are always one request behind,
* since they cannot be measured before the request is finished.
*/
private ValueMap serverTimingInfo;
static final int MAX_CSS_WAITS = 100;
protected void handleWhenCSSLoaded(final String jsonText,
final ValueMap json) {
if (!isCSSLoaded() && cssWaits < MAX_CSS_WAITS) {
(new Timer() {
@Override
public void run() {
handleWhenCSSLoaded(jsonText, json);
}
}).schedule(50);
VConsole.log("Assuming CSS loading is not complete, "
+ "postponing render phase. "
+ "(.v-loading-indicator height == 0)");
cssWaits++;
} else {
cssLoaded = true;
handleReceivedJSONMessage(new Date(), jsonText, json);
if (cssWaits >= MAX_CSS_WAITS) {
VConsole.error("CSS files may have not loaded properly.");
}
}
}
/**
* Checks whether or not the CSS is loaded. By default checks the size of
* the loading indicator element.
*
* @return
*/
protected boolean isCSSLoaded() {
return cssLoaded
|| getLoadingIndicator().getElement().getOffsetHeight() != 0;
}
/**
* Shows the communication error notification.
*
* @param details
* Optional details for debugging.
* @param statusCode
* The status code returned for the request
*
*/
protected void showCommunicationError(String details, int statusCode) {
VConsole.error("Communication error: " + details);
showError(details, configuration.getCommunicationError());
}
/**
* Shows the authentication error notification.
*
* @param details
* Optional details for debugging.
*/
protected void showAuthenticationError(String details) {
VConsole.error("Authentication error: " + details);
showError(details, configuration.getAuthorizationError());
}
/**
* Shows the session expiration notification.
*
* @param details
* Optional details for debugging.
*/
public void showSessionExpiredError(String details) {
VConsole.error("Session expired: " + details);
showError(details, configuration.getSessionExpiredError());
}
/**
* Shows an error notification.
*
* @param details
* Optional details for debugging.
* @param message
* An ErrorMessage describing the error.
*/
protected void showError(String details, ErrorMessage message) {
showError(details, message.getCaption(), message.getMessage(),
message.getUrl());
}
/**
* Shows the error notification.
*
* @param details
* Optional details for debugging.
*/
private void showError(String details, String caption, String message,
String url) {
StringBuilder html = new StringBuilder();
if (caption != null) {
html.append("<h1>");
html.append(caption);
html.append("</h1>");
}
if (message != null) {
html.append("<p>");
html.append(message);
html.append("</p>");
}
if (html.length() > 0) {
// Add error description
if (details != null) {
html.append("<p><i style=\"font-size:0.7em\">");
html.append(details);
html.append("</i></p>");
}
VNotification n = VNotification.createNotification(1000 * 60 * 45,
uIConnector.getWidget());
n.addEventListener(new NotificationRedirect(url));
n.show(html.toString(), VNotification.CENTERED_TOP,
VNotification.STYLE_SYSTEM);
} else {
redirect(url);
}
}
protected void startRequest() {
if (hasActiveRequest) {
VConsole.error("Trying to start a new request while another is active");
}
hasActiveRequest = true;
requestStartTime = new Date();
loadingIndicator.trigger();
eventBus.fireEvent(new RequestStartingEvent(this));
}
protected void endRequest() {
if (!hasActiveRequest) {
VConsole.error("No active request");
}
// After checkForPendingVariableBursts() there may be a new active
// request, so we must set hasActiveRequest to false before, not after,
// the call. Active requests used to be tracked with an integer counter,
// so setting it after used to work but not with the #8505 changes.
hasActiveRequest = false;
retryCanceledActiveRequest = false;
webkitMaybeIgnoringRequests = false;
if (applicationRunning) {
checkForPendingVariableBursts();
runPostRequestHooks(configuration.getRootPanelId());
}
// deferring to avoid flickering
Scheduler.get().scheduleDeferred(new Command() {
@Override
public void execute() {
if (!hasActiveRequest()) {
getLoadingIndicator().hide();
// If on Liferay and session expiration management is in
// use, extend session duration on each request.
// Doing it here rather than before the request to improve
// responsiveness.
// Postponed until the end of the next request if other
// requests still pending.
extendLiferaySession();
}
}
});
eventBus.fireEvent(new ResponseHandlingEndedEvent(this));
}
/**
* This method is called after applying uidl change set to application.
*
* It will clean current and queued variable change sets. And send next
* change set if it exists.
*/
private void checkForPendingVariableBursts() {
cleanVariableBurst(pendingInvocations);
if (pendingBursts.size() > 0) {
for (LinkedHashMap<String, MethodInvocation> pendingBurst : pendingBursts) {
cleanVariableBurst(pendingBurst);
}
LinkedHashMap<String, MethodInvocation> nextBurst = pendingBursts
.remove(0);
buildAndSendVariableBurst(nextBurst);
}
}
/**
* Cleans given queue of variable changes of such changes that came from
* components that do not exist anymore.
*
* @param variableBurst
*/
private void cleanVariableBurst(
LinkedHashMap<String, MethodInvocation> variableBurst) {
Iterator<MethodInvocation> iterator = variableBurst.values().iterator();
while (iterator.hasNext()) {
String id = iterator.next().getConnectorId();
if (!getConnectorMap().hasConnector(id)
&& !getConnectorMap().isDragAndDropPaintable(id)) {
// variable owner does not exist anymore
iterator.remove();
VConsole.log("Removed variable from removed component: " + id);
}
}
}
/**
* Checks if deferred commands are (potentially) still being executed as a
* result of an update from the server. Returns true if a deferred command
* might still be executing, false otherwise. This will not work correctly
* if a deferred command is added in another deferred command.
* <p>
* Used by the native "client.isActive" function.
* </p>
*
* @return true if deferred commands are (potentially) being executed, false
* otherwise
*/
private boolean isExecutingDeferredCommands() {
Scheduler s = Scheduler.get();
if (s instanceof VSchedulerImpl) {
return ((VSchedulerImpl) s).hasWorkQueued();
} else {
return false;
}
}
/**
* Returns the loading indicator used by this ApplicationConnection
*
* @return The loading indicator for this ApplicationConnection
*/
public VLoadingIndicator getLoadingIndicator() {
return loadingIndicator;
}
/**
* Determines whether or not the loading indicator is showing.
*
* @return true if the loading indicator is visible
* @deprecated As of 7.1. Use {@link #getLoadingIndicator()} and
* {@link VLoadingIndicator#isVisible()}.isVisible() instead.
*/
@Deprecated
public boolean isLoadingIndicatorVisible() {
return getLoadingIndicator().isVisible();
}
private static native ValueMap parseJSONResponse(String jsonText)
/*-{
try {
return JSON.parse(jsonText);
} catch (ignored) {
return eval('(' + jsonText + ')');
}
}-*/;
private void handleReceivedJSONMessage(Date start, String jsonText,
ValueMap json) {
handleUIDLMessage(start, jsonText, json);
}
/**
* Gets the id of the last received response. This id can be used by
* connectors to determine whether new data has been received from the
* server to avoid doing the same calculations multiple times.
* <p>
* No guarantees are made for the structure of the id other than that there
* will be a new unique value every time a new response with data from the
* server is received.
* <p>
* The initial id when no request has yet been processed is -1.
*
* @return and id identifying the response
*/
public int getLastResponseId() {
return lastResponseId;
}
protected void handleUIDLMessage(final Date start, final String jsonText,
final ValueMap json) {
if (!responseHandlingLocks.isEmpty()) {
// Some component is doing something that can't be interrupted
// (e.g. animation that should be smooth). Enqueue the UIDL
// message for later processing.
VConsole.log("Postponing UIDL handling due to lock...");
pendingUIDLMessages.add(new PendingUIDLMessage(start, jsonText,
json));
forceHandleMessage.schedule(MAX_SUSPENDED_TIMEOUT);
return;
}
/*
* Lock response handling to avoid a situation where something pushed
* from the server gets processed while waiting for e.g. lazily loaded
* connectors that are needed for processing the current message.
*/
final Object lock = new Object();
suspendReponseHandling(lock);
VConsole.log("Handling message from server");
eventBus.fireEvent(new ResponseHandlingStartedEvent(this));
// Handle redirect
if (json.containsKey("redirect")) {
String url = json.getValueMap("redirect").getString("url");
VConsole.log("redirecting to " + url);
redirect(url);
return;
}
lastResponseId++;
final MultiStepDuration handleUIDLDuration = new MultiStepDuration();
// Get security key
if (json.containsKey(ApplicationConstants.UIDL_SECURITY_TOKEN_ID)) {
csrfToken = json
.getString(ApplicationConstants.UIDL_SECURITY_TOKEN_ID);
}
VConsole.log(" * Handling resources from server");
if (json.containsKey("resources")) {
ValueMap resources = json.getValueMap("resources");
JsArrayString keyArray = resources.getKeyArray();
int l = keyArray.length();
for (int i = 0; i < l; i++) {
String key = keyArray.get(i);
resourcesMap.put(key, resources.getAsString(key));
}
}
handleUIDLDuration.logDuration(
" * Handling resources from server completed", 10);
VConsole.log(" * Handling type inheritance map from server");
if (json.containsKey("typeInheritanceMap")) {
configuration.addComponentInheritanceInfo(json
.getValueMap("typeInheritanceMap"));
}
handleUIDLDuration.logDuration(
" * Handling type inheritance map from server completed", 10);
VConsole.log("Handling type mappings from server");
if (json.containsKey("typeMappings")) {
configuration.addComponentMappings(
json.getValueMap("typeMappings"), widgetSet);
}
VConsole.log("Handling resource dependencies");
if (json.containsKey("scriptDependencies")) {
loadScriptDependencies(json.getJSStringArray("scriptDependencies"));
}
if (json.containsKey("styleDependencies")) {
loadStyleDependencies(json.getJSStringArray("styleDependencies"));
}
handleUIDLDuration.logDuration(
" * Handling type mappings from server completed", 10);
/*
* Hook for e.g. TestBench to get details about server peformance
*/
if (json.containsKey("timings")) {
serverTimingInfo = json.getValueMap("timings");
}
Command c = new Command() {
@Override
public void execute() {
handleUIDLDuration.logDuration(" * Loading widgets completed",
10);
Profiler.enter("Handling locales");
if (json.containsKey("locales")) {
VConsole.log(" * Handling locales");
// Store locale data
JsArray<ValueMap> valueMapArray = json
.getJSValueMapArray("locales");
LocaleService.addLocales(valueMapArray);
}
Profiler.leave("Handling locales");
Profiler.enter("Handling meta information");
ValueMap meta = null;
if (json.containsKey("meta")) {
VConsole.log(" * Handling meta information");
meta = json.getValueMap("meta");
if (meta.containsKey("repaintAll")) {
prepareRepaintAll();
if (meta.containsKey("invalidLayouts")) {
validatingLayouts = true;
}
}
if (meta.containsKey("timedRedirect")) {
final ValueMap timedRedirect = meta
.getValueMap("timedRedirect");
redirectTimer = new Timer() {
@Override
public void run() {
redirect(timedRedirect.getString("url"));
}
};
sessionExpirationInterval = timedRedirect
.getInt("interval");
}
}
Profiler.leave("Handling meta information");
if (redirectTimer != null) {
redirectTimer.schedule(1000 * sessionExpirationInterval);
}
double processUidlStart = Duration.currentTimeMillis();
// Ensure that all connectors that we are about to update exist
JsArrayString createdConnectorIds = createConnectorsIfNeeded(json);
// Update states, do not fire events
JsArrayObject<StateChangeEvent> pendingStateChangeEvents = updateConnectorState(
json, createdConnectorIds);
// Update hierarchy, do not fire events
ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(json);
// Fire hierarchy change events
sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
updateCaptions(pendingStateChangeEvents,
connectorHierarchyUpdateResult.parentChangedIds);
delegateToWidget(pendingStateChangeEvents);
// Fire state change events.
sendStateChangeEvents(pendingStateChangeEvents);
// Update of legacy (UIDL) style connectors
updateVaadin6StyleConnectors(json);
// Handle any RPC invocations done on the server side
handleRpcInvocations(json);
if (json.containsKey("dd")) {
// response contains data for drag and drop service
VDragAndDropManager.get().handleServerResponse(
json.getValueMap("dd"));
}
unregisterRemovedConnectors();
VConsole.log("handleUIDLMessage: "
+ (Duration.currentTimeMillis() - processUidlStart)
+ " ms");
Profiler.enter("Layout processing");
try {
LayoutManager layoutManager = getLayoutManager();
layoutManager.setEverythingNeedsMeasure();
layoutManager.layoutNow();
} catch (final Throwable e) {
VConsole.error(e);
}
Profiler.leave("Layout processing");
if (ApplicationConfiguration.isDebugMode()) {
Profiler.enter("Dumping state changes to the console");
VConsole.log(" * Dumping state changes to the console");
VConsole.dirUIDL(json, ApplicationConnection.this);
Profiler.leave("Dumping state changes to the console");
}
if (meta != null) {
Profiler.enter("Error handling");
if (meta.containsKey("appError")) {
ValueMap error = meta.getValueMap("appError");
showError(null, error.getString("caption"),
error.getString("message"),
error.getString("url"));
applicationRunning = false;
}
if (validatingLayouts) {
Set<ComponentConnector> zeroHeightComponents = new HashSet<ComponentConnector>();
Set<ComponentConnector> zeroWidthComponents = new HashSet<ComponentConnector>();
findZeroSizeComponents(zeroHeightComponents,
zeroWidthComponents, getUIConnector());
VConsole.printLayoutProblems(meta,
ApplicationConnection.this,
zeroHeightComponents, zeroWidthComponents);
validatingLayouts = false;
}
Profiler.leave("Error handling");
}
// TODO build profiling for widget impl loading time
lastProcessingTime = (int) ((new Date().getTime()) - start
.getTime());
totalProcessingTime += lastProcessingTime;
if (bootstrapTime == 0) {
bootstrapTime = calculateBootstrapTime();
if (Profiler.isEnabled() && bootstrapTime != -1) {
Profiler.logBootstrapTimings();
}
}
VConsole.log(" Processing time was "
+ String.valueOf(lastProcessingTime) + "ms for "
+ jsonText.length() + " characters of JSON");
VConsole.log("Referenced paintables: " + connectorMap.size());
if (meta == null || !meta.containsKey("async")) {
// End the request if the received message was a response,
// not sent asynchronously
endRequest();
}
resumeResponseHandling(lock);
if (Profiler.isEnabled()) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
Profiler.logTimings();
Profiler.reset();
}
});
}
}
/**
* Properly clean up any old stuff to ensure everything is properly
* reinitialized.
*/
private void prepareRepaintAll() {
String uiConnectorId = uIConnector.getConnectorId();
if (uiConnectorId == null) {
// Nothing to clear yet
return;
}
// Create fake server response that says that the uiConnector
// has no children
JSONObject fakeHierarchy = new JSONObject();
fakeHierarchy.put(uiConnectorId, new JSONArray());
JSONObject fakeJson = new JSONObject();
fakeJson.put("hierarchy", fakeHierarchy);
ValueMap fakeValueMap = fakeJson.getJavaScriptObject().cast();
// Update hierarchy based on the fake response
ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(fakeValueMap);
// Send hierarchy events based on the fake update
sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
// Unregister all the old connectors that have now been removed
unregisterRemovedConnectors();
getLayoutManager().cleanMeasuredSizes();
}
private void updateCaptions(
JsArrayObject<StateChangeEvent> pendingStateChangeEvents,
FastStringSet parentChangedIds) {
Profiler.enter("updateCaptions");
/*
* Find all components that might need a caption update based on
* pending state and hierarchy changes
*/
FastStringSet needsCaptionUpdate = FastStringSet.create();
needsCaptionUpdate.addAll(parentChangedIds);
// Find components with potentially changed caption state
int size = pendingStateChangeEvents.size();
for (int i = 0; i < size; i++) {
StateChangeEvent event = pendingStateChangeEvents.get(i);
if (VCaption.mightChange(event)) {
ServerConnector connector = event.getConnector();
needsCaptionUpdate.add(connector.getConnectorId());
}
}
ConnectorMap connectorMap = getConnectorMap();
// Update captions for all suitable candidates
JsArrayString dump = needsCaptionUpdate.dump();
int needsUpdateLength = dump.length();
for (int i = 0; i < needsUpdateLength; i++) {
String childId = dump.get(i);
ServerConnector child = connectorMap.getConnector(childId);
if (child instanceof ComponentConnector
&& ((ComponentConnector) child)
.delegateCaptionHandling()) {
ServerConnector parent = child.getParent();
if (parent instanceof HasComponentsConnector) {
Profiler.enter("HasComponentsConnector.updateCaption");
((HasComponentsConnector) parent)
.updateCaption((ComponentConnector) child);
Profiler.leave("HasComponentsConnector.updateCaption");
}
}
}
Profiler.leave("updateCaptions");
}
private void delegateToWidget(
JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
Profiler.enter("@DelegateToWidget");
VConsole.log(" * Running @DelegateToWidget");
// Keep track of types that have no @DelegateToWidget in their
// state to optimize performance
FastStringSet noOpTypes = FastStringSet.create();
int size = pendingStateChangeEvents.size();
for (int eventIndex = 0; eventIndex < size; eventIndex++) {
StateChangeEvent sce = pendingStateChangeEvents
.get(eventIndex);
ServerConnector connector = sce.getConnector();
if (connector instanceof ComponentConnector) {
String className = connector.getClass().getName();
if (noOpTypes.contains(className)) {
continue;
}
ComponentConnector component = (ComponentConnector) connector;
Type stateType = AbstractConnector
.getStateType(component);
JsArrayString delegateToWidgetProperties = stateType
.getDelegateToWidgetProperties();
if (delegateToWidgetProperties == null) {
noOpTypes.add(className);
continue;
}
int length = delegateToWidgetProperties.length();
for (int i = 0; i < length; i++) {
String propertyName = delegateToWidgetProperties
.get(i);
if (sce.hasPropertyChanged(propertyName)) {
Property property = stateType
.getProperty(propertyName);
String method = property
.getDelegateToWidgetMethodName();
Profiler.enter("doDelegateToWidget");
doDelegateToWidget(component, property, method);
Profiler.leave("doDelegateToWidget");
}
}
}
}
Profiler.leave("@DelegateToWidget");
}
private void doDelegateToWidget(ComponentConnector component,
Property property, String methodName) {
Type type = TypeData.getType(component.getClass());
try {
Type widgetType = type.getMethod("getWidget")
.getReturnType();
Widget widget = component.getWidget();
Object propertyValue = property.getValue(component
.getState());
widgetType.getMethod(methodName).invoke(widget,
propertyValue);
} catch (NoDataException e) {
throw new RuntimeException(
"Missing data needed to invoke @DelegateToWidget for "
+ Util.getSimpleName(component), e);
}
}
/**
* Sends the state change events created while updating the state
* information.
*
* This must be called after hierarchy change listeners have been
* called. At least caption updates for the parent are strange if
* fired from state change listeners and thus calls the parent
* BEFORE the parent is aware of the child (through a
* ConnectorHierarchyChangedEvent)
*
* @param pendingStateChangeEvents
* The events to send
*/
private void sendStateChangeEvents(
JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
Profiler.enter("sendStateChangeEvents");
VConsole.log(" * Sending state change events");
int size = pendingStateChangeEvents.size();
for (int i = 0; i < size; i++) {
StateChangeEvent sce = pendingStateChangeEvents.get(i);
try {
sce.getConnector().fireEvent(sce);
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("sendStateChangeEvents");
}
private void unregisterRemovedConnectors() {
Profiler.enter("unregisterRemovedConnectors");
int unregistered = 0;
JsArrayObject<ServerConnector> currentConnectors = connectorMap
.getConnectorsAsJsArray();
int size = currentConnectors.size();
for (int i = 0; i < size; i++) {
ServerConnector c = currentConnectors.get(i);
if (c.getParent() != null) {
if (!c.getParent().getChildren().contains(c)) {
VConsole.error("ERROR: Connector is connected to a parent but the parent does not contain the connector");
}
} else if (c == getUIConnector()) {
// UIConnector for this connection, leave as-is
} else if (c instanceof WindowConnector
&& getUIConnector().hasSubWindow(
(WindowConnector) c)) {
// Sub window attached to this UIConnector, leave
// as-is
} else {
// The connector has been detached from the
// hierarchy, unregister it and any possible
// children. The UIConnector should never be
// unregistered even though it has no parent.
connectorMap.unregisterConnector(c);
unregistered++;
}
}
VConsole.log("* Unregistered " + unregistered + " connectors");
Profiler.leave("unregisterRemovedConnectors");
}
private JsArrayString createConnectorsIfNeeded(ValueMap json) {
VConsole.log(" * Creating connectors (if needed)");
JsArrayString createdConnectors = JavaScriptObject
.createArray().cast();
if (!json.containsKey("types")) {
return createdConnectors;
}
Profiler.enter("Creating connectors");
ValueMap types = json.getValueMap("types");
JsArrayString keyArray = types.getKeyArray();
for (int i = 0; i < keyArray.length(); i++) {
try {
String connectorId = keyArray.get(i);
ServerConnector connector = connectorMap
.getConnector(connectorId);
if (connector != null) {
continue;
}
int connectorType = Integer.parseInt(types
.getString(connectorId));
Class<? extends ServerConnector> connectorClass = configuration
.getConnectorClassByEncodedTag(connectorType);
// Connector does not exist so we must create it
if (connectorClass != uIConnector.getClass()) {
// create, initialize and register the paintable
Profiler.enter("ApplicationConnection.getConnector");
connector = getConnector(connectorId, connectorType);
Profiler.leave("ApplicationConnection.getConnector");
createdConnectors.push(connectorId);
} else {
// First UIConnector update. Before this the
// UIConnector has been created but not
// initialized as the connector id has not been
// known
connectorMap.registerConnector(connectorId,
uIConnector);
uIConnector.doInit(connectorId,
ApplicationConnection.this);
createdConnectors.push(connectorId);
}
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("Creating connectors");
return createdConnectors;
}
private void updateVaadin6StyleConnectors(ValueMap json) {
Profiler.enter("updateVaadin6StyleConnectors");
JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
int length = changes.length();
VConsole.log(" * Passing UIDL to Vaadin 6 style connectors");
// update paintables
for (int i = 0; i < length; i++) {
try {
final UIDL change = changes.get(i).cast();
final UIDL uidl = change.getChildUIDL(0);
String connectorId = uidl.getId();
final ComponentConnector legacyConnector = (ComponentConnector) connectorMap
.getConnector(connectorId);
if (legacyConnector instanceof Paintable) {
String key = null;
if (Profiler.isEnabled()) {
key = "updateFromUIDL for "
+ Util.getSimpleName(legacyConnector);
Profiler.enter(key);
}
((Paintable) legacyConnector).updateFromUIDL(uidl,
ApplicationConnection.this);
if (Profiler.isEnabled()) {
Profiler.leave(key);
}
} else if (legacyConnector == null) {
VConsole.error("Received update for "
+ uidl.getTag()
+ ", but there is no such paintable ("
+ connectorId + ") rendered.");
} else {
VConsole.error("Server sent Vaadin 6 style updates for "
+ Util.getConnectorString(legacyConnector)
+ " but this is not a Vaadin 6 Paintable");
}
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("updateVaadin6StyleConnectors");
}
private void sendHierarchyChangeEvents(
JsArrayObject<ConnectorHierarchyChangeEvent> events) {
int eventCount = events.size();
if (eventCount == 0) {
return;
}
Profiler.enter("sendHierarchyChangeEvents");
VConsole.log(" * Sending hierarchy change events");
for (int i = 0; i < eventCount; i++) {
ConnectorHierarchyChangeEvent event = events.get(i);
try {
logHierarchyChange(event);
event.getConnector().fireEvent(event);
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("sendHierarchyChangeEvents");
}
private void logHierarchyChange(ConnectorHierarchyChangeEvent event) {
if (true) {
// Always disabled for now. Can be enabled manually
return;
}
VConsole.log("Hierarchy changed for "
+ Util.getConnectorString(event.getConnector()));
String oldChildren = "* Old children: ";
for (ComponentConnector child : event.getOldChildren()) {
oldChildren += Util.getConnectorString(child) + " ";
}
VConsole.log(oldChildren);
String newChildren = "* New children: ";
HasComponentsConnector parent = (HasComponentsConnector) event
.getConnector();
for (ComponentConnector child : parent.getChildComponents()) {
newChildren += Util.getConnectorString(child) + " ";
}
VConsole.log(newChildren);
}
private JsArrayObject<StateChangeEvent> updateConnectorState(
ValueMap json, JsArrayString createdConnectorIds) {
JsArrayObject<StateChangeEvent> events = JavaScriptObject
.createArray().cast();
VConsole.log(" * Updating connector states");
if (!json.containsKey("state")) {
return events;
}
Profiler.enter("updateConnectorState");
FastStringSet remainingNewConnectors = FastStringSet.create();
remainingNewConnectors.addAll(createdConnectorIds);
// set states for all paintables mentioned in "state"
ValueMap states = json.getValueMap("state");
JsArrayString keyArray = states.getKeyArray();
for (int i = 0; i < keyArray.length(); i++) {
try {
String connectorId = keyArray.get(i);
ServerConnector connector = connectorMap
.getConnector(connectorId);
if (null != connector) {
Profiler.enter("updateConnectorState inner loop");
if (Profiler.isEnabled()) {
Profiler.enter("Decode connector state "
+ Util.getSimpleName(connector));
}
JSONObject stateJson = new JSONObject(
states.getJavaScriptObject(connectorId));
if (connector instanceof HasJavaScriptConnectorHelper) {
((HasJavaScriptConnectorHelper) connector)
.getJavascriptConnectorHelper()
.setNativeState(
stateJson.getJavaScriptObject());
}
SharedState state = connector.getState();
Profiler.enter("updateConnectorState decodeValue");
JsonDecoder.decodeValue(new Type(state.getClass()
.getName(), null), stateJson, state,
ApplicationConnection.this);
Profiler.leave("updateConnectorState decodeValue");
if (Profiler.isEnabled()) {
Profiler.leave("Decode connector state "
+ Util.getSimpleName(connector));
}
Profiler.enter("updateConnectorState create event");
boolean isNewConnector = remainingNewConnectors
.contains(connectorId);
if (isNewConnector) {
remainingNewConnectors.remove(connectorId);
}
StateChangeEvent event = new StateChangeEvent(
connector, stateJson, isNewConnector);
events.add(event);
Profiler.leave("updateConnectorState create event");
Profiler.leave("updateConnectorState inner loop");
}
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.enter("updateConnectorState newWithoutState");
// Fire events for properties using the default value for newly
// created connectors even if there were no state changes
JsArrayString dump = remainingNewConnectors.dump();
int length = dump.length();
for (int i = 0; i < length; i++) {
String connectorId = dump.get(i);
ServerConnector connector = connectorMap
.getConnector(connectorId);
StateChangeEvent event = new StateChangeEvent(connector,
new JSONObject(), true);
events.add(event);
}
Profiler.leave("updateConnectorState newWithoutState");
Profiler.leave("updateConnectorState");
return events;
}
/**
* Updates the connector hierarchy and returns a list of events that
* should be fired after update of the hierarchy and the state is
* done.
*
* @param json
* The JSON containing the hierarchy information
* @return A collection of events that should be fired when update
* of hierarchy and state is complete and a list of all
* connectors for which the parent has changed
*/
private ConnectorHierarchyUpdateResult updateConnectorHierarchy(
ValueMap json) {
ConnectorHierarchyUpdateResult result = new ConnectorHierarchyUpdateResult();
VConsole.log(" * Updating connector hierarchy");
if (!json.containsKey("hierarchy")) {
return result;
}
Profiler.enter("updateConnectorHierarchy");
FastStringSet maybeDetached = FastStringSet.create();
ValueMap hierarchies = json.getValueMap("hierarchy");
JsArrayString hierarchyKeys = hierarchies.getKeyArray();
for (int i = 0; i < hierarchyKeys.length(); i++) {
try {
String connectorId = hierarchyKeys.get(i);
ServerConnector parentConnector = connectorMap
.getConnector(connectorId);
JsArrayString childConnectorIds = hierarchies
.getJSStringArray(connectorId);
int childConnectorSize = childConnectorIds.length();
List<ServerConnector> newChildren = new ArrayList<ServerConnector>();
List<ComponentConnector> newComponents = new ArrayList<ComponentConnector>();
for (int connectorIndex = 0; connectorIndex < childConnectorSize; connectorIndex++) {
String childConnectorId = childConnectorIds
.get(connectorIndex);
ServerConnector childConnector = connectorMap
.getConnector(childConnectorId);
if (childConnector == null) {
VConsole.error("Hierarchy claims that "
+ childConnectorId + " is a child for "
+ connectorId + " ("
+ parentConnector.getClass().getName()
+ ") but no connector with id "
+ childConnectorId
+ " has been registered");
continue;
}
newChildren.add(childConnector);
if (childConnector instanceof ComponentConnector) {
newComponents
.add((ComponentConnector) childConnector);
} else if (!(childConnector instanceof AbstractExtensionConnector)) {
throw new IllegalStateException(
Util.getConnectorString(childConnector)
+ " is not a ComponentConnector nor an AbstractExtensionConnector");
}
if (childConnector.getParent() != parentConnector) {
childConnector.setParent(parentConnector);
result.parentChangedIds.add(childConnectorId);
// Not detached even if previously removed from
// parent
maybeDetached.remove(childConnectorId);
}
}
// TODO This check should be done on the server side in
// the future so the hierarchy update is only sent when
// something actually has changed
List<ServerConnector> oldChildren = parentConnector
.getChildren();
boolean actuallyChanged = !Util.collectionsEquals(
oldChildren, newChildren);
if (!actuallyChanged) {
continue;
}
if (parentConnector instanceof HasComponentsConnector) {
HasComponentsConnector ccc = (HasComponentsConnector) parentConnector;
List<ComponentConnector> oldComponents = ccc
.getChildComponents();
if (!Util.collectionsEquals(oldComponents,
newComponents)) {
// Fire change event if the hierarchy has
// changed
ConnectorHierarchyChangeEvent event = GWT
.create(ConnectorHierarchyChangeEvent.class);
event.setOldChildren(oldComponents);
event.setConnector(parentConnector);
ccc.setChildComponents(newComponents);
result.events.add(event);
}
} else if (!newComponents.isEmpty()) {
VConsole.error("Hierachy claims "
+ Util.getConnectorString(parentConnector)
+ " has component children even though it isn't a HasComponentsConnector");
}
parentConnector.setChildren(newChildren);
/*
* Find children removed from this parent and mark for
* removal unless they are already attached to some
* other parent.
*/
for (ServerConnector oldChild : oldChildren) {
if (oldChild.getParent() != parentConnector) {
// Ignore if moved to some other connector
continue;
}
if (!newChildren.contains(oldChild)) {
/*
* Consider child detached for now, will be
* cleared if it is later on added to some other
* parent.
*/
maybeDetached.add(oldChild.getConnectorId());
}
}
} catch (final Throwable e) {
VConsole.error(e);
}
}
/*
* Connector is in maybeDetached at this point if it has been
* removed from its parent but not added to any other parent
*/
JsArrayString maybeDetachedArray = maybeDetached.dump();
for (int i = 0; i < maybeDetachedArray.length(); i++) {
ServerConnector removed = connectorMap
.getConnector(maybeDetachedArray.get(i));
recursivelyDetach(removed, result.events);
}
Profiler.leave("updateConnectorHierarchy");
return result;
}
private void recursivelyDetach(ServerConnector connector,
JsArrayObject<ConnectorHierarchyChangeEvent> events) {
/*
* Reset state in an attempt to keep it consistent with the
* hierarchy. No children and no parent is the initial situation
* for the hierarchy, so changing the state to its initial value
* is the closest we can get without data from the server.
* #10151
*/
try {
Type stateType = AbstractConnector.getStateType(connector);
// Empty state instance to get default property values from
Object defaultState = stateType.createInstance();
SharedState state = connector.getState();
JsArrayObject<Property> properties = stateType
.getPropertiesAsArray();
int size = properties.size();
for (int i = 0; i < size; i++) {
Property property = properties.get(i);
property.setValue(state,
property.getValue(defaultState));
}
} catch (NoDataException e) {
throw new RuntimeException("Can't reset state for "
+ Util.getConnectorString(connector), e);
}
/*
* Recursively detach children to make sure they get
* setParent(null) and hierarchy change events as needed.
*/
for (ServerConnector child : connector.getChildren()) {
/*
* Server doesn't send updated child data for removed
* connectors -> ignore child that still seems to be a child
* of this connector although it has been moved to some part
* of the hierarchy that is not detached.
*/
if (child.getParent() != connector) {
continue;
}
recursivelyDetach(child, events);
}
/*
* Clear child list and parent
*/
connector
.setChildren(Collections.<ServerConnector> emptyList());
connector.setParent(null);
/*
* Create an artificial hierarchy event for containers to give
* it a chance to clean up after its children if it has any
*/
if (connector instanceof HasComponentsConnector) {
HasComponentsConnector ccc = (HasComponentsConnector) connector;
List<ComponentConnector> oldChildren = ccc
.getChildComponents();
if (!oldChildren.isEmpty()) {
/*
* HasComponentsConnector has a separate child component
* list that should also be cleared
*/
ccc.setChildComponents(Collections
.<ComponentConnector> emptyList());
// Create event and add it to the list of pending events
ConnectorHierarchyChangeEvent event = GWT
.create(ConnectorHierarchyChangeEvent.class);
event.setConnector(connector);
event.setOldChildren(oldChildren);
events.add(event);
}
}
}
private void handleRpcInvocations(ValueMap json) {
if (json.containsKey("rpc")) {
Profiler.enter("handleRpcInvocations");
VConsole.log(" * Performing server to client RPC calls");
JSONArray rpcCalls = new JSONArray(
json.getJavaScriptObject("rpc"));
int rpcLength = rpcCalls.size();
for (int i = 0; i < rpcLength; i++) {
try {
JSONArray rpcCall = (JSONArray) rpcCalls.get(i);
rpcManager.parseAndApplyInvocation(rpcCall,
ApplicationConnection.this);
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("handleRpcInvocations");
}
}
};
ApplicationConfiguration.runWhenDependenciesLoaded(c);
}
private void findZeroSizeComponents(
Set<ComponentConnector> zeroHeightComponents,
Set<ComponentConnector> zeroWidthComponents,
ComponentConnector connector) {
Widget widget = connector.getWidget();
ComputedStyle computedStyle = new ComputedStyle(widget.getElement());
if (computedStyle.getIntProperty("height") == 0) {
zeroHeightComponents.add(connector);
}
if (computedStyle.getIntProperty("width") == 0) {
zeroWidthComponents.add(connector);
}
List<ServerConnector> children = connector.getChildren();
for (ServerConnector serverConnector : children) {
if (serverConnector instanceof ComponentConnector) {
findZeroSizeComponents(zeroHeightComponents,
zeroWidthComponents,
(ComponentConnector) serverConnector);
}
}
}
private void loadStyleDependencies(JsArrayString dependencies) {
// Assuming no reason to interpret in a defined order
ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
@Override
public void onLoad(ResourceLoadEvent event) {
ApplicationConfiguration.endDependencyLoading();
}
@Override
public void onError(ResourceLoadEvent event) {
VConsole.error(event.getResourceUrl()
+ " could not be loaded, or the load detection failed because the stylesheet is empty.");
// The show must go on
onLoad(event);
}
};
ResourceLoader loader = ResourceLoader.get();
for (int i = 0; i < dependencies.length(); i++) {
String url = translateVaadinUri(dependencies.get(i));
ApplicationConfiguration.startDependencyLoading();
loader.loadStylesheet(url, resourceLoadListener);
}
}
private void loadScriptDependencies(final JsArrayString dependencies) {
if (dependencies.length() == 0) {
return;
}
// Listener that loads the next when one is completed
ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
@Override
public void onLoad(ResourceLoadEvent event) {
if (dependencies.length() != 0) {
String url = translateVaadinUri(dependencies.shift());
ApplicationConfiguration.startDependencyLoading();
// Load next in chain (hopefully already preloaded)
event.getResourceLoader().loadScript(url, this);
}
// Call start for next before calling end for current
ApplicationConfiguration.endDependencyLoading();
}
@Override
public void onError(ResourceLoadEvent event) {
VConsole.error(event.getResourceUrl() + " could not be loaded.");
// The show must go on
onLoad(event);
}
};
ResourceLoader loader = ResourceLoader.get();
// Start chain by loading first
String url = translateVaadinUri(dependencies.shift());
ApplicationConfiguration.startDependencyLoading();
loader.loadScript(url, resourceLoadListener);
// Preload all remaining
for (int i = 0; i < dependencies.length(); i++) {
String preloadUrl = translateVaadinUri(dependencies.get(i));
loader.preloadResource(preloadUrl, null);
}
}
// Redirect browser, null reloads current page
private static native void redirect(String url)
/*-{
if (url) {
$wnd.location = url;
} else {
$wnd.location.reload(false);
}
}-*/;
private void addVariableToQueue(String connectorId, String variableName,
Object value, boolean immediate) {
boolean lastOnly = !immediate;
// note that type is now deduced from value
addMethodInvocationToQueue(new LegacyChangeVariablesInvocation(
connectorId, variableName, value), lastOnly, lastOnly);
}
/**
* Adds an explicit RPC method invocation to the send queue.
*
* @since 7.0
*
* @param invocation
* RPC method invocation
* @param delayed
* <code>false</code> to trigger sending within a short time
* window (possibly combining subsequent calls to a single
* request), <code>true</code> to let the framework delay sending
* of RPC calls and variable changes until the next non-delayed
* change
* @param lastOnly
* <code>true</code> to remove all previously delayed invocations
* of the same method that were also enqueued with lastonly set
* to <code>true</code>. <code>false</code> to add invocation to
* the end of the queue without touching previously enqueued
* invocations.
*/
public void addMethodInvocationToQueue(MethodInvocation invocation,
boolean delayed, boolean lastOnly) {
String tag;
if (lastOnly) {
tag = invocation.getLastOnlyTag();
assert !tag.matches("\\d+") : "getLastOnlyTag value must have at least one non-digit character";
pendingInvocations.remove(tag);
} else {
tag = Integer.toString(lastInvocationTag++);
}
pendingInvocations.put(tag, invocation);
if (!delayed) {
sendPendingVariableChanges();
}
}
/**
* Removes any pending invocation of the given method from the queue
*
* @param invocation
* The invocation to remove
*/
public void removePendingInvocations(MethodInvocation invocation) {
Iterator<MethodInvocation> iter = pendingInvocations.values()
.iterator();
while (iter.hasNext()) {
MethodInvocation mi = iter.next();
if (mi.equals(invocation)) {
iter.remove();
}
}
}
/**
* This method sends currently queued variable changes to server. It is
* called when immediate variable update must happen.
*
* To ensure correct order for variable changes (due servers multithreading
* or network), we always wait for active request to be handler before
* sending a new one. If there is an active request, we will put varible
* "burst" to queue that will be purged after current request is handled.
*
*/
public void sendPendingVariableChanges() {
if (!deferedSendPending) {
deferedSendPending = true;
Scheduler.get().scheduleFinally(sendPendingCommand);
}
}
private final ScheduledCommand sendPendingCommand = new ScheduledCommand() {
@Override
public void execute() {
deferedSendPending = false;
doSendPendingVariableChanges();
}
};
private boolean deferedSendPending = false;
private void doSendPendingVariableChanges() {
if (applicationRunning) {
if (hasActiveRequest() || (push != null && !push.isActive())) {
// skip empty queues if there are pending bursts to be sent
if (pendingInvocations.size() > 0 || pendingBursts.size() == 0) {
pendingBursts.add(pendingInvocations);
pendingInvocations = new LinkedHashMap<String, MethodInvocation>();
// Keep tag string short
lastInvocationTag = 0;
}
} else {
buildAndSendVariableBurst(pendingInvocations);
}
}
}
/**
* Build the variable burst and send it to server.
*
* When sync is forced, we also force sending of all pending variable-bursts
* at the same time. This is ok as we can assume that DOM will never be
* updated after this.
*
* @param pendingInvocations
* List of RPC method invocations to send
*/
private void buildAndSendVariableBurst(
LinkedHashMap<String, MethodInvocation> pendingInvocations) {
final StringBuffer req = new StringBuffer();
while (!pendingInvocations.isEmpty()) {
if (ApplicationConfiguration.isDebugMode()) {
Util.logVariableBurst(this, pendingInvocations.values());
}
JSONArray reqJson = new JSONArray();
for (MethodInvocation invocation : pendingInvocations.values()) {
JSONArray invocationJson = new JSONArray();
invocationJson.set(0,
new JSONString(invocation.getConnectorId()));
invocationJson.set(1,
new JSONString(invocation.getInterfaceName()));
invocationJson.set(2,
new JSONString(invocation.getMethodName()));
JSONArray paramJson = new JSONArray();
Type[] parameterTypes = null;
if (!isLegacyVariableChange(invocation)
&& !isJavascriptRpc(invocation)) {
try {
Type type = new Type(invocation.getInterfaceName(),
null);
Method method = type.getMethod(invocation
.getMethodName());
parameterTypes = method.getParameterTypes();
} catch (NoDataException e) {
throw new RuntimeException("No type data for "
+ invocation.toString(), e);
}
}
for (int i = 0; i < invocation.getParameters().length; ++i) {
// TODO non-static encoder?
Type type = null;
if (parameterTypes != null) {
type = parameterTypes[i];
}
Object value = invocation.getParameters()[i];
paramJson.set(i, JsonEncoder.encode(value, type, this));
}
invocationJson.set(3, paramJson);
reqJson.set(reqJson.size(), invocationJson);
}
// escape burst separators (if any)
req.append(escapeBurstContents(reqJson.toString()));
pendingInvocations.clear();
// Keep tag string short
lastInvocationTag = 0;
}
// Include the browser detail parameters if they aren't already sent
String extraParams;
if (!getConfiguration().isBrowserDetailsSent()) {
extraParams = getNativeBrowserDetailsParameters(getConfiguration()
.getRootPanelId());
getConfiguration().setBrowserDetailsSent();
} else {
extraParams = "";
}
if (!getConfiguration().isWidgetsetVersionSent()) {
if (!extraParams.isEmpty()) {
extraParams += "&";
}
String widgetsetVersion = Version.getFullVersion();
extraParams += "v-wsver=" + widgetsetVersion;
getConfiguration().setWidgetsetVersionSent();
}
makeUidlRequest(req.toString(), extraParams);
}
private boolean isJavascriptRpc(MethodInvocation invocation) {
return invocation instanceof JavaScriptMethodInvocation;
}
private boolean isLegacyVariableChange(MethodInvocation invocation) {
return ApplicationConstants.UPDATE_VARIABLE_METHOD.equals(invocation
.getInterfaceName())
&& ApplicationConstants.UPDATE_VARIABLE_METHOD
.equals(invocation.getMethodName());
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
ServerConnector newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
String newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
int newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
long newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
float newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
double newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
boolean newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param map
* the new values to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
Map<String, Object> map, boolean immediate) {
addVariableToQueue(paintableId, variableName, map, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
*
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
*
* A null array is sent as an empty array.
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param values
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
String[] values, boolean immediate) {
addVariableToQueue(paintableId, variableName, values, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
*
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update. </p>
*
* A null array is sent as an empty array.
*
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param values
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
Object[] values, boolean immediate) {
addVariableToQueue(paintableId, variableName, values, immediate);
}
/**
* Encode burst separator characters in a String for transport over the
* network. This protects from separator injection attacks.
*
* @param value
* to encode
* @return encoded value
*/
protected String escapeBurstContents(String value) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < value.length(); ++i) {
char character = value.charAt(i);
switch (character) {
case VAR_ESCAPE_CHARACTER:
// fall-through - escape character is duplicated
case VAR_BURST_SEPARATOR:
result.append(VAR_ESCAPE_CHARACTER);
// encode as letters for easier reading
result.append(((char) (character + 0x30)));
break;
default:
// the char is not a special one - add it to the result as is
result.append(character);
break;
}
}
return result.toString();
}
/**
* Does absolutely nothing. Replaced by {@link LayoutManager}.
*
* @param container
* @deprecated As of 7.0, serves no purpose
*/
@Deprecated
public void runDescendentsLayout(HasWidgets container) {
}
/**
* This will cause re-layouting of all components. Mainly used for
* development. Published to JavaScript.
*/
public void forceLayout() {
Duration duration = new Duration();
layoutManager.forceLayout();
VConsole.log("forceLayout in " + duration.elapsedMillis() + " ms");
}
/**
* Returns false
*
* @param paintable
* @return false, always
* @deprecated As of 7.0, serves no purpose
*/
@Deprecated
private boolean handleComponentRelativeSize(ComponentConnector paintable) {
return false;
}
/**
* Returns false
*
* @param paintable
* @return false, always
* @deprecated As of 7.0, serves no purpose
*/
@Deprecated
public boolean handleComponentRelativeSize(Widget widget) {
return handleComponentRelativeSize(connectorMap.getConnector(widget));
}
@Deprecated
public ComponentConnector getPaintable(UIDL uidl) {
// Non-component connectors shouldn't be painted from legacy connectors
return (ComponentConnector) getConnector(uidl.getId(),
Integer.parseInt(uidl.getTag()));
}
/**
* Get either an existing ComponentConnector or create a new
* ComponentConnector with the given type and id.
*
* If a ComponentConnector with the given id already exists, returns it.
* Otherwise creates and registers a new ComponentConnector of the given
* type.
*
* @param connectorId
* Id of the paintable
* @param connectorType
* Type of the connector, as passed from the server side
*
* @return Either an existing ComponentConnector or a new ComponentConnector
* of the given type
*/
public ServerConnector getConnector(String connectorId, int connectorType) {
if (!connectorMap.hasConnector(connectorId)) {
return createAndRegisterConnector(connectorId, connectorType);
}
return connectorMap.getConnector(connectorId);
}
/**
* Creates a new ServerConnector with the given type and id.
*
* Creates and registers a new ServerConnector of the given type. Should
* never be called with the connector id of an existing connector.
*
* @param connectorId
* Id of the new connector
* @param connectorType
* Type of the connector, as passed from the server side
*
* @return A new ServerConnector of the given type
*/
private ServerConnector createAndRegisterConnector(String connectorId,
int connectorType) {
Profiler.enter("ApplicationConnection.createAndRegisterConnector");
// Create and register a new connector with the given type
ServerConnector p = widgetSet.createConnector(connectorType,
configuration);
connectorMap.registerConnector(connectorId, p);
p.doInit(connectorId, this);
Profiler.leave("ApplicationConnection.createAndRegisterConnector");
return p;
}
/**
* Gets a recource that has been pre-loaded via UIDL, such as custom
* layouts.
*
* @param name
* identifier of the resource to get
* @return the resource
*/
public String getResource(String name) {
return resourcesMap.get(name);
}
/**
* Singleton method to get instance of app's context menu.
*
* @return VContextMenu object
*/
public VContextMenu getContextMenu() {
if (contextMenu == null) {
contextMenu = new VContextMenu();
contextMenu.setOwner(uIConnector.getWidget());
DOM.setElementProperty(contextMenu.getElement(), "id",
"PID_VAADIN_CM");
}
return contextMenu;
}
/**
* Translates custom protocols in UIDL URI's to be recognizable by browser.
* All uri's from UIDL should be routed via this method before giving them
* to browser due URI's in UIDL may contain custom protocols like theme://.
*
* @param uidlUri
* Vaadin URI from uidl
* @return translated URI ready for browser
*/
public String translateVaadinUri(String uidlUri) {
if (uidlUri == null) {
return null;
}
if (uidlUri.startsWith("theme://")) {
final String themeUri = configuration.getThemeUri();
if (themeUri == null) {
VConsole.error("Theme not set: ThemeResource will not be found. ("
+ uidlUri + ")");
}
uidlUri = themeUri + uidlUri.substring(7);
}
if (uidlUri.startsWith(ApplicationConstants.PUBLISHED_PROTOCOL_PREFIX)) {
// getAppUri *should* always end with /
// substring *should* always start with / (published:///foo.bar
// without published://)
uidlUri = ApplicationConstants.APP_PROTOCOL_PREFIX
+ ApplicationConstants.PUBLISHED_FILE_PATH
+ uidlUri
.substring(ApplicationConstants.PUBLISHED_PROTOCOL_PREFIX
.length());
// Let translation of app:// urls take care of the rest
}
if (uidlUri.startsWith(ApplicationConstants.APP_PROTOCOL_PREFIX)) {
String relativeUrl = uidlUri
.substring(ApplicationConstants.APP_PROTOCOL_PREFIX
.length());
ApplicationConfiguration conf = getConfiguration();
String serviceUrl = conf.getServiceUrl();
if (conf.useServiceUrlPathParam()) {
// Should put path in v-resourcePath parameter and append query
// params to base portlet url
String[] parts = relativeUrl.split("\\?", 2);
String path = parts[0];
// If there's a "?" followed by something, append it as a query
// string to the base URL
if (parts.length > 1) {
String appUrlParams = parts[1];
serviceUrl = addGetParameters(serviceUrl, appUrlParams);
}
if (!path.startsWith("/")) {
path = '/' + path;
}
String pathParam = ApplicationConstants.V_RESOURCE_PATH + "="
+ URL.encodeQueryString(path);
serviceUrl = addGetParameters(serviceUrl, pathParam);
uidlUri = serviceUrl;
} else {
uidlUri = serviceUrl + relativeUrl;
}
}
return uidlUri;
}
/**
* Gets the URI for the current theme. Can be used to reference theme
* resources.
*
* @return URI to the current theme
*/
public String getThemeUri() {
return configuration.getThemeUri();
}
/**
* Listens for Notification hide event, and redirects. Used for system
* messages, such as session expired.
*
*/
private class NotificationRedirect implements VNotification.EventListener {
String url;
NotificationRedirect(String url) {
this.url = url;
}
@Override
public void notificationHidden(HideEvent event) {
redirect(url);
}
}
/* Extended title handling */
private final VTooltip tooltip;
private ConnectorMap connectorMap = GWT.create(ConnectorMap.class);
protected String getUidlSecurityKey() {
return getCsrfToken();
}
/**
* Gets the token (aka double submit cookie) that the server uses to protect
* against Cross Site Request Forgery attacks.
*
* @return the CSRF token string
*/
public String getCsrfToken() {
return csrfToken;
}
/**
* Use to notify that the given component's caption has changed; layouts may
* have to be recalculated.
*
* @param component
* the Paintable whose caption has changed
* @deprecated As of 7.0.2, has not had any effect for a long time
*/
@Deprecated
public void captionSizeUpdated(Widget widget) {
// This doesn't do anything, it's just kept here for compatibility
}
/**
* Gets the main view
*
* @return the main view
*/
public UIConnector getUIConnector() {
return uIConnector;
}
/**
* Gets the {@link ApplicationConfiguration} for the current application.
*
* @see ApplicationConfiguration
* @return the configuration for this application
*/
public ApplicationConfiguration getConfiguration() {
return configuration;
}
/**
* Checks if there is a registered server side listener for the event. The
* list of events which has server side listeners is updated automatically
* before the component is updated so the value is correct if called from
* updatedFromUIDL.
*
* @param paintable
* The connector to register event listeners for
* @param eventIdentifier
* The identifier for the event
* @return true if at least one listener has been registered on server side
* for the event identified by eventIdentifier.
* @deprecated As of 7.0. Use
* {@link AbstractComponentState#hasEventListener(String)}
* instead
*/
@Deprecated
public boolean hasEventListeners(ComponentConnector paintable,
String eventIdentifier) {
return paintable.hasEventListener(eventIdentifier);
}
/**
* Adds the get parameters to the uri and returns the new uri that contains
* the parameters.
*
* @param uri
* The uri to which the parameters should be added.
* @param extraParams
* One or more parameters in the format "a=b" or "c=d&e=f". An
* empty string is allowed but will not modify the url.
* @return The modified URI with the get parameters in extraParams added.
*/
public static String addGetParameters(String uri, String extraParams) {
if (extraParams == null || extraParams.length() == 0) {
return uri;
}
// RFC 3986: The query component is indicated by the first question
// mark ("?") character and terminated by a number sign ("#") character
// or by the end of the URI.
String fragment = null;
int hashPosition = uri.indexOf('#');
if (hashPosition != -1) {
// Fragment including "#"
fragment = uri.substring(hashPosition);
// The full uri before the fragment
uri = uri.substring(0, hashPosition);
}
if (uri.contains("?")) {
uri += "&";
} else {
uri += "?";
}
uri += extraParams;
if (fragment != null) {
uri += fragment;
}
return uri;
}
ConnectorMap getConnectorMap() {
return connectorMap;
}
/**
* @deprecated As of 7.0. No longer serves any purpose.
*/
@Deprecated
public void unregisterPaintable(ServerConnector p) {
VConsole.log("unregisterPaintable (unnecessarily) called for "
+ Util.getConnectorString(p));
}
/**
* Get VTooltip instance related to application connection
*
* @return VTooltip instance
*/
public VTooltip getVTooltip() {
return tooltip;
}
/**
* Method provided for backwards compatibility. Duties previously done by
* this method is now handled by the state change event handler in
* AbstractComponentConnector. The only function this method has is to
* return true if the UIDL is a "cached" update.
*
* @param component
* @param uidl
* @param manageCaption
* @deprecated As of 7.0, no longer serves any purpose
* @return
*/
@Deprecated
public boolean updateComponent(Widget component, UIDL uidl,
boolean manageCaption) {
ComponentConnector connector = getConnectorMap()
.getConnector(component);
if (!AbstractComponentConnector.isRealUpdate(uidl)) {
return true;
}
if (!manageCaption) {
VConsole.error(Util.getConnectorString(connector)
+ " called updateComponent with manageCaption=false. The parameter was ignored - override delegateCaption() to return false instead. It is however not recommended to use caption this way at all.");
}
return false;
}
/**
* @deprecated As of 7.0. Use
* {@link AbstractComponentConnector#hasEventListener(String)}
* instead
*/
@Deprecated
public boolean hasEventListeners(Widget widget, String eventIdentifier) {
ComponentConnector connector = getConnectorMap().getConnector(widget);
if (connector == null) {
/*
* No connector will exist in cases where Vaadin widgets have been
* re-used without implementing server<->client communication.
*/
return false;
}
return hasEventListeners(getConnectorMap().getConnector(widget),
eventIdentifier);
}
LayoutManager getLayoutManager() {
return layoutManager;
}
/**
* Schedules a heartbeat request to occur after the configured heartbeat
* interval elapses if the interval is a positive number. Otherwise, does
* nothing.
*
* @see #sendHeartbeat()
* @see ApplicationConfiguration#getHeartbeatInterval()
*/
protected void scheduleHeartbeat() {
final int interval = getConfiguration().getHeartbeatInterval();
if (interval > 0) {
VConsole.log("Scheduling heartbeat in " + interval + " seconds");
new Timer() {
@Override
public void run() {
sendHeartbeat();
}
}.schedule(interval * 1000);
}
}
/**
* Sends a heartbeat request to the server.
* <p>
* Heartbeat requests are used to inform the server that the client-side is
* still alive. If the client page is closed or the connection lost, the
* server will eventually close the inactive UI.
* <p>
* <b>TODO</b>: Improved error handling, like in doUidlRequest().
*
* @see #scheduleHeartbeat()
*/
protected void sendHeartbeat() {
final String uri = addGetParameters(
translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
+ ApplicationConstants.HEARTBEAT_PATH + '/'),
UIConstants.UI_ID_PARAMETER + "="
+ getConfiguration().getUIId());
final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
final RequestCallback callback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
int status = response.getStatusCode();
if (status == Response.SC_OK) {
// TODO Permit retry in some error situations
VConsole.log("Heartbeat response OK");
scheduleHeartbeat();
} else if (status == Response.SC_GONE) {
showSessionExpiredError(null);
} else {
VConsole.error("Failed sending heartbeat to server. Error code: "
+ status);
}
}
@Override
public void onError(Request request, Throwable exception) {
VConsole.error("Exception sending heartbeat: " + exception);
}
};
rb.setCallback(callback);
try {
VConsole.log("Sending heartbeat request...");
rb.send();
} catch (RequestException re) {
callback.onError(null, re);
}
}
/**
* Timer used to make sure that no misbehaving components can delay response
* handling forever.
*/
Timer forceHandleMessage = new Timer() {
@Override
public void run() {
if (responseHandlingLocks.isEmpty()) {
/*
* Timer fired but there's nothing to clear. This can happen
* with IE8 as Timer.cancel is not always effective (see GWT
* issue 8101).
*/
return;
}
VConsole.log("WARNING: reponse handling was never resumed, forcibly removing locks...");
responseHandlingLocks.clear();
handlePendingMessages();
}
};
/**
* This method can be used to postpone rendering of a response for a short
* period of time (e.g. to avoid the rendering process during animation).
*
* @param lock
*/
public void suspendReponseHandling(Object lock) {
responseHandlingLocks.add(lock);
}
/**
* Resumes the rendering process once all locks have been removed.
*
* @param lock
*/
public void resumeResponseHandling(Object lock) {
responseHandlingLocks.remove(lock);
if (responseHandlingLocks.isEmpty()) {
// Cancel timer that breaks the lock
forceHandleMessage.cancel();
if (!pendingUIDLMessages.isEmpty()) {
VConsole.log("No more response handling locks, handling pending requests.");
handlePendingMessages();
}
}
}
/**
* Handles all pending UIDL messages queued while response handling was
* suspended.
*/
private void handlePendingMessages() {
if (!pendingUIDLMessages.isEmpty()) {
/*
* Clear the list before processing enqueued messages to support
* reentrancy
*/
List<PendingUIDLMessage> pendingMessages = pendingUIDLMessages;
pendingUIDLMessages = new ArrayList<PendingUIDLMessage>();
for (PendingUIDLMessage pending : pendingMessages) {
handleReceivedJSONMessage(pending.getStart(),
pending.getJsonText(), pending.getJson());
}
}
}
private boolean handleErrorInDelegate(String details, int statusCode) {
if (communicationErrorDelegate == null) {
return false;
}
return communicationErrorDelegate.onError(details, statusCode);
}
/**
* Sets the delegate that is called whenever a communication error occurrs.
*
* @param delegate
* the delegate.
*/
public void setCommunicationErrorDelegate(CommunicationErrorHandler delegate) {
communicationErrorDelegate = delegate;
}
public void setApplicationRunning(boolean running) {
applicationRunning = running;
}
public boolean isApplicationRunning() {
return applicationRunning;
}
public <H extends EventHandler> HandlerRegistration addHandler(
GwtEvent.Type<H> type, H handler) {
return eventBus.addHandler(type, handler);
}
/**
* Calls {@link ComponentConnector#flush()} on the active connector. Does
* nothing if there is no active (focused) connector.
*/
public void flushActiveConnector() {
ComponentConnector activeConnector = getActiveConnector();
if (activeConnector == null) {
return;
}
activeConnector.flush();
}
/**
* Gets the active connector for focused element in browser.
*
* @return Connector for focused element or null.
*/
private ComponentConnector getActiveConnector() {
Element focusedElement = Util.getFocusedElement();
if (focusedElement == null) {
return null;
}
return Util.getConnectorForElement(this, getUIConnector().getWidget(),
focusedElement);
}
/**
* Sets the status for the push connection.
*
* @param enabled
* <code>true</code> to enable the push connection;
* <code>false</code> to disable the push connection.
*/
public void setPushEnabled(boolean enabled) {
if (enabled && push == null) {
push = GWT.create(PushConnection.class);
push.init(this);
} else if (!enabled && push != null && push.isActive()) {
push.disconnect(new Command() {
@Override
public void execute() {
push = null;
/*
* If push has been enabled again while we were waiting for
* the old connection to disconnect, now is the right time
* to open a new connection
*/
if (uIConnector.getState().pushMode.isEnabled()) {
setPushEnabled(true);
}
/*
* Send anything that was enqueued while we waited for the
* connection to close
*/
if (pendingInvocations.size() > 0) {
sendPendingVariableChanges();
}
}
});
}
}
public void handlePushMessage(String message) {
handleJSONText(message, 200);
}
}
| client/src/com/vaadin/client/ApplicationConnection.java | /*
* Copyright 2000-2013 Vaadin Ltd.
*
* 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.vaadin.client;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.gwt.core.client.Duration;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ClosingEvent;
import com.google.gwt.user.client.Window.ClosingHandler;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.ApplicationConfiguration.ErrorMessage;
import com.vaadin.client.ResourceLoader.ResourceLoadEvent;
import com.vaadin.client.ResourceLoader.ResourceLoadListener;
import com.vaadin.client.communication.HasJavaScriptConnectorHelper;
import com.vaadin.client.communication.JavaScriptMethodInvocation;
import com.vaadin.client.communication.JsonDecoder;
import com.vaadin.client.communication.JsonEncoder;
import com.vaadin.client.communication.PushConnection;
import com.vaadin.client.communication.RpcManager;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.extensions.AbstractExtensionConnector;
import com.vaadin.client.metadata.ConnectorBundleLoader;
import com.vaadin.client.metadata.Method;
import com.vaadin.client.metadata.NoDataException;
import com.vaadin.client.metadata.Property;
import com.vaadin.client.metadata.Type;
import com.vaadin.client.metadata.TypeData;
import com.vaadin.client.ui.AbstractComponentConnector;
import com.vaadin.client.ui.AbstractConnector;
import com.vaadin.client.ui.VContextMenu;
import com.vaadin.client.ui.VNotification;
import com.vaadin.client.ui.VNotification.HideEvent;
import com.vaadin.client.ui.dd.VDragAndDropManager;
import com.vaadin.client.ui.ui.UIConnector;
import com.vaadin.client.ui.window.WindowConnector;
import com.vaadin.shared.AbstractComponentState;
import com.vaadin.shared.ApplicationConstants;
import com.vaadin.shared.Version;
import com.vaadin.shared.communication.LegacyChangeVariablesInvocation;
import com.vaadin.shared.communication.MethodInvocation;
import com.vaadin.shared.communication.SharedState;
import com.vaadin.shared.ui.ui.UIConstants;
/**
* This is the client side communication "engine", managing client-server
* communication with its server side counterpart
* com.vaadin.server.VaadinService.
*
* Client-side connectors receive updates from the corresponding server-side
* connector (typically component) as state updates or RPC calls. The connector
* has the possibility to communicate back with its server side counter part
* through RPC calls.
*
* TODO document better
*
* Entry point classes (widgetsets) define <code>onModuleLoad()</code>.
*/
public class ApplicationConnection {
/**
* Helper used to return two values when updating the connector hierarchy.
*/
private static class ConnectorHierarchyUpdateResult {
/**
* Needed at a later point when the created events are fired
*/
private JsArrayObject<ConnectorHierarchyChangeEvent> events = JavaScriptObject
.createArray().cast();
/**
* Needed to know where captions might need to get updated
*/
private FastStringSet parentChangedIds = FastStringSet.create();
}
public static final String MODIFIED_CLASSNAME = "v-modified";
public static final String DISABLED_CLASSNAME = "v-disabled";
public static final String REQUIRED_CLASSNAME_EXT = "-required";
public static final String ERROR_CLASSNAME_EXT = "-error";
public static final char VAR_BURST_SEPARATOR = '\u001d';
public static final char VAR_ESCAPE_CHARACTER = '\u001b';
/**
* A string that, if found in a non-JSON response to a UIDL request, will
* cause the browser to refresh the page. If followed by a colon, optional
* whitespace, and a URI, causes the browser to synchronously load the URI.
*
* <p>
* This allows, for instance, a servlet filter to redirect the application
* to a custom login page when the session expires. For example:
* </p>
*
* <pre>
* if (sessionExpired) {
* response.setHeader("Content-Type", "text/html");
* response.getWriter().write(
* myLoginPageHtml + "<!-- Vaadin-Refresh: "
* + request.getContextPath() + " -->");
* }
* </pre>
*/
public static final String UIDL_REFRESH_TOKEN = "Vaadin-Refresh";
// will hold the CSRF token once received
private String csrfToken = "init";
private final HashMap<String, String> resourcesMap = new HashMap<String, String>();
/**
* The pending method invocations that will be send to the server by
* {@link #sendPendingCommand}. The key is defined differently based on
* whether the method invocation is enqueued with lastonly. With lastonly
* enabled, the method signature ( {@link MethodInvocation#getLastOnlyTag()}
* ) is used as the key to make enable removing a previously enqueued
* invocation. Without lastonly, an incremental id based on
* {@link #lastInvocationTag} is used to get unique values.
*/
private LinkedHashMap<String, MethodInvocation> pendingInvocations = new LinkedHashMap<String, MethodInvocation>();
private int lastInvocationTag = 0;
private WidgetSet widgetSet;
private VContextMenu contextMenu = null;
private final UIConnector uIConnector;
protected boolean applicationRunning = false;
private boolean hasActiveRequest = false;
/**
* Some browsers cancel pending XHR requests when a request that might
* navigate away from the page starts (indicated by a beforeunload event).
* In that case, we should just send the request again without displaying
* any error.
*/
private boolean retryCanceledActiveRequest = false;
/**
* Webkit will ignore outgoing requests while waiting for a response to a
* navigation event (indicated by a beforeunload event). When this happens,
* we should keep trying to send the request every now and then until there
* is a response or until it throws an exception saying that it is already
* being sent.
*/
private boolean webkitMaybeIgnoringRequests = false;
protected boolean cssLoaded = false;
/** Parameters for this application connection loaded from the web-page */
private ApplicationConfiguration configuration;
/** List of pending variable change bursts that must be submitted in order */
private final ArrayList<LinkedHashMap<String, MethodInvocation>> pendingBursts = new ArrayList<LinkedHashMap<String, MethodInvocation>>();
/** Timer for automatic refirect to SessionExpiredURL */
private Timer redirectTimer;
/** redirectTimer scheduling interval in seconds */
private int sessionExpirationInterval;
private Date requestStartTime;
private boolean validatingLayouts = false;
private final LayoutManager layoutManager;
private final RpcManager rpcManager;
private PushConnection push;
/**
* If responseHandlingLocks contains any objects, response handling is
* suspended until the collection is empty or a timeout has occurred.
*/
private Set<Object> responseHandlingLocks = new HashSet<Object>();
/**
* Data structure holding information about pending UIDL messages.
*/
private class PendingUIDLMessage {
private Date start;
private String jsonText;
private ValueMap json;
public PendingUIDLMessage(Date start, String jsonText, ValueMap json) {
this.start = start;
this.jsonText = jsonText;
this.json = json;
}
public Date getStart() {
return start;
}
public String getJsonText() {
return jsonText;
}
public ValueMap getJson() {
return json;
}
}
/** Contains all UIDL messages received while response handling is suspended */
private List<PendingUIDLMessage> pendingUIDLMessages = new ArrayList<PendingUIDLMessage>();
/** The max timeout that response handling may be suspended */
private static final int MAX_SUSPENDED_TIMEOUT = 5000;
/** Event bus for communication events */
private EventBus eventBus = GWT.create(SimpleEventBus.class);
private int lastResponseId = -1;
/**
* The communication handler methods are called at certain points during
* communication with the server. This allows for making add-ons that keep
* track of different aspects of the communication.
*/
public interface CommunicationHandler extends EventHandler {
void onRequestStarting(RequestStartingEvent e);
void onResponseHandlingStarted(ResponseHandlingStartedEvent e);
void onResponseHandlingEnded(ResponseHandlingEndedEvent e);
}
public static class RequestStartingEvent extends ApplicationConnectionEvent {
public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
public RequestStartingEvent(ApplicationConnection connection) {
super(connection);
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<CommunicationHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(CommunicationHandler handler) {
handler.onRequestStarting(this);
}
}
public static class ResponseHandlingEndedEvent extends
ApplicationConnectionEvent {
public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
public ResponseHandlingEndedEvent(ApplicationConnection connection) {
super(connection);
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<CommunicationHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(CommunicationHandler handler) {
handler.onResponseHandlingEnded(this);
}
}
public static abstract class ApplicationConnectionEvent extends
GwtEvent<CommunicationHandler> {
private ApplicationConnection connection;
protected ApplicationConnectionEvent(ApplicationConnection connection) {
this.connection = connection;
}
public ApplicationConnection getConnection() {
return connection;
}
}
public static class ResponseHandlingStartedEvent extends
ApplicationConnectionEvent {
public ResponseHandlingStartedEvent(ApplicationConnection connection) {
super(connection);
}
public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
@Override
public com.google.gwt.event.shared.GwtEvent.Type<CommunicationHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(CommunicationHandler handler) {
handler.onResponseHandlingStarted(this);
}
}
/**
* Allows custom handling of communication errors.
*/
public interface CommunicationErrorHandler {
/**
* Called when a communication error has occurred. Returning
* <code>true</code> from this method suppresses error handling.
*
* @param details
* A string describing the error.
* @param statusCode
* The HTTP status code (e.g. 404, etc).
* @return true if the error reporting should be suppressed, false to
* perform normal error reporting.
*/
public boolean onError(String details, int statusCode);
}
private CommunicationErrorHandler communicationErrorDelegate = null;
private VLoadingIndicator loadingIndicator;
public static class MultiStepDuration extends Duration {
private int previousStep = elapsedMillis();
public void logDuration(String message) {
logDuration(message, 0);
}
public void logDuration(String message, int minDuration) {
int currentTime = elapsedMillis();
int stepDuration = currentTime - previousStep;
if (stepDuration >= minDuration) {
VConsole.log(message + ": " + stepDuration + " ms");
}
previousStep = currentTime;
}
}
public ApplicationConnection() {
// Assuming UI data is eagerly loaded
ConnectorBundleLoader.get().loadBundle(
ConnectorBundleLoader.EAGER_BUNDLE_NAME, null);
uIConnector = GWT.create(UIConnector.class);
rpcManager = GWT.create(RpcManager.class);
layoutManager = GWT.create(LayoutManager.class);
layoutManager.setConnection(this);
tooltip = GWT.create(VTooltip.class);
loadingIndicator = GWT.create(VLoadingIndicator.class);
loadingIndicator.setConnection(this);
}
public void init(WidgetSet widgetSet, ApplicationConfiguration cnf) {
VConsole.log("Starting application " + cnf.getRootPanelId());
VConsole.log("Using theme: " + cnf.getThemeName());
VConsole.log("Vaadin application servlet version: "
+ cnf.getServletVersion());
if (!cnf.getServletVersion().equals(Version.getFullVersion())) {
VConsole.error("Warning: your widget set seems to be built with a different "
+ "version than the one used on server. Unexpected "
+ "behavior may occur.");
}
this.widgetSet = widgetSet;
configuration = cnf;
ComponentLocator componentLocator = new ComponentLocator(this);
String appRootPanelName = cnf.getRootPanelId();
// remove the end (window name) of autogenerated rootpanel id
appRootPanelName = appRootPanelName.replaceFirst("-\\d+$", "");
initializeTestbenchHooks(componentLocator, appRootPanelName);
initializeClientHooks();
uIConnector.init(cnf.getRootPanelId(), this);
tooltip.setOwner(uIConnector.getWidget());
getLoadingIndicator().trigger();
scheduleHeartbeat();
Window.addWindowClosingHandler(new ClosingHandler() {
@Override
public void onWindowClosing(ClosingEvent event) {
/*
* Set some flags to avoid potential problems with XHR requests,
* see javadocs of the flags for details
*/
if (hasActiveRequest()) {
retryCanceledActiveRequest = true;
}
webkitMaybeIgnoringRequests = true;
}
});
}
/**
* Starts this application. Don't call this method directly - it's called by
* {@link ApplicationConfiguration#startNextApplication()}, which should be
* called once this application has started (first response received) or
* failed to start. This ensures that the applications are started in order,
* to avoid session-id problems.
*
*/
public void start() {
String jsonText = configuration.getUIDL();
if (jsonText == null) {
// inital UIDL not in DOM, request later
repaintAll();
} else {
// Update counter so TestBench knows something is still going on
hasActiveRequest = true;
// initial UIDL provided in DOM, continue as if returned by request
handleJSONText(jsonText, -1);
}
}
private native void initializeTestbenchHooks(
ComponentLocator componentLocator, String TTAppId)
/*-{
var ap = this;
var client = {};
client.isActive = $entry(function() {
return [email protected]::hasActiveRequest()()
|| [email protected]::isExecutingDeferredCommands()();
});
var vi = [email protected]::getVersionInfo()();
if (vi) {
client.getVersionInfo = function() {
return vi;
}
}
client.getProfilingData = $entry(function() {
var pd = [
[email protected]::lastProcessingTime,
[email protected]::totalProcessingTime
];
pd = pd.concat([email protected]::serverTimingInfo);
pd[pd.length] = [email protected]::bootstrapTime;
return pd;
});
client.getElementByPath = $entry(function(id) {
return [email protected]::getElementByPath(Ljava/lang/String;)(id);
});
client.getPathForElement = $entry(function(element) {
return [email protected]::getPathForElement(Lcom/google/gwt/user/client/Element;)(element);
});
client.initializing = false;
$wnd.vaadin.clients[TTAppId] = client;
}-*/;
private static native final int calculateBootstrapTime()
/*-{
if ($wnd.performance && $wnd.performance.timing) {
return (new Date).getTime() - $wnd.performance.timing.responseStart;
} else {
// performance.timing not supported
return -1;
}
}-*/;
/**
* Helper for tt initialization
*/
private JavaScriptObject getVersionInfo() {
return configuration.getVersionInfoJSObject();
}
/**
* Publishes a JavaScript API for mash-up applications.
* <ul>
* <li><code>vaadin.forceSync()</code> sends pending variable changes, in
* effect synchronizing the server and client state. This is done for all
* applications on host page.</li>
* <li><code>vaadin.postRequestHooks</code> is a map of functions which gets
* called after each XHR made by vaadin application. Note, that it is
* attaching js functions responsibility to create the variable like this:
*
* <code><pre>
* if(!vaadin.postRequestHooks) {vaadin.postRequestHooks = new Object();}
* postRequestHooks.myHook = function(appId) {
* if(appId == "MyAppOfInterest") {
* // do the staff you need on xhr activity
* }
* }
* </pre></code> First parameter passed to these functions is the identifier
* of Vaadin application that made the request.
* </ul>
*
* TODO make this multi-app aware
*/
private native void initializeClientHooks()
/*-{
var app = this;
var oldSync;
if ($wnd.vaadin.forceSync) {
oldSync = $wnd.vaadin.forceSync;
}
$wnd.vaadin.forceSync = $entry(function() {
if (oldSync) {
oldSync();
}
[email protected]::sendPendingVariableChanges()();
});
var oldForceLayout;
if ($wnd.vaadin.forceLayout) {
oldForceLayout = $wnd.vaadin.forceLayout;
}
$wnd.vaadin.forceLayout = $entry(function() {
if (oldForceLayout) {
oldForceLayout();
}
[email protected]::forceLayout()();
});
}-*/;
/**
* Runs possibly registered client side post request hooks. This is expected
* to be run after each uidl request made by Vaadin application.
*
* @param appId
*/
private static native void runPostRequestHooks(String appId)
/*-{
if ($wnd.vaadin.postRequestHooks) {
for ( var hook in $wnd.vaadin.postRequestHooks) {
if (typeof ($wnd.vaadin.postRequestHooks[hook]) == "function") {
try {
$wnd.vaadin.postRequestHooks[hook](appId);
} catch (e) {
}
}
}
}
}-*/;
/**
* If on Liferay and logged in, ask the client side session management
* JavaScript to extend the session duration.
*
* Otherwise, Liferay client side JavaScript will explicitly expire the
* session even though the server side considers the session to be active.
* See ticket #8305 for more information.
*/
protected native void extendLiferaySession()
/*-{
if ($wnd.Liferay && $wnd.Liferay.Session) {
$wnd.Liferay.Session.extend();
// if the extend banner is visible, hide it
if ($wnd.Liferay.Session.banner) {
$wnd.Liferay.Session.banner.remove();
}
}
}-*/;
/**
* Indicates whether or not there are currently active UIDL requests. Used
* internally to sequence requests properly, seldom needed in Widgets.
*
* @return true if there are active requests
*/
public boolean hasActiveRequest() {
return hasActiveRequest;
}
private String getRepaintAllParameters() {
// collect some client side data that will be sent to server on
// initial uidl request
String nativeBootstrapParameters = getNativeBrowserDetailsParameters(getConfiguration()
.getRootPanelId());
// TODO figure out how client and view size could be used better on
// server. screen size can be accessed via Browser object, but other
// values currently only via transaction listener.
String parameters = ApplicationConstants.URL_PARAMETER_REPAINT_ALL
+ "=1&" + nativeBootstrapParameters;
return parameters;
}
/**
* Gets the browser detail parameters that are sent by the bootstrap
* javascript for two-request initialization.
*
* @param parentElementId
* @return
*/
private static native String getNativeBrowserDetailsParameters(
String parentElementId)
/*-{
return $wnd.vaadin.getBrowserDetailsParameters(parentElementId);
}-*/;
protected void repaintAll() {
makeUidlRequest("", getRepaintAllParameters());
}
/**
* Requests an analyze of layouts, to find inconsistencies. Exclusively used
* for debugging during development.
*/
public void analyzeLayouts() {
String params = getRepaintAllParameters() + "&"
+ ApplicationConstants.PARAM_ANALYZE_LAYOUTS + "=1";
makeUidlRequest("", params);
}
/**
* Sends a request to the server to print details to console that will help
* the developer to locate the corresponding server-side connector in the
* source code.
*
* @param serverConnector
*/
void highlightConnector(ServerConnector serverConnector) {
String params = getRepaintAllParameters() + "&"
+ ApplicationConstants.PARAM_HIGHLIGHT_CONNECTOR + "="
+ serverConnector.getConnectorId();
makeUidlRequest("", params);
}
/**
* Makes an UIDL request to the server.
*
* @param requestData
* Data that is passed to the server.
* @param extraParams
* Parameters that are added as GET parameters to the url.
* Contains key=value pairs joined by & characters or is empty if
* no parameters should be added. Should not start with any
* special character.
*/
protected void makeUidlRequest(final String requestData,
final String extraParams) {
startRequest();
// Security: double cookie submission pattern
final String payload = getCsrfToken() + VAR_BURST_SEPARATOR
+ requestData;
VConsole.log("Making UIDL Request with params: " + payload);
String uri = translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
+ ApplicationConstants.UIDL_PATH + '/');
if (extraParams != null && extraParams.length() > 0) {
uri = addGetParameters(uri, extraParams);
}
uri = addGetParameters(uri, UIConstants.UI_ID_PARAMETER + "="
+ configuration.getUIId());
doUidlRequest(uri, payload);
}
/**
* Sends an asynchronous or synchronous UIDL request to the server using the
* given URI.
*
* @param uri
* The URI to use for the request. May includes GET parameters
* @param payload
* The contents of the request to send
*/
protected void doUidlRequest(final String uri, final String payload) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onError(Request request, Throwable exception) {
handleCommunicationError(exception.getMessage(), -1);
}
private void handleCommunicationError(String details, int statusCode) {
if (!handleErrorInDelegate(details, statusCode)) {
showCommunicationError(details, statusCode);
}
endRequest();
}
@Override
public void onResponseReceived(Request request, Response response) {
VConsole.log("Server visit took "
+ String.valueOf((new Date()).getTime()
- requestStartTime.getTime()) + "ms");
int statusCode = response.getStatusCode();
switch (statusCode) {
case 0:
if (retryCanceledActiveRequest) {
/*
* Request was most likely canceled because the browser
* is maybe navigating away from the page. Just send the
* request again without displaying any error in case
* the navigation isn't carried through.
*/
retryCanceledActiveRequest = false;
doUidlRequest(uri, payload);
} else {
handleCommunicationError(
"Invalid status code 0 (server down?)",
statusCode);
}
return;
case 401:
/*
* Authorization has failed. Could be that the session has
* timed out and the container is redirecting to a login
* page.
*/
showAuthenticationError("");
endRequest();
return;
case 503:
/*
* We'll assume msec instead of the usual seconds. If
* there's no Retry-After header, handle the error like a
* 500, as per RFC 2616 section 10.5.4.
*/
String delay = response.getHeader("Retry-After");
if (delay != null) {
VConsole.log("503, retrying in " + delay + "msec");
(new Timer() {
@Override
public void run() {
doUidlRequest(uri, payload);
}
}).schedule(Integer.parseInt(delay));
return;
}
}
if ((statusCode / 100) == 4) {
// Handle all 4xx errors the same way as (they are
// all permanent errors)
showCommunicationError(
"UIDL could not be read from server. Check servlets mappings. Error code: "
+ statusCode, statusCode);
endRequest();
return;
} else if ((statusCode / 100) == 5) {
// Something's wrong on the server, there's nothing the
// client can do except maybe try again.
handleCommunicationError("Server error. Error code: "
+ statusCode, statusCode);
return;
}
String contentType = response.getHeader("Content-Type");
if (contentType == null
|| !contentType.startsWith("application/json")) {
/*
* A servlet filter or equivalent may have intercepted the
* request and served non-UIDL content (for instance, a
* login page if the session has expired.) If the response
* contains a magic substring, do a synchronous refresh. See
* #8241.
*/
MatchResult refreshToken = RegExp.compile(
UIDL_REFRESH_TOKEN + "(:\\s*(.*?))?(\\s|$)").exec(
response.getText());
if (refreshToken != null) {
redirect(refreshToken.getGroup(2));
return;
}
}
// for(;;);[realjson]
final String jsonText = response.getText().substring(9,
response.getText().length() - 1);
handleJSONText(jsonText, statusCode);
}
};
if (push != null) {
push.push(payload);
} else {
try {
doAjaxRequest(uri, payload, requestCallback);
} catch (RequestException e) {
VConsole.error(e);
endRequest();
}
}
}
/**
* Handles received UIDL JSON text, parsing it, and passing it on to the
* appropriate handlers, while logging timing information.
*
* @param jsonText
* @param statusCode
*/
private void handleJSONText(String jsonText, int statusCode) {
final Date start = new Date();
final ValueMap json;
try {
json = parseJSONResponse(jsonText);
} catch (final Exception e) {
endRequest();
showCommunicationError(e.getMessage() + " - Original JSON-text:"
+ jsonText, statusCode);
return;
}
VConsole.log("JSON parsing took "
+ (new Date().getTime() - start.getTime()) + "ms");
if (applicationRunning) {
handleReceivedJSONMessage(start, jsonText, json);
} else {
applicationRunning = true;
handleWhenCSSLoaded(jsonText, json);
}
}
/**
* Sends an asynchronous UIDL request to the server using the given URI.
*
* @param uri
* The URI to use for the request. May includes GET parameters
* @param payload
* The contents of the request to send
* @param requestCallback
* The handler for the response
* @throws RequestException
* if the request could not be sent
*/
protected void doAjaxRequest(String uri, String payload,
RequestCallback requestCallback) throws RequestException {
RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
// TODO enable timeout
// rb.setTimeoutMillis(timeoutMillis);
// TODO this should be configurable
rb.setHeader("Content-Type", "text/plain;charset=utf-8");
rb.setRequestData(payload);
rb.setCallback(requestCallback);
final Request request = rb.send();
if (webkitMaybeIgnoringRequests && BrowserInfo.get().isWebkit()) {
final int retryTimeout = 250;
new Timer() {
@Override
public void run() {
// Use native js to access private field in Request
if (resendRequest(request) && webkitMaybeIgnoringRequests) {
// Schedule retry if still needed
schedule(retryTimeout);
}
}
}.schedule(retryTimeout);
}
}
private static native boolean resendRequest(Request request)
/*-{
var xhr = [email protected]::xmlHttpRequest
if (xhr.readyState != 1) {
// Progressed to some other readyState -> no longer blocked
return false;
}
try {
xhr.send();
return true;
} catch (e) {
// send throws exception if it is running for real
return false;
}
}-*/;
int cssWaits = 0;
/**
* Holds the time spent rendering the last request
*/
protected int lastProcessingTime;
/**
* Holds the total time spent rendering requests during the lifetime of the
* session.
*/
protected int totalProcessingTime;
/**
* Holds the time it took to load the page and render the first view. 0
* means that this value has not yet been calculated because the first view
* has not yet been rendered (or that your browser is very fast). -1 means
* that the browser does not support the performance.timing feature used to
* get this measurement.
*/
private int bootstrapTime;
/**
* Holds the timing information from the server-side. How much time was
* spent servicing the last request and how much time has been spent
* servicing the session so far. These values are always one request behind,
* since they cannot be measured before the request is finished.
*/
private ValueMap serverTimingInfo;
static final int MAX_CSS_WAITS = 100;
protected void handleWhenCSSLoaded(final String jsonText,
final ValueMap json) {
if (!isCSSLoaded() && cssWaits < MAX_CSS_WAITS) {
(new Timer() {
@Override
public void run() {
handleWhenCSSLoaded(jsonText, json);
}
}).schedule(50);
VConsole.log("Assuming CSS loading is not complete, "
+ "postponing render phase. "
+ "(.v-loading-indicator height == 0)");
cssWaits++;
} else {
cssLoaded = true;
handleReceivedJSONMessage(new Date(), jsonText, json);
if (cssWaits >= MAX_CSS_WAITS) {
VConsole.error("CSS files may have not loaded properly.");
}
}
}
/**
* Checks whether or not the CSS is loaded. By default checks the size of
* the loading indicator element.
*
* @return
*/
protected boolean isCSSLoaded() {
return cssLoaded
|| getLoadingIndicator().getElement().getOffsetHeight() != 0;
}
/**
* Shows the communication error notification.
*
* @param details
* Optional details for debugging.
* @param statusCode
* The status code returned for the request
*
*/
protected void showCommunicationError(String details, int statusCode) {
VConsole.error("Communication error: " + details);
showError(details, configuration.getCommunicationError());
}
/**
* Shows the authentication error notification.
*
* @param details
* Optional details for debugging.
*/
protected void showAuthenticationError(String details) {
VConsole.error("Authentication error: " + details);
showError(details, configuration.getAuthorizationError());
}
/**
* Shows the session expiration notification.
*
* @param details
* Optional details for debugging.
*/
public void showSessionExpiredError(String details) {
VConsole.error("Session expired: " + details);
showError(details, configuration.getSessionExpiredError());
}
/**
* Shows an error notification.
*
* @param details
* Optional details for debugging.
* @param message
* An ErrorMessage describing the error.
*/
protected void showError(String details, ErrorMessage message) {
showError(details, message.getCaption(), message.getMessage(),
message.getUrl());
}
/**
* Shows the error notification.
*
* @param details
* Optional details for debugging.
*/
private void showError(String details, String caption, String message,
String url) {
StringBuilder html = new StringBuilder();
if (caption != null) {
html.append("<h1>");
html.append(caption);
html.append("</h1>");
}
if (message != null) {
html.append("<p>");
html.append(message);
html.append("</p>");
}
if (html.length() > 0) {
// Add error description
if (details != null) {
html.append("<p><i style=\"font-size:0.7em\">");
html.append(details);
html.append("</i></p>");
}
VNotification n = VNotification.createNotification(1000 * 60 * 45,
uIConnector.getWidget());
n.addEventListener(new NotificationRedirect(url));
n.show(html.toString(), VNotification.CENTERED_TOP,
VNotification.STYLE_SYSTEM);
} else {
redirect(url);
}
}
protected void startRequest() {
if (hasActiveRequest) {
VConsole.error("Trying to start a new request while another is active");
}
hasActiveRequest = true;
requestStartTime = new Date();
loadingIndicator.trigger();
eventBus.fireEvent(new RequestStartingEvent(this));
}
protected void endRequest() {
if (!hasActiveRequest) {
VConsole.error("No active request");
}
// After checkForPendingVariableBursts() there may be a new active
// request, so we must set hasActiveRequest to false before, not after,
// the call. Active requests used to be tracked with an integer counter,
// so setting it after used to work but not with the #8505 changes.
hasActiveRequest = false;
retryCanceledActiveRequest = false;
webkitMaybeIgnoringRequests = false;
if (applicationRunning) {
checkForPendingVariableBursts();
runPostRequestHooks(configuration.getRootPanelId());
}
// deferring to avoid flickering
Scheduler.get().scheduleDeferred(new Command() {
@Override
public void execute() {
if (!hasActiveRequest()) {
getLoadingIndicator().hide();
// If on Liferay and session expiration management is in
// use, extend session duration on each request.
// Doing it here rather than before the request to improve
// responsiveness.
// Postponed until the end of the next request if other
// requests still pending.
extendLiferaySession();
}
}
});
eventBus.fireEvent(new ResponseHandlingEndedEvent(this));
}
/**
* This method is called after applying uidl change set to application.
*
* It will clean current and queued variable change sets. And send next
* change set if it exists.
*/
private void checkForPendingVariableBursts() {
cleanVariableBurst(pendingInvocations);
if (pendingBursts.size() > 0) {
for (LinkedHashMap<String, MethodInvocation> pendingBurst : pendingBursts) {
cleanVariableBurst(pendingBurst);
}
LinkedHashMap<String, MethodInvocation> nextBurst = pendingBursts
.remove(0);
buildAndSendVariableBurst(nextBurst);
}
}
/**
* Cleans given queue of variable changes of such changes that came from
* components that do not exist anymore.
*
* @param variableBurst
*/
private void cleanVariableBurst(
LinkedHashMap<String, MethodInvocation> variableBurst) {
Iterator<MethodInvocation> iterator = variableBurst.values().iterator();
while (iterator.hasNext()) {
String id = iterator.next().getConnectorId();
if (!getConnectorMap().hasConnector(id)
&& !getConnectorMap().isDragAndDropPaintable(id)) {
// variable owner does not exist anymore
iterator.remove();
VConsole.log("Removed variable from removed component: " + id);
}
}
}
/**
* Checks if deferred commands are (potentially) still being executed as a
* result of an update from the server. Returns true if a deferred command
* might still be executing, false otherwise. This will not work correctly
* if a deferred command is added in another deferred command.
* <p>
* Used by the native "client.isActive" function.
* </p>
*
* @return true if deferred commands are (potentially) being executed, false
* otherwise
*/
private boolean isExecutingDeferredCommands() {
Scheduler s = Scheduler.get();
if (s instanceof VSchedulerImpl) {
return ((VSchedulerImpl) s).hasWorkQueued();
} else {
return false;
}
}
/**
* Returns the loading indicator used by this ApplicationConnection
*
* @return The loading indicator for this ApplicationConnection
*/
public VLoadingIndicator getLoadingIndicator() {
return loadingIndicator;
}
/**
* Determines whether or not the loading indicator is showing.
*
* @return true if the loading indicator is visible
* @deprecated As of 7.1. Use {@link #getLoadingIndicator()} and
* {@link VLoadingIndicator#isVisible()}.isVisible() instead.
*/
@Deprecated
public boolean isLoadingIndicatorVisible() {
return getLoadingIndicator().isVisible();
}
private static native ValueMap parseJSONResponse(String jsonText)
/*-{
try {
return JSON.parse(jsonText);
} catch (ignored) {
return eval('(' + jsonText + ')');
}
}-*/;
private void handleReceivedJSONMessage(Date start, String jsonText,
ValueMap json) {
handleUIDLMessage(start, jsonText, json);
}
/**
* Gets the id of the last received response. This id can be used by
* connectors to determine whether new data has been received from the
* server to avoid doing the same calculations multiple times.
* <p>
* No guarantees are made for the structure of the id other than that there
* will be a new unique value every time a new response with data from the
* server is received.
* <p>
* The initial id when no request has yet been processed is -1.
*
* @return and id identifying the response
*/
public int getLastResponseId() {
return lastResponseId;
}
protected void handleUIDLMessage(final Date start, final String jsonText,
final ValueMap json) {
if (!responseHandlingLocks.isEmpty()) {
// Some component is doing something that can't be interrupted
// (e.g. animation that should be smooth). Enqueue the UIDL
// message for later processing.
VConsole.log("Postponing UIDL handling due to lock...");
pendingUIDLMessages.add(new PendingUIDLMessage(start, jsonText,
json));
forceHandleMessage.schedule(MAX_SUSPENDED_TIMEOUT);
return;
}
/*
* Lock response handling to avoid a situation where something pushed
* from the server gets processed while waiting for e.g. lazily loaded
* connectors that are needed for processing the current message.
*/
final Object lock = new Object();
suspendReponseHandling(lock);
VConsole.log("Handling message from server");
eventBus.fireEvent(new ResponseHandlingStartedEvent(this));
// Handle redirect
if (json.containsKey("redirect")) {
String url = json.getValueMap("redirect").getString("url");
VConsole.log("redirecting to " + url);
redirect(url);
return;
}
lastResponseId++;
final MultiStepDuration handleUIDLDuration = new MultiStepDuration();
// Get security key
if (json.containsKey(ApplicationConstants.UIDL_SECURITY_TOKEN_ID)) {
csrfToken = json
.getString(ApplicationConstants.UIDL_SECURITY_TOKEN_ID);
}
VConsole.log(" * Handling resources from server");
if (json.containsKey("resources")) {
ValueMap resources = json.getValueMap("resources");
JsArrayString keyArray = resources.getKeyArray();
int l = keyArray.length();
for (int i = 0; i < l; i++) {
String key = keyArray.get(i);
resourcesMap.put(key, resources.getAsString(key));
}
}
handleUIDLDuration.logDuration(
" * Handling resources from server completed", 10);
VConsole.log(" * Handling type inheritance map from server");
if (json.containsKey("typeInheritanceMap")) {
configuration.addComponentInheritanceInfo(json
.getValueMap("typeInheritanceMap"));
}
handleUIDLDuration.logDuration(
" * Handling type inheritance map from server completed", 10);
VConsole.log("Handling type mappings from server");
if (json.containsKey("typeMappings")) {
configuration.addComponentMappings(
json.getValueMap("typeMappings"), widgetSet);
}
VConsole.log("Handling resource dependencies");
if (json.containsKey("scriptDependencies")) {
loadScriptDependencies(json.getJSStringArray("scriptDependencies"));
}
if (json.containsKey("styleDependencies")) {
loadStyleDependencies(json.getJSStringArray("styleDependencies"));
}
handleUIDLDuration.logDuration(
" * Handling type mappings from server completed", 10);
/*
* Hook for e.g. TestBench to get details about server peformance
*/
if (json.containsKey("timings")) {
serverTimingInfo = json.getValueMap("timings");
}
Command c = new Command() {
@Override
public void execute() {
handleUIDLDuration.logDuration(" * Loading widgets completed",
10);
Profiler.enter("Handling locales");
if (json.containsKey("locales")) {
VConsole.log(" * Handling locales");
// Store locale data
JsArray<ValueMap> valueMapArray = json
.getJSValueMapArray("locales");
LocaleService.addLocales(valueMapArray);
}
Profiler.leave("Handling locales");
Profiler.enter("Handling meta information");
ValueMap meta = null;
if (json.containsKey("meta")) {
VConsole.log(" * Handling meta information");
meta = json.getValueMap("meta");
if (meta.containsKey("repaintAll")) {
prepareRepaintAll();
if (meta.containsKey("invalidLayouts")) {
validatingLayouts = true;
}
}
if (meta.containsKey("timedRedirect")) {
final ValueMap timedRedirect = meta
.getValueMap("timedRedirect");
redirectTimer = new Timer() {
@Override
public void run() {
redirect(timedRedirect.getString("url"));
}
};
sessionExpirationInterval = timedRedirect
.getInt("interval");
}
}
Profiler.leave("Handling meta information");
if (redirectTimer != null) {
redirectTimer.schedule(1000 * sessionExpirationInterval);
}
double processUidlStart = Duration.currentTimeMillis();
// Ensure that all connectors that we are about to update exist
JsArrayString createdConnectorIds = createConnectorsIfNeeded(json);
// Update states, do not fire events
JsArrayObject<StateChangeEvent> pendingStateChangeEvents = updateConnectorState(
json, createdConnectorIds);
// Update hierarchy, do not fire events
ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(json);
// Fire hierarchy change events
sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
updateCaptions(pendingStateChangeEvents,
connectorHierarchyUpdateResult.parentChangedIds);
delegateToWidget(pendingStateChangeEvents);
// Fire state change events.
sendStateChangeEvents(pendingStateChangeEvents);
// Update of legacy (UIDL) style connectors
updateVaadin6StyleConnectors(json);
// Handle any RPC invocations done on the server side
handleRpcInvocations(json);
if (json.containsKey("dd")) {
// response contains data for drag and drop service
VDragAndDropManager.get().handleServerResponse(
json.getValueMap("dd"));
}
unregisterRemovedConnectors();
VConsole.log("handleUIDLMessage: "
+ (Duration.currentTimeMillis() - processUidlStart)
+ " ms");
Profiler.enter("Layout processing");
try {
LayoutManager layoutManager = getLayoutManager();
layoutManager.setEverythingNeedsMeasure();
layoutManager.layoutNow();
} catch (final Throwable e) {
VConsole.error(e);
}
Profiler.leave("Layout processing");
if (ApplicationConfiguration.isDebugMode()) {
Profiler.enter("Dumping state changes to the console");
VConsole.log(" * Dumping state changes to the console");
VConsole.dirUIDL(json, ApplicationConnection.this);
Profiler.leave("Dumping state changes to the console");
}
if (meta != null) {
Profiler.enter("Error handling");
if (meta.containsKey("appError")) {
ValueMap error = meta.getValueMap("appError");
showError(null, error.getString("caption"),
error.getString("message"),
error.getString("url"));
applicationRunning = false;
}
if (validatingLayouts) {
Set<ComponentConnector> zeroHeightComponents = new HashSet<ComponentConnector>();
Set<ComponentConnector> zeroWidthComponents = new HashSet<ComponentConnector>();
findZeroSizeComponents(zeroHeightComponents,
zeroWidthComponents, getUIConnector());
VConsole.printLayoutProblems(meta,
ApplicationConnection.this,
zeroHeightComponents, zeroWidthComponents);
validatingLayouts = false;
}
Profiler.leave("Error handling");
}
// TODO build profiling for widget impl loading time
lastProcessingTime = (int) ((new Date().getTime()) - start
.getTime());
totalProcessingTime += lastProcessingTime;
if (bootstrapTime == 0) {
bootstrapTime = calculateBootstrapTime();
if (Profiler.isEnabled() && bootstrapTime != -1) {
Profiler.logBootstrapTimings();
}
}
VConsole.log(" Processing time was "
+ String.valueOf(lastProcessingTime) + "ms for "
+ jsonText.length() + " characters of JSON");
VConsole.log("Referenced paintables: " + connectorMap.size());
if (meta == null || !meta.containsKey("async")) {
// End the request if the received message was a response,
// not sent asynchronously
endRequest();
}
resumeResponseHandling(lock);
if (Profiler.isEnabled()) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
Profiler.logTimings();
Profiler.reset();
}
});
}
}
/**
* Properly clean up any old stuff to ensure everything is properly
* reinitialized.
*/
private void prepareRepaintAll() {
String uiConnectorId = uIConnector.getConnectorId();
if (uiConnectorId == null) {
// Nothing to clear yet
return;
}
// Create fake server response that says that the uiConnector
// has no children
JSONObject fakeHierarchy = new JSONObject();
fakeHierarchy.put(uiConnectorId, new JSONArray());
JSONObject fakeJson = new JSONObject();
fakeJson.put("hierarchy", fakeHierarchy);
ValueMap fakeValueMap = fakeJson.getJavaScriptObject().cast();
// Update hierarchy based on the fake response
ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(fakeValueMap);
// Send hierarchy events based on the fake update
sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
// Unregister all the old connectors that have now been removed
unregisterRemovedConnectors();
getLayoutManager().cleanMeasuredSizes();
}
private void updateCaptions(
JsArrayObject<StateChangeEvent> pendingStateChangeEvents,
FastStringSet parentChangedIds) {
Profiler.enter("updateCaptions");
/*
* Find all components that might need a caption update based on
* pending state and hierarchy changes
*/
FastStringSet needsCaptionUpdate = FastStringSet.create();
needsCaptionUpdate.addAll(parentChangedIds);
// Find components with potentially changed caption state
int size = pendingStateChangeEvents.size();
for (int i = 0; i < size; i++) {
StateChangeEvent event = pendingStateChangeEvents.get(i);
if (VCaption.mightChange(event)) {
ServerConnector connector = event.getConnector();
needsCaptionUpdate.add(connector.getConnectorId());
}
}
ConnectorMap connectorMap = getConnectorMap();
// Update captions for all suitable candidates
JsArrayString dump = needsCaptionUpdate.dump();
int needsUpdateLength = dump.length();
for (int i = 0; i < needsUpdateLength; i++) {
String childId = dump.get(i);
ServerConnector child = connectorMap.getConnector(childId);
if (child instanceof ComponentConnector
&& ((ComponentConnector) child)
.delegateCaptionHandling()) {
ServerConnector parent = child.getParent();
if (parent instanceof HasComponentsConnector) {
Profiler.enter("HasComponentsConnector.updateCaption");
((HasComponentsConnector) parent)
.updateCaption((ComponentConnector) child);
Profiler.leave("HasComponentsConnector.updateCaption");
}
}
}
Profiler.leave("updateCaptions");
}
private void delegateToWidget(
JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
Profiler.enter("@DelegateToWidget");
VConsole.log(" * Running @DelegateToWidget");
// Keep track of types that have no @DelegateToWidget in their
// state to optimize performance
FastStringSet noOpTypes = FastStringSet.create();
int size = pendingStateChangeEvents.size();
for (int eventIndex = 0; eventIndex < size; eventIndex++) {
StateChangeEvent sce = pendingStateChangeEvents
.get(eventIndex);
ServerConnector connector = sce.getConnector();
if (connector instanceof ComponentConnector) {
String className = connector.getClass().getName();
if (noOpTypes.contains(className)) {
continue;
}
ComponentConnector component = (ComponentConnector) connector;
Type stateType = AbstractConnector
.getStateType(component);
JsArrayString delegateToWidgetProperties = stateType
.getDelegateToWidgetProperties();
if (delegateToWidgetProperties == null) {
noOpTypes.add(className);
continue;
}
int length = delegateToWidgetProperties.length();
for (int i = 0; i < length; i++) {
String propertyName = delegateToWidgetProperties
.get(i);
if (sce.hasPropertyChanged(propertyName)) {
Property property = stateType
.getProperty(propertyName);
String method = property
.getDelegateToWidgetMethodName();
Profiler.enter("doDelegateToWidget");
doDelegateToWidget(component, property, method);
Profiler.leave("doDelegateToWidget");
}
}
}
}
Profiler.leave("@DelegateToWidget");
}
private void doDelegateToWidget(ComponentConnector component,
Property property, String methodName) {
Type type = TypeData.getType(component.getClass());
try {
Type widgetType = type.getMethod("getWidget")
.getReturnType();
Widget widget = component.getWidget();
Object propertyValue = property.getValue(component
.getState());
widgetType.getMethod(methodName).invoke(widget,
propertyValue);
} catch (NoDataException e) {
throw new RuntimeException(
"Missing data needed to invoke @DelegateToWidget for "
+ Util.getSimpleName(component), e);
}
}
/**
* Sends the state change events created while updating the state
* information.
*
* This must be called after hierarchy change listeners have been
* called. At least caption updates for the parent are strange if
* fired from state change listeners and thus calls the parent
* BEFORE the parent is aware of the child (through a
* ConnectorHierarchyChangedEvent)
*
* @param pendingStateChangeEvents
* The events to send
*/
private void sendStateChangeEvents(
JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
Profiler.enter("sendStateChangeEvents");
VConsole.log(" * Sending state change events");
int size = pendingStateChangeEvents.size();
for (int i = 0; i < size; i++) {
StateChangeEvent sce = pendingStateChangeEvents.get(i);
try {
sce.getConnector().fireEvent(sce);
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("sendStateChangeEvents");
}
private void unregisterRemovedConnectors() {
Profiler.enter("unregisterRemovedConnectors");
int unregistered = 0;
JsArrayObject<ServerConnector> currentConnectors = connectorMap
.getConnectorsAsJsArray();
int size = currentConnectors.size();
for (int i = 0; i < size; i++) {
ServerConnector c = currentConnectors.get(i);
if (c.getParent() != null) {
if (!c.getParent().getChildren().contains(c)) {
VConsole.error("ERROR: Connector is connected to a parent but the parent does not contain the connector");
}
} else if (c == getUIConnector()) {
// UIConnector for this connection, leave as-is
} else if (c instanceof WindowConnector
&& getUIConnector().hasSubWindow(
(WindowConnector) c)) {
// Sub window attached to this UIConnector, leave
// as-is
} else {
// The connector has been detached from the
// hierarchy, unregister it and any possible
// children. The UIConnector should never be
// unregistered even though it has no parent.
connectorMap.unregisterConnector(c);
unregistered++;
}
}
VConsole.log("* Unregistered " + unregistered + " connectors");
Profiler.leave("unregisterRemovedConnectors");
}
private JsArrayString createConnectorsIfNeeded(ValueMap json) {
VConsole.log(" * Creating connectors (if needed)");
JsArrayString createdConnectors = JavaScriptObject
.createArray().cast();
if (!json.containsKey("types")) {
return createdConnectors;
}
Profiler.enter("Creating connectors");
ValueMap types = json.getValueMap("types");
JsArrayString keyArray = types.getKeyArray();
for (int i = 0; i < keyArray.length(); i++) {
try {
String connectorId = keyArray.get(i);
ServerConnector connector = connectorMap
.getConnector(connectorId);
if (connector != null) {
continue;
}
int connectorType = Integer.parseInt(types
.getString(connectorId));
Class<? extends ServerConnector> connectorClass = configuration
.getConnectorClassByEncodedTag(connectorType);
// Connector does not exist so we must create it
if (connectorClass != uIConnector.getClass()) {
// create, initialize and register the paintable
Profiler.enter("ApplicationConnection.getConnector");
connector = getConnector(connectorId, connectorType);
Profiler.leave("ApplicationConnection.getConnector");
createdConnectors.push(connectorId);
} else {
// First UIConnector update. Before this the
// UIConnector has been created but not
// initialized as the connector id has not been
// known
connectorMap.registerConnector(connectorId,
uIConnector);
uIConnector.doInit(connectorId,
ApplicationConnection.this);
createdConnectors.push(connectorId);
}
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("Creating connectors");
return createdConnectors;
}
private void updateVaadin6StyleConnectors(ValueMap json) {
Profiler.enter("updateVaadin6StyleConnectors");
JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
int length = changes.length();
VConsole.log(" * Passing UIDL to Vaadin 6 style connectors");
// update paintables
for (int i = 0; i < length; i++) {
try {
final UIDL change = changes.get(i).cast();
final UIDL uidl = change.getChildUIDL(0);
String connectorId = uidl.getId();
final ComponentConnector legacyConnector = (ComponentConnector) connectorMap
.getConnector(connectorId);
if (legacyConnector instanceof Paintable) {
String key = null;
if (Profiler.isEnabled()) {
key = "updateFromUIDL for "
+ Util.getSimpleName(legacyConnector);
Profiler.enter(key);
}
((Paintable) legacyConnector).updateFromUIDL(uidl,
ApplicationConnection.this);
if (Profiler.isEnabled()) {
Profiler.leave(key);
}
} else if (legacyConnector == null) {
VConsole.error("Received update for "
+ uidl.getTag()
+ ", but there is no such paintable ("
+ connectorId + ") rendered.");
} else {
VConsole.error("Server sent Vaadin 6 style updates for "
+ Util.getConnectorString(legacyConnector)
+ " but this is not a Vaadin 6 Paintable");
}
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("updateVaadin6StyleConnectors");
}
private void sendHierarchyChangeEvents(
JsArrayObject<ConnectorHierarchyChangeEvent> events) {
int eventCount = events.size();
if (eventCount == 0) {
return;
}
Profiler.enter("sendHierarchyChangeEvents");
VConsole.log(" * Sending hierarchy change events");
for (int i = 0; i < eventCount; i++) {
ConnectorHierarchyChangeEvent event = events.get(i);
try {
logHierarchyChange(event);
event.getConnector().fireEvent(event);
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("sendHierarchyChangeEvents");
}
private void logHierarchyChange(ConnectorHierarchyChangeEvent event) {
if (true) {
// Always disabled for now. Can be enabled manually
return;
}
VConsole.log("Hierarchy changed for "
+ Util.getConnectorString(event.getConnector()));
String oldChildren = "* Old children: ";
for (ComponentConnector child : event.getOldChildren()) {
oldChildren += Util.getConnectorString(child) + " ";
}
VConsole.log(oldChildren);
String newChildren = "* New children: ";
HasComponentsConnector parent = (HasComponentsConnector) event
.getConnector();
for (ComponentConnector child : parent.getChildComponents()) {
newChildren += Util.getConnectorString(child) + " ";
}
VConsole.log(newChildren);
}
private JsArrayObject<StateChangeEvent> updateConnectorState(
ValueMap json, JsArrayString createdConnectorIds) {
JsArrayObject<StateChangeEvent> events = JavaScriptObject
.createArray().cast();
VConsole.log(" * Updating connector states");
if (!json.containsKey("state")) {
return events;
}
Profiler.enter("updateConnectorState");
FastStringSet remainingNewConnectors = FastStringSet.create();
remainingNewConnectors.addAll(createdConnectorIds);
// set states for all paintables mentioned in "state"
ValueMap states = json.getValueMap("state");
JsArrayString keyArray = states.getKeyArray();
for (int i = 0; i < keyArray.length(); i++) {
try {
String connectorId = keyArray.get(i);
ServerConnector connector = connectorMap
.getConnector(connectorId);
if (null != connector) {
Profiler.enter("updateConnectorState inner loop");
if (Profiler.isEnabled()) {
Profiler.enter("Decode connector state "
+ Util.getSimpleName(connector));
}
JSONObject stateJson = new JSONObject(
states.getJavaScriptObject(connectorId));
if (connector instanceof HasJavaScriptConnectorHelper) {
((HasJavaScriptConnectorHelper) connector)
.getJavascriptConnectorHelper()
.setNativeState(
stateJson.getJavaScriptObject());
}
SharedState state = connector.getState();
Profiler.enter("updateConnectorState decodeValue");
JsonDecoder.decodeValue(new Type(state.getClass()
.getName(), null), stateJson, state,
ApplicationConnection.this);
Profiler.leave("updateConnectorState decodeValue");
if (Profiler.isEnabled()) {
Profiler.leave("Decode connector state "
+ Util.getSimpleName(connector));
}
Profiler.enter("updateConnectorState create event");
boolean isNewConnector = remainingNewConnectors
.contains(connectorId);
if (isNewConnector) {
remainingNewConnectors.remove(connectorId);
}
StateChangeEvent event = new StateChangeEvent(
connector, stateJson, isNewConnector);
events.add(event);
Profiler.leave("updateConnectorState create event");
Profiler.leave("updateConnectorState inner loop");
}
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.enter("updateConnectorState newWithoutState");
// Fire events for properties using the default value for newly
// created connectors even if there were no state changes
JsArrayString dump = remainingNewConnectors.dump();
int length = dump.length();
for (int i = 0; i < length; i++) {
String connectorId = dump.get(i);
ServerConnector connector = connectorMap
.getConnector(connectorId);
StateChangeEvent event = new StateChangeEvent(connector,
new JSONObject(), true);
events.add(event);
}
Profiler.leave("updateConnectorState newWithoutState");
Profiler.leave("updateConnectorState");
return events;
}
/**
* Updates the connector hierarchy and returns a list of events that
* should be fired after update of the hierarchy and the state is
* done.
*
* @param json
* The JSON containing the hierarchy information
* @return A collection of events that should be fired when update
* of hierarchy and state is complete and a list of all
* connectors for which the parent has changed
*/
private ConnectorHierarchyUpdateResult updateConnectorHierarchy(
ValueMap json) {
ConnectorHierarchyUpdateResult result = new ConnectorHierarchyUpdateResult();
VConsole.log(" * Updating connector hierarchy");
if (!json.containsKey("hierarchy")) {
return result;
}
Profiler.enter("updateConnectorHierarchy");
FastStringSet maybeDetached = FastStringSet.create();
ValueMap hierarchies = json.getValueMap("hierarchy");
JsArrayString hierarchyKeys = hierarchies.getKeyArray();
for (int i = 0; i < hierarchyKeys.length(); i++) {
try {
String connectorId = hierarchyKeys.get(i);
ServerConnector parentConnector = connectorMap
.getConnector(connectorId);
JsArrayString childConnectorIds = hierarchies
.getJSStringArray(connectorId);
int childConnectorSize = childConnectorIds.length();
List<ServerConnector> newChildren = new ArrayList<ServerConnector>();
List<ComponentConnector> newComponents = new ArrayList<ComponentConnector>();
for (int connectorIndex = 0; connectorIndex < childConnectorSize; connectorIndex++) {
String childConnectorId = childConnectorIds
.get(connectorIndex);
ServerConnector childConnector = connectorMap
.getConnector(childConnectorId);
if (childConnector == null) {
VConsole.error("Hierarchy claims that "
+ childConnectorId + " is a child for "
+ connectorId + " ("
+ parentConnector.getClass().getName()
+ ") but no connector with id "
+ childConnectorId
+ " has been registered");
continue;
}
newChildren.add(childConnector);
if (childConnector instanceof ComponentConnector) {
newComponents
.add((ComponentConnector) childConnector);
} else if (!(childConnector instanceof AbstractExtensionConnector)) {
throw new IllegalStateException(
Util.getConnectorString(childConnector)
+ " is not a ComponentConnector nor an AbstractExtensionConnector");
}
if (childConnector.getParent() != parentConnector) {
childConnector.setParent(parentConnector);
result.parentChangedIds.add(childConnectorId);
// Not detached even if previously removed from
// parent
maybeDetached.remove(childConnectorId);
}
}
// TODO This check should be done on the server side in
// the future so the hierarchy update is only sent when
// something actually has changed
List<ServerConnector> oldChildren = parentConnector
.getChildren();
boolean actuallyChanged = !Util.collectionsEquals(
oldChildren, newChildren);
if (!actuallyChanged) {
continue;
}
if (parentConnector instanceof HasComponentsConnector) {
HasComponentsConnector ccc = (HasComponentsConnector) parentConnector;
List<ComponentConnector> oldComponents = ccc
.getChildComponents();
if (!Util.collectionsEquals(oldComponents,
newComponents)) {
// Fire change event if the hierarchy has
// changed
ConnectorHierarchyChangeEvent event = GWT
.create(ConnectorHierarchyChangeEvent.class);
event.setOldChildren(oldComponents);
event.setConnector(parentConnector);
ccc.setChildComponents(newComponents);
result.events.add(event);
}
} else if (!newComponents.isEmpty()) {
VConsole.error("Hierachy claims "
+ Util.getConnectorString(parentConnector)
+ " has component children even though it isn't a HasComponentsConnector");
}
parentConnector.setChildren(newChildren);
/*
* Find children removed from this parent and mark for
* removal unless they are already attached to some
* other parent.
*/
for (ServerConnector oldChild : oldChildren) {
if (oldChild.getParent() != parentConnector) {
// Ignore if moved to some other connector
continue;
}
if (!newChildren.contains(oldChild)) {
/*
* Consider child detached for now, will be
* cleared if it is later on added to some other
* parent.
*/
maybeDetached.add(oldChild.getConnectorId());
}
}
} catch (final Throwable e) {
VConsole.error(e);
}
}
/*
* Connector is in maybeDetached at this point if it has been
* removed from its parent but not added to any other parent
*/
JsArrayString maybeDetachedArray = maybeDetached.dump();
for (int i = 0; i < maybeDetachedArray.length(); i++) {
ServerConnector removed = connectorMap
.getConnector(maybeDetachedArray.get(i));
recursivelyDetach(removed, result.events);
}
Profiler.leave("updateConnectorHierarchy");
return result;
}
private void recursivelyDetach(ServerConnector connector,
JsArrayObject<ConnectorHierarchyChangeEvent> events) {
/*
* Reset state in an attempt to keep it consistent with the
* hierarchy. No children and no parent is the initial situation
* for the hierarchy, so changing the state to its initial value
* is the closest we can get without data from the server.
* #10151
*/
try {
Type stateType = AbstractConnector.getStateType(connector);
// Empty state instance to get default property values from
Object defaultState = stateType.createInstance();
SharedState state = connector.getState();
JsArrayObject<Property> properties = stateType
.getPropertiesAsArray();
int size = properties.size();
for (int i = 0; i < size; i++) {
Property property = properties.get(i);
property.setValue(state,
property.getValue(defaultState));
}
} catch (NoDataException e) {
throw new RuntimeException("Can't reset state for "
+ Util.getConnectorString(connector), e);
}
/*
* Recursively detach children to make sure they get
* setParent(null) and hierarchy change events as needed.
*/
for (ServerConnector child : connector.getChildren()) {
/*
* Server doesn't send updated child data for removed
* connectors -> ignore child that still seems to be a child
* of this connector although it has been moved to some part
* of the hierarchy that is not detached.
*/
if (child.getParent() != connector) {
continue;
}
recursivelyDetach(child, events);
}
/*
* Clear child list and parent
*/
connector
.setChildren(Collections.<ServerConnector> emptyList());
connector.setParent(null);
/*
* Create an artificial hierarchy event for containers to give
* it a chance to clean up after its children if it has any
*/
if (connector instanceof HasComponentsConnector) {
HasComponentsConnector ccc = (HasComponentsConnector) connector;
List<ComponentConnector> oldChildren = ccc
.getChildComponents();
if (!oldChildren.isEmpty()) {
/*
* HasComponentsConnector has a separate child component
* list that should also be cleared
*/
ccc.setChildComponents(Collections
.<ComponentConnector> emptyList());
// Create event and add it to the list of pending events
ConnectorHierarchyChangeEvent event = GWT
.create(ConnectorHierarchyChangeEvent.class);
event.setConnector(connector);
event.setOldChildren(oldChildren);
events.add(event);
}
}
}
private void handleRpcInvocations(ValueMap json) {
if (json.containsKey("rpc")) {
Profiler.enter("handleRpcInvocations");
VConsole.log(" * Performing server to client RPC calls");
JSONArray rpcCalls = new JSONArray(
json.getJavaScriptObject("rpc"));
int rpcLength = rpcCalls.size();
for (int i = 0; i < rpcLength; i++) {
try {
JSONArray rpcCall = (JSONArray) rpcCalls.get(i);
rpcManager.parseAndApplyInvocation(rpcCall,
ApplicationConnection.this);
} catch (final Throwable e) {
VConsole.error(e);
}
}
Profiler.leave("handleRpcInvocations");
}
}
};
ApplicationConfiguration.runWhenDependenciesLoaded(c);
}
private void findZeroSizeComponents(
Set<ComponentConnector> zeroHeightComponents,
Set<ComponentConnector> zeroWidthComponents,
ComponentConnector connector) {
Widget widget = connector.getWidget();
ComputedStyle computedStyle = new ComputedStyle(widget.getElement());
if (computedStyle.getIntProperty("height") == 0) {
zeroHeightComponents.add(connector);
}
if (computedStyle.getIntProperty("width") == 0) {
zeroWidthComponents.add(connector);
}
List<ServerConnector> children = connector.getChildren();
for (ServerConnector serverConnector : children) {
if (serverConnector instanceof ComponentConnector) {
findZeroSizeComponents(zeroHeightComponents,
zeroWidthComponents,
(ComponentConnector) serverConnector);
}
}
}
private void loadStyleDependencies(JsArrayString dependencies) {
// Assuming no reason to interpret in a defined order
ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
@Override
public void onLoad(ResourceLoadEvent event) {
ApplicationConfiguration.endDependencyLoading();
}
@Override
public void onError(ResourceLoadEvent event) {
VConsole.error(event.getResourceUrl()
+ " could not be loaded, or the load detection failed because the stylesheet is empty.");
// The show must go on
onLoad(event);
}
};
ResourceLoader loader = ResourceLoader.get();
for (int i = 0; i < dependencies.length(); i++) {
String url = translateVaadinUri(dependencies.get(i));
ApplicationConfiguration.startDependencyLoading();
loader.loadStylesheet(url, resourceLoadListener);
}
}
private void loadScriptDependencies(final JsArrayString dependencies) {
if (dependencies.length() == 0) {
return;
}
// Listener that loads the next when one is completed
ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
@Override
public void onLoad(ResourceLoadEvent event) {
if (dependencies.length() != 0) {
String url = translateVaadinUri(dependencies.shift());
ApplicationConfiguration.startDependencyLoading();
// Load next in chain (hopefully already preloaded)
event.getResourceLoader().loadScript(url, this);
}
// Call start for next before calling end for current
ApplicationConfiguration.endDependencyLoading();
}
@Override
public void onError(ResourceLoadEvent event) {
VConsole.error(event.getResourceUrl() + " could not be loaded.");
// The show must go on
onLoad(event);
}
};
ResourceLoader loader = ResourceLoader.get();
// Start chain by loading first
String url = translateVaadinUri(dependencies.shift());
ApplicationConfiguration.startDependencyLoading();
loader.loadScript(url, resourceLoadListener);
// Preload all remaining
for (int i = 0; i < dependencies.length(); i++) {
String preloadUrl = translateVaadinUri(dependencies.get(i));
loader.preloadResource(preloadUrl, null);
}
}
// Redirect browser, null reloads current page
private static native void redirect(String url)
/*-{
if (url) {
$wnd.location = url;
} else {
$wnd.location.reload(false);
}
}-*/;
private void addVariableToQueue(String connectorId, String variableName,
Object value, boolean immediate) {
boolean lastOnly = !immediate;
// note that type is now deduced from value
addMethodInvocationToQueue(new LegacyChangeVariablesInvocation(
connectorId, variableName, value), lastOnly, lastOnly);
}
/**
* Adds an explicit RPC method invocation to the send queue.
*
* @since 7.0
*
* @param invocation
* RPC method invocation
* @param delayed
* <code>false</code> to trigger sending within a short time
* window (possibly combining subsequent calls to a single
* request), <code>true</code> to let the framework delay sending
* of RPC calls and variable changes until the next non-delayed
* change
* @param lastOnly
* <code>true</code> to remove all previously delayed invocations
* of the same method that were also enqueued with lastonly set
* to <code>true</code>. <code>false</code> to add invocation to
* the end of the queue without touching previously enqueued
* invocations.
*/
public void addMethodInvocationToQueue(MethodInvocation invocation,
boolean delayed, boolean lastOnly) {
String tag;
if (lastOnly) {
tag = invocation.getLastOnlyTag();
assert !tag.matches("\\d+") : "getLastOnlyTag value must have at least one non-digit character";
pendingInvocations.remove(tag);
} else {
tag = Integer.toString(lastInvocationTag++);
}
pendingInvocations.put(tag, invocation);
if (!delayed) {
sendPendingVariableChanges();
}
}
/**
* Removes any pending invocation of the given method from the queue
*
* @param invocation
* The invocation to remove
*/
public void removePendingInvocations(MethodInvocation invocation) {
Iterator<MethodInvocation> iter = pendingInvocations.values()
.iterator();
while (iter.hasNext()) {
MethodInvocation mi = iter.next();
if (mi.equals(invocation)) {
iter.remove();
}
}
}
/**
* This method sends currently queued variable changes to server. It is
* called when immediate variable update must happen.
*
* To ensure correct order for variable changes (due servers multithreading
* or network), we always wait for active request to be handler before
* sending a new one. If there is an active request, we will put varible
* "burst" to queue that will be purged after current request is handled.
*
*/
public void sendPendingVariableChanges() {
if (!deferedSendPending) {
deferedSendPending = true;
Scheduler.get().scheduleFinally(sendPendingCommand);
}
}
private final ScheduledCommand sendPendingCommand = new ScheduledCommand() {
@Override
public void execute() {
deferedSendPending = false;
doSendPendingVariableChanges();
}
};
private boolean deferedSendPending = false;
private void doSendPendingVariableChanges() {
if (applicationRunning) {
if (hasActiveRequest() || (push != null && !push.isActive())) {
// skip empty queues if there are pending bursts to be sent
if (pendingInvocations.size() > 0 || pendingBursts.size() == 0) {
pendingBursts.add(pendingInvocations);
pendingInvocations = new LinkedHashMap<String, MethodInvocation>();
// Keep tag string short
lastInvocationTag = 0;
}
} else {
buildAndSendVariableBurst(pendingInvocations);
}
}
}
/**
* Build the variable burst and send it to server.
*
* When sync is forced, we also force sending of all pending variable-bursts
* at the same time. This is ok as we can assume that DOM will never be
* updated after this.
*
* @param pendingInvocations
* List of RPC method invocations to send
*/
private void buildAndSendVariableBurst(
LinkedHashMap<String, MethodInvocation> pendingInvocations) {
final StringBuffer req = new StringBuffer();
while (!pendingInvocations.isEmpty()) {
if (ApplicationConfiguration.isDebugMode()) {
Util.logVariableBurst(this, pendingInvocations.values());
}
JSONArray reqJson = new JSONArray();
for (MethodInvocation invocation : pendingInvocations.values()) {
JSONArray invocationJson = new JSONArray();
invocationJson.set(0,
new JSONString(invocation.getConnectorId()));
invocationJson.set(1,
new JSONString(invocation.getInterfaceName()));
invocationJson.set(2,
new JSONString(invocation.getMethodName()));
JSONArray paramJson = new JSONArray();
Type[] parameterTypes = null;
if (!isLegacyVariableChange(invocation)
&& !isJavascriptRpc(invocation)) {
try {
Type type = new Type(invocation.getInterfaceName(),
null);
Method method = type.getMethod(invocation
.getMethodName());
parameterTypes = method.getParameterTypes();
} catch (NoDataException e) {
throw new RuntimeException("No type data for "
+ invocation.toString(), e);
}
}
for (int i = 0; i < invocation.getParameters().length; ++i) {
// TODO non-static encoder?
Type type = null;
if (parameterTypes != null) {
type = parameterTypes[i];
}
Object value = invocation.getParameters()[i];
paramJson.set(i, JsonEncoder.encode(value, type, this));
}
invocationJson.set(3, paramJson);
reqJson.set(reqJson.size(), invocationJson);
}
// escape burst separators (if any)
req.append(escapeBurstContents(reqJson.toString()));
pendingInvocations.clear();
// Keep tag string short
lastInvocationTag = 0;
}
// Include the browser detail parameters if they aren't already sent
String extraParams;
if (!getConfiguration().isBrowserDetailsSent()) {
extraParams = getNativeBrowserDetailsParameters(getConfiguration()
.getRootPanelId());
getConfiguration().setBrowserDetailsSent();
} else {
extraParams = "";
}
if (!getConfiguration().isWidgetsetVersionSent()) {
if (!extraParams.isEmpty()) {
extraParams += "&";
}
String widgetsetVersion = Version.getFullVersion();
extraParams += "v-wsver=" + widgetsetVersion;
getConfiguration().setWidgetsetVersionSent();
}
makeUidlRequest(req.toString(), extraParams);
}
private boolean isJavascriptRpc(MethodInvocation invocation) {
return invocation instanceof JavaScriptMethodInvocation;
}
private boolean isLegacyVariableChange(MethodInvocation invocation) {
return ApplicationConstants.UPDATE_VARIABLE_METHOD.equals(invocation
.getInterfaceName())
&& ApplicationConstants.UPDATE_VARIABLE_METHOD
.equals(invocation.getMethodName());
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
ServerConnector newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
String newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
int newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
long newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
float newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
double newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param newValue
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
boolean newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
* <p>
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
* </p>
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param map
* the new values to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
Map<String, Object> map, boolean immediate) {
addVariableToQueue(paintableId, variableName, map, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
*
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update.
*
* A null array is sent as an empty array.
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param values
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
String[] values, boolean immediate) {
addVariableToQueue(paintableId, variableName, values, immediate);
}
/**
* Sends a new value for the given paintables given variable to the server.
*
* The update is actually queued to be sent at a suitable time. If immediate
* is true, the update is sent as soon as possible. If immediate is false,
* the update will be sent along with the next immediate update. </p>
*
* A null array is sent as an empty array.
*
*
* @param paintableId
* the id of the paintable that owns the variable
* @param variableName
* the name of the variable
* @param values
* the new value to be sent
* @param immediate
* true if the update is to be sent as soon as possible
*/
public void updateVariable(String paintableId, String variableName,
Object[] values, boolean immediate) {
addVariableToQueue(paintableId, variableName, values, immediate);
}
/**
* Encode burst separator characters in a String for transport over the
* network. This protects from separator injection attacks.
*
* @param value
* to encode
* @return encoded value
*/
protected String escapeBurstContents(String value) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < value.length(); ++i) {
char character = value.charAt(i);
switch (character) {
case VAR_ESCAPE_CHARACTER:
// fall-through - escape character is duplicated
case VAR_BURST_SEPARATOR:
result.append(VAR_ESCAPE_CHARACTER);
// encode as letters for easier reading
result.append(((char) (character + 0x30)));
break;
default:
// the char is not a special one - add it to the result as is
result.append(character);
break;
}
}
return result.toString();
}
/**
* Does absolutely nothing. Replaced by {@link LayoutManager}.
*
* @param container
* @deprecated As of 7.0, serves no purpose
*/
@Deprecated
public void runDescendentsLayout(HasWidgets container) {
}
/**
* This will cause re-layouting of all components. Mainly used for
* development. Published to JavaScript.
*/
public void forceLayout() {
Duration duration = new Duration();
layoutManager.forceLayout();
VConsole.log("forceLayout in " + duration.elapsedMillis() + " ms");
}
/**
* Returns false
*
* @param paintable
* @return false, always
* @deprecated As of 7.0, serves no purpose
*/
@Deprecated
private boolean handleComponentRelativeSize(ComponentConnector paintable) {
return false;
}
/**
* Returns false
*
* @param paintable
* @return false, always
* @deprecated As of 7.0, serves no purpose
*/
@Deprecated
public boolean handleComponentRelativeSize(Widget widget) {
return handleComponentRelativeSize(connectorMap.getConnector(widget));
}
@Deprecated
public ComponentConnector getPaintable(UIDL uidl) {
// Non-component connectors shouldn't be painted from legacy connectors
return (ComponentConnector) getConnector(uidl.getId(),
Integer.parseInt(uidl.getTag()));
}
/**
* Get either an existing ComponentConnector or create a new
* ComponentConnector with the given type and id.
*
* If a ComponentConnector with the given id already exists, returns it.
* Otherwise creates and registers a new ComponentConnector of the given
* type.
*
* @param connectorId
* Id of the paintable
* @param connectorType
* Type of the connector, as passed from the server side
*
* @return Either an existing ComponentConnector or a new ComponentConnector
* of the given type
*/
public ServerConnector getConnector(String connectorId, int connectorType) {
if (!connectorMap.hasConnector(connectorId)) {
return createAndRegisterConnector(connectorId, connectorType);
}
return connectorMap.getConnector(connectorId);
}
/**
* Creates a new ServerConnector with the given type and id.
*
* Creates and registers a new ServerConnector of the given type. Should
* never be called with the connector id of an existing connector.
*
* @param connectorId
* Id of the new connector
* @param connectorType
* Type of the connector, as passed from the server side
*
* @return A new ServerConnector of the given type
*/
private ServerConnector createAndRegisterConnector(String connectorId,
int connectorType) {
Profiler.enter("ApplicationConnection.createAndRegisterConnector");
// Create and register a new connector with the given type
ServerConnector p = widgetSet.createConnector(connectorType,
configuration);
connectorMap.registerConnector(connectorId, p);
p.doInit(connectorId, this);
Profiler.leave("ApplicationConnection.createAndRegisterConnector");
return p;
}
/**
* Gets a recource that has been pre-loaded via UIDL, such as custom
* layouts.
*
* @param name
* identifier of the resource to get
* @return the resource
*/
public String getResource(String name) {
return resourcesMap.get(name);
}
/**
* Singleton method to get instance of app's context menu.
*
* @return VContextMenu object
*/
public VContextMenu getContextMenu() {
if (contextMenu == null) {
contextMenu = new VContextMenu();
contextMenu.setOwner(uIConnector.getWidget());
DOM.setElementProperty(contextMenu.getElement(), "id",
"PID_VAADIN_CM");
}
return contextMenu;
}
/**
* Translates custom protocols in UIDL URI's to be recognizable by browser.
* All uri's from UIDL should be routed via this method before giving them
* to browser due URI's in UIDL may contain custom protocols like theme://.
*
* @param uidlUri
* Vaadin URI from uidl
* @return translated URI ready for browser
*/
public String translateVaadinUri(String uidlUri) {
if (uidlUri == null) {
return null;
}
if (uidlUri.startsWith("theme://")) {
final String themeUri = configuration.getThemeUri();
if (themeUri == null) {
VConsole.error("Theme not set: ThemeResource will not be found. ("
+ uidlUri + ")");
}
uidlUri = themeUri + uidlUri.substring(7);
}
if (uidlUri.startsWith(ApplicationConstants.PUBLISHED_PROTOCOL_PREFIX)) {
// getAppUri *should* always end with /
// substring *should* always start with / (published:///foo.bar
// without published://)
uidlUri = ApplicationConstants.APP_PROTOCOL_PREFIX
+ ApplicationConstants.PUBLISHED_FILE_PATH
+ uidlUri
.substring(ApplicationConstants.PUBLISHED_PROTOCOL_PREFIX
.length());
// Let translation of app:// urls take care of the rest
}
if (uidlUri.startsWith(ApplicationConstants.APP_PROTOCOL_PREFIX)) {
String relativeUrl = uidlUri
.substring(ApplicationConstants.APP_PROTOCOL_PREFIX
.length());
ApplicationConfiguration conf = getConfiguration();
String serviceUrl = conf.getServiceUrl();
if (conf.useServiceUrlPathParam()) {
// Should put path in v-resourcePath parameter and append query
// params to base portlet url
String[] parts = relativeUrl.split("\\?", 2);
String path = parts[0];
// If there's a "?" followed by something, append it as a query
// string to the base URL
if (parts.length > 1) {
String appUrlParams = parts[1];
serviceUrl = addGetParameters(serviceUrl, appUrlParams);
}
if (!path.startsWith("/")) {
path = '/' + path;
}
String pathParam = ApplicationConstants.V_RESOURCE_PATH + "="
+ URL.encodeQueryString(path);
serviceUrl = addGetParameters(serviceUrl, pathParam);
uidlUri = serviceUrl;
} else {
uidlUri = serviceUrl + relativeUrl;
}
}
return uidlUri;
}
/**
* Gets the URI for the current theme. Can be used to reference theme
* resources.
*
* @return URI to the current theme
*/
public String getThemeUri() {
return configuration.getThemeUri();
}
/**
* Listens for Notification hide event, and redirects. Used for system
* messages, such as session expired.
*
*/
private class NotificationRedirect implements VNotification.EventListener {
String url;
NotificationRedirect(String url) {
this.url = url;
}
@Override
public void notificationHidden(HideEvent event) {
redirect(url);
}
}
/* Extended title handling */
private final VTooltip tooltip;
private ConnectorMap connectorMap = GWT.create(ConnectorMap.class);
protected String getUidlSecurityKey() {
return getCsrfToken();
}
/**
* Gets the token (aka double submit cookie) that the server uses to protect
* against Cross Site Request Forgery attacks.
*
* @return the CSRF token string
*/
public String getCsrfToken() {
return csrfToken;
}
/**
* Use to notify that the given component's caption has changed; layouts may
* have to be recalculated.
*
* @param component
* the Paintable whose caption has changed
* @deprecated As of 7.0.2, has not had any effect for a long time
*/
@Deprecated
public void captionSizeUpdated(Widget widget) {
// This doesn't do anything, it's just kept here for compatibility
}
/**
* Gets the main view
*
* @return the main view
*/
public UIConnector getUIConnector() {
return uIConnector;
}
/**
* Gets the {@link ApplicationConfiguration} for the current application.
*
* @see ApplicationConfiguration
* @return the configuration for this application
*/
public ApplicationConfiguration getConfiguration() {
return configuration;
}
/**
* Checks if there is a registered server side listener for the event. The
* list of events which has server side listeners is updated automatically
* before the component is updated so the value is correct if called from
* updatedFromUIDL.
*
* @param paintable
* The connector to register event listeners for
* @param eventIdentifier
* The identifier for the event
* @return true if at least one listener has been registered on server side
* for the event identified by eventIdentifier.
* @deprecated As of 7.0. Use
* {@link AbstractComponentState#hasEventListener(String)}
* instead
*/
@Deprecated
public boolean hasEventListeners(ComponentConnector paintable,
String eventIdentifier) {
return paintable.hasEventListener(eventIdentifier);
}
/**
* Adds the get parameters to the uri and returns the new uri that contains
* the parameters.
*
* @param uri
* The uri to which the parameters should be added.
* @param extraParams
* One or more parameters in the format "a=b" or "c=d&e=f". An
* empty string is allowed but will not modify the url.
* @return The modified URI with the get parameters in extraParams added.
*/
public static String addGetParameters(String uri, String extraParams) {
if (extraParams == null || extraParams.length() == 0) {
return uri;
}
// RFC 3986: The query component is indicated by the first question
// mark ("?") character and terminated by a number sign ("#") character
// or by the end of the URI.
String fragment = null;
int hashPosition = uri.indexOf('#');
if (hashPosition != -1) {
// Fragment including "#"
fragment = uri.substring(hashPosition);
// The full uri before the fragment
uri = uri.substring(0, hashPosition);
}
if (uri.contains("?")) {
uri += "&";
} else {
uri += "?";
}
uri += extraParams;
if (fragment != null) {
uri += fragment;
}
return uri;
}
ConnectorMap getConnectorMap() {
return connectorMap;
}
/**
* @deprecated As of 7.0. No longer serves any purpose.
*/
@Deprecated
public void unregisterPaintable(ServerConnector p) {
VConsole.log("unregisterPaintable (unnecessarily) called for "
+ Util.getConnectorString(p));
}
/**
* Get VTooltip instance related to application connection
*
* @return VTooltip instance
*/
public VTooltip getVTooltip() {
return tooltip;
}
/**
* Method provided for backwards compatibility. Duties previously done by
* this method is now handled by the state change event handler in
* AbstractComponentConnector. The only function this method has is to
* return true if the UIDL is a "cached" update.
*
* @param component
* @param uidl
* @param manageCaption
* @deprecated As of 7.0, no longer serves any purpose
* @return
*/
@Deprecated
public boolean updateComponent(Widget component, UIDL uidl,
boolean manageCaption) {
ComponentConnector connector = getConnectorMap()
.getConnector(component);
if (!AbstractComponentConnector.isRealUpdate(uidl)) {
return true;
}
if (!manageCaption) {
VConsole.error(Util.getConnectorString(connector)
+ " called updateComponent with manageCaption=false. The parameter was ignored - override delegateCaption() to return false instead. It is however not recommended to use caption this way at all.");
}
return false;
}
/**
* @deprecated As of 7.0. Use
* {@link AbstractComponentConnector#hasEventListener(String)}
* instead
*/
@Deprecated
public boolean hasEventListeners(Widget widget, String eventIdentifier) {
ComponentConnector connector = getConnectorMap().getConnector(widget);
if (connector == null) {
/*
* No connector will exist in cases where Vaadin widgets have been
* re-used without implementing server<->client communication.
*/
return false;
}
return hasEventListeners(getConnectorMap().getConnector(widget),
eventIdentifier);
}
LayoutManager getLayoutManager() {
return layoutManager;
}
/**
* Schedules a heartbeat request to occur after the configured heartbeat
* interval elapses if the interval is a positive number. Otherwise, does
* nothing.
*
* @see #sendHeartbeat()
* @see ApplicationConfiguration#getHeartbeatInterval()
*/
protected void scheduleHeartbeat() {
final int interval = getConfiguration().getHeartbeatInterval();
if (interval > 0) {
VConsole.log("Scheduling heartbeat in " + interval + " seconds");
new Timer() {
@Override
public void run() {
sendHeartbeat();
}
}.schedule(interval * 1000);
}
}
/**
* Sends a heartbeat request to the server.
* <p>
* Heartbeat requests are used to inform the server that the client-side is
* still alive. If the client page is closed or the connection lost, the
* server will eventually close the inactive UI.
* <p>
* <b>TODO</b>: Improved error handling, like in doUidlRequest().
*
* @see #scheduleHeartbeat()
*/
protected void sendHeartbeat() {
final String uri = addGetParameters(
translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
+ ApplicationConstants.HEARTBEAT_PATH + '/'),
UIConstants.UI_ID_PARAMETER + "="
+ getConfiguration().getUIId());
final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
final RequestCallback callback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
int status = response.getStatusCode();
if (status == Response.SC_OK) {
// TODO Permit retry in some error situations
VConsole.log("Heartbeat response OK");
scheduleHeartbeat();
} else if (status == Response.SC_GONE) {
showSessionExpiredError(null);
} else {
VConsole.error("Failed sending heartbeat to server. Error code: "
+ status);
}
}
@Override
public void onError(Request request, Throwable exception) {
VConsole.error("Exception sending heartbeat: " + exception);
}
};
rb.setCallback(callback);
try {
VConsole.log("Sending heartbeat request...");
rb.send();
} catch (RequestException re) {
callback.onError(null, re);
}
}
/**
* Timer used to make sure that no misbehaving components can delay response
* handling forever.
*/
Timer forceHandleMessage = new Timer() {
@Override
public void run() {
if (responseHandlingLocks.isEmpty()) {
/*
* Timer fired but there's nothing to clear. This can happen
* with IE8 as Timer.cancel is not always effective (see GWT
* issue 8101).
*/
return;
}
VConsole.log("WARNING: reponse handling was never resumed, forcibly removing locks...");
responseHandlingLocks.clear();
handlePendingMessages();
}
};
/**
* This method can be used to postpone rendering of a response for a short
* period of time (e.g. to avoid the rendering process during animation).
*
* @param lock
*/
public void suspendReponseHandling(Object lock) {
responseHandlingLocks.add(lock);
}
/**
* Resumes the rendering process once all locks have been removed.
*
* @param lock
*/
public void resumeResponseHandling(Object lock) {
responseHandlingLocks.remove(lock);
if (responseHandlingLocks.isEmpty()) {
// Cancel timer that breaks the lock
forceHandleMessage.cancel();
if (!pendingUIDLMessages.isEmpty()) {
VConsole.log("No more response handling locks, handling pending requests.");
handlePendingMessages();
}
}
}
/**
* Handles all pending UIDL messages queued while response handling was
* suspended.
*/
private void handlePendingMessages() {
if (!pendingUIDLMessages.isEmpty()) {
/*
* Clear the list before processing enqueued messages to support
* reentrancy
*/
List<PendingUIDLMessage> pendingMessages = pendingUIDLMessages;
pendingUIDLMessages = new ArrayList<PendingUIDLMessage>();
for (PendingUIDLMessage pending : pendingMessages) {
handleReceivedJSONMessage(pending.getStart(),
pending.getJsonText(), pending.getJson());
}
}
}
private boolean handleErrorInDelegate(String details, int statusCode) {
if (communicationErrorDelegate == null) {
return false;
}
return communicationErrorDelegate.onError(details, statusCode);
}
/**
* Sets the delegate that is called whenever a communication error occurrs.
*
* @param delegate
* the delegate.
*/
public void setCommunicationErrorDelegate(CommunicationErrorHandler delegate) {
communicationErrorDelegate = delegate;
}
public void setApplicationRunning(boolean running) {
applicationRunning = running;
}
public boolean isApplicationRunning() {
return applicationRunning;
}
public <H extends EventHandler> HandlerRegistration addHandler(
GwtEvent.Type<H> type, H handler) {
return eventBus.addHandler(type, handler);
}
/**
* Calls {@link ComponentConnector#flush()} on the active connector. Does
* nothing if there is no active (focused) connector.
*/
public void flushActiveConnector() {
ComponentConnector activeConnector = getActiveConnector();
if (activeConnector == null) {
return;
}
activeConnector.flush();
}
/**
* Gets the active connector for focused element in browser.
*
* @return Connector for focused element or null.
*/
private ComponentConnector getActiveConnector() {
Element focusedElement = Util.getFocusedElement();
if (focusedElement == null) {
return null;
}
return Util.getConnectorForElement(this, getUIConnector().getWidget(),
focusedElement);
}
/**
* Sets the status for the push connection.
*
* @param enabled
* <code>true</code> to enable the push connection;
* <code>false</code> to disable the push connection.
*/
public void setPushEnabled(boolean enabled) {
if (enabled && push == null) {
push = GWT.create(PushConnection.class);
push.init(this);
} else if (!enabled && push != null && push.isActive()) {
push.disconnect(new Command() {
@Override
public void execute() {
push = null;
/*
* If push has been enabled again while we were waiting for
* the old connection to disconnect, now is the right time
* to open a new connection
*/
if (uIConnector.getState().pushMode.isEnabled()) {
setPushEnabled(true);
}
/*
* Send anything that was enqueued while we waited for the
* connection to close
*/
if (pendingInvocations.size() > 0) {
sendPendingVariableChanges();
}
}
});
}
}
public void handlePushMessage(String message) {
handleJSONText(message, 200);
}
}
| Show loading indicator immediately in init as before (#11850)
f7ee755e cherry-picked from the master branch.
Merge: no
Change-Id: Ibe91db13b301aaf0a2b5e6e5fb08f566bf5cadab
| client/src/com/vaadin/client/ApplicationConnection.java | Show loading indicator immediately in init as before (#11850) |
|
Java | apache-2.0 | 302cb86d8e5f05567c6c5a42e5e4124cb3575331 | 0 | fhieber/incubator-joshua,kpu/joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,gwenniger/joshua,thammegowda/incubator-joshua,lukeorland/joshua,thammegowda/incubator-joshua,lukeorland/joshua,lukeorland/joshua,gwenniger/joshua,lukeorland/joshua,kpu/joshua,kpu/joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,gwenniger/joshua,gwenniger/joshua,fhieber/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,gwenniger/joshua,lukeorland/joshua,thammegowda/incubator-joshua,kpu/joshua,gwenniger/joshua,lukeorland/joshua,lukeorland/joshua,kpu/joshua,kpu/joshua,fhieber/incubator-joshua,lukeorland/joshua | /* This file is part of the Joshua Machine Translation System.
*
* Joshua is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
package joshua.decoder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import joshua.util.Ngram;
import joshua.util.Regex;
/**
* this class implements:
* (1) nbest min risk (MBR) reranking using BLEU as a gain funtion.
* <p>
* This assume that the string is unique in the nbest list In Hiero,
* due to spurious ambiguity, a string may correspond to many
* possible derivations, and ideally the probability of a string
* should be the sum of all the derivataions leading to that string.
* But, in practice, one normally uses a Viterbi approximation: the
* probability of a string is its best derivation probability So,
* if one want to deal with spurious ambiguity, he/she should do
* that before calling this class
*
* @author Zhifei Li, <[email protected]>
* @version $LastChangedDate$
*/
public class NbestMinRiskReranker {
//TODO: this functionality is not implemented yet; default is to produce 1best without any feature scores;
boolean produceRerankedNbest = false;
double scalingFactor = 1.0;
static int bleuOrder = 4;
static boolean doNgramClip = true;
static boolean useGoogleLinearCorpusGain = false;
final PriorityBlockingQueue<RankerResult> resultsQueue =
new PriorityBlockingQueue<RankerResult>();
public NbestMinRiskReranker(boolean produceRerankedNbest, double scalingFactor) {
this.produceRerankedNbest = produceRerankedNbest;
this.scalingFactor = scalingFactor;
}
public String processOneSent( List<String> nbest, int sentID) {
System.err.println("Now process sentence " + sentID);
//step-0: preprocess
//assumption: each hyp has a formate: "sent_id ||| hyp_itself ||| feature scores ||| linear-combination-of-feature-scores(this should be logP)"
List<String> hypsItself = new ArrayList<String>();
//ArrayList<String> l_feat_scores = new ArrayList<String>();
List<Double> baselineScores = new ArrayList<Double>(); // linear combination of all baseline features
List<HashMap<String,Integer>> ngramTbls = new ArrayList<HashMap<String,Integer>>();
List<Integer> sentLens = new ArrayList<Integer>();
for (String hyp : nbest) {
String[] fds = Regex.threeBarsWithSpace.split(hyp);
int tSentID = Integer.parseInt(fds[0]);
if (sentID != tSentID) {
throw new RuntimeException("sentence_id does not match");
}
String hypothesis = (fds.length==4) ? fds[1] : "";
hypsItself.add(hypothesis);
String[] words = Regex.spaces.split(hypothesis);
sentLens.add(words.length);
HashMap<String,Integer> ngramTbl = new HashMap<String,Integer>();
Ngram.getNgrams(ngramTbl, 1, bleuOrder, words);
ngramTbls.add(ngramTbl);
//l_feat_scores.add(fds[2]);
// The value of finalIndex is expected to be 3,
// unless the hyp_itself is empty,
// in which case finalIndex will be 2.
int finalIndex = fds.length - 1;
baselineScores.add(Double.parseDouble(fds[finalIndex]));
}
//step-1: get normalized distribution
/**value in baselineScores will be changed to normalized probability
* */
computeNormalizedProbs(baselineScores, scalingFactor);
List<Double> normalizedProbs = baselineScores;
//=== required by google linear corpus gain
HashMap<String, Double> posteriorCountsTbl = null;
if (useGoogleLinearCorpusGain) {
posteriorCountsTbl = new HashMap<String,Double>();
getGooglePosteriorCounts(ngramTbls, normalizedProbs, posteriorCountsTbl);
}
//step-2: rerank the nbest
/**TODO: zhifei: now the re-ranking takes O(n^2) where n is the size of the nbest.
* But, we can significantly speed up this (leadding to O(n)) by
* first estimating a model on nbest, and then rerank the nbest
* using the estimated model.
* */
double bestGain = -1000000000;//set as worst gain
String bestHyp = null;
List<Double> gains = new ArrayList<Double>();
for (int i = 0; i < hypsItself.size(); i++) {
String curHyp = hypsItself.get(i);
int curHypLen = sentLens.get(i);
HashMap<String, Integer> curHypNgramTbl = ngramTbls.get(i);
//double cur_gain = computeGain(cur_hyp, l_hyp_itself, l_normalized_probs);
double curGain = 0;
if (useGoogleLinearCorpusGain) {
curGain = computeExpectedLinearCorpusGain(curHypLen, curHypNgramTbl, posteriorCountsTbl);
} else {
curGain = computeExpectedGain(curHypLen, curHypNgramTbl, ngramTbls, sentLens,normalizedProbs);
}
gains.add( curGain);
if (i == 0 || curGain > bestGain) { // maximize
bestGain = curGain;
bestHyp = curHyp;
}
}
//step-3: output the 1best or nbest
if (this.produceRerankedNbest) {
//TOTO: sort the list and write the reranked nbest; Use Collections.sort(List list, Comparator c)
} else {
/*
this.out.write(best_hyp);
this.out.write("\n");
out.flush();
*/
}
System.err.println("best gain: " + bestGain);
if (null == bestHyp) {
throw new RuntimeException("mbr reranked one best is null, must be wrong");
}
return bestHyp;
}
/**based on a list of log-probabilities in nbestLogProbs, obtain a
* normalized distribution, and put the normalized probability (real value in [0,1]) into nbestLogProbs
* */
//get a normalized distributeion and put it back to nbestLogProbs
static public void computeNormalizedProbs(List<Double> nbestLogProbs, double scalingFactor){
//=== get noralization constant, remember features, remember the combined linear score
double normalizationConstant = Double.NEGATIVE_INFINITY;//log-semiring
for (double logp : nbestLogProbs) {
normalizationConstant = addInLogSemiring(normalizationConstant, logp * scalingFactor, 0);
}
//System.out.println("normalization_constant (logP) is " + normalization_constant);
//=== get normalized prob for each hyp
double tSum = 0;
for (int i = 0; i < nbestLogProbs.size(); i++) {
double normalizedProb = Math.exp(nbestLogProbs.get(i) * scalingFactor-normalizationConstant);
tSum += normalizedProb;
nbestLogProbs.set(i, normalizedProb);
if (Double.isNaN(normalizedProb)) {
throw new RuntimeException(
"prob is NaN, must be wrong\nnbest_logps.get(i): "
+ nbestLogProbs.get(i)
+ "; scaling_factor: " + scalingFactor
+ "; normalization_constant:" + normalizationConstant );
}
//logger.info("probability: " + normalized_prob);
}
//sanity check
if (Math.abs(tSum - 1.0) > 1e-4) {
throw new RuntimeException("probabilities not sum to one, must be wrong");
}
}
//Gain(e) = negative risk = \sum_{e'} G(e, e')P(e')
//curHyp: e
//trueHyp: e'
public double computeExpectedGain(int curHypLen, HashMap<String, Integer> curHypNgramTbl, List<HashMap<String,Integer>> ngramTbls,
List<Integer> sentLens, List<Double> nbestProbs) {
//### get noralization constant, remember features, remember the combined linear score
double gain = 0;
for (int i = 0; i < nbestProbs.size(); i++) {
HashMap<String,Integer> trueHypNgramTbl = ngramTbls.get(i);
double trueProb = nbestProbs.get(i);
int trueLen = sentLens.get(i);
gain += trueProb * BLEU.computeSentenceBleu(trueLen, trueHypNgramTbl, curHypLen, curHypNgramTbl, doNgramClip, bleuOrder);
}
//System.out.println("Gain is " + gain);
return gain;
}
//Gain(e) = negative risk = \sum_{e'} G(e, e')P(e')
//curHyp: e
//trueHyp: e'
static public double computeExpectedGain(String curHyp, List<String> nbestHyps, List<Double> nbestProbs) {
//### get noralization constant, remember features, remember the combined linear score
double gain = 0;
for (int i = 0; i < nbestHyps.size(); i++) {
String trueHyp = nbestHyps.get(i);
double trueProb = nbestProbs.get(i);
gain += trueProb * BLEU.computeSentenceBleu(trueHyp, curHyp, doNgramClip, bleuOrder);
}
//System.out.println("Gain is " + gain);
return gain;
}
void getGooglePosteriorCounts( List<HashMap<String,Integer>> ngramTbls, List<Double> normalizedProbs, HashMap<String,Double> posteriorCountsTbl) {
//TODO
}
double computeExpectedLinearCorpusGain(int curHypLen, HashMap<String,Integer> curHypNgramTbl, HashMap<String,Double> posteriorCountsTbl) {
//TODO
double[] thetas = { -1, 1, 1, 1, 1 };
double res = 0;
res += thetas[0] * curHypLen;
for (Entry<String,Integer> entry : curHypNgramTbl.entrySet()) {
String key = entry.getKey();
String[] tem = Regex.spaces.split(key);
double post_prob = posteriorCountsTbl.get(key);
res += entry.getValue() * post_prob * thetas[tem.length];
}
return res;
}
// OR: return Math.log(Math.exp(x) + Math.exp(y));
static private double addInLogSemiring(double x, double y, int addMode){//prevent over-flow
if (addMode == 0) { // sum
if (x == Double.NEGATIVE_INFINITY) {//if y is also n-infinity, then return n-infinity
return y;
}
if (y == Double.NEGATIVE_INFINITY) {
return x;
}
if (y <= x) {
return x + Math.log(1+Math.exp(y-x));
} else {
return y + Math.log(1+Math.exp(x-y));
}
} else if (addMode == 1) { // viter-min
return (x <= y) ? x : y;
} else if (addMode == 2) { // viter-max
return (x >= y) ? x : y;
} else {
throw new RuntimeException("invalid add mode");
}
}
public static void main(String[] args) throws IOException {
// If you don't know what to use for scaling factor, try using 1
if (args.length<2) {
System.err.println("usage: java NbestMinRiskReranker <produce_reranked_nbest> <scaling_factor> [numThreads]");
return;
}
long startTime = System.currentTimeMillis();
boolean produceRerankedNbest = Boolean.valueOf(args[0].trim());
double scalingFactor = Double.parseDouble(args[1].trim());
int numThreads = (args.length > 2) ? Integer.parseInt(args[2].trim()) : 1;
NbestMinRiskReranker mbrReranker =
new NbestMinRiskReranker(produceRerankedNbest, scalingFactor);
System.err.println("##############running mbr reranking");
int oldSentID = -1;
List<String> nbest = new ArrayList<String>();
Scanner scanner = new Scanner(System.in, "UTF-8");
if (numThreads==1) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] fds = Regex.threeBarsWithSpace.split(line);
int newSentID = Integer.parseInt(fds[0]);
if (oldSentID != -1 && oldSentID != newSentID) {
if (nbest.size() > 0) {
String best_hyp = mbrReranker.processOneSent(nbest, oldSentID);//nbest: list of unique strings
System.out.println(best_hyp);
} else {
System.out.println();
}
nbest.clear();
}
oldSentID = newSentID;
if (! fds[1].matches("^\\s*$"))
nbest.add(line);
}
//last nbest
if (oldSentID >= 0) {
String bestHyp = mbrReranker.processOneSent(nbest, oldSentID);
System.out.println(bestHyp);
nbest.clear();
}
} else {
ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] fds = Regex.threeBarsWithSpace.split(line);
int newSentID = Integer.parseInt(fds[0]);
if (oldSentID != -1 && oldSentID != newSentID) {
threadPool.execute(mbrReranker.new RankerTask(nbest, oldSentID));
nbest.clear();
}
oldSentID = newSentID;
nbest.add(line);
}
//last nbest
threadPool.execute(mbrReranker.new RankerTask(nbest, oldSentID));
nbest.clear();
threadPool.shutdown();
try {
threadPool.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
while (! mbrReranker.resultsQueue.isEmpty()) {
RankerResult result = mbrReranker.resultsQueue.remove();
String best_hyp = result.toString();
System.out.println(best_hyp);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.err.println("Total running time (seconds) is "
+ (System.currentTimeMillis() - startTime) / 1000.0);
}
private class RankerTask implements Runnable {
final List<String> nbest;
final int sentID;
RankerTask(final List<String> nbest, final int sentID) {
this.nbest = new ArrayList<String>(nbest);
this.sentID = sentID;
}
public void run() {
String result = processOneSent(nbest, sentID);
resultsQueue.add(new RankerResult(result,sentID));
}
}
private static class RankerResult implements Comparable<RankerResult> {
final String result;
final Integer sentenceNumber;
RankerResult(String result, int sentenceNumber) {
this.result = result;
this.sentenceNumber = sentenceNumber;
}
public int compareTo(RankerResult o) {
return sentenceNumber.compareTo(o.sentenceNumber);
}
public String toString() {
return result;
}
}
}
| src/joshua/decoder/NbestMinRiskReranker.java | /* This file is part of the Joshua Machine Translation System.
*
* Joshua is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
package joshua.decoder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import joshua.util.Ngram;
import joshua.util.Regex;
/**
* this class implements:
* (1) nbest min risk (MBR) reranking using BLEU as a gain funtion.
* <p>
* This assume that the string is unique in the nbest list In Hiero,
* due to spurious ambiguity, a string may correspond to many
* possible derivations, and ideally the probability of a string
* should be the sum of all the derivataions leading to that string.
* But, in practice, one normally uses a Viterbi approximation: the
* probability of a string is its best derivation probability So,
* if one want to deal with spurious ambiguity, he/she should do
* that before calling this class
*
* @author Zhifei Li, <[email protected]>
* @version $LastChangedDate$
*/
public class NbestMinRiskReranker {
//TODO: this functionality is not implemented yet; default is to produce 1best without any feature scores;
boolean produceRerankedNbest = false;
double scalingFactor = 1.0;
static int bleuOrder = 4;
static boolean doNgramClip = true;
static boolean useGoogleLinearCorpusGain = false;
final PriorityBlockingQueue<RankerResult> resultsQueue =
new PriorityBlockingQueue<RankerResult>();
public NbestMinRiskReranker(boolean produceRerankedNbest, double scalingFactor) {
this.produceRerankedNbest = produceRerankedNbest;
this.scalingFactor = scalingFactor;
}
public String processOneSent( List<String> nbest, int sentID) {
System.err.println("Now process sentence " + sentID);
//step-0: preprocess
//assumption: each hyp has a formate: "sent_id ||| hyp_itself ||| feature scores ||| linear-combination-of-feature-scores(this should be logP)"
List<String> hypsItself = new ArrayList<String>();
//ArrayList<String> l_feat_scores = new ArrayList<String>();
List<Double> baselineScores = new ArrayList<Double>(); // linear combination of all baseline features
List<HashMap<String,Integer>> ngramTbls = new ArrayList<HashMap<String,Integer>>();
List<Integer> sentLens = new ArrayList<Integer>();
for (String hyp : nbest) {
String[] fds = Regex.threeBarsWithSpace.split(hyp);
int tSentID = Integer.parseInt(fds[0]);
if (sentID != tSentID) {
throw new RuntimeException("sentence_id does not match");
}
String hypothesis = (fds.length==4) ? fds[1] : "";
hypsItself.add(hypothesis);
String[] words = Regex.spaces.split(hypothesis);
sentLens.add(words.length);
HashMap<String,Integer> ngramTbl = new HashMap<String,Integer>();
Ngram.getNgrams(ngramTbl, 1, bleuOrder, words);
ngramTbls.add(ngramTbl);
//l_feat_scores.add(fds[2]);
// The value of finalIndex is expected to be 3,
// unless the hyp_itself is empty,
// in which case finalIndex will be 2.
int finalIndex = fds.length - 1;
baselineScores.add(Double.parseDouble(fds[finalIndex]));
}
//step-1: get normalized distribution
/**value in baselineScores will be changed to normalized probability
* */
computeNormalizedProbs(baselineScores, scalingFactor);
List<Double> normalizedProbs = baselineScores;
//=== required by google linear corpus gain
HashMap<String, Double> posteriorCountsTbl = null;
if (useGoogleLinearCorpusGain) {
posteriorCountsTbl = new HashMap<String,Double>();
getGooglePosteriorCounts(ngramTbls, normalizedProbs, posteriorCountsTbl);
}
//step-2: rerank the nbest
/**TODO: zhifei: now the re-ranking takes O(n^2) where n is the size of the nbest.
* But, we can significantly speed up this (leadding to O(n)) by
* first estimating a model on nbest, and then rerank the nbest
* using the estimated model.
* */
double bestGain = -1000000000;//set as worst gain
String bestHyp = null;
List<Double> gains = new ArrayList<Double>();
for (int i = 0; i < hypsItself.size(); i++) {
String curHyp = hypsItself.get(i);
int curHypLen = sentLens.get(i);
HashMap<String, Integer> curHypNgramTbl = ngramTbls.get(i);
//double cur_gain = computeGain(cur_hyp, l_hyp_itself, l_normalized_probs);
double curGain = 0;
if (useGoogleLinearCorpusGain) {
curGain = computeExpectedLinearCorpusGain(curHypLen, curHypNgramTbl, posteriorCountsTbl);
} else {
curGain = computeExpectedGain(curHypLen, curHypNgramTbl, ngramTbls, sentLens,normalizedProbs);
}
gains.add( curGain);
if (i == 0 || curGain > bestGain) { // maximize
bestGain = curGain;
bestHyp = curHyp;
}
}
//step-3: output the 1best or nbest
if (this.produceRerankedNbest) {
//TOTO: sort the list and write the reranked nbest; Use Collections.sort(List list, Comparator c)
} else {
/*
this.out.write(best_hyp);
this.out.write("\n");
out.flush();
*/
}
System.err.println("best gain: " + bestGain);
if (null == bestHyp) {
throw new RuntimeException("mbr reranked one best is null, must be wrong");
}
return bestHyp;
}
/**based on a list of log-probabilities in nbestLogProbs, obtain a
* normalized distribution, and put the normalized probability (real value in [0,1]) into nbestLogProbs
* */
//get a normalized distributeion and put it back to nbestLogProbs
static public void computeNormalizedProbs(List<Double> nbestLogProbs, double scalingFactor){
//=== get noralization constant, remember features, remember the combined linear score
double normalizationConstant = Double.NEGATIVE_INFINITY;//log-semiring
for (double logp : nbestLogProbs) {
normalizationConstant = addInLogSemiring(normalizationConstant, logp * scalingFactor, 0);
}
//System.out.println("normalization_constant (logP) is " + normalization_constant);
//=== get normalized prob for each hyp
double tSum = 0;
for (int i = 0; i < nbestLogProbs.size(); i++) {
double normalizedProb = Math.exp(nbestLogProbs.get(i) * scalingFactor-normalizationConstant);
tSum += normalizedProb;
nbestLogProbs.set(i, normalizedProb);
if (Double.isNaN(normalizedProb)) {
throw new RuntimeException(
"prob is NaN, must be wrong\nnbest_logps.get(i): "
+ nbestLogProbs.get(i)
+ "; scaling_factor: " + scalingFactor
+ "; normalization_constant:" + normalizationConstant );
}
//logger.info("probability: " + normalized_prob);
}
//sanity check
if (Math.abs(tSum - 1.0) > 1e-4) {
throw new RuntimeException("probabilities not sum to one, must be wrong");
}
}
//Gain(e) = negative risk = \sum_{e'} G(e, e')P(e')
//curHyp: e
//trueHyp: e'
public double computeExpectedGain(int curHypLen, HashMap<String, Integer> curHypNgramTbl, List<HashMap<String,Integer>> ngramTbls,
List<Integer> sentLens, List<Double> nbestProbs) {
//### get noralization constant, remember features, remember the combined linear score
double gain = 0;
for (int i = 0; i < nbestProbs.size(); i++) {
HashMap<String,Integer> trueHypNgramTbl = ngramTbls.get(i);
double trueProb = nbestProbs.get(i);
int trueLen = sentLens.get(i);
gain += trueProb * BLEU.computeSentenceBleu(trueLen, trueHypNgramTbl, curHypLen, curHypNgramTbl, doNgramClip, bleuOrder);
}
//System.out.println("Gain is " + gain);
return gain;
}
//Gain(e) = negative risk = \sum_{e'} G(e, e')P(e')
//curHyp: e
//trueHyp: e'
static public double computeExpectedGain(String curHyp, List<String> nbestHyps, List<Double> nbestProbs) {
//### get noralization constant, remember features, remember the combined linear score
double gain = 0;
for (int i = 0; i < nbestHyps.size(); i++) {
String trueHyp = nbestHyps.get(i);
double trueProb = nbestProbs.get(i);
gain += trueProb * BLEU.computeSentenceBleu(trueHyp, curHyp, doNgramClip, bleuOrder);
}
//System.out.println("Gain is " + gain);
return gain;
}
void getGooglePosteriorCounts( List<HashMap<String,Integer>> ngramTbls, List<Double> normalizedProbs, HashMap<String,Double> posteriorCountsTbl) {
//TODO
}
double computeExpectedLinearCorpusGain(int curHypLen, HashMap<String,Integer> curHypNgramTbl, HashMap<String,Double> posteriorCountsTbl) {
//TODO
double[] thetas = { -1, 1, 1, 1, 1 };
double res = 0;
res += thetas[0] * curHypLen;
for (Entry<String,Integer> entry : curHypNgramTbl.entrySet()) {
String key = entry.getKey();
String[] tem = Regex.spaces.split(key);
double post_prob = posteriorCountsTbl.get(key);
res += entry.getValue() * post_prob * thetas[tem.length];
}
return res;
}
// OR: return Math.log(Math.exp(x) + Math.exp(y));
static private double addInLogSemiring(double x, double y, int addMode){//prevent over-flow
if (addMode == 0) { // sum
if (x == Double.NEGATIVE_INFINITY) {//if y is also n-infinity, then return n-infinity
return y;
}
if (y == Double.NEGATIVE_INFINITY) {
return x;
}
if (y <= x) {
return x + Math.log(1+Math.exp(y-x));
} else {
return y + Math.log(1+Math.exp(x-y));
}
} else if (addMode == 1) { // viter-min
return (x <= y) ? x : y;
} else if (addMode == 2) { // viter-max
return (x >= y) ? x : y;
} else {
throw new RuntimeException("invalid add mode");
}
}
public static void main(String[] args) throws IOException {
// If you don't know what to use for scaling factor, try using 1
if (args.length<2) {
System.err.println("usage: java NbestMinRiskReranker <produce_reranked_nbest> <scaling_factor> [numThreads]");
return;
}
long startTime = System.currentTimeMillis();
boolean produceRerankedNbest = Boolean.valueOf(args[0].trim());
double scalingFactor = Double.parseDouble(args[1].trim());
int numThreads = (args.length > 2) ? Integer.parseInt(args[2].trim()) : 1;
NbestMinRiskReranker mbrReranker =
new NbestMinRiskReranker(produceRerankedNbest, scalingFactor);
System.err.println("##############running mbr reranking");
int oldSentID = -1;
List<String> nbest = new ArrayList<String>();
Scanner scanner = new Scanner(System.in, "UTF-8");
if (numThreads==1) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] fds = Regex.threeBarsWithSpace.split(line);
int newSentID = Integer.parseInt(fds[0]);
if (oldSentID != -1 && oldSentID != newSentID) {
String best_hyp = mbrReranker.processOneSent(nbest, oldSentID);//nbest: list of unique strings
System.out.println(best_hyp);
nbest.clear();
}
oldSentID = newSentID;
nbest.add(line);
}
//last nbest
if (oldSentID >= 0) {
String bestHyp = mbrReranker.processOneSent(nbest, oldSentID);
System.out.println(bestHyp);
nbest.clear();
}
} else {
ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] fds = Regex.threeBarsWithSpace.split(line);
int newSentID = Integer.parseInt(fds[0]);
if (oldSentID != -1 && oldSentID != newSentID) {
threadPool.execute(mbrReranker.new RankerTask(nbest, oldSentID));
nbest.clear();
}
oldSentID = newSentID;
nbest.add(line);
}
//last nbest
threadPool.execute(mbrReranker.new RankerTask(nbest, oldSentID));
nbest.clear();
threadPool.shutdown();
try {
threadPool.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
while (! mbrReranker.resultsQueue.isEmpty()) {
RankerResult result = mbrReranker.resultsQueue.remove();
String best_hyp = result.toString();
System.out.println(best_hyp);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.err.println("Total running time (seconds) is "
+ (System.currentTimeMillis() - startTime) / 1000.0);
}
private class RankerTask implements Runnable {
final List<String> nbest;
final int sentID;
RankerTask(final List<String> nbest, final int sentID) {
this.nbest = new ArrayList<String>(nbest);
this.sentID = sentID;
}
public void run() {
String result = processOneSent(nbest, sentID);
resultsQueue.add(new RankerResult(result,sentID));
}
}
private static class RankerResult implements Comparable<RankerResult> {
final String result;
final Integer sentenceNumber;
RankerResult(String result, int sentenceNumber) {
this.result = result;
this.sentenceNumber = sentenceNumber;
}
public int compareTo(RankerResult o) {
return sentenceNumber.compareTo(o.sentenceNumber);
}
public String toString() {
return result;
}
}
}
| bugfix: skipping blank lines
| src/joshua/decoder/NbestMinRiskReranker.java | bugfix: skipping blank lines |
|
Java | apache-2.0 | 61ab54d99d32ffbb4b6045cb2becd4997c502de4 | 0 | cmbntr/httpclient,atlassian/httpclient,UlrichColby/httpcomponents-client,ok2c/httpclient,apache/httpcomponents-client,cmbntr/httpclient,atlassian/httpclient | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.client.cache;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import org.apache.http.annotation.Immutable;
@Immutable
class IOUtils {
static void copy(final InputStream in, final OutputStream out) throws IOException {
byte[] buf = new byte[2048];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
static void closeSilently(final Closeable closable) {
try {
closable.close();
} catch (IOException ignore) {
}
}
static void copyAndClose(final InputStream in, final OutputStream out) throws IOException {
try {
copy(in, out);
in.close();
out.close();
} catch (IOException ex) {
closeSilently(in);
closeSilently(out);
// Propagate the original exception
throw ex;
}
}
static void copyFile(final File in, final File out) throws IOException {
RandomAccessFile f1 = new RandomAccessFile(in, "r");
RandomAccessFile f2 = new RandomAccessFile(out, "rw");
try {
FileChannel c1 = f1.getChannel();
FileChannel c2 = f2.getChannel();
try {
c1.transferTo(0, f1.length(), c2);
c1.close();
c2.close();
} catch (IOException ex) {
closeSilently(c1);
closeSilently(c2);
// Propagate the original exception
throw ex;
}
f1.close();
f2.close();
} catch (IOException ex) {
closeSilently(f1);
closeSilently(f2);
// Propagate the original exception
throw ex;
}
}
}
| httpclient-cache/src/main/java/org/apache/http/impl/client/cache/IOUtils.java | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.client.cache;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import org.apache.http.annotation.Immutable;
@Immutable
class IOUtils {
static void copy(final InputStream in, final OutputStream out) throws IOException {
byte[] buf = new byte[2048];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
static void closeSilently(final Closeable closable) {
try {
closable.close();
} catch (IOException ignore) {
}
}
static void copyAndClose(final InputStream in, final OutputStream out) throws IOException {
try {
copy(in, out);
in.close();
out.close();
} catch (IOException ex) {
closeSilently(in);
closeSilently(out);
// Propagate the original exception
throw ex;
}
}
static void copyFile(final File in, final File out) throws IOException {
RandomAccessFile f1 = new RandomAccessFile(in, "r");
RandomAccessFile f2 = new RandomAccessFile(out, "w");
try {
FileChannel c1 = f1.getChannel();
FileChannel c2 = f2.getChannel();
try {
c1.transferTo(0, f1.length(), c2);
c1.close();
c2.close();
} catch (IOException ex) {
closeSilently(c1);
closeSilently(c2);
// Propagate the original exception
throw ex;
}
f1.close();
f2.close();
} catch (IOException ex) {
closeSilently(f1);
closeSilently(f2);
// Propagate the original exception
throw ex;
}
}
}
| HTTPCLIENT-1135: RandomAccessFile mode w is not valid
git-svn-id: 897293da6115b9493049ecf64199cf2f9a0ac287@1180373 13f79535-47bb-0310-9956-ffa450edef68
| httpclient-cache/src/main/java/org/apache/http/impl/client/cache/IOUtils.java | HTTPCLIENT-1135: RandomAccessFile mode w is not valid |
|
Java | apache-2.0 | efc3bd73c3fd8e28d688d32c257f577dddcaee8d | 0 | tarasane/h2o-3,michalkurka/h2o-3,PawarPawan/h2o-v3,h2oai/h2o-dev,ChristosChristofidis/h2o-3,bospetersen/h2o-3,jangorecki/h2o-3,nilbody/h2o-3,bospetersen/h2o-3,jangorecki/h2o-3,YzPaul3/h2o-3,YzPaul3/h2o-3,mathemage/h2o-3,junwucs/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,printedheart/h2o-3,h2oai/h2o-dev,nilbody/h2o-3,jangorecki/h2o-3,tarasane/h2o-3,pchmieli/h2o-3,jangorecki/h2o-3,bospetersen/h2o-3,junwucs/h2o-3,PawarPawan/h2o-v3,datachand/h2o-3,h2oai/h2o-3,YzPaul3/h2o-3,mrgloom/h2o-3,kyoren/https-github.com-h2oai-h2o-3,brightchen/h2o-3,printedheart/h2o-3,bospetersen/h2o-3,spennihana/h2o-3,weaver-viii/h2o-3,madmax983/h2o-3,michalkurka/h2o-3,junwucs/h2o-3,mrgloom/h2o-3,h2oai/h2o-3,h2oai/h2o-3,mathemage/h2o-3,ChristosChristofidis/h2o-3,PawarPawan/h2o-v3,printedheart/h2o-3,kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,printedheart/h2o-3,mrgloom/h2o-3,brightchen/h2o-3,spennihana/h2o-3,madmax983/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,tarasane/h2o-3,brightchen/h2o-3,kyoren/https-github.com-h2oai-h2o-3,bospetersen/h2o-3,nilbody/h2o-3,spennihana/h2o-3,PawarPawan/h2o-v3,pchmieli/h2o-3,spennihana/h2o-3,ChristosChristofidis/h2o-3,mathemage/h2o-3,jangorecki/h2o-3,pchmieli/h2o-3,printedheart/h2o-3,spennihana/h2o-3,nilbody/h2o-3,weaver-viii/h2o-3,junwucs/h2o-3,brightchen/h2o-3,h2oai/h2o-3,ChristosChristofidis/h2o-3,michalkurka/h2o-3,datachand/h2o-3,tarasane/h2o-3,printedheart/h2o-3,spennihana/h2o-3,brightchen/h2o-3,michalkurka/h2o-3,nilbody/h2o-3,madmax983/h2o-3,madmax983/h2o-3,pchmieli/h2o-3,pchmieli/h2o-3,mrgloom/h2o-3,madmax983/h2o-3,weaver-viii/h2o-3,weaver-viii/h2o-3,jangorecki/h2o-3,junwucs/h2o-3,h2oai/h2o-3,tarasane/h2o-3,YzPaul3/h2o-3,mathemage/h2o-3,h2oai/h2o-3,mrgloom/h2o-3,printedheart/h2o-3,ChristosChristofidis/h2o-3,mrgloom/h2o-3,PawarPawan/h2o-v3,weaver-viii/h2o-3,brightchen/h2o-3,kyoren/https-github.com-h2oai-h2o-3,tarasane/h2o-3,mrgloom/h2o-3,datachand/h2o-3,pchmieli/h2o-3,bospetersen/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,YzPaul3/h2o-3,brightchen/h2o-3,datachand/h2o-3,PawarPawan/h2o-v3,ChristosChristofidis/h2o-3,madmax983/h2o-3,nilbody/h2o-3,ChristosChristofidis/h2o-3,jangorecki/h2o-3,datachand/h2o-3,bospetersen/h2o-3,PawarPawan/h2o-v3,YzPaul3/h2o-3,michalkurka/h2o-3,mathemage/h2o-3,datachand/h2o-3,weaver-viii/h2o-3,kyoren/https-github.com-h2oai-h2o-3,junwucs/h2o-3,kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,pchmieli/h2o-3,YzPaul3/h2o-3,nilbody/h2o-3,junwucs/h2o-3,weaver-viii/h2o-3,tarasane/h2o-3,datachand/h2o-3,h2oai/h2o-dev,kyoren/https-github.com-h2oai-h2o-3,madmax983/h2o-3,mathemage/h2o-3,mathemage/h2o-3 | package hex;
import hex.schemas.ModelBuilderSchema;
import water.*;
import water.exceptions.H2OIllegalArgumentException;
import water.exceptions.H2OKeyNotFoundArgumentException;
import water.fvec.*;
import water.util.FrameUtils;
import water.util.Log;
import water.util.MRUtils;
import water.util.ReflectionUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Model builder parent class. Contains the common interfaces and fields across all model builders.
*/
abstract public class ModelBuilder<M extends Model<M,P,O>, P extends Model.Parameters, O extends Model.Output> extends Job<M> {
/** All the parameters required to build the model. */
public final P _parms;
/** Training frame: derived from the parameter's training frame, excluding
* all ignored columns, all constant and bad columns, perhaps flipping the
* response column to an Categorical, etc. */
public final Frame train() { return _train; }
protected transient Frame _train;
/** Validation frame: derived from the parameter's validation frame, excluding
* all ignored columns, all constant and bad columns, perhaps flipping the
* response column to a Categorical, etc. Is null if no validation key is set. */
public final Frame valid() { return _valid; }
protected transient Frame _valid;
// TODO: tighten up the type
// Map the algo name (e.g., "deeplearning") to the builder class (e.g., DeepLearning.class) :
private static final Map<String, Class<? extends ModelBuilder>> _builders = new HashMap<>();
// Map the Model class (e.g., DeepLearningModel.class) to the algo name (e.g., "deeplearning"):
private static final Map<Class<? extends Model>, String> _model_class_to_algo = new HashMap<>();
// Map the simple algo name (e.g., deeplearning) to the full algo name (e.g., "Deep Learning"):
private static final Map<String, String> _algo_to_algo_full_name = new HashMap<>();
// Map the algo name (e.g., "deeplearning") to the Model class (e.g., DeepLearningModel.class):
private static final Map<String, Class<? extends Model>> _algo_to_model_class = new HashMap<>();
/** Train response vector. */
public Vec response(){return _response;}
/** Validation response vector. */
public Vec vresponse(){return _vresponse;}
/**
* Compute the (weighted) mean of the response (subtracting possible offset terms)
* @return mean
*/
protected double responseMean() {
if (hasWeights() || hasOffset()) {
return new FrameUtils.WeightedMean().doAll(
_response,
hasWeights() ? _weights : _response.makeCon(1),
hasOffset() ? _offset : _response.makeCon(0)
).weightedMean();
}
return _response.mean();
}
/**
* Register a ModelBuilder, assigning it an algo name.
*/
public static void registerModelBuilder(String name, String full_name, Class<? extends ModelBuilder> clz) {
_builders.put(name, clz);
Class<? extends Model> model_class = (Class<? extends Model>)ReflectionUtils.findActualClassParameter(clz, 0);
_model_class_to_algo.put(model_class, name);
_algo_to_algo_full_name.put(name, full_name);
_algo_to_model_class.put(name, model_class);
}
/** Get a Map of all algo names to their ModelBuilder classes. */
public static Map<String, Class<? extends ModelBuilder>>getModelBuilders() { return _builders; }
/** Get the ModelBuilder class for the given algo name. */
public static Class<? extends ModelBuilder> getModelBuilder(String name) {
return _builders.get(name);
}
/** Get the Model class for the given algo name. */
public static Class<? extends Model> getModelClass(String name) {
return _algo_to_model_class.get(name);
}
/** Get the algo name for the given Model. */
public static String getAlgo(Model model) {
return _model_class_to_algo.get(model.getClass());
}
/** Get the algo full name for the given algo. */
public static String getAlgoFullName(String algo) {
return _algo_to_algo_full_name.get(algo);
}
public String getAlgo() {
return getAlgo(this.getClass());
}
public static String getAlgo(Class<? extends ModelBuilder> clz) {
// Check for unknown algo names, but if none are registered keep going; we're probably in JUnit.
if (_builders.isEmpty())
return "Unknown algo (should only happen under JUnit)";
if (! _builders.containsValue(clz))
throw new H2OIllegalArgumentException("Failed to find ModelBuilder class in registry: " + clz, "Failed to find ModelBuilder class in registry: " + clz);
for (Map.Entry<String, Class<? extends ModelBuilder>> entry : _builders.entrySet())
if (entry.getValue().equals(clz))
return entry.getKey();
// Note: unreachable:
throw new H2OIllegalArgumentException("Failed to find ModelBuilder class in registry: " + clz, "Failed to find ModelBuilder class in registry: " + clz);
}
/**
* Externally visible default schema
* TODO: this is in the wrong layer: the internals should not know anything about the schemas!!!
* This puts a reverse edge into the dependency graph.
*/
public abstract ModelBuilderSchema schema();
/** Constructor called from an http request; MUST override in subclasses. */
public ModelBuilder(P ignore) {
super(Key.make("Failed"),"ModelBuilder constructor needs to be overridden.");
throw H2O.fail("ModelBuilder subclass failed to override the params constructor: " + this.getClass());
}
/** Constructor making a default destination key */
public ModelBuilder(String desc, P parms) {
this((parms == null || parms._model_id == null) ? Key.make(desc + "Model_" + Key.rand()) : parms._model_id, desc, parms);
}
/** Default constructor, given all arguments */
public ModelBuilder(Key dest, String desc, P parms) {
super(dest,desc);
_parms = parms;
}
/** Factory method to create a ModelBuilder instance of the correct class given the algo name. */
public static ModelBuilder createModelBuilder(String algo) {
ModelBuilder modelBuilder;
Class<? extends ModelBuilder> clz = null;
try {
clz = ModelBuilder.getModelBuilder(algo);
}
catch (Exception ignore) {}
if (clz == null) {
throw new H2OIllegalArgumentException("algo", "createModelBuilder", "Algo not known (" + algo + ")");
}
try {
if (! (clz.getGenericSuperclass() instanceof ParameterizedType)) {
throw H2O.fail("Class is not parameterized as expected: " + clz);
}
Type[] handler_type_parms = ((ParameterizedType)(clz.getGenericSuperclass())).getActualTypeArguments();
// [0] is the Model type; [1] is the Model.Parameters type; [2] is the Model.Output type.
Class<? extends Model.Parameters> pclz = (Class<? extends Model.Parameters>)handler_type_parms[1];
Constructor<ModelBuilder> constructor = (Constructor<ModelBuilder>)clz.getDeclaredConstructor(new Class[] { (Class)handler_type_parms[1] });
Model.Parameters p = pclz.newInstance();
modelBuilder = constructor.newInstance(p);
} catch (java.lang.reflect.InvocationTargetException e) {
throw H2O.fail("Exception when trying to instantiate ModelBuilder for: " + algo + ": " + e.getCause(), e);
} catch (Exception e) {
throw H2O.fail("Exception when trying to instantiate ModelBuilder for: " + algo + ": " + e.getCause(), e);
}
return modelBuilder;
}
/** Method to launch training of a Model, based on its parameters. */
abstract public Job<M> trainModel();
/** List containing the categories of models that this builder can
* build. Each ModelBuilder must have one of these. */
abstract public ModelCategory[] can_build();
/**
* Visibility for this algo: is it always visible, is it beta (always visible but with a note in the UI)
* or is it experimental (hidden by default, visible in the UI if the user gives an "experimental" flag
* at startup).
*/
public enum BuilderVisibility {
Experimental,
Beta,
Stable
}
/**
* Visibility for this algo: is it always visible, is it beta (always visible but with a note in the UI)
* or is it experimental (hidden by default, visible in the UI if the user gives an "experimental" flag
* at startup).
*/
abstract public BuilderVisibility builderVisibility();
/** Clear whatever was done by init() so it can be run again. */
public void clearInitState() {
clearValidationErrors();
}
public boolean isSupervised(){return false;}
protected transient Vec _response; // Handy response column
protected transient Vec _vresponse; // Handy response column
protected transient Vec _offset; // Handy offset column
protected transient Vec _weights;
public boolean hasOffset(){ return _offset != null;}
public boolean hasWeights(){return _weights != null;}
// no hasResponse, call isSupervised instead (response is mandatory if isSupervised is true)
protected int _nclass; // Number of classes; 1 for regression; 2+ for classification
public int nclasses(){return _nclass;}
public final boolean isClassifier() { return _nclass > 1; }
/**
* Find and set response/weights/offset and put them all in the end,
* @return number of non-feature vecs
*/
protected int separateFeatureVecs() {
int res = 0;
if(_parms._weights_column != null) {
Vec w = _train.remove(_parms._weights_column);
if(w == null)
error("_weights_column","Weights column '" + _parms._weights_column + "' not found in the training frame");
else {
if(!w.isNumeric())
error("_weights_column","Invalid weights column '" + _parms._weights_column + "', weights must be numeric");
_weights = w;
if(w.naCnt() > 0)
error("_weights_columns","Weights cannot have missing values.");
if(w.min() < 0)
error("_weights_columns","Weights must be >= 0");
if(w.max() == 0)
error("_weights_columns","Max. weight must be > 0");
_train.add(_parms._weights_column, w);
++res;
}
}
if(_parms._offset_column != null) {
Vec o = _train.remove(_parms._offset_column);
if(o == null)
error("_offset_column","Offset column '" + _parms._offset_column + "' not found in the training frame");
else {
if(!o.isNumeric())
error("_offset_column","Invalid offset column '" + _parms._offset_column + "', offset must be numeric");
_offset = o;
if(o.naCnt() > 0)
error("_offset_column","Offset cannot have missing values.");
if(_weights == _offset)
error("_offset_column", "Offset must be different from weights");
_train.add(_parms._offset_column, o);
++res;
}
}
if(isSupervised() && _parms._response_column != null) {
_response = _train.remove(_parms._response_column);
if (_response == null) {
if (isSupervised())
error("_response_column", "Response column '" + _parms._response_column + "' not found in the training frame");
} else {
_train.add(_parms._response_column, _response);
++res;
}
}
return res;
}
protected boolean ignoreStringColumns(){return true;}
/**
* Ignore constant columns, columns with all NAs and strings.
* @param npredictors
* @param expensive
*/
protected void ignoreBadColumns(int npredictors, boolean expensive){
// Drop all-constant and all-bad columns.
if( _parms._ignore_const_cols)
new FilterCols(npredictors) {
@Override protected boolean filter(Vec v) { return v.isConst() || v.isBad() || (ignoreStringColumns() && v.isString()); }
}.doIt(_train,"Dropping constant columns: ",expensive);
}
/**
* Override this method to call error() if the model is expected to not fit in memory, and say why
*/
protected void checkMemoryFootPrint() {}
transient double [] _distribution;
transient double [] _priorClassDist;
protected boolean computePriorClassDistribution(){
return _parms._balance_classes;
}
// ==========================================================================
/** Initialize the ModelBuilder, validating all arguments and preparing the
* training frame. This call is expected to be overridden in the subclasses
* and each subclass will start with "super.init();". This call is made by
* the front-end whenever the GUI is clicked, and needs to be fast whenever
* {@code expensive} is false; it will be called once again at the start of
* model building {@see #trainModel()} with expensive set to true.
*<p>
* The incoming training frame (and validation frame) will have ignored
* columns dropped out, plus whatever work the parent init did.
*<p>
* NOTE: The front end initially calls this through the parameters validation
* endpoint with no training_frame, so each subclass's {@code init()} method
* has to work correctly with the training_frame missing.
*<p>
* @see #updateValidationMessages()
*/
public void init(boolean expensive) {
// Log parameters
if (expensive) {
Log.info("Building H2O " + this.getClass().getSimpleName().toString() + " model with these parameters:");
Log.info(new String(_parms.writeJSON(new AutoBuffer()).buf()));
}
// NOTE: allow re-init:
clearInitState();
assert _parms != null; // Parms must already be set in
if( _parms._train == null ) {
if (expensive)
error("_train","Missing training frame");
return;
}
Frame tr = _parms.train();
if( tr == null ) { error("_train","Missing training frame: "+_parms._train); return; }
_train = new Frame(null /* not putting this into KV */, tr._names.clone(), tr.vecs().clone());
// Drop explicitly dropped columns
if( _parms._ignored_columns != null ) {
_train.remove(_parms._ignored_columns);
if( expensive ) Log.info("Dropping ignored columns: "+Arrays.toString(_parms._ignored_columns));
}
// Drop all non-numeric columns (e.g., String and UUID). No current algo
// can use them, and otherwise all algos will then be forced to remove
// them. Text algos (grep, word2vec) take raw text columns - which are
// numeric (arrays of bytes).
ignoreBadColumns(separateFeatureVecs(), expensive);
// Check that at least some columns are not-constant and not-all-NAs
if( _train.numCols() == 0 )
error("_train","There are no usable columns to generate model");
if(isSupervised()) {
if(_response != null) {
_nclass = _response.isEnum() ? _response.cardinality() : 1;
if (_response.isConst())
error("_response","Response cannot be constant.");
}
if (! _parms._balance_classes)
hide("_max_after_balance_size", "Balance classes is false, hide max_after_balance_size");
else if (_parms._weights_column != null)
error("_balance_classes", "Balance classes and observation weights are not currently supported together.");
if( _parms._max_after_balance_size <= 0.0 )
error("_max_after_balance_size","Max size after balancing needs to be positive, suggest 1.0f");
if( _train != null ) {
if (_train.numCols() <= 1)
error("_train", "Training data must have at least 2 features (incl. response).");
if( null == _parms._response_column) {
error("_response_column", "Response column parameter not set.");
return;
}
if(_response != null && computePriorClassDistribution()) {
if (isClassifier() && isSupervised()) {
MRUtils.ClassDist cdmt =
_weights != null ? new MRUtils.ClassDist(nclasses()).doAll(_response, _weights) : new MRUtils.ClassDist(nclasses()).doAll(_response);
_distribution = cdmt.dist();
_priorClassDist = cdmt.rel_dist();
} else { // Regression; only 1 "class"
_distribution = new double[]{ (_weights != null ? _weights.mean() : 1.0) * train().numRows() };
_priorClassDist = new double[]{1.0f};
}
}
}
if( !isClassifier() ) {
hide("_balance_classes", "Balance classes is only applicable to classification problems.");
hide("_class_sampling_factors", "Class sampling factors is only applicable to classification problems.");
hide("_max_after_balance_size", "Max after balance size is only applicable to classification problems.");
hide("_max_confusion_matrix_size", "Max confusion matrix size is only applicable to classification problems.");
}
if (_nclass <= 2) {
hide("_max_hit_ratio_k", "Max K-value for hit ratio is only applicable to multi-class classification problems.");
hide("_max_confusion_matrix_size", "Only for multi-class classification problems.");
}
if( !_parms._balance_classes ) {
hide("_max_after_balance_size", "Only used with balanced classes");
hide("_class_sampling_factors", "Class sampling factors is only applicable if balancing classes.");
}
}
else {
hide("_response_column", "Ignored for unsupervised methods.");
hide("_balance_classes", "Ignored for unsupervised methods.");
hide("_class_sampling_factors", "Ignored for unsupervised methods.");
hide("_max_after_balance_size", "Ignored for unsupervised methods.");
hide("_max_confusion_matrix_size", "Ignored for unsupervised methods.");
_response = null;
_vresponse = null;
_nclass = 1;
}
// Build the validation set to be compatible with the training set.
// Toss out extra columns, complain about missing ones, remap enums
Frame va = _parms.valid(); // User-given validation set
if (va != null) {
_valid = new Frame(null /* not putting this into KV */, va._names.clone(), va.vecs().clone());
try {
String[] msgs = Model.adaptTestForTrain(_train._names, _parms._weights_column, _parms._offset_column, null, _train.domains(), _valid, _parms.missingColumnsType(), expensive, true);
_vresponse = _valid.vec(_parms._response_column);
if (_vresponse == null && _parms._response_column != null)
error("_validation_frame", "Validation frame must have a response column '" + _parms._response_column + "'.");
if (expensive) {
for (String s : msgs) {
Log.info(s);
info("_valid", s);
}
}
assert !expensive || (_valid == null || Arrays.equals(_train._names, _valid._names));
} catch (IllegalArgumentException iae) {
error("_valid", iae.getMessage());
}
}
}
/**
* init(expensive) is called inside a DTask, not from the http request thread. If we add validation messages to the
* ModelBuilder (aka the Job) we want to update it in the DKV so the client can see them when polling and later on
* after the job completes.
* <p>
* NOTE: this should only be called when no other threads are updating the job, for example from init() or after the
* DTask is stopped and is getting cleaned up.
* @see #init(boolean)
*/
public void updateValidationMessages() {
// Atomically update the validation messages in the Job in the DKV.
// In some cases we haven't stored to the DKV yet:
new TAtomic<Job>() {
@Override public Job atomic(Job old) {
if( old == null ) throw new H2OKeyNotFoundArgumentException(old._key);
ModelBuilder builder = (ModelBuilder)old;
builder._messages = ModelBuilder.this._messages;
return builder;
}
}.invoke(_key);
}
abstract class FilterCols {
final int _specialVecs; // special vecs to skip at the end
public FilterCols(int n) {_specialVecs = n;}
abstract protected boolean filter(Vec v);
void doIt( Frame f, String msg, boolean expensive ) {
boolean any=false;
for( int i = 0; i < f.vecs().length - _specialVecs; i++ ) {
if( filter(f.vecs()[i]) ) {
if( any ) msg += ", "; // Log dropped cols
any = true;
msg += f._names[i];
f.remove(i);
i--; // Re-run at same iteration after dropping a col
}
}
if( any ) {
warn("_train", msg);
if (expensive) Log.info(msg);
}
}
}
/** A list of field validation issues. */
public ValidationMessage[] _messages = new ValidationMessage[0];
private int _error_count = -1; // -1 ==> init not run yet; note, this counts ONLY errors, not WARNs and etc.
public int error_count() { assert _error_count>=0 : "init() not run yet"; return _error_count; }
public void hide (String field_name, String message) { message(ValidationMessage.MessageType.HIDE , field_name, message); }
public void info (String field_name, String message) { message(ValidationMessage.MessageType.INFO , field_name, message); }
public void warn (String field_name, String message) { message(ValidationMessage.MessageType.WARN , field_name, message); }
public void error(String field_name, String message) { message(ValidationMessage.MessageType.ERROR, field_name, message); _error_count++; }
private void clearValidationErrors() {
_messages = new ValidationMessage[0];
_error_count = 0;
}
private void message(ValidationMessage.MessageType message_type, String field_name, String message) {
_messages = Arrays.copyOf(_messages, _messages.length + 1);
_messages[_messages.length - 1] = new ValidationMessage(message_type, field_name, message);
}
/** Get a string representation of only the ERROR ValidationMessages (e.g., to use in an exception throw). */
public String validationErrors() {
StringBuilder sb = new StringBuilder();
for( ValidationMessage vm : _messages )
if( vm.message_type == ValidationMessage.MessageType.ERROR )
sb.append(vm.toString()).append("\n");
return sb.toString();
}
/** The result of an abnormal Model.Parameter check. Contains a
* level, a field name, and a message.
*
* Can be an ERROR, meaning the parameters can't be used as-is,
* a HIDE, which means the specified field should be hidden given
* the values of other fields, or a WARN or INFO for informative
* messages to the user.
*/
public static final class ValidationMessage extends Iced {
public enum MessageType { HIDE, INFO, WARN, ERROR }
final MessageType message_type;
final String field_name;
final String message;
public ValidationMessage(MessageType message_type, String field_name, String message) {
this.message_type = message_type;
this.field_name = field_name;
this.message = message;
switch (message_type) {
case INFO: Log.info(field_name + ": " + message); break;
case WARN: Log.warn(field_name + ": " + message); break;
case ERROR: Log.err(field_name + ": " + message); break;
}
}
@Override public String toString() { return message_type + " on field: " + field_name + ": " + message; }
}
}
| h2o-core/src/main/java/hex/ModelBuilder.java | package hex;
import hex.schemas.ModelBuilderSchema;
import water.*;
import water.exceptions.H2OIllegalArgumentException;
import water.exceptions.H2OKeyNotFoundArgumentException;
import water.fvec.*;
import water.util.FrameUtils;
import water.util.Log;
import water.util.MRUtils;
import water.util.ReflectionUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Model builder parent class. Contains the common interfaces and fields across all model builders.
*/
abstract public class ModelBuilder<M extends Model<M,P,O>, P extends Model.Parameters, O extends Model.Output> extends Job<M> {
/** All the parameters required to build the model. */
public final P _parms;
/** Training frame: derived from the parameter's training frame, excluding
* all ignored columns, all constant and bad columns, perhaps flipping the
* response column to an Categorical, etc. */
public final Frame train() { return _train; }
protected transient Frame _train;
/** Validation frame: derived from the parameter's validation frame, excluding
* all ignored columns, all constant and bad columns, perhaps flipping the
* response column to a Categorical, etc. Is null if no validation key is set. */
public final Frame valid() { return _valid; }
protected transient Frame _valid;
// TODO: tighten up the type
// Map the algo name (e.g., "deeplearning") to the builder class (e.g., DeepLearning.class) :
private static final Map<String, Class<? extends ModelBuilder>> _builders = new HashMap<>();
// Map the Model class (e.g., DeepLearningModel.class) to the algo name (e.g., "deeplearning"):
private static final Map<Class<? extends Model>, String> _model_class_to_algo = new HashMap<>();
// Map the simple algo name (e.g., deeplearning) to the full algo name (e.g., "Deep Learning"):
private static final Map<String, String> _algo_to_algo_full_name = new HashMap<>();
// Map the algo name (e.g., "deeplearning") to the Model class (e.g., DeepLearningModel.class):
private static final Map<String, Class<? extends Model>> _algo_to_model_class = new HashMap<>();
/** Train response vector. */
public Vec response(){return _response;}
/** Validation response vector. */
public Vec vresponse(){return _vresponse;}
/**
* Compute the (weighted) mean of the response (subtracting possible offset terms)
* @return mean
*/
protected double responseMean() {
if (hasWeights() || hasOffset()) {
return new FrameUtils.WeightedMean().doAll(
_response,
hasWeights() ? _weights : _response.makeCon(1),
hasOffset() ? _offset : _response.makeCon(0)
).weightedMean();
}
return _response.mean();
}
/**
* Register a ModelBuilder, assigning it an algo name.
*/
public static void registerModelBuilder(String name, String full_name, Class<? extends ModelBuilder> clz) {
_builders.put(name, clz);
Class<? extends Model> model_class = (Class<? extends Model>)ReflectionUtils.findActualClassParameter(clz, 0);
_model_class_to_algo.put(model_class, name);
_algo_to_algo_full_name.put(name, full_name);
_algo_to_model_class.put(name, model_class);
}
/** Get a Map of all algo names to their ModelBuilder classes. */
public static Map<String, Class<? extends ModelBuilder>>getModelBuilders() { return _builders; }
/** Get the ModelBuilder class for the given algo name. */
public static Class<? extends ModelBuilder> getModelBuilder(String name) {
return _builders.get(name);
}
/** Get the Model class for the given algo name. */
public static Class<? extends Model> getModelClass(String name) {
return _algo_to_model_class.get(name);
}
/** Get the algo name for the given Model. */
public static String getAlgo(Model model) {
return _model_class_to_algo.get(model.getClass());
}
/** Get the algo full name for the given algo. */
public static String getAlgoFullName(String algo) {
return _algo_to_algo_full_name.get(algo);
}
public String getAlgo() {
return getAlgo(this.getClass());
}
public static String getAlgo(Class<? extends ModelBuilder> clz) {
// Check for unknown algo names, but if none are registered keep going; we're probably in JUnit.
if (_builders.isEmpty())
return "Unknown algo (should only happen under JUnit)";
if (! _builders.containsValue(clz))
throw new H2OIllegalArgumentException("Failed to find ModelBuilder class in registry: " + clz, "Failed to find ModelBuilder class in registry: " + clz);
for (Map.Entry<String, Class<? extends ModelBuilder>> entry : _builders.entrySet())
if (entry.getValue().equals(clz))
return entry.getKey();
// Note: unreachable:
throw new H2OIllegalArgumentException("Failed to find ModelBuilder class in registry: " + clz, "Failed to find ModelBuilder class in registry: " + clz);
}
/**
* Externally visible default schema
* TODO: this is in the wrong layer: the internals should not know anything about the schemas!!!
* This puts a reverse edge into the dependency graph.
*/
public abstract ModelBuilderSchema schema();
/** Constructor called from an http request; MUST override in subclasses. */
public ModelBuilder(P ignore) {
super(Key.make("Failed"),"ModelBuilder constructor needs to be overridden.");
throw H2O.fail("ModelBuilder subclass failed to override the params constructor: " + this.getClass());
}
/** Constructor making a default destination key */
public ModelBuilder(String desc, P parms) {
this((parms == null || parms._model_id == null) ? Key.make(desc + "Model_" + Key.rand()) : parms._model_id, desc, parms);
}
/** Default constructor, given all arguments */
public ModelBuilder(Key dest, String desc, P parms) {
super(dest,desc);
_parms = parms;
}
/** Factory method to create a ModelBuilder instance of the correct class given the algo name. */
public static ModelBuilder createModelBuilder(String algo) {
ModelBuilder modelBuilder;
Class<? extends ModelBuilder> clz = null;
try {
clz = ModelBuilder.getModelBuilder(algo);
}
catch (Exception ignore) {}
if (clz == null) {
throw new H2OIllegalArgumentException("algo", "createModelBuilder", "Algo not known (" + algo + ")");
}
try {
if (! (clz.getGenericSuperclass() instanceof ParameterizedType)) {
throw H2O.fail("Class is not parameterized as expected: " + clz);
}
Type[] handler_type_parms = ((ParameterizedType)(clz.getGenericSuperclass())).getActualTypeArguments();
// [0] is the Model type; [1] is the Model.Parameters type; [2] is the Model.Output type.
Class<? extends Model.Parameters> pclz = (Class<? extends Model.Parameters>)handler_type_parms[1];
Constructor<ModelBuilder> constructor = (Constructor<ModelBuilder>)clz.getDeclaredConstructor(new Class[] { (Class)handler_type_parms[1] });
Model.Parameters p = pclz.newInstance();
modelBuilder = constructor.newInstance(p);
} catch (java.lang.reflect.InvocationTargetException e) {
throw H2O.fail("Exception when trying to instantiate ModelBuilder for: " + algo + ": " + e.getCause(), e);
} catch (Exception e) {
throw H2O.fail("Exception when trying to instantiate ModelBuilder for: " + algo + ": " + e.getCause(), e);
}
return modelBuilder;
}
/** Method to launch training of a Model, based on its parameters. */
abstract public Job<M> trainModel();
/** List containing the categories of models that this builder can
* build. Each ModelBuilder must have one of these. */
abstract public ModelCategory[] can_build();
/**
* Visibility for this algo: is it always visible, is it beta (always visible but with a note in the UI)
* or is it experimental (hidden by default, visible in the UI if the user gives an "experimental" flag
* at startup).
*/
public enum BuilderVisibility {
Experimental,
Beta,
Stable
}
/**
* Visibility for this algo: is it always visible, is it beta (always visible but with a note in the UI)
* or is it experimental (hidden by default, visible in the UI if the user gives an "experimental" flag
* at startup).
*/
abstract public BuilderVisibility builderVisibility();
/** Clear whatever was done by init() so it can be run again. */
public void clearInitState() {
clearValidationErrors();
}
public boolean isSupervised(){return false;}
protected transient Vec _response; // Handy response column
protected transient Vec _vresponse; // Handy response column
protected transient Vec _offset; // Handy offset column
protected transient Vec _weights;
public boolean hasOffset(){ return _offset != null;}
public boolean hasWeights(){return _weights != null;}
// no hasResponse, call isSupervised instead (response is mandatory if isSupervised is true)
protected int _nclass; // Number of classes; 1 for regression; 2+ for classification
public int nclasses(){return _nclass;}
public final boolean isClassifier() { return _nclass > 1; }
/**
* Find and set response/weights/offset and put them all in the end,
* @return number of non-feature vecs
*/
protected int separateFeatureVecs() {
int res = 0;
if(_parms._weights_column != null) {
Vec w = _train.remove(_parms._weights_column);
if(w == null)
error("_weights_column","Offset column '" + _parms._weights_column + "' not found in the training frame");
else {
if(!w.isNumeric())
error("_weights_column","Invalid weights column '" + _parms._weights_column + "', weights must be numeric");
_weights = w;
if(w.naCnt() > 0)
error("_weights_columns","Weights cannot have missing values.");
if(w.min() < 0)
error("_weights_columns","Weights must be >= 0");
if(w.max() == 0)
error("_weights_columns","Max. weight must be > 0");
_train.add(_parms._weights_column, w);
++res;
}
}
if(_parms._offset_column != null) {
Vec o = _train.remove(_parms._offset_column);
if(o == null)
error("_offset_column","Offset column '" + _parms._offset_column + "' not found in the training frame");
else {
if(!o.isNumeric())
error("_offset_column","Invalid offset column '" + _parms._offset_column + "', offset must be numeric");
_offset = o;
if(o.naCnt() > 0)
error("_offset_column","Offset cannot have missing values.");
if(_weights == _offset)
error("_offset_column", "Offset must be different from weights");
_train.add(_parms._offset_column, o);
++res;
}
}
if(isSupervised() && _parms._response_column != null) {
_response = _train.remove(_parms._response_column);
if (_response == null) {
if (isSupervised())
error("_response_column", "Response column '" + _parms._response_column + "' not found in the training frame");
} else {
_train.add(_parms._response_column, _response);
++res;
}
}
return res;
}
protected boolean ignoreStringColumns(){return true;}
/**
* Ignore constant columns, columns with all NAs and strings.
* @param npredictors
* @param expensive
*/
protected void ignoreBadColumns(int npredictors, boolean expensive){
// Drop all-constant and all-bad columns.
if( _parms._ignore_const_cols)
new FilterCols(npredictors) {
@Override protected boolean filter(Vec v) { return v.isConst() || v.isBad() || (ignoreStringColumns() && v.isString()); }
}.doIt(_train,"Dropping constant columns: ",expensive);
}
/**
* Override this method to call error() if the model is expected to not fit in memory, and say why
*/
protected void checkMemoryFootPrint() {}
transient double [] _distribution;
transient double [] _priorClassDist;
protected boolean computePriorClassDistribution(){
return _parms._balance_classes;
}
// ==========================================================================
/** Initialize the ModelBuilder, validating all arguments and preparing the
* training frame. This call is expected to be overridden in the subclasses
* and each subclass will start with "super.init();". This call is made by
* the front-end whenever the GUI is clicked, and needs to be fast whenever
* {@code expensive} is false; it will be called once again at the start of
* model building {@see #trainModel()} with expensive set to true.
*<p>
* The incoming training frame (and validation frame) will have ignored
* columns dropped out, plus whatever work the parent init did.
*<p>
* NOTE: The front end initially calls this through the parameters validation
* endpoint with no training_frame, so each subclass's {@code init()} method
* has to work correctly with the training_frame missing.
*<p>
* @see #updateValidationMessages()
*/
public void init(boolean expensive) {
// Log parameters
if (expensive) {
Log.info("Building H2O " + this.getClass().getSimpleName().toString() + " model with these parameters:");
Log.info(new String(_parms.writeJSON(new AutoBuffer()).buf()));
}
// NOTE: allow re-init:
clearInitState();
assert _parms != null; // Parms must already be set in
if( _parms._train == null ) {
if (expensive)
error("_train","Missing training frame");
return;
}
Frame tr = _parms.train();
if( tr == null ) { error("_train","Missing training frame: "+_parms._train); return; }
_train = new Frame(null /* not putting this into KV */, tr._names.clone(), tr.vecs().clone());
// Drop explicitly dropped columns
if( _parms._ignored_columns != null ) {
_train.remove(_parms._ignored_columns);
if( expensive ) Log.info("Dropping ignored columns: "+Arrays.toString(_parms._ignored_columns));
}
// Drop all non-numeric columns (e.g., String and UUID). No current algo
// can use them, and otherwise all algos will then be forced to remove
// them. Text algos (grep, word2vec) take raw text columns - which are
// numeric (arrays of bytes).
ignoreBadColumns(separateFeatureVecs(), expensive);
// Check that at least some columns are not-constant and not-all-NAs
if( _train.numCols() == 0 )
error("_train","There are no usable columns to generate model");
if(isSupervised()) {
if(_response != null) {
_nclass = _response.isEnum() ? _response.cardinality() : 1;
if (_response.isConst())
error("_response","Response cannot be constant.");
}
if (! _parms._balance_classes)
hide("_max_after_balance_size", "Balance classes is false, hide max_after_balance_size");
else if (_parms._weights_column != null)
error("_balance_classes", "Balance classes and observation weights are not currently supported together.");
if( _parms._max_after_balance_size <= 0.0 )
error("_max_after_balance_size","Max size after balancing needs to be positive, suggest 1.0f");
if( _train != null ) {
if (_train.numCols() <= 1)
error("_train", "Training data must have at least 2 features (incl. response).");
if( null == _parms._response_column) {
error("_response_column", "Response column parameter not set.");
return;
}
if(_response != null && computePriorClassDistribution()) {
if (isClassifier() && isSupervised()) {
MRUtils.ClassDist cdmt =
_weights != null ? new MRUtils.ClassDist(nclasses()).doAll(_response, _weights) : new MRUtils.ClassDist(nclasses()).doAll(_response);
_distribution = cdmt.dist();
_priorClassDist = cdmt.rel_dist();
} else { // Regression; only 1 "class"
_distribution = new double[]{ (_weights != null ? _weights.mean() : 1.0) * train().numRows() };
_priorClassDist = new double[]{1.0f};
}
}
}
if( !isClassifier() ) {
hide("_balance_classes", "Balance classes is only applicable to classification problems.");
hide("_class_sampling_factors", "Class sampling factors is only applicable to classification problems.");
hide("_max_after_balance_size", "Max after balance size is only applicable to classification problems.");
hide("_max_confusion_matrix_size", "Max confusion matrix size is only applicable to classification problems.");
}
if (_nclass <= 2) {
hide("_max_hit_ratio_k", "Max K-value for hit ratio is only applicable to multi-class classification problems.");
hide("_max_confusion_matrix_size", "Only for multi-class classification problems.");
}
if( !_parms._balance_classes ) {
hide("_max_after_balance_size", "Only used with balanced classes");
hide("_class_sampling_factors", "Class sampling factors is only applicable if balancing classes.");
}
}
else {
hide("_response_column", "Ignored for unsupervised methods.");
hide("_balance_classes", "Ignored for unsupervised methods.");
hide("_class_sampling_factors", "Ignored for unsupervised methods.");
hide("_max_after_balance_size", "Ignored for unsupervised methods.");
hide("_max_confusion_matrix_size", "Ignored for unsupervised methods.");
_response = null;
_vresponse = null;
_nclass = 1;
}
// Build the validation set to be compatible with the training set.
// Toss out extra columns, complain about missing ones, remap enums
Frame va = _parms.valid(); // User-given validation set
if (va != null) {
_valid = new Frame(null /* not putting this into KV */, va._names.clone(), va.vecs().clone());
try {
String[] msgs = Model.adaptTestForTrain(_train._names, _parms._weights_column, _parms._offset_column, null, _train.domains(), _valid, _parms.missingColumnsType(), expensive, true);
_vresponse = _valid.vec(_parms._response_column);
if (_vresponse == null && _parms._response_column != null)
error("_validation_frame", "Validation frame must have a response column '" + _parms._response_column + "'.");
if (expensive) {
for (String s : msgs) {
Log.info(s);
info("_valid", s);
}
}
assert !expensive || (_valid == null || Arrays.equals(_train._names, _valid._names));
} catch (IllegalArgumentException iae) {
error("_valid", iae.getMessage());
}
}
}
/**
* init(expensive) is called inside a DTask, not from the http request thread. If we add validation messages to the
* ModelBuilder (aka the Job) we want to update it in the DKV so the client can see them when polling and later on
* after the job completes.
* <p>
* NOTE: this should only be called when no other threads are updating the job, for example from init() or after the
* DTask is stopped and is getting cleaned up.
* @see #init(boolean)
*/
public void updateValidationMessages() {
// Atomically update the validation messages in the Job in the DKV.
// In some cases we haven't stored to the DKV yet:
new TAtomic<Job>() {
@Override public Job atomic(Job old) {
if( old == null ) throw new H2OKeyNotFoundArgumentException(old._key);
ModelBuilder builder = (ModelBuilder)old;
builder._messages = ModelBuilder.this._messages;
return builder;
}
}.invoke(_key);
}
abstract class FilterCols {
final int _specialVecs; // special vecs to skip at the end
public FilterCols(int n) {_specialVecs = n;}
abstract protected boolean filter(Vec v);
void doIt( Frame f, String msg, boolean expensive ) {
boolean any=false;
for( int i = 0; i < f.vecs().length - _specialVecs; i++ ) {
if( filter(f.vecs()[i]) ) {
if( any ) msg += ", "; // Log dropped cols
any = true;
msg += f._names[i];
f.remove(i);
i--; // Re-run at same iteration after dropping a col
}
}
if( any ) {
warn("_train", msg);
if (expensive) Log.info(msg);
}
}
}
/** A list of field validation issues. */
public ValidationMessage[] _messages = new ValidationMessage[0];
private int _error_count = -1; // -1 ==> init not run yet; note, this counts ONLY errors, not WARNs and etc.
public int error_count() { assert _error_count>=0 : "init() not run yet"; return _error_count; }
public void hide (String field_name, String message) { message(ValidationMessage.MessageType.HIDE , field_name, message); }
public void info (String field_name, String message) { message(ValidationMessage.MessageType.INFO , field_name, message); }
public void warn (String field_name, String message) { message(ValidationMessage.MessageType.WARN , field_name, message); }
public void error(String field_name, String message) { message(ValidationMessage.MessageType.ERROR, field_name, message); _error_count++; }
private void clearValidationErrors() {
_messages = new ValidationMessage[0];
_error_count = 0;
}
private void message(ValidationMessage.MessageType message_type, String field_name, String message) {
_messages = Arrays.copyOf(_messages, _messages.length + 1);
_messages[_messages.length - 1] = new ValidationMessage(message_type, field_name, message);
}
/** Get a string representation of only the ERROR ValidationMessages (e.g., to use in an exception throw). */
public String validationErrors() {
StringBuilder sb = new StringBuilder();
for( ValidationMessage vm : _messages )
if( vm.message_type == ValidationMessage.MessageType.ERROR )
sb.append(vm.toString()).append("\n");
return sb.toString();
}
/** The result of an abnormal Model.Parameter check. Contains a
* level, a field name, and a message.
*
* Can be an ERROR, meaning the parameters can't be used as-is,
* a HIDE, which means the specified field should be hidden given
* the values of other fields, or a WARN or INFO for informative
* messages to the user.
*/
public static final class ValidationMessage extends Iced {
public enum MessageType { HIDE, INFO, WARN, ERROR }
final MessageType message_type;
final String field_name;
final String message;
public ValidationMessage(MessageType message_type, String field_name, String message) {
this.message_type = message_type;
this.field_name = field_name;
this.message = message;
switch (message_type) {
case INFO: Log.info(field_name + ": " + message); break;
case WARN: Log.warn(field_name + ": " + message); break;
case ERROR: Log.err(field_name + ": " + message); break;
}
}
@Override public String toString() { return message_type + " on field: " + field_name + ": " + message; }
}
}
| Fix typo.
| h2o-core/src/main/java/hex/ModelBuilder.java | Fix typo. |
|
Java | apache-2.0 | 07a96cf84d909eb93d79753d9e5a0e0943298429 | 0 | jagguli/intellij-community,adedayo/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,signed/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,allotria/intellij-community,fitermay/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,samthor/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,supersven/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,supersven/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,izonder/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,holmes/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,hurricup/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,da1z/intellij-community,samthor/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,kool79/intellij-community,da1z/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,jagguli/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,slisson/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,supersven/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,diorcety/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,semonte/intellij-community,robovm/robovm-studio,allotria/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,jagguli/intellij-community,hurricup/intellij-community,caot/intellij-community,kool79/intellij-community,samthor/intellij-community,vladmm/intellij-community,caot/intellij-community,gnuhub/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,semonte/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,caot/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,vladmm/intellij-community,clumsy/intellij-community,hurricup/intellij-community,samthor/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,jagguli/intellij-community,dslomov/intellij-community,slisson/intellij-community,slisson/intellij-community,caot/intellij-community,da1z/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,amith01994/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,caot/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,caot/intellij-community,supersven/intellij-community,allotria/intellij-community,asedunov/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,caot/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,allotria/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,asedunov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,blademainer/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,clumsy/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,clumsy/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,retomerz/intellij-community,jagguli/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,samthor/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,da1z/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,signed/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,fnouama/intellij-community,izonder/intellij-community,FHannes/intellij-community,dslomov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,caot/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,petteyg/intellij-community,kool79/intellij-community,clumsy/intellij-community,izonder/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,da1z/intellij-community,suncycheng/intellij-community,signed/intellij-community,semonte/intellij-community,ryano144/intellij-community,jagguli/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,slisson/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,dslomov/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,signed/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,blademainer/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,ryano144/intellij-community,slisson/intellij-community,allotria/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,signed/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,allotria/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,kool79/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,da1z/intellij-community,amith01994/intellij-community,signed/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,supersven/intellij-community,adedayo/intellij-community,clumsy/intellij-community,caot/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,supersven/intellij-community,clumsy/intellij-community,signed/intellij-community,caot/intellij-community,dslomov/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,allotria/intellij-community,gnuhub/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,ibinti/intellij-community,hurricup/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,kool79/intellij-community,hurricup/intellij-community,apixandru/intellij-community,da1z/intellij-community,hurricup/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,fnouama/intellij-community,kdwink/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,semonte/intellij-community,retomerz/intellij-community,holmes/intellij-community,kool79/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,holmes/intellij-community,ryano144/intellij-community,blademainer/intellij-community,samthor/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,slisson/intellij-community,ibinti/intellij-community,kool79/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,orekyuu/intellij-community,allotria/intellij-community,Lekanich/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,izonder/intellij-community,signed/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,amith01994/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,orekyuu/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,vladmm/intellij-community,robovm/robovm-studio,hurricup/intellij-community,robovm/robovm-studio,fitermay/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ibinti/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,robovm/robovm-studio,xfournet/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,vladmm/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,slisson/intellij-community,izonder/intellij-community,slisson/intellij-community,robovm/robovm-studio,amith01994/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,hurricup/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,hurricup/intellij-community,apixandru/intellij-community,signed/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,kdwink/intellij-community,hurricup/intellij-community,signed/intellij-community,adedayo/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,petteyg/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,retomerz/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,xfournet/intellij-community,dslomov/intellij-community,semonte/intellij-community | package com.jetbrains.python.inspections;
import com.intellij.codeInspection.*;
import com.intellij.psi.PsiElement;
import com.jetbrains.python.psi.PyElementVisitor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Created by IntelliJ IDEA.
* User: dcheryasov
* Date: Nov 14, 2008
* A copy of Ruby's visitor helper.
*/
public class PyInspectionVisitor extends PyElementVisitor {
private final ProblemsHolder myHolder;
public PyInspectionVisitor(final ProblemsHolder holder) {
myHolder = holder;
}
public ProblemsHolder getHolder() {
return myHolder;
}
protected final void registerProblem(final PsiElement element,
final String message){
if (element == null || element.getTextLength() == 0){
return;
}
myHolder.registerProblem(element, message);
}
protected final void registerProblem(@Nullable final PsiElement element,
@NotNull final String message,
@NotNull final LocalQuickFix quickFix){
if (element == null || element.getTextLength() == 0){
return;
}
myHolder.registerProblem(element, message, quickFix);
}
protected final void registerProblem(final PsiElement element,
final String message,
final ProblemHighlightType type,
final HintAction action) {
if (element == null || element.getTextLength() == 0){
return;
}
myHolder.registerProblem(myHolder.getManager().createProblemDescriptor(element, message, type, action, myHolder.isOnTheFly()));
}
/**
* The most full-blown version.
* @see ProblemDescriptor
*/
protected final void registerProblem(
@NotNull final PsiElement psiElement,
@NotNull final String descriptionTemplate,
final ProblemHighlightType highlightType,
final HintAction hintAction,
final LocalQuickFix... fixes)
{
myHolder.registerProblem(myHolder.getManager().createProblemDescriptor(psiElement, descriptionTemplate, highlightType, hintAction,
myHolder.isOnTheFly(), fixes));
}
}
| python/src/com/jetbrains/python/inspections/PyInspectionVisitor.java | package com.jetbrains.python.inspections;
import com.jetbrains.python.psi.PyElementVisitor;
import com.intellij.psi.PsiElement;
import com.intellij.codeInspection.*;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
/**
* Created by IntelliJ IDEA.
* User: dcheryasov
* Date: Nov 14, 2008
* A copy of Ruby's visitor helper.
*/
public class PyInspectionVisitor extends PyElementVisitor {
private final ProblemsHolder myHolder;
public PyInspectionVisitor(final ProblemsHolder holder) {
myHolder = holder;
}
public ProblemsHolder getHolder() {
return myHolder;
}
protected final void registerProblem(final PsiElement element,
final String message){
if (element == null || element.getTextLength() == 0){
return;
}
myHolder.registerProblem(element, message);
}
protected final void registerProblem(@Nullable final PsiElement element,
@NotNull final String message,
@NotNull final LocalQuickFix quickFix){
if (element == null || element.getTextLength() == 0){
return;
}
myHolder.registerProblem(element, message, quickFix);
}
protected final void registerProblem(final PsiElement element,
final String message,
final ProblemHighlightType type,
final HintAction action) {
if (element == null || element.getTextLength() == 0){
return;
}
myHolder.registerProblem(myHolder.getManager().createProblemDescriptor(element, message, type, action));
}
/**
* The most full-blown version.
* @see ProblemDescriptor
*/
protected final void registerProblem(
@NotNull final PsiElement psiElement,
@NotNull final String descriptionTemplate,
final ProblemHighlightType highlightType,
final HintAction hintAction,
final LocalQuickFix... fixes)
{
myHolder.registerProblem(myHolder.getManager().createProblemDescriptor(psiElement, descriptionTemplate, highlightType, hintAction, fixes));
}
}
| Inspections - pass onTheFly into ProblemDescriptors & use it to create LAZY refs in batch run.
| python/src/com/jetbrains/python/inspections/PyInspectionVisitor.java | Inspections - pass onTheFly into ProblemDescriptors & use it to create LAZY refs in batch run. |
|
Java | apache-2.0 | 4c25275e66e766e4cb28ac02e82e7d8e08245408 | 0 | allotria/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,vladmm/intellij-community,izonder/intellij-community,FHannes/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,jexp/idea2,wreckJ/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,signed/intellij-community,youdonghai/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,semonte/intellij-community,fitermay/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,akosyakov/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,jagguli/intellij-community,diorcety/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,allotria/intellij-community,da1z/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ibinti/intellij-community,slisson/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,ernestp/consulo,signed/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,da1z/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,amith01994/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,supersven/intellij-community,suncycheng/intellij-community,supersven/intellij-community,clumsy/intellij-community,consulo/consulo,ol-loginov/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,consulo/consulo,caot/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,fitermay/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,diorcety/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,caot/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,amith01994/intellij-community,petteyg/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,vladmm/intellij-community,hurricup/intellij-community,FHannes/intellij-community,da1z/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,semonte/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,amith01994/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,kool79/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,mglukhikh/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,jagguli/intellij-community,consulo/consulo,slisson/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,jexp/idea2,vvv1559/intellij-community,asedunov/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,ibinti/intellij-community,jexp/idea2,consulo/consulo,ernestp/consulo,mglukhikh/intellij-community,hurricup/intellij-community,caot/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,kool79/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,holmes/intellij-community,blademainer/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,tmpgit/intellij-community,holmes/intellij-community,da1z/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,consulo/consulo,supersven/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ernestp/consulo,SerCeMan/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,clumsy/intellij-community,apixandru/intellij-community,semonte/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,adedayo/intellij-community,caot/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,jagguli/intellij-community,ibinti/intellij-community,petteyg/intellij-community,jexp/idea2,orekyuu/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,orekyuu/intellij-community,signed/intellij-community,blademainer/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,samthor/intellij-community,dslomov/intellij-community,ryano144/intellij-community,xfournet/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,da1z/intellij-community,orekyuu/intellij-community,allotria/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,jagguli/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,samthor/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,fnouama/intellij-community,izonder/intellij-community,joewalnes/idea-community,xfournet/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,blademainer/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,holmes/intellij-community,holmes/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,xfournet/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,semonte/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,adedayo/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,izonder/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,holmes/intellij-community,kool79/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,clumsy/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,jexp/idea2,holmes/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,ibinti/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,allotria/intellij-community,kool79/intellij-community,clumsy/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,ernestp/consulo,FHannes/intellij-community,supersven/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,signed/intellij-community,holmes/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,ibinti/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,allotria/intellij-community,dslomov/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,jexp/idea2,supersven/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,apixandru/intellij-community,fnouama/intellij-community,xfournet/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,caot/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,blademainer/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,ernestp/consulo,TangHao1987/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,supersven/intellij-community,kool79/intellij-community,allotria/intellij-community,blademainer/intellij-community,asedunov/intellij-community,consulo/consulo,diorcety/intellij-community,jagguli/intellij-community,retomerz/intellij-community,slisson/intellij-community,jagguli/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,slisson/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,xfournet/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,ryano144/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,caot/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,petteyg/intellij-community,blademainer/intellij-community,adedayo/intellij-community,joewalnes/idea-community,slisson/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,fitermay/intellij-community,xfournet/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,petteyg/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,da1z/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,holmes/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,akosyakov/intellij-community,signed/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,samthor/intellij-community,wreckJ/intellij-community,signed/intellij-community,dslomov/intellij-community,caot/intellij-community,dslomov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,caot/intellij-community,ryano144/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,supersven/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,samthor/intellij-community,xfournet/intellij-community,samthor/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,apixandru/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,allotria/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,supersven/intellij-community,semonte/intellij-community,dslomov/intellij-community,xfournet/intellij-community,adedayo/intellij-community,samthor/intellij-community,suncycheng/intellij-community,samthor/intellij-community,petteyg/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,jexp/idea2,vladmm/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,kdwink/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,dslomov/intellij-community,jexp/idea2,caot/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,blademainer/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,izonder/intellij-community,clumsy/intellij-community,semonte/intellij-community,da1z/intellij-community,signed/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,izonder/intellij-community,asedunov/intellij-community,vladmm/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,retomerz/intellij-community,blademainer/intellij-community,apixandru/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,fitermay/intellij-community | package com.intellij.codeInsight.javadoc;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.hint.ParameterInfoController;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.gotoByName.ChooseByNameBase;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.ex.http.HttpFileSystem;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.jsp.JspImplUtil;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.presentation.java.SymbolPresentationUtil;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.popup.JBPopupImpl;
import com.intellij.util.Alarm;
import com.intellij.xml.util.documentation.HtmlDocumentationProvider;
import com.intellij.xml.util.documentation.XHtmlDocumentationProvider;
import com.intellij.xml.util.documentation.XmlDocumentationProvider;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
public class JavaDocManager implements ProjectComponent {
@NonNls public static final String JAVADOC_LOCATION_AND_SIZE = "javadoc.popup";
private final Project myProject;
private Editor myEditor = null;
private ParameterInfoController myParameterInfoController;
private Alarm myUpdateDocAlarm = new Alarm();
private WeakReference<JBPopup> myDocInfoHintRef;
private Component myPreviouslyFocused = null;
private HashMap<FileType,DocumentationProvider> documentationProviders = new HashMap<FileType, DocumentationProvider>();
public static final Key<PsiElement> ORIGINAL_ELEMENT_KEY = Key.create("Original element");
public static final @NonNls String HTML_EXTENSION = ".html";
public static final @NonNls String PACKAGE_SUMMARY_FILE = "package-summary.html";
public static final @NonNls String PSI_ELEMENT_PROTOCOL = "psi_element://";
public static final @NonNls String DOC_ELEMENT_PROTOCOL = "doc_element://";
public DocumentationProvider getProvider(FileType fileType) {
return documentationProviders.get(fileType);
}
public interface DocumentationProvider {
String getUrlFor(PsiElement element, PsiElement originalElement);
String generateDoc(PsiElement element, PsiElement originalElement);
PsiElement getDocumentationElementForLookupItem(Object object, PsiElement element);
PsiElement getDocumentationElementForLink(String link, PsiElement context);
}
public void registerDocumentationProvider(FileType fileType,DocumentationProvider provider) {
documentationProviders.put(fileType, provider);
}
public static JavaDocManager getInstance(Project project) {
return project.getComponent(JavaDocManager.class);
}
public JavaDocManager(Project project) {
myProject = project;
registerDocumentationProvider(StdFileTypes.HTML, new HtmlDocumentationProvider(project));
registerDocumentationProvider(StdFileTypes.XHTML, new XHtmlDocumentationProvider(project));
final JspImplUtil.JspDocumentationProvider provider = new JspImplUtil.JspDocumentationProvider(project);
registerDocumentationProvider(StdFileTypes.JSP,provider);
registerDocumentationProvider(StdFileTypes.JSPX, provider);
registerDocumentationProvider(StdFileTypes.XML, new XmlDocumentationProvider());
}
@NotNull
public String getComponentName() {
return "JavaDocManager";
}
public void initComponent() { }
public void disposeComponent() {
}
public void projectOpened() {
}
public void projectClosed() {
}
public JBPopup showJavaDocInfo(@NotNull PsiElement element) {
final JavaDocInfoComponent component = new JavaDocInfoComponent(this);
final String title = SymbolPresentationUtil.getSymbolPresentableText(element);
final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component)
.setRequestFocusIfNotLookupOrSearch(myProject)
.setLookupAndSearchUpdater(new Condition<PsiElement>() {
public boolean value(final PsiElement element) {
showJavaDocInfo(element);
return false;
}
}, myProject)
.setForceHeavyweight(true)
.setDimensionServiceKey(JAVADOC_LOCATION_AND_SIZE)
.setResizable(true)
.setMovable(true)
.setTitle(CodeInsightBundle.message("javadoc.info.title", title != null ? title : element.getText()))
.setCancelCallback(new Computable<Boolean>() {
public Boolean compute() {
if (fromQuickSearch()) {
((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint();
}
myEditor = null;
myPreviouslyFocused = null;
return Boolean.TRUE;
}
})
.createPopup();
JBPopupImpl oldHint = (JBPopupImpl)getDocInfoHint();
if (oldHint != null) {
JavaDocInfoComponent oldComponent = (JavaDocInfoComponent)oldHint.getComponent();
PsiElement element1 = oldComponent.getElement();
if (Comparing.equal(element, element1)) {
return oldHint;
}
oldHint.cancel();
}
component.setHint(hint);
fetchDocInfo(getDefaultProvider(element), component);
myDocInfoHintRef = new WeakReference<JBPopup>(hint);
myPreviouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(myProject);
if (fromQuickSearch()) {
((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).registerHint(hint);
}
return hint;
}
public JBPopup showJavaDocInfo(final Editor editor, PsiFile file, boolean requestFocus) {
myEditor = editor;
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
final PsiExpressionList list =
ParameterInfoController.findArgumentList(file, editor.getCaretModel().getOffset(), -1);
if (list != null) {
myParameterInfoController = ParameterInfoController.getControllerAtOffset(editor, list.getTextRange().getStartOffset());
}
PsiElement element = TargetElementUtil.findTargetElement(editor,
TargetElementUtil.ELEMENT_NAME_ACCEPTED
| TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED
| TargetElementUtil.LOOKUP_ITEM_ACCEPTED
| TargetElementUtil.NEW_AS_CONSTRUCTOR
| TargetElementUtil.THIS_ACCEPTED
| TargetElementUtil.SUPER_ACCEPTED);
PsiElement originalElement = (file != null)?file.findElementAt(editor.getCaretModel().getOffset()): null;
if (element == null && editor != null) {
final PsiReference ref = TargetElementUtil.findReference(editor, editor.getCaretModel().getOffset());
if (ref != null) {
final PsiElement parent = ref.getElement().getParent();
if (parent instanceof PsiMethodCallExpression) {
element = parent;
}
}
Lookup activeLookup = LookupManager.getInstance(myProject).getActiveLookup();
if (activeLookup != null) {
LookupItem item = activeLookup.getCurrentItem();
if (item == null) return null;
if (file!=null) {
DocumentationProvider documentationProvider = documentationProviders.get(file.getFileType());
if (documentationProvider!=null) {
if (ref!=null) originalElement = ref.getElement();
element = documentationProvider.getDocumentationElementForLookupItem(item.getObject(), originalElement);
}
}
}
}
if (element instanceof PsiAnonymousClass) {
element = ((PsiAnonymousClass)element).getBaseClassType().resolve();
}
if (element == null && myParameterInfoController != null) {
final Object[] objects = myParameterInfoController.getSelectedElements();
if (objects != null && objects.length > 0) {
element = getPsiElementFromParameterInfoObject(objects[0], element);
}
}
if (element == null && file != null) { // look if we are within a javadoc comment
element = originalElement;
if (element == null) return null;
PsiDocComment comment = PsiTreeUtil.getParentOfType(element, PsiDocComment.class);
if (comment == null) return null;
element = comment.getParent();
if (!(element instanceof PsiDocCommentOwner)) return null;
}
JBPopupImpl oldHint = (JBPopupImpl)getDocInfoHint();
if (oldHint != null) {
JavaDocInfoComponent component = (JavaDocInfoComponent)oldHint.getComponent();
PsiElement element1 = component.getElement();
if (element != null && Comparing.equal(element, element1)) {
if (requestFocus) {
component.getComponent().requestFocus();
}
return oldHint;
}
oldHint.cancel();
}
JavaDocInfoComponent component = new JavaDocInfoComponent(this);
try {
element.putUserData(ORIGINAL_ELEMENT_KEY,originalElement);
} catch (RuntimeException ex) {
// PsiPackage does not allow putUserData
}
final String title = SymbolPresentationUtil.getSymbolPresentableText(element);
final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component)
.setRequestFocusIfNotLookupOrSearch(myProject)
.setLookupAndSearchUpdater(new Condition<PsiElement>() {
public boolean value(final PsiElement element) {
if (myEditor != null){
final PsiFile file = element.getContainingFile();
if (file != null) {
Editor editor = myEditor;
showJavaDocInfo(myEditor, file, false);
myEditor = editor;
}
} else {
showJavaDocInfo(element);
}
return false;
}
}, myProject)
.setForceHeavyweight(false)
.setDimensionServiceKey(JAVADOC_LOCATION_AND_SIZE)
.setResizable(true)
.setMovable(true)
.setTitle(CodeInsightBundle.message("javadoc.info.title", title != null ? title : element.getText()))
.setCancelCallback(new Computable<Boolean>(){
public Boolean compute() {
if (fromQuickSearch()) {
((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint();
}
myEditor = null;
myPreviouslyFocused = null;
myParameterInfoController = null;
return Boolean.TRUE;
}
})
.createPopup();
component.setHint(hint);
fetchDocInfo(getDefaultProvider(element), component);
myDocInfoHintRef = new WeakReference<JBPopup>(hint);
return hint;
}
private boolean fromQuickSearch() {
return myPreviouslyFocused != null && myPreviouslyFocused.getParent() instanceof ChooseByNameBase.JPanelProvider;
}
private static PsiElement getPsiElementFromParameterInfoObject(final Object o, PsiElement element) {
if (o instanceof CandidateInfo) {
element = ((CandidateInfo)o).getElement();
} else if (o instanceof PsiElement) {
element = (PsiElement)o;
}
return element;
}
public JavaDocProvider getDefaultProvider(final PsiElement _element) {
return new JavaDocProvider() {
private SmartPsiElementPointer element = SmartPointerManager.getInstance(_element.getProject()).createSmartPsiElementPointer(_element);
public String getJavaDoc() {
return getDocInfo(element.getElement());
}
public PsiElement getElement() {
return element.getElement();
}
};
}
private String getExternalJavaDocUrl(final PsiElement element) {
String url = null;
if (element instanceof PsiClass) {
url = findUrlForClass((PsiClass)element);
}
else if (element instanceof PsiField) {
PsiField field = (PsiField)element;
PsiClass aClass = field.getContainingClass();
if (aClass != null) {
url = findUrlForClass(aClass);
if (url != null) {
url += "#" + field.getName();
}
}
}
else if (element instanceof PsiMethod) {
PsiMethod method = (PsiMethod)element;
PsiClass aClass = method.getContainingClass();
if (aClass != null) {
url = findUrlForClass(aClass);
if (url != null) {
String signature = PsiFormatUtil.formatMethod(method,
PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_NAME |
PsiFormatUtil.SHOW_PARAMETERS,
PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_FQ_CLASS_NAMES, 999);
url += "#" + signature;
}
}
}
else if (element instanceof PsiPackage) {
url = findUrlForPackage((PsiPackage)element);
}
else if (element instanceof PsiDirectory) {
PsiPackage aPackage = ((PsiDirectory)element).getPackage();
if (aPackage != null) {
url = findUrlForPackage(aPackage);
}
} else {
DocumentationProvider provider = getProviderFromElement(element);
if (provider!=null) url = provider.getUrlFor(element,element.getUserData(ORIGINAL_ELEMENT_KEY));
}
return url == null ? null : url.replace('\\', '/');
}
public void openJavaDoc(final PsiElement element) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.javadoc.external");
String url = getExternalJavaDocUrl(element);
if (url != null) {
BrowserUtil.launchBrowser(url);
}
else {
final JBPopup docInfoHint = getDocInfoHint();
if (docInfoHint != null && docInfoHint.isVisible()){
docInfoHint.cancel();
}
Messages.showMessageDialog(myProject,
CodeInsightBundle.message("javadoc.documentation.not.found.message"),
CodeInsightBundle.message("javadoc.documentation.not.found.title"),
Messages.getErrorIcon());
}
}
public JBPopup getDocInfoHint() {
if (myDocInfoHintRef == null) return null;
JBPopup hint = myDocInfoHintRef.get();
if (hint == null || !hint.isVisible()) {
myDocInfoHintRef = null;
return null;
}
return hint;
}
private String findUrlForClass(PsiClass aClass) {
String qName = aClass.getQualifiedName();
if (qName == null) return null;
PsiFile file = aClass.getContainingFile();
if (!(file instanceof PsiJavaFile)) return null;
String packageName = ((PsiJavaFile)file).getPackageName();
String relPath;
if (packageName.length() > 0) {
relPath = packageName.replace('.', '/') + '/' + qName.substring(packageName.length() + 1) + HTML_EXTENSION;
}
else {
relPath = qName + HTML_EXTENSION;
}
final PsiFile containingFile = aClass.getContainingFile();
if (containingFile == null) return null;
final VirtualFile virtualFile = containingFile.getVirtualFile();
if (virtualFile == null) return null;
return findUrlForVirtualFile(virtualFile, relPath);
}
private String findUrlForVirtualFile(final VirtualFile virtualFile, final String relPath) {
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
Module module = fileIndex.getModuleForFile(virtualFile);
if (module != null) {
VirtualFile[] javadocPaths = ModuleRootManager.getInstance(module).getJavadocPaths();
String httpRoot = getHttpRoot(javadocPaths, relPath);
if (httpRoot != null) return httpRoot;
}
final List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(virtualFile);
for (OrderEntry orderEntry : orderEntries) {
final VirtualFile[] files = orderEntry.getFiles(OrderRootType.JAVADOC);
final String httpRoot = getHttpRoot(files, relPath);
if (httpRoot != null) return httpRoot;
}
return null;
}
private static String getHttpRoot(final VirtualFile[] roots, String relPath) {
for (VirtualFile root : roots) {
if (root.getFileSystem() instanceof HttpFileSystem) {
return root.getUrl() + relPath;
}
else {
VirtualFile file = root.findFileByRelativePath(relPath);
if (file != null) return file.getUrl();
}
}
return null;
}
private String findUrlForPackage(PsiPackage aPackage) {
String qName = aPackage.getQualifiedName();
qName = qName.replace('.', '/') + '/' + PACKAGE_SUMMARY_FILE;
for(PsiDirectory directory: aPackage.getDirectories()) {
String url = findUrlForVirtualFile(directory.getVirtualFile(), qName);
if (url != null) {
return url;
}
}
return null;
}
private String findUrlForLink(PsiPackage basePackage, String link) {
int index = link.indexOf('#');
String tail = "";
if (index >= 0) {
tail = link.substring(index);
link = link.substring(0, index);
}
String qName = basePackage.getQualifiedName();
qName = qName.replace('.', File.separatorChar);
String[] docPaths = JavaDocUtil.getDocPaths(myProject);
for (String docPath : docPaths) {
String url = docPath + File.separator + qName + File.separatorChar + link;
File file = new File(url);
if (file.exists()) return url + tail;
}
return null;
}
public void fetchDocInfo(final JavaDocProvider provider, final JavaDocInfoComponent component) {
doFetchDocInfo(component, provider, true);
}
public void queueFetchDocInfo(final JavaDocProvider provider, final JavaDocInfoComponent component) {
doFetchDocInfo(component, provider, false);
}
private void doFetchDocInfo(final JavaDocInfoComponent component, final JavaDocProvider provider, final boolean cancelRequests) {
component.startWait();
if (cancelRequests) {
myUpdateDocAlarm.cancelAllRequests();
}
myUpdateDocAlarm.addRequest(new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (component.isEmpty()) {
component.setText(CodeInsightBundle.message("javadoc.fetching.progress"));
}
}
});
}
}, 600);
myUpdateDocAlarm.addRequest(new Runnable() {
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
final String text = provider.getJavaDoc();
if (text == null) {
component.setText(CodeInsightBundle.message("no.documentation.found"), true);
}
else if (text.length() == 0) {
component.setText(component.getText(), true);
}
else {
component.setData(provider.getElement(), text);
}
}
});
}
}, 10);
}
public String getDocInfo(PsiElement element) {
if (element instanceof PsiMethodCallExpression) {
return getMethodCandidateInfo(((PsiMethodCallExpression)element));
}
else {
final DocumentationProvider provider = getProviderFromElement(element);
final JavaDocInfoGenerator javaDocInfoGenerator =
new JavaDocInfoGenerator(myProject, element, provider);
if (myParameterInfoController != null) {
final Object[] objects = myParameterInfoController.getSelectedElements();
if (objects.length > 0) {
@NonNls StringBuffer sb = null;
for(Object o:objects) {
PsiElement parameter = getPsiElementFromParameterInfoObject(o, null);
if (parameter != null) {
if (sb == null) sb = new StringBuffer();
final String str2 = new JavaDocInfoGenerator(myProject, parameter, provider).generateDocInfo();
sb.append(str2);
sb.append("<br>");
} else {
sb = null;
break;
}
}
if (sb != null) return sb.toString();
}
}
JavaDocExternalFilter docFilter = new JavaDocExternalFilter(myProject);
String docURL = getExternalJavaDocUrl(element);
if (element instanceof PsiCompiledElement) {
String externalDoc = docFilter.getExternalDocInfoForElement(docURL, element);
if (externalDoc != null) {
return externalDoc;
}
}
return docFilter.filterInternalDocInfo(
javaDocInfoGenerator.generateDocInfo(),
docURL);
}
}
public DocumentationProvider getProviderFromElement(final PsiElement element) {
PsiElement originalElement = element!=null ? element.getUserData(ORIGINAL_ELEMENT_KEY):null;
PsiFile containingFile = (originalElement!=null)?originalElement.getContainingFile() : (element!=null)?element.getContainingFile():null;
VirtualFile vfile = (containingFile!=null)?containingFile.getVirtualFile() : null;
return (vfile!=null)?getProvider(vfile.getFileType()):null;
}
private String getMethodCandidateInfo(PsiMethodCallExpression expr) {
final PsiResolveHelper rh = expr.getManager().getResolveHelper();
final CandidateInfo[] candidates = rh.getReferencedMethodCandidates(expr, true);
final String text = expr.getText();
if (candidates.length > 0) {
final @NonNls StringBuffer sb = new StringBuffer();
for (final CandidateInfo candidate : candidates) {
final PsiElement element = candidate.getElement();
if (!(element instanceof PsiMethod)) {
continue;
}
final String str = PsiFormatUtil.formatMethod(((PsiMethod)element), candidate.getSubstitutor(),
PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_PARAMETERS,
PsiFormatUtil.SHOW_TYPE);
createElementLink(sb, element, str, null);
}
return CodeInsightBundle.message("javadoc.candiates", text, sb);
}
return CodeInsightBundle.message("javadoc.candidates.not.found", text);
}
private void createElementLink(final @NonNls StringBuffer sb, final PsiElement element, final String str,final String str2) {
sb.append(" <a href=\"psi_element://");
sb.append(JavaDocUtil.getReferenceText(myProject, element));
sb.append("\">");
sb.append(str);
sb.append("</a>");
if (str2 != null) sb.append(str2);
sb.append("<br>");
}
void navigateByLink(final JavaDocInfoComponent component, String url) {
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
final PsiManager manager = PsiManager.getInstance(myProject);
if (url.startsWith(PSI_ELEMENT_PROTOCOL)) {
final String refText = url.substring(PSI_ELEMENT_PROTOCOL.length());
final PsiElement targetElement = JavaDocUtil.findReferenceTarget(manager, refText, component.getElement());
if (targetElement != null) {
fetchDocInfo(getDefaultProvider(targetElement), component);
}
}
else {
final String docUrl = url;
fetchDocInfo
(new JavaDocProvider() {
String getElementLocator(String url) {
if (url.startsWith(DOC_ELEMENT_PROTOCOL)) {
return url.substring(DOC_ELEMENT_PROTOCOL.length());
}
return null;
}
public String getJavaDoc() {
String url = getElementLocator(docUrl);
if (url != null && JavaDocExternalFilter.isJavaDocURL(url)) {
String text = new JavaDocExternalFilter(myProject).getExternalDocInfo(url);
if (text != null) {
return text;
}
}
if (url == null) {
url = docUrl;
}
PsiElement element = component.getElement();
if (element != null) {
PsiElement parent = element;
while (true) {
if (parent == null || parent instanceof PsiDirectory) break;
parent = parent.getParent();
}
if (parent != null) {
PsiPackage aPackage = ((PsiDirectory)parent).getPackage();
if (aPackage != null) {
String url1 = findUrlForLink(aPackage, url);
if (url1 != null) {
url = url1;
}
}
}
}
BrowserUtil.launchBrowser(url);
return "";
}
public PsiElement getElement() {
//String loc = getElementLocator(docUrl);
//
//if (loc != null) {
// PsiElement context = component.getElement();
// return JavaDocUtil.findReferenceTarget(context.getManager(), loc, context);
//}
return component.getElement();
}
}, component);
}
component.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
void showHint(final JBPopup hint) {
if (myEditor != null) {
hint.showInBestPositionFor(myEditor);
}
else if (myPreviouslyFocused != null) {
hint.showInBestPositionFor(DataManager.getInstance().getDataContext(myPreviouslyFocused));
}
}
public void requestFocus() {
if (fromQuickSearch()) {
myPreviouslyFocused.getParent().requestFocus();
}
}
public Project getProject() {
return myProject;
}
} | codeInsight/impl/com/intellij/codeInsight/javadoc/JavaDocManager.java | package com.intellij.codeInsight.javadoc;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.hint.ParameterInfoController;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.gotoByName.ChooseByNameBase;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.ex.http.HttpFileSystem;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.jsp.JspImplUtil;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.presentation.java.SymbolPresentationUtil;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.popup.JBPopupImpl;
import com.intellij.util.Alarm;
import com.intellij.xml.util.documentation.HtmlDocumentationProvider;
import com.intellij.xml.util.documentation.XHtmlDocumentationProvider;
import com.intellij.xml.util.documentation.XmlDocumentationProvider;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
public class JavaDocManager implements ProjectComponent {
@NonNls public static final String JAVADOC_LOCATION_AND_SIZE = "javadoc.popup";
private final Project myProject;
private Editor myEditor = null;
private ParameterInfoController myParameterInfoController;
private Alarm myUpdateDocAlarm = new Alarm();
private WeakReference<JBPopup> myDocInfoHintRef;
private Component myPreviouslyFocused = null;
private HashMap<FileType,DocumentationProvider> documentationProviders = new HashMap<FileType, DocumentationProvider>();
public static final Key<PsiElement> ORIGINAL_ELEMENT_KEY = Key.create("Original element");
public static final @NonNls String HTML_EXTENSION = ".html";
public static final @NonNls String PACKAGE_SUMMARY_FILE = "package-summary.html";
public static final @NonNls String PSI_ELEMENT_PROTOCOL = "psi_element://";
public static final @NonNls String DOC_ELEMENT_PROTOCOL = "doc_element://";
public DocumentationProvider getProvider(FileType fileType) {
return documentationProviders.get(fileType);
}
public interface DocumentationProvider {
String getUrlFor(PsiElement element, PsiElement originalElement);
String generateDoc(PsiElement element, PsiElement originalElement);
PsiElement getDocumentationElementForLookupItem(Object object, PsiElement element);
PsiElement getDocumentationElementForLink(String link, PsiElement context);
}
public void registerDocumentationProvider(FileType fileType,DocumentationProvider provider) {
documentationProviders.put(fileType, provider);
}
public static JavaDocManager getInstance(Project project) {
return project.getComponent(JavaDocManager.class);
}
public JavaDocManager(Project project) {
myProject = project;
registerDocumentationProvider(StdFileTypes.HTML, new HtmlDocumentationProvider(project));
registerDocumentationProvider(StdFileTypes.XHTML, new XHtmlDocumentationProvider(project));
final JspImplUtil.JspDocumentationProvider provider = new JspImplUtil.JspDocumentationProvider(project);
registerDocumentationProvider(StdFileTypes.JSP,provider);
registerDocumentationProvider(StdFileTypes.JSPX, provider);
registerDocumentationProvider(StdFileTypes.XML, new XmlDocumentationProvider());
}
@NotNull
public String getComponentName() {
return "JavaDocManager";
}
public void initComponent() { }
public void disposeComponent() {
}
public void projectOpened() {
}
public void projectClosed() {
}
public JBPopup showJavaDocInfo(@NotNull PsiElement element) {
final JavaDocInfoComponent component = new JavaDocInfoComponent(this);
final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component)
.setRequestFocusIfNotLookupOrSearch(myProject)
.setLookupAndSearchUpdater(new Condition<PsiElement>() {
public boolean value(final PsiElement element) {
showJavaDocInfo(element);
return false;
}
}, myProject)
.setForceHeavyweight(true)
.setDimensionServiceKey(JAVADOC_LOCATION_AND_SIZE)
.setResizable(true)
.setMovable(true)
.setTitle(CodeInsightBundle.message("javadoc.info.title", SymbolPresentationUtil.getSymbolPresentableText(element)))
.setCancelCallback(new Computable<Boolean>() {
public Boolean compute() {
if (fromQuickSearch()) {
((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint();
}
myEditor = null;
myPreviouslyFocused = null;
return Boolean.TRUE;
}
})
.createPopup();
JBPopupImpl oldHint = (JBPopupImpl)getDocInfoHint();
if (oldHint != null) {
JavaDocInfoComponent oldComponent = (JavaDocInfoComponent)oldHint.getComponent();
PsiElement element1 = oldComponent.getElement();
if (Comparing.equal(element, element1)) {
return oldHint;
}
oldHint.cancel();
}
component.setHint(hint);
fetchDocInfo(getDefaultProvider(element), component);
myDocInfoHintRef = new WeakReference<JBPopup>(hint);
myPreviouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(myProject);
if (fromQuickSearch()) {
((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).registerHint(hint);
}
return hint;
}
public JBPopup showJavaDocInfo(final Editor editor, PsiFile file, boolean requestFocus) {
myEditor = editor;
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
final PsiExpressionList list =
ParameterInfoController.findArgumentList(file, editor.getCaretModel().getOffset(), -1);
if (list != null) {
myParameterInfoController = ParameterInfoController.getControllerAtOffset(editor, list.getTextRange().getStartOffset());
}
PsiElement element = TargetElementUtil.findTargetElement(editor,
TargetElementUtil.ELEMENT_NAME_ACCEPTED
| TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED
| TargetElementUtil.LOOKUP_ITEM_ACCEPTED
| TargetElementUtil.NEW_AS_CONSTRUCTOR
| TargetElementUtil.THIS_ACCEPTED
| TargetElementUtil.SUPER_ACCEPTED);
PsiElement originalElement = (file != null)?file.findElementAt(editor.getCaretModel().getOffset()): null;
if (element == null && editor != null) {
final PsiReference ref = TargetElementUtil.findReference(editor, editor.getCaretModel().getOffset());
if (ref != null) {
final PsiElement parent = ref.getElement().getParent();
if (parent instanceof PsiMethodCallExpression) {
element = parent;
}
}
Lookup activeLookup = LookupManager.getInstance(myProject).getActiveLookup();
if (activeLookup != null) {
LookupItem item = activeLookup.getCurrentItem();
if (item == null) return null;
if (file!=null) {
DocumentationProvider documentationProvider = documentationProviders.get(file.getFileType());
if (documentationProvider!=null) {
if (ref!=null) originalElement = ref.getElement();
element = documentationProvider.getDocumentationElementForLookupItem(item.getObject(), originalElement);
}
}
}
}
if (element instanceof PsiAnonymousClass) {
element = ((PsiAnonymousClass)element).getBaseClassType().resolve();
}
if (element == null && myParameterInfoController != null) {
final Object[] objects = myParameterInfoController.getSelectedElements();
if (objects != null && objects.length > 0) {
element = getPsiElementFromParameterInfoObject(objects[0], element);
}
}
if (element == null && file != null) { // look if we are within a javadoc comment
element = originalElement;
if (element == null) return null;
PsiDocComment comment = PsiTreeUtil.getParentOfType(element, PsiDocComment.class);
if (comment == null) return null;
element = comment.getParent();
if (!(element instanceof PsiDocCommentOwner)) return null;
}
JBPopupImpl oldHint = (JBPopupImpl)getDocInfoHint();
if (oldHint != null) {
JavaDocInfoComponent component = (JavaDocInfoComponent)oldHint.getComponent();
PsiElement element1 = component.getElement();
if (element != null && Comparing.equal(element, element1)) {
if (requestFocus) {
component.getComponent().requestFocus();
}
return oldHint;
}
oldHint.cancel();
}
JavaDocInfoComponent component = new JavaDocInfoComponent(this);
try {
element.putUserData(ORIGINAL_ELEMENT_KEY,originalElement);
} catch(RuntimeException ex) {} // PsiPackage does not allow putUserData
final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component)
.setRequestFocusIfNotLookupOrSearch(myProject)
.setLookupAndSearchUpdater(new Condition<PsiElement>() {
public boolean value(final PsiElement element) {
if (myEditor != null){
final PsiFile file = element.getContainingFile();
if (file != null) {
Editor editor = myEditor;
showJavaDocInfo(myEditor, file, false);
myEditor = editor;
}
} else {
showJavaDocInfo(element);
}
return false;
}
}, myProject)
.setForceHeavyweight(false)
.setDimensionServiceKey(JAVADOC_LOCATION_AND_SIZE)
.setResizable(true)
.setMovable(true)
.setTitle(CodeInsightBundle.message("javadoc.info.title", SymbolPresentationUtil.getSymbolPresentableText(element)))
.setCancelCallback(new Computable<Boolean>(){
public Boolean compute() {
if (fromQuickSearch()) {
((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint();
}
myEditor = null;
myPreviouslyFocused = null;
myParameterInfoController = null;
return Boolean.TRUE;
}
})
.createPopup();
component.setHint(hint);
fetchDocInfo(getDefaultProvider(element), component);
myDocInfoHintRef = new WeakReference<JBPopup>(hint);
return hint;
}
private boolean fromQuickSearch() {
return myPreviouslyFocused != null && myPreviouslyFocused.getParent() instanceof ChooseByNameBase.JPanelProvider;
}
private static PsiElement getPsiElementFromParameterInfoObject(final Object o, PsiElement element) {
if (o instanceof CandidateInfo) {
element = ((CandidateInfo)o).getElement();
} else if (o instanceof PsiElement) {
element = (PsiElement)o;
}
return element;
}
public JavaDocProvider getDefaultProvider(final PsiElement _element) {
return new JavaDocProvider() {
private SmartPsiElementPointer element = SmartPointerManager.getInstance(_element.getProject()).createSmartPsiElementPointer(_element);
public String getJavaDoc() {
return getDocInfo(element.getElement());
}
public PsiElement getElement() {
return element.getElement();
}
};
}
private String getExternalJavaDocUrl(final PsiElement element) {
String url = null;
if (element instanceof PsiClass) {
url = findUrlForClass((PsiClass)element);
}
else if (element instanceof PsiField) {
PsiField field = (PsiField)element;
PsiClass aClass = field.getContainingClass();
if (aClass != null) {
url = findUrlForClass(aClass);
if (url != null) {
url += "#" + field.getName();
}
}
}
else if (element instanceof PsiMethod) {
PsiMethod method = (PsiMethod)element;
PsiClass aClass = method.getContainingClass();
if (aClass != null) {
url = findUrlForClass(aClass);
if (url != null) {
String signature = PsiFormatUtil.formatMethod(method,
PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_NAME |
PsiFormatUtil.SHOW_PARAMETERS,
PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_FQ_CLASS_NAMES, 999);
url += "#" + signature;
}
}
}
else if (element instanceof PsiPackage) {
url = findUrlForPackage((PsiPackage)element);
}
else if (element instanceof PsiDirectory) {
PsiPackage aPackage = ((PsiDirectory)element).getPackage();
if (aPackage != null) {
url = findUrlForPackage(aPackage);
}
} else {
DocumentationProvider provider = getProviderFromElement(element);
if (provider!=null) url = provider.getUrlFor(element,element.getUserData(ORIGINAL_ELEMENT_KEY));
}
return url == null ? null : url.replace('\\', '/');
}
public void openJavaDoc(final PsiElement element) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.javadoc.external");
String url = getExternalJavaDocUrl(element);
if (url != null) {
BrowserUtil.launchBrowser(url);
}
else {
final JBPopup docInfoHint = getDocInfoHint();
if (docInfoHint != null && docInfoHint.isVisible()){
docInfoHint.cancel();
}
Messages.showMessageDialog(myProject,
CodeInsightBundle.message("javadoc.documentation.not.found.message"),
CodeInsightBundle.message("javadoc.documentation.not.found.title"),
Messages.getErrorIcon());
}
}
public JBPopup getDocInfoHint() {
if (myDocInfoHintRef == null) return null;
JBPopup hint = myDocInfoHintRef.get();
if (hint == null || !hint.isVisible()) {
myDocInfoHintRef = null;
return null;
}
return hint;
}
private String findUrlForClass(PsiClass aClass) {
String qName = aClass.getQualifiedName();
if (qName == null) return null;
PsiFile file = aClass.getContainingFile();
if (!(file instanceof PsiJavaFile)) return null;
String packageName = ((PsiJavaFile)file).getPackageName();
String relPath;
if (packageName.length() > 0) {
relPath = packageName.replace('.', '/') + '/' + qName.substring(packageName.length() + 1) + HTML_EXTENSION;
}
else {
relPath = qName + HTML_EXTENSION;
}
final PsiFile containingFile = aClass.getContainingFile();
if (containingFile == null) return null;
final VirtualFile virtualFile = containingFile.getVirtualFile();
if (virtualFile == null) return null;
return findUrlForVirtualFile(virtualFile, relPath);
}
private String findUrlForVirtualFile(final VirtualFile virtualFile, final String relPath) {
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
Module module = fileIndex.getModuleForFile(virtualFile);
if (module != null) {
VirtualFile[] javadocPaths = ModuleRootManager.getInstance(module).getJavadocPaths();
String httpRoot = getHttpRoot(javadocPaths, relPath);
if (httpRoot != null) return httpRoot;
}
final List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(virtualFile);
for (OrderEntry orderEntry : orderEntries) {
final VirtualFile[] files = orderEntry.getFiles(OrderRootType.JAVADOC);
final String httpRoot = getHttpRoot(files, relPath);
if (httpRoot != null) return httpRoot;
}
return null;
}
private static String getHttpRoot(final VirtualFile[] roots, String relPath) {
for (VirtualFile root : roots) {
if (root.getFileSystem() instanceof HttpFileSystem) {
return root.getUrl() + relPath;
}
else {
VirtualFile file = root.findFileByRelativePath(relPath);
if (file != null) return file.getUrl();
}
}
return null;
}
private String findUrlForPackage(PsiPackage aPackage) {
String qName = aPackage.getQualifiedName();
qName = qName.replace('.', '/') + '/' + PACKAGE_SUMMARY_FILE;
for(PsiDirectory directory: aPackage.getDirectories()) {
String url = findUrlForVirtualFile(directory.getVirtualFile(), qName);
if (url != null) {
return url;
}
}
return null;
}
private String findUrlForLink(PsiPackage basePackage, String link) {
int index = link.indexOf('#');
String tail = "";
if (index >= 0) {
tail = link.substring(index);
link = link.substring(0, index);
}
String qName = basePackage.getQualifiedName();
qName = qName.replace('.', File.separatorChar);
String[] docPaths = JavaDocUtil.getDocPaths(myProject);
for (String docPath : docPaths) {
String url = docPath + File.separator + qName + File.separatorChar + link;
File file = new File(url);
if (file.exists()) return url + tail;
}
return null;
}
public void fetchDocInfo(final JavaDocProvider provider, final JavaDocInfoComponent component) {
doFetchDocInfo(component, provider, true);
}
public void queueFetchDocInfo(final JavaDocProvider provider, final JavaDocInfoComponent component) {
doFetchDocInfo(component, provider, false);
}
private void doFetchDocInfo(final JavaDocInfoComponent component, final JavaDocProvider provider, final boolean cancelRequests) {
component.startWait();
if (cancelRequests) {
myUpdateDocAlarm.cancelAllRequests();
}
myUpdateDocAlarm.addRequest(new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (component.isEmpty()) {
component.setText(CodeInsightBundle.message("javadoc.fetching.progress"));
}
}
});
}
}, 600);
myUpdateDocAlarm.addRequest(new Runnable() {
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
final String text = provider.getJavaDoc();
if (text == null) {
component.setText(CodeInsightBundle.message("no.documentation.found"), true);
}
else if (text.length() == 0) {
component.setText(component.getText(), true);
}
else {
component.setData(provider.getElement(), text);
}
}
});
}
}, 10);
}
public String getDocInfo(PsiElement element) {
if (element instanceof PsiMethodCallExpression) {
return getMethodCandidateInfo(((PsiMethodCallExpression)element));
}
else {
final DocumentationProvider provider = getProviderFromElement(element);
final JavaDocInfoGenerator javaDocInfoGenerator =
new JavaDocInfoGenerator(myProject, element, provider);
if (myParameterInfoController != null) {
final Object[] objects = myParameterInfoController.getSelectedElements();
if (objects.length > 0) {
@NonNls StringBuffer sb = null;
for(Object o:objects) {
PsiElement parameter = getPsiElementFromParameterInfoObject(o, null);
if (parameter != null) {
if (sb == null) sb = new StringBuffer();
final String str2 = new JavaDocInfoGenerator(myProject, parameter, provider).generateDocInfo();
sb.append(str2);
sb.append("<br>");
} else {
sb = null;
break;
}
}
if (sb != null) return sb.toString();
}
}
JavaDocExternalFilter docFilter = new JavaDocExternalFilter(myProject);
String docURL = getExternalJavaDocUrl(element);
if (element instanceof PsiCompiledElement) {
String externalDoc = docFilter.getExternalDocInfoForElement(docURL, element);
if (externalDoc != null) {
return externalDoc;
}
}
return docFilter.filterInternalDocInfo(
javaDocInfoGenerator.generateDocInfo(),
docURL);
}
}
public DocumentationProvider getProviderFromElement(final PsiElement element) {
PsiElement originalElement = element!=null ? element.getUserData(ORIGINAL_ELEMENT_KEY):null;
PsiFile containingFile = (originalElement!=null)?originalElement.getContainingFile() : (element!=null)?element.getContainingFile():null;
VirtualFile vfile = (containingFile!=null)?containingFile.getVirtualFile() : null;
return (vfile!=null)?getProvider(vfile.getFileType()):null;
}
private String getMethodCandidateInfo(PsiMethodCallExpression expr) {
final PsiResolveHelper rh = expr.getManager().getResolveHelper();
final CandidateInfo[] candidates = rh.getReferencedMethodCandidates(expr, true);
final String text = expr.getText();
if (candidates.length > 0) {
final @NonNls StringBuffer sb = new StringBuffer();
for (final CandidateInfo candidate : candidates) {
final PsiElement element = candidate.getElement();
if (!(element instanceof PsiMethod)) {
continue;
}
final String str = PsiFormatUtil.formatMethod(((PsiMethod)element), candidate.getSubstitutor(),
PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_PARAMETERS,
PsiFormatUtil.SHOW_TYPE);
createElementLink(sb, element, str, null);
}
return CodeInsightBundle.message("javadoc.candiates", text, sb);
}
return CodeInsightBundle.message("javadoc.candidates.not.found", text);
}
private void createElementLink(final @NonNls StringBuffer sb, final PsiElement element, final String str,final String str2) {
sb.append(" <a href=\"psi_element://" + JavaDocUtil.getReferenceText(myProject, element) + "\">");
sb.append(str);
sb.append("</a>");
if (str2 != null) sb.append(str2);
sb.append("<br>");
}
void navigateByLink(final JavaDocInfoComponent component, String url) {
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
final PsiManager manager = PsiManager.getInstance(myProject);
if (url.startsWith(PSI_ELEMENT_PROTOCOL)) {
final String refText = url.substring(PSI_ELEMENT_PROTOCOL.length());
final PsiElement targetElement = JavaDocUtil.findReferenceTarget(manager, refText, component.getElement());
if (targetElement != null) {
fetchDocInfo(getDefaultProvider(targetElement), component);
}
}
else {
final String docUrl = url;
fetchDocInfo
(new JavaDocProvider() {
String getElementLocator(String url) {
if (url.startsWith(DOC_ELEMENT_PROTOCOL)) {
return url.substring(DOC_ELEMENT_PROTOCOL.length());
}
return null;
}
public String getJavaDoc() {
String url = getElementLocator(docUrl);
if (url != null && JavaDocExternalFilter.isJavaDocURL(url)) {
String text = new JavaDocExternalFilter(myProject).getExternalDocInfo(url);
if (text != null) {
return text;
}
}
if (url == null) {
url = docUrl;
}
PsiElement element = component.getElement();
if (element != null) {
PsiElement parent = element;
while (true) {
if (parent == null || parent instanceof PsiDirectory) break;
parent = parent.getParent();
}
if (parent != null) {
PsiPackage aPackage = ((PsiDirectory)parent).getPackage();
if (aPackage != null) {
String url1 = findUrlForLink(aPackage, url);
if (url1 != null) {
url = url1;
}
}
}
}
BrowserUtil.launchBrowser(url);
return "";
}
public PsiElement getElement() {
//String loc = getElementLocator(docUrl);
//
//if (loc != null) {
// PsiElement context = component.getElement();
// return JavaDocUtil.findReferenceTarget(context.getManager(), loc, context);
//}
return component.getElement();
}
}, component);
}
component.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
void showHint(final JBPopup hint) {
if (myEditor != null) {
hint.showInBestPositionFor(myEditor);
}
else if (myPreviouslyFocused != null) {
hint.showInBestPositionFor(DataManager.getInstance().getDataContext(myPreviouslyFocused));
}
}
public void requestFocus() {
if (fromQuickSearch()) {
myPreviouslyFocused.getParent().requestFocus();
}
}
public Project getProject() {
return myProject;
}
} | fix Ctrl-Q presentation for 'unnamed' elements
| codeInsight/impl/com/intellij/codeInsight/javadoc/JavaDocManager.java | fix Ctrl-Q presentation for 'unnamed' elements |
|
Java | apache-2.0 | 133ac7eeaa5e42457fa8e0fb007438390e2979d9 | 0 | dslomov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,ryano144/intellij-community,adedayo/intellij-community,caot/intellij-community,apixandru/intellij-community,slisson/intellij-community,tmpgit/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,caot/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,semonte/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,semonte/intellij-community,amith01994/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,da1z/intellij-community,dslomov/intellij-community,fnouama/intellij-community,ryano144/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,retomerz/intellij-community,asedunov/intellij-community,supersven/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,da1z/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,allotria/intellij-community,samthor/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,petteyg/intellij-community,allotria/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,signed/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,slisson/intellij-community,robovm/robovm-studio,clumsy/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,da1z/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,ibinti/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,signed/intellij-community,kdwink/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,adedayo/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,caot/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,FHannes/intellij-community,holmes/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,robovm/robovm-studio,xfournet/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,da1z/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,clumsy/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,hurricup/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,samthor/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,xfournet/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,holmes/intellij-community,ibinti/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,allotria/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,caot/intellij-community,signed/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,apixandru/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,semonte/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,slisson/intellij-community,kdwink/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,apixandru/intellij-community,adedayo/intellij-community,kool79/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,blademainer/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,semonte/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,allotria/intellij-community,FHannes/intellij-community,slisson/intellij-community,supersven/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,holmes/intellij-community,asedunov/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,adedayo/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,izonder/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,signed/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,petteyg/intellij-community,FHannes/intellij-community,fnouama/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,supersven/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,semonte/intellij-community,caot/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,signed/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,amith01994/intellij-community,adedayo/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,dslomov/intellij-community,samthor/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,diorcety/intellij-community,kool79/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,holmes/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,clumsy/intellij-community,jagguli/intellij-community,diorcety/intellij-community,fnouama/intellij-community,izonder/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,xfournet/intellij-community,diorcety/intellij-community,signed/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,da1z/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,signed/intellij-community,Distrotech/intellij-community,kool79/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,kool79/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,holmes/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,da1z/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,vladmm/intellij-community,da1z/intellij-community,samthor/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,slisson/intellij-community,petteyg/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,da1z/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,supersven/intellij-community,vvv1559/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,allotria/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,fitermay/intellij-community,slisson/intellij-community,FHannes/intellij-community,da1z/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,izonder/intellij-community,semonte/intellij-community,slisson/intellij-community,gnuhub/intellij-community,caot/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,kool79/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,samthor/intellij-community,jagguli/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,semonte/intellij-community,Lekanich/intellij-community,supersven/intellij-community,allotria/intellij-community,FHannes/intellij-community,fitermay/intellij-community,diorcety/intellij-community,blademainer/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,amith01994/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,signed/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,da1z/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,vladmm/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,apixandru/intellij-community,kool79/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,holmes/intellij-community,vladmm/intellij-community,caot/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,supersven/intellij-community,hurricup/intellij-community,izonder/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,samthor/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,caot/intellij-community,vladmm/intellij-community,dslomov/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,caot/intellij-community,asedunov/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,xfournet/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,retomerz/intellij-community,signed/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,samthor/intellij-community,dslomov/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,holmes/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,FHannes/intellij-community,ryano144/intellij-community,da1z/intellij-community,dslomov/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,allotria/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,vladmm/intellij-community,retomerz/intellij-community | package com.intellij.tasks.jira;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.tasks.LocalTask;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskState;
import com.intellij.tasks.impl.BaseRepositoryImpl;
import com.intellij.tasks.impl.TaskUtil;
import com.intellij.tasks.jira.model.JiraIssue;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.Tag;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.InputStream;
import java.util.List;
/**
* @author Dmitry Avdeev
*/
@Tag("JIRA")
public class JiraRepository extends BaseRepositoryImpl {
public static final Gson GSON = TaskUtil.installDateDeserializer(new GsonBuilder()).create();
private final static Logger LOG = Logger.getInstance("#com.intellij.tasks.jira.JiraRepository");
public static final String LOGIN_FAILED_CHECK_YOUR_PERMISSIONS = "Login failed. Check your permissions.";
public static final String REST_API_PATH = "/rest/api/latest";
/**
* Default JQL query
*/
private String mySearchQuery = "assignee = currentUser() and resolution = Unresolved order by updated";
private JiraRestApi myRestApiVersion;
/**
* Serialization constructor
*/
@SuppressWarnings({"UnusedDeclaration"})
public JiraRepository() {
}
public JiraRepository(JiraRepositoryType type) {
super(type);
}
private JiraRepository(JiraRepository other) {
super(other);
mySearchQuery = other.mySearchQuery;
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) return false;
if (o.getClass() != getClass()) return false;
return Comparing.equal(mySearchQuery, ((JiraRepository)o).mySearchQuery);
}
/**
* Always use Basic HTTP authentication for JIRA REST interface
*/
@Override
public boolean isUseHttpAuthentication() {
return true;
}
public Task[] getIssues(@Nullable String query, int max, long since) throws Exception {
if (myRestApiVersion == null) {
myRestApiVersion = discoverRestApiVersion();
}
String jqlQuery = mySearchQuery;
if (!StringUtil.isEmpty(query)) {
jqlQuery = String.format("summary ~ '%s'", query);
if (!StringUtil.isEmpty(mySearchQuery)) {
jqlQuery += String.format(" and %s", mySearchQuery);
}
}
List<JiraIssue> issues = myRestApiVersion.findIssues(jqlQuery, max);
return ContainerUtil.map2Array(issues, Task.class, new Function<JiraIssue, Task>() {
@Override
public JiraTask fun(JiraIssue issue) {
return new JiraTask(issue, JiraRepository.this);
}
});
}
@Nullable
@Override
public Task findTask(String id) throws Exception {
if (myRestApiVersion == null) {
myRestApiVersion = discoverRestApiVersion();
}
JiraIssue issue = myRestApiVersion.findIssue(id);
return issue == null ? null : new JiraTask(issue, this);
}
@Nullable
@Override
public CancellableConnection createCancellableConnection() {
String uri = getUrl() + REST_API_PATH + "/search?maxResults=1&jql=" + encodeUrl(mySearchQuery);
return new HttpTestConnection<GetMethod>(new GetMethod(uri)) {
@Override
public void doTest(GetMethod method) throws Exception {
executeMethod(method);
}
};
}
public JiraRepository clone() {
return new JiraRepository(this);
}
@Override
protected int getFeatures() {
return super.getFeatures() | TIME_MANAGEMENT;
}
public String getSearchQuery() {
return mySearchQuery;
}
public void setSearchQuery(String searchQuery) {
mySearchQuery = searchQuery;
}
@NotNull
public JiraRestApi discoverRestApiVersion() throws Exception {
String responseBody;
try {
responseBody = executeMethod(new GetMethod(getRestUrl("serverInfo")));
}
catch (Exception e) {
LOG.warn("Can't find out JIRA REST API version");
throw e;
}
JsonObject object = GSON.fromJson(responseBody, JsonObject.class);
// when JIRA 4.x support will be dropped 'versionNumber' array in response
// may be used instead version string parsing
JiraRestApi version = JiraRestApi.fromJiraVersion(object.get("version").getAsString(), this);
if (version == null) {
throw new Exception("JIRA below 4.0.0 doesn't have REST API and is no longer supported.");
}
return version;
}
@Override
public void setTaskState(Task task, TaskState state) throws Exception {
myRestApiVersion.setTaskState(task, state);
}
@Override
public void updateTimeSpent(@NotNull LocalTask task, @NotNull String timeSpent, @NotNull String comment) throws Exception {
myRestApiVersion.updateTimeSpend(task, timeSpent, comment);
}
@NotNull
public String executeMethod(@NotNull HttpMethod method) throws Exception {
LOG.debug("URI: " + method.getURI());
int statusCode;
String entityContent;
try {
statusCode = getHttpClient().executeMethod(method);
LOG.debug("Status code: " + statusCode);
// may be null if 204 No Content received
final InputStream stream = method.getResponseBodyAsStream();
entityContent = stream == null ? "" : StreamUtil.readText(stream, CharsetToolkit.UTF8);
LOG.debug(entityContent);
}
finally {
method.releaseConnection();
}
// besides SC_OK, can also be SC_NO_CONTENT in issue transition requests
// see: JiraRestApi#setTaskStatus
//if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT) {
if (statusCode >= 200 && statusCode < 300) {
return entityContent;
}
else if (method.getResponseHeader("Content-Type") != null) {
Header header = method.getResponseHeader("Content-Type");
if (header.getValue().startsWith("application/json")) {
JsonObject object = GSON.fromJson(entityContent, JsonObject.class);
if (object.has("errorMessages")) {
String reason = StringUtil.join(object.getAsJsonArray("errorMessages"), " ");
// something meaningful to user, e.g. invalid field name in JQL query
LOG.warn(reason);
throw new Exception("Request failed. Reason: " + reason);
}
}
}
if (method.getResponseHeader("X-Authentication-Denied-Reason") != null) {
Header header = method.getResponseHeader("X-Authentication-Denied-Reason");
// only in JIRA >= 5.x.x
if (header.getValue().startsWith("CAPTCHA_CHALLENGE")) {
throw new Exception("Login failed. Enter captcha in web-interface.");
}
}
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
throw new Exception(LOGIN_FAILED_CHECK_YOUR_PERMISSIONS);
}
String statusText = HttpStatus.getStatusText(method.getStatusCode());
throw new Exception(String.format("Request failed with HTTP error: %d %s", statusCode, statusText));
}
@Override
public void setUrl(String url) {
myRestApiVersion = null;
super.setUrl(url);
}
public String getRestUrl(String... parts) {
return getUrl() + REST_API_PATH + "/" + FileUtil.join(parts);
}
}
| plugins/tasks/tasks-core/src/com/intellij/tasks/jira/JiraRepository.java | package com.intellij.tasks.jira;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.tasks.LocalTask;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskState;
import com.intellij.tasks.impl.BaseRepositoryImpl;
import com.intellij.tasks.impl.TaskUtil;
import com.intellij.tasks.jira.model.JiraIssue;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.Tag;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.InputStream;
import java.util.List;
/**
* @author Dmitry Avdeev
*/
@Tag("JIRA")
public class JiraRepository extends BaseRepositoryImpl {
public static final Gson GSON = TaskUtil.installDateDeserializer(new GsonBuilder()).create();
private final static Logger LOG = Logger.getInstance("#com.intellij.tasks.jira.JiraRepository");
public static final String LOGIN_FAILED_CHECK_YOUR_PERMISSIONS = "Login failed. Check your permissions.";
public static final String REST_API_PATH = "/rest/api/latest";
/**
* Default JQL query
*/
private String mySearchQuery = "assignee = currentUser() and resolution = Unresolved order by updated";
private JiraRestApi myRestApiVersion;
/**
* Serialization constructor
*/
@SuppressWarnings({"UnusedDeclaration"})
public JiraRepository() {
}
public JiraRepository(JiraRepositoryType type) {
super(type);
}
private JiraRepository(JiraRepository other) {
super(other);
mySearchQuery = other.mySearchQuery;
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) return false;
if (o.getClass() != getClass()) return false;
return Comparing.equal(mySearchQuery, ((JiraRepository)o).mySearchQuery);
}
/**
* Always use Basic HTTP authentication for JIRA REST interface
*/
@Override
public boolean isUseHttpAuthentication() {
return true;
}
public Task[] getIssues(@Nullable String query, int max, long since) throws Exception {
if (myRestApiVersion == null) {
myRestApiVersion = discoverRestApiVersion();
}
String jqlQuery = mySearchQuery;
if (!StringUtil.isEmpty(query)) {
jqlQuery = String.format("summary ~ '%s'", query);
if (!StringUtil.isEmpty(mySearchQuery)) {
jqlQuery += String.format(" and %s", mySearchQuery);
}
}
List<JiraIssue> issues = myRestApiVersion.findIssues(jqlQuery, max);
return ContainerUtil.map2Array(issues, Task.class, new Function<JiraIssue, Task>() {
@Override
public JiraTask fun(JiraIssue issue) {
return new JiraTask(issue, JiraRepository.this);
}
});
}
@Nullable
@Override
public Task findTask(String id) throws Exception {
if (myRestApiVersion == null) {
myRestApiVersion = discoverRestApiVersion();
}
JiraIssue issue = myRestApiVersion.findIssue(id);
return issue == null ? null : new JiraTask(issue, this);
}
@Nullable
@Override
public CancellableConnection createCancellableConnection() {
String uri = getUrl() + REST_API_PATH + "/search?maxResults=1&jql=" + encodeUrl(mySearchQuery);
return new HttpTestConnection<GetMethod>(new GetMethod(uri)) {
@Override
public void doTest(GetMethod method) throws Exception {
executeMethod(method);
}
};
}
public JiraRepository clone() {
return new JiraRepository(this);
}
@Override
protected int getFeatures() {
return super.getFeatures() | TIME_MANAGEMENT;
}
public String getSearchQuery() {
return mySearchQuery;
}
public void setSearchQuery(String searchQuery) {
mySearchQuery = searchQuery;
}
@NotNull
public JiraRestApi discoverRestApiVersion() throws Exception {
String responseBody;
try {
responseBody = executeMethod(new GetMethod(getRestUrl("serverInfo")));
}
catch (Exception e) {
LOG.warn("Can't find out JIRA REST API version");
throw e;
}
JsonObject object = GSON.fromJson(responseBody, JsonObject.class);
// when JIRA 4.x support will be dropped 'versionNumber' array in response
// may be used instead version string parsing
return JiraRestApi.fromJiraVersion(object.get("version").getAsString(), this);
}
@Override
public void setTaskState(Task task, TaskState state) throws Exception {
myRestApiVersion.setTaskState(task, state);
}
@Override
public void updateTimeSpent(@NotNull LocalTask task, @NotNull String timeSpent, @NotNull String comment) throws Exception {
myRestApiVersion.updateTimeSpend(task, timeSpent, comment);
}
@NotNull
public String executeMethod(@NotNull HttpMethod method) throws Exception {
LOG.debug("URI: " + method.getURI());
int statusCode;
String entityContent;
try {
statusCode = getHttpClient().executeMethod(method);
LOG.debug("Status code: " + statusCode);
// may be null if 204 No Content received
final InputStream stream = method.getResponseBodyAsStream();
entityContent = stream == null ? "" : StreamUtil.readText(stream, CharsetToolkit.UTF8);
LOG.debug(entityContent);
}
finally {
method.releaseConnection();
}
// besides SC_OK, can also be SC_NO_CONTENT in issue transition requests
// see: JiraRestApi#setTaskStatus
//if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT) {
if (statusCode >= 200 && statusCode < 300) {
return entityContent;
}
else if (method.getResponseHeader("Content-Type") != null) {
Header header = method.getResponseHeader("Content-Type");
if (header.getValue().startsWith("application/json")) {
JsonObject object = GSON.fromJson(entityContent, JsonObject.class);
if (object.has("errorMessages")) {
String reason = StringUtil.join(object.getAsJsonArray("errorMessages"), " ");
// something meaningful to user, e.g. invalid field name in JQL query
LOG.warn(reason);
throw new Exception("Request failed. Reason: " + reason);
}
}
}
if (method.getResponseHeader("X-Authentication-Denied-Reason") != null) {
Header header = method.getResponseHeader("X-Authentication-Denied-Reason");
// only in JIRA >= 5.x.x
if (header.getValue().startsWith("CAPTCHA_CHALLENGE")) {
throw new Exception("Login failed. Enter captcha in web-interface.");
}
}
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
throw new Exception(LOGIN_FAILED_CHECK_YOUR_PERMISSIONS);
}
String statusText = HttpStatus.getStatusText(method.getStatusCode());
throw new Exception(String.format("Request failed with HTTP error: %d %s", statusCode, statusText));
}
@Override
public void setUrl(String url) {
myRestApiVersion = null;
super.setUrl(url);
}
public String getRestUrl(String... parts) {
return getUrl() + REST_API_PATH + "/" + FileUtil.join(parts);
}
}
| Add notification about unsupported version of JIRA
| plugins/tasks/tasks-core/src/com/intellij/tasks/jira/JiraRepository.java | Add notification about unsupported version of JIRA |
|
Java | apache-2.0 | d7deab0b7c5669fd88292cab8d259a06b8958a0f | 0 | soygul/nbusy-android,nbusy/nbusy-android | package com.nbusy.sdk.titan.jsonrpc.neptulon;
import android.net.SSLCertificateSocketFactory;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
/**
* Neptulon client implementation: https://github.com/neptulon/neptulon
*/
public class NeptulonClient implements Neptulon {
private final SSLSocket socket;
public NeptulonClient(InputStream caCert) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
// todo: provide session cache instance and limit ciphers
SSLCertificateSocketFactory factory = (SSLCertificateSocketFactory)SSLCertificateSocketFactory.getDefault(60 * 1000, null);
// trust given CA certificate
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca = cf.generateCertificate(caCert);
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
factory.setTrustManagers(tmf.getTrustManagers());
// create socket but don't connect yet
socket = (SSLSocket)factory.createSocket("localhost", 8081);
}
}
| app/src/main/java/com/nbusy/sdk/titan/jsonrpc/neptulon/NeptulonClient.java | package com.nbusy.sdk.titan.jsonrpc.neptulon;
import android.net.SSLCertificateSocketFactory;
import android.net.SSLSessionCache;
import java.io.IOException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
/**
* Neptulon client implementation: https://github.com/neptulon/neptulon
*/
public class NeptulonClient implements Neptulon {
private final SSLSocket socket;
public NeptulonClient() throws IOException {
// todo: provide session cache instance
// SSLContext.getDefault() instead if it returns SSLCertificateSocketFactory?
SSLCertificateSocketFactory factory = (SSLCertificateSocketFactory)SSLCertificateSocketFactory.getDefault(60 * 1000, null);
socket = (SSLSocket)factory.createSocket("localhost", 8081);
}
}
| cert certificate trust
| app/src/main/java/com/nbusy/sdk/titan/jsonrpc/neptulon/NeptulonClient.java | cert certificate trust |
|
Java | apache-2.0 | 23bd130a48c425ca534e33d868c9b5595e9294c0 | 0 | mglukhikh/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,da1z/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.gotoByName;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.actions.ApplyIntentionAction;
import com.intellij.ide.actions.ShowSettingsUtilImpl;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.search.BooleanOptionDescription;
import com.intellij.ide.ui.search.OptionDescription;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.codeStyle.MinusculeMatcher;
import com.intellij.ui.*;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.OnOffButton;
import com.intellij.ui.speedSearch.SpeedSearchUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.intellij.openapi.keymap.KeymapUtil.getActiveKeymapShortcuts;
import static com.intellij.ui.SimpleTextAttributes.STYLE_PLAIN;
import static com.intellij.ui.SimpleTextAttributes.STYLE_SEARCH_MATCH;
public class GotoActionModel implements ChooseByNameModel, Comparator<Object>, DumbAware {
private static final Pattern INNER_GROUP_WITH_IDS = Pattern.compile("(.*) \\(\\d+\\)");
@Nullable private final Project myProject;
private final Component myContextComponent;
@Nullable private final Editor myEditor;
protected final ActionManager myActionManager = ActionManager.getInstance();
private static final Icon EMPTY_ICON = EmptyIcon.ICON_18;
protected final Map<AnAction, String> myActionGroups = ContainerUtil.newHashMap();
private final NotNullLazyValue<Map<String, String>> myConfigurablesNames = VolatileNotNullLazyValue.createValue(() -> {
Map<String, String> map = ContainerUtil.newTroveMap();
for (Configurable configurable : ShowSettingsUtilImpl.getConfigurables(getProject(), true)) {
if (configurable instanceof SearchableConfigurable) {
map.put(((SearchableConfigurable)configurable).getId(), configurable.getDisplayName());
}
}
return map;
});
private final ModalityState myModality;
public GotoActionModel(@Nullable Project project, Component component, @Nullable Editor editor) {
this(project, component, editor, ModalityState.defaultModalityState());
}
public GotoActionModel(@Nullable Project project, Component component, @Nullable Editor editor, @Nullable ModalityState modalityState) {
myProject = project;
myContextComponent = component;
myEditor = editor;
myModality = modalityState;
ActionGroup mainMenu = (ActionGroup)myActionManager.getActionOrStub(IdeActions.GROUP_MAIN_MENU);
assert mainMenu != null;
collectActions(myActionGroups, mainMenu, mainMenu.getTemplatePresentation().getText());
}
@NotNull
Map<String, ApplyIntentionAction> getAvailableIntentions() {
Map<String, ApplyIntentionAction> map = new TreeMap<>();
if (myProject != null && !myProject.isDisposed() && myEditor != null && !myEditor.isDisposed()) {
ApplyIntentionAction[] children = ApplyIntentionAction.getAvailableIntentions(myEditor, PsiDocumentManager.getInstance(myProject).getPsiFile(
myEditor.getDocument()));
if (children != null) {
for (ApplyIntentionAction action : children) {
map.put(action.getName(), action);
}
}
}
return map;
}
@Override
public String getPromptText() {
return IdeBundle.message("prompt.gotoaction.enter.action");
}
@Nullable
@Override
public String getCheckBoxName() {
return IdeBundle.message("checkbox.disabled.included");
}
@Override
public char getCheckBoxMnemonic() {
return 'd';
}
@Override
public String getNotInMessage() {
return IdeBundle.message("label.no.enabled.actions.found");
}
@Override
public String getNotFoundMessage() {
return IdeBundle.message("label.no.actions.found");
}
@Override
public boolean loadInitialCheckBoxState() {
return false;
}
@Override
public void saveInitialCheckBoxState(boolean state) {
}
public static class MatchedValue implements Comparable<MatchedValue> {
@NotNull public final Comparable value;
@NotNull final String pattern;
public MatchedValue(@NotNull Comparable value, @NotNull String pattern) {
this.value = value;
this.pattern = pattern;
}
@Nullable
@VisibleForTesting
public String getValueText() {
if (value instanceof OptionDescription) return ((OptionDescription)value).getHit();
if (!(value instanceof ActionWrapper)) return null;
return ((ActionWrapper)value).getAction().getTemplatePresentation().getText();
}
@Nullable
@Override
public String toString() {
return getMatchingDegree() + " " + getValueText();
}
private int getMatchingDegree() {
String text = getValueText();
if (text != null) {
int degree = getRank(text);
return value instanceof ActionWrapper && !((ActionWrapper)value).isGroupAction() ? degree + 1 : degree;
}
return 0;
}
private int getRank(@NotNull String text) {
if (StringUtil.equalsIgnoreCase(StringUtil.trimEnd(text, "..."), pattern)) return 3;
if (StringUtil.startsWithIgnoreCase(text, pattern)) return 2;
if (StringUtil.containsIgnoreCase(text, pattern)) return 1;
return 0;
}
@Override
public int compareTo(@NotNull MatchedValue o) {
if (o == this) return 0;
int diff = o.getMatchingDegree() - getMatchingDegree();
if (diff != 0) return diff;
boolean edt = ApplicationManager.getApplication().isDispatchThread();
if (value instanceof ActionWrapper && o.value instanceof ActionWrapper) {
if (edt || ((ActionWrapper)value).hasPresentation() && ((ActionWrapper)o.value).hasPresentation()) {
boolean p1Enable = ((ActionWrapper)value).isAvailable();
boolean p2enable = ((ActionWrapper)o.value).isAvailable();
if (p1Enable && !p2enable) return -1;
if (!p1Enable && p2enable) return 1;
}
//noinspection unchecked
int compared = value.compareTo(o.value);
if (compared != 0) return compared;
}
if (value instanceof ActionWrapper && o.value instanceof BooleanOptionDescription) {
return edt && ((ActionWrapper)value).isAvailable() ? -1 : 1;
}
if (o.value instanceof ActionWrapper && value instanceof BooleanOptionDescription) {
return edt && ((ActionWrapper)o.value).isAvailable() ? 1 : -1;
}
if (value instanceof BooleanOptionDescription && !(o.value instanceof BooleanOptionDescription) && o.value instanceof OptionDescription) return -1;
if (o.value instanceof BooleanOptionDescription && !(value instanceof BooleanOptionDescription) && value instanceof OptionDescription) return 1;
if (value instanceof OptionDescription && !(o.value instanceof OptionDescription)) return 1;
if (o.value instanceof OptionDescription && !(value instanceof OptionDescription)) return -1;
diff = StringUtil.notNullize(getValueText()).length() - StringUtil.notNullize(o.getValueText()).length();
if (diff != 0) return diff;
//noinspection unchecked
diff = value.compareTo(o.value);
if (diff != 0) return diff;
return o.hashCode() - hashCode();
}
}
@Override
public ListCellRenderer getListCellRenderer() {
return new GotoActionListCellRenderer(this::getGroupName);
}
protected String getActionId(@NotNull AnAction anAction) {
return myActionManager.getId(anAction);
}
@NotNull
private static JLabel createIconLabel(@Nullable Icon icon, boolean disabled) {
LayeredIcon layeredIcon = new LayeredIcon(2);
layeredIcon.setIcon(EMPTY_ICON, 0);
if (icon == null) return new JLabel(layeredIcon);
int width = icon.getIconWidth();
int height = icon.getIconHeight();
int emptyIconWidth = EMPTY_ICON.getIconWidth();
int emptyIconHeight = EMPTY_ICON.getIconHeight();
if (width <= emptyIconWidth && height <= emptyIconHeight) {
layeredIcon.setIcon(disabled && IconLoader.isGoodSize(icon) ? IconLoader.getDisabledIcon(icon) : icon, 1,
(emptyIconWidth - width) / 2,
(emptyIconHeight - height) / 2);
}
return new JLabel(layeredIcon);
}
@Override
public int compare(@NotNull Object o1, @NotNull Object o2) {
if (ChooseByNameBase.EXTRA_ELEM.equals(o1)) return 1;
if (ChooseByNameBase.EXTRA_ELEM.equals(o2)) return -1;
return ((MatchedValue)o1).compareTo((MatchedValue)o2);
}
@NotNull
public static AnActionEvent updateActionBeforeShow(@NotNull AnAction anAction, @NotNull DataContext dataContext) {
AnActionEvent event = AnActionEvent.createFromDataContext(ActionPlaces.ACTION_SEARCH, null, dataContext);
ActionUtil.performDumbAwareUpdate(anAction, event, false);
return event;
}
public static Color defaultActionForeground(boolean isSelected, @Nullable Presentation presentation) {
if (presentation != null && (!presentation.isEnabled() || !presentation.isVisible())) return UIUtil.getInactiveTextColor();
if (isSelected) return UIUtil.getListSelectionForeground();
return UIUtil.getListForeground();
}
@Override
@NotNull
public String[] getNames(boolean checkBoxState) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
@Override
@NotNull
public Object[] getElementsByName(String id, boolean checkBoxState, String pattern) {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
@NotNull
public String getGroupName(@NotNull OptionDescription description) {
String name = description.getGroupName();
if (name == null) name = myConfigurablesNames.getValue().get(description.getConfigurableId());
String settings = SystemInfo.isMac ? "Preferences" : "Settings";
if (name == null || name.equals(description.getHit())) return settings;
return settings + " > " + name;
}
@NotNull
Map<String, String> getConfigurablesNames() {
return myConfigurablesNames.getValue();
}
private void collectActions(@NotNull Map<AnAction, String> result, @NotNull ActionGroup group, @Nullable String containingGroupName) {
AnAction[] actions = group.getChildren(null);
includeGroup(result, group, actions, containingGroupName);
for (AnAction action : actions) {
if (action == null || action instanceof Separator) continue;
if (action instanceof ActionGroup) {
ActionGroup actionGroup = (ActionGroup)action;
String groupName = actionGroup.getTemplatePresentation().getText();
collectActions(result, actionGroup, getGroupName(StringUtil.isEmpty(groupName) || !actionGroup.isPopup() ? containingGroupName : groupName));
}
else {
String groupName = group.getTemplatePresentation().getText();
if (result.containsKey(action)) {
result.put(action, null);
}
else {
result.put(action, getGroupName(StringUtil.isEmpty(groupName) ? containingGroupName : groupName));
}
}
}
}
@Nullable
private static String getGroupName(@Nullable String groupName) {
if (groupName != null) {
Matcher matcher = INNER_GROUP_WITH_IDS.matcher(groupName);
if (matcher.matches()) return matcher.group(1);
}
return groupName;
}
private void includeGroup(@NotNull Map<AnAction, String> result,
@NotNull ActionGroup group,
@NotNull AnAction[] actions,
@Nullable String containingGroupName) {
boolean showGroup = true;
for (AnAction action : actions) {
if (myActionManager.getId(action) != null) {
showGroup = false;
break;
}
}
if (showGroup) {
result.put(group, getGroupName(containingGroupName));
}
}
@Override
@Nullable
public String getFullName(@NotNull Object element) {
return getElementName(element);
}
@NonNls
@Override
public String getHelpId() {
return "procedures.navigating.goto.action";
}
@Override
@NotNull
public String[] getSeparators() {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
@Nullable
@Override
public String getElementName(@NotNull Object mv) {
return ((MatchedValue) mv).getValueText();
}
protected MatchMode actionMatches(@NotNull String pattern, MinusculeMatcher matcher, @NotNull AnAction anAction) {
Presentation presentation = anAction.getTemplatePresentation();
String text = presentation.getText();
String description = presentation.getDescription();
String groupName = myActionGroups.get(anAction);
if (text != null && matcher.matches(text)) {
return MatchMode.NAME;
}
else if (description != null && !description.equals(text) && matcher.matches(description)) {
return MatchMode.DESCRIPTION;
}
if (text == null) {
return MatchMode.NONE;
}
if (matcher.matches(groupName + " " + text)) {
return anAction instanceof ToggleAction ? MatchMode.NAME : MatchMode.GROUP;
}
return matcher.matches(text + " " + groupName) ? MatchMode.GROUP : MatchMode.NONE;
}
@Nullable
protected Project getProject() {
return myProject;
}
protected Component getContextComponent() {
return myContextComponent;
}
@NotNull
public SortedSet<Object> sortItems(@NotNull Set<Object> elements) {
TreeSet<Object> objects = ContainerUtilRt.newTreeSet(this);
objects.addAll(elements);
return objects;
}
private void updateOnEdt(Runnable update) {
Semaphore semaphore = new Semaphore(1);
ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
ApplicationManager.getApplication().invokeLater(() -> {
try {
update.run();
}
finally {
semaphore.up();
}
}, myModality, __ -> indicator != null && indicator.isCanceled());
while (!semaphore.waitFor(10)) {
if (indicator != null && indicator.isCanceled()) {
// don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788
throw new ProcessCanceledException();
}
}
}
public enum MatchMode {
NONE, INTENTION, NAME, DESCRIPTION, GROUP, NON_MENU
}
@Override
public boolean willOpenEditor() {
return false;
}
@Override
public boolean useMiddleMatching() {
return true;
}
public static class ActionWrapper implements Comparable<ActionWrapper> {
@NotNull private final AnAction myAction;
@NotNull private final MatchMode myMode;
@Nullable private final String myGroupName;
private final DataContext myDataContext;
private final GotoActionModel myModel;
private volatile Presentation myPresentation;
public ActionWrapper(@NotNull AnAction action, @Nullable String groupName, @NotNull MatchMode mode, DataContext dataContext, GotoActionModel model) {
myAction = action;
myMode = mode;
myGroupName = groupName;
myDataContext = dataContext;
myModel = model;
}
@NotNull
public AnAction getAction() {
return myAction;
}
@NotNull
public MatchMode getMode() {
return myMode;
}
@Override
public int compareTo(@NotNull ActionWrapper o) {
int compared = myMode.compareTo(o.getMode());
if (compared != 0) return compared;
Presentation myPresentation = myAction.getTemplatePresentation();
Presentation oPresentation = o.getAction().getTemplatePresentation();
String myText = myPresentation.getText();
String oText = oPresentation.getText();
int byText = StringUtil.compare(StringUtil.trimEnd(myText, "..."), StringUtil.trimEnd(oText, "..."), true);
if (byText != 0) return byText;
int byTextLength = StringUtil.notNullize(myText).length() - StringUtil.notNullize(oText).length();
if (byTextLength != 0) return byTextLength;
int byGroup = Comparing.compare(myGroupName, o.myGroupName);
if (byGroup != 0) return byGroup;
int byDesc = StringUtil.compare(myPresentation.getDescription(), oPresentation.getDescription(), true);
if (byDesc != 0) return byDesc;
return 0;
}
public boolean isAvailable() {
Presentation presentation = getPresentation();
return presentation != null && presentation.isEnabledAndVisible();
}
public Presentation getPresentation() {
if (myPresentation != null) return myPresentation;
Runnable r = () -> myPresentation = updateActionBeforeShow(myAction, myDataContext).getPresentation();
if (ApplicationManager.getApplication().isDispatchThread()) {
r.run();
} else {
myModel.updateOnEdt(r);
}
return myPresentation;
}
private boolean hasPresentation() {
return myPresentation != null;
}
@Nullable
public String getGroupName() {
if (myAction instanceof ActionGroup && Comparing.equal(myAction.getTemplatePresentation().getText(), myGroupName)) return null;
return myGroupName;
}
public boolean isGroupAction() {
return myAction instanceof ActionGroup;
}
@Override
public boolean equals(Object obj) {
return obj instanceof ActionWrapper && compareTo((ActionWrapper)obj) == 0;
}
@Override
public int hashCode() {
String text = myAction.getTemplatePresentation().getText();
return text != null ? text.hashCode() : 0;
}
@Override
public String toString() {
return myAction.toString();
}
}
public static class GotoActionListCellRenderer extends DefaultListCellRenderer {
private final Function<OptionDescription, String> myGroupNamer;
public GotoActionListCellRenderer(Function<OptionDescription, String> groupNamer) {
myGroupNamer = groupNamer;
}
@NotNull
@Override
public Component getListCellRendererComponent(@NotNull JList list,
Object matchedValue,
int index, boolean isSelected, boolean cellHasFocus) {
boolean showIcon = UISettings.getInstance().getShowIconsInMenus();
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(JBUI.Borders.empty(2));
panel.setOpaque(true);
Color bg = UIUtil.getListBackground(isSelected);
panel.setBackground(bg);
SimpleColoredComponent nameComponent = new SimpleColoredComponent();
nameComponent.setBackground(bg);
panel.add(nameComponent, BorderLayout.CENTER);
if (matchedValue instanceof String) { //...
nameComponent.append((String)matchedValue, new SimpleTextAttributes(STYLE_PLAIN, defaultActionForeground(isSelected, null)));
if (showIcon) {
panel.add(new JBLabel(EMPTY_ICON), BorderLayout.WEST);
}
return panel;
}
Color groupFg = isSelected ? UIUtil.getListSelectionForeground() : UIUtil.getLabelDisabledForeground();
Object value = ((MatchedValue) matchedValue).value;
String pattern = ((MatchedValue)matchedValue).pattern;
Border eastBorder = JBUI.Borders.emptyRight(2);
if (value instanceof ActionWrapper) {
ActionWrapper actionWithParentGroup = (ActionWrapper)value;
AnAction anAction = actionWithParentGroup.getAction();
Presentation presentation = anAction.getTemplatePresentation();
boolean toggle = anAction instanceof ToggleAction;
String groupName = actionWithParentGroup.getAction() instanceof ApplyIntentionAction ? null : actionWithParentGroup.getGroupName();
Presentation actionPresentation = actionWithParentGroup.getPresentation();
Color fg = defaultActionForeground(isSelected, actionPresentation);
boolean disabled = actionPresentation != null && (!actionPresentation.isEnabled() || !actionPresentation.isVisible());
if (disabled) {
groupFg = UIUtil.getLabelDisabledForeground();
}
if (showIcon) {
Icon icon = presentation.getIcon();
panel.add(createIconLabel(icon, disabled), BorderLayout.WEST);
}
appendWithColoredMatches(nameComponent, getName(presentation.getText(), groupName, toggle), pattern, fg, isSelected);
panel.setToolTipText(presentation.getDescription());
Shortcut[] shortcuts = getActiveKeymapShortcuts(ActionManager.getInstance().getId(anAction)).getShortcuts();
String shortcutText = KeymapUtil.getPreferredShortcutText(
shortcuts);
if (StringUtil.isNotEmpty(shortcutText)) {
nameComponent.append(" " + shortcutText,
new SimpleTextAttributes(SimpleTextAttributes.STYLE_SMALLER | SimpleTextAttributes.STYLE_BOLD,
UIUtil.isUnderDarcula() ? groupFg : ColorUtil.shift(groupFg, 1.3)));
}
if (toggle) {
AnActionEvent event = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, ((ActionWrapper)value).myDataContext);
boolean selected = ((ToggleAction)anAction).isSelected(event);
addOnOffButton(panel, selected);
}
else {
if (groupName != null) {
JLabel groupLabel = new JLabel(groupName);
groupLabel.setBackground(bg);
groupLabel.setBorder(eastBorder);
groupLabel.setForeground(groupFg);
panel.add(groupLabel, BorderLayout.EAST);
}
}
}
else if (value instanceof OptionDescription) {
if (!isSelected && !(value instanceof BooleanOptionDescription)) {
Color descriptorBg = UIUtil.isUnderDarcula() ? ColorUtil.brighter(UIUtil.getListBackground(), 1) : LightColors.SLIGHTLY_GRAY;
panel.setBackground(descriptorBg);
nameComponent.setBackground(descriptorBg);
}
String hit = ((OptionDescription)value).getHit();
if (hit == null) {
hit = ((OptionDescription)value).getOption();
}
hit = StringUtil.unescapeXml(hit);
hit = hit.replace(" ", " "); // avoid extra spaces from mnemonics and xml conversion
String fullHit = hit;
hit = StringUtil.first(hit, 45, true);
Color fg = UIUtil.getListForeground(isSelected);
appendWithColoredMatches(nameComponent, hit.trim(), pattern, fg, isSelected);
if (showIcon) {
panel.add(new JLabel(EMPTY_ICON), BorderLayout.WEST);
}
panel.setToolTipText(fullHit);
if (value instanceof BooleanOptionDescription) {
boolean selected = ((BooleanOptionDescription)value).isOptionEnabled();
addOnOffButton(panel, selected);
}
else {
JLabel settingsLabel = new JLabel(myGroupNamer.fun((OptionDescription)value));
settingsLabel.setForeground(groupFg);
settingsLabel.setBackground(bg);
settingsLabel.setBorder(eastBorder);
panel.add(settingsLabel, BorderLayout.EAST);
}
}
return panel;
}
private static void addOnOffButton(@NotNull JPanel panel, boolean selected) {
OnOffButton button = new OnOffButton();
button.setSelected(selected);
panel.add(button, BorderLayout.EAST);
panel.setBorder(JBUI.Borders.empty(0, 2));
}
@NotNull
private static String getName(@Nullable String text, @Nullable String groupName, boolean toggle) {
return toggle && StringUtil.isNotEmpty(groupName)
? StringUtil.isNotEmpty(text) ? groupName + ": " + text
: groupName : StringUtil.notNullize(text);
}
private static void appendWithColoredMatches(SimpleColoredComponent nameComponent,
@NotNull String name,
@NotNull String pattern,
Color fg,
boolean selected) {
SimpleTextAttributes plain = new SimpleTextAttributes(STYLE_PLAIN, fg);
SimpleTextAttributes highlighted = new SimpleTextAttributes(null, fg, null, STYLE_SEARCH_MATCH);
List<TextRange> fragments = ContainerUtil.newArrayList();
if (selected) {
int matchStart = StringUtil.indexOfIgnoreCase(name, pattern, 0);
if (matchStart >= 0) {
fragments.add(TextRange.from(matchStart, pattern.length()));
}
}
SpeedSearchUtil.appendColoredFragments(nameComponent, name, fragments, plain, highlighted);
}
}
}
| platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.gotoByName;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.actions.ApplyIntentionAction;
import com.intellij.ide.actions.ShowSettingsUtilImpl;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.search.BooleanOptionDescription;
import com.intellij.ide.ui.search.OptionDescription;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.codeStyle.MinusculeMatcher;
import com.intellij.ui.*;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.OnOffButton;
import com.intellij.ui.speedSearch.SpeedSearchUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.intellij.openapi.keymap.KeymapUtil.getActiveKeymapShortcuts;
import static com.intellij.ui.SimpleTextAttributes.STYLE_PLAIN;
import static com.intellij.ui.SimpleTextAttributes.STYLE_SEARCH_MATCH;
public class GotoActionModel implements ChooseByNameModel, Comparator<Object>, DumbAware {
private static final Pattern INNER_GROUP_WITH_IDS = Pattern.compile("(.*) \\(\\d+\\)");
@Nullable private final Project myProject;
private final Component myContextComponent;
@Nullable private final Editor myEditor;
protected final ActionManager myActionManager = ActionManager.getInstance();
private static final Icon EMPTY_ICON = EmptyIcon.ICON_18;
protected final Map<AnAction, String> myActionGroups = ContainerUtil.newHashMap();
private final NotNullLazyValue<Map<String, String>> myConfigurablesNames = VolatileNotNullLazyValue.createValue(() -> {
Map<String, String> map = ContainerUtil.newTroveMap();
for (Configurable configurable : ShowSettingsUtilImpl.getConfigurables(getProject(), true)) {
if (configurable instanceof SearchableConfigurable) {
map.put(((SearchableConfigurable)configurable).getId(), configurable.getDisplayName());
}
}
return map;
});
private final ModalityState myModality;
public GotoActionModel(@Nullable Project project, Component component, @Nullable Editor editor) {
this(project, component, editor, ModalityState.defaultModalityState());
}
public GotoActionModel(@Nullable Project project, Component component, @Nullable Editor editor, @Nullable ModalityState modalityState) {
myProject = project;
myContextComponent = component;
myEditor = editor;
myModality = modalityState;
ActionGroup mainMenu = (ActionGroup)myActionManager.getActionOrStub(IdeActions.GROUP_MAIN_MENU);
assert mainMenu != null;
collectActions(myActionGroups, mainMenu, mainMenu.getTemplatePresentation().getText());
}
@NotNull
Map<String, ApplyIntentionAction> getAvailableIntentions() {
Map<String, ApplyIntentionAction> map = new TreeMap<>();
if (myProject != null && !myProject.isDisposed() && myEditor != null && !myEditor.isDisposed()) {
ApplyIntentionAction[] children = ApplyIntentionAction.getAvailableIntentions(myEditor, PsiDocumentManager.getInstance(myProject).getPsiFile(
myEditor.getDocument()));
if (children != null) {
for (ApplyIntentionAction action : children) {
map.put(action.getName(), action);
}
}
}
return map;
}
@Override
public String getPromptText() {
return IdeBundle.message("prompt.gotoaction.enter.action");
}
@Nullable
@Override
public String getCheckBoxName() {
return IdeBundle.message("checkbox.disabled.included");
}
@Override
public char getCheckBoxMnemonic() {
return 'd';
}
@Override
public String getNotInMessage() {
return IdeBundle.message("label.no.enabled.actions.found");
}
@Override
public String getNotFoundMessage() {
return IdeBundle.message("label.no.actions.found");
}
@Override
public boolean loadInitialCheckBoxState() {
return false;
}
@Override
public void saveInitialCheckBoxState(boolean state) {
}
public static class MatchedValue implements Comparable<MatchedValue> {
@NotNull public final Comparable value;
@NotNull final String pattern;
public MatchedValue(@NotNull Comparable value, @NotNull String pattern) {
this.value = value;
this.pattern = pattern;
}
@Nullable
@VisibleForTesting
public String getValueText() {
if (value instanceof OptionDescription) return ((OptionDescription)value).getHit();
if (!(value instanceof ActionWrapper)) return null;
return ((ActionWrapper)value).getAction().getTemplatePresentation().getText();
}
@Nullable
@Override
public String toString() {
return getMatchingDegree() + " " + getValueText();
}
private int getMatchingDegree() {
String text = getValueText();
if (text != null) {
int degree = getRank(text);
return value instanceof ActionWrapper && !((ActionWrapper)value).isGroupAction() ? degree + 1 : degree;
}
return 0;
}
private int getRank(@NotNull String text) {
if (StringUtil.equalsIgnoreCase(StringUtil.trimEnd(text, "..."), pattern)) return 3;
if (StringUtil.startsWithIgnoreCase(text, pattern)) return 2;
if (StringUtil.containsIgnoreCase(text, pattern)) return 1;
return 0;
}
@Override
public int compareTo(@NotNull MatchedValue o) {
if (o == this) return 0;
int diff = o.getMatchingDegree() - getMatchingDegree();
if (diff != 0) return diff;
boolean edt = ApplicationManager.getApplication().isDispatchThread();
if (value instanceof ActionWrapper && o.value instanceof ActionWrapper) {
if (edt || ((ActionWrapper)value).hasPresentation() && ((ActionWrapper)o.value).hasPresentation()) {
boolean p1Enable = ((ActionWrapper)value).isAvailable();
boolean p2enable = ((ActionWrapper)o.value).isAvailable();
if (p1Enable && !p2enable) return -1;
if (!p1Enable && p2enable) return 1;
}
//noinspection unchecked
int compared = value.compareTo(o.value);
if (compared != 0) return compared;
}
if (value instanceof ActionWrapper && o.value instanceof BooleanOptionDescription) {
return edt && ((ActionWrapper)value).isAvailable() ? -1 : 1;
}
if (o.value instanceof ActionWrapper && value instanceof BooleanOptionDescription) {
return edt && ((ActionWrapper)o.value).isAvailable() ? 1 : -1;
}
if (value instanceof BooleanOptionDescription && !(o.value instanceof BooleanOptionDescription) && o.value instanceof OptionDescription) return -1;
if (o.value instanceof BooleanOptionDescription && !(value instanceof BooleanOptionDescription) && value instanceof OptionDescription) return 1;
if (value instanceof OptionDescription && !(o.value instanceof OptionDescription)) return 1;
if (o.value instanceof OptionDescription && !(value instanceof OptionDescription)) return -1;
diff = StringUtil.notNullize(getValueText()).length() - StringUtil.notNullize(o.getValueText()).length();
if (diff != 0) return diff;
//noinspection unchecked
diff = value.compareTo(o.value);
if (diff != 0) return diff;
return o.hashCode() - hashCode();
}
}
@Override
public ListCellRenderer getListCellRenderer() {
return new GotoActionListCellRenderer(this::getGroupName);
}
protected String getActionId(@NotNull AnAction anAction) {
return myActionManager.getId(anAction);
}
@NotNull
private static JLabel createIconLabel(@Nullable Icon icon, boolean disabled) {
LayeredIcon layeredIcon = new LayeredIcon(2);
layeredIcon.setIcon(EMPTY_ICON, 0);
if (icon == null) return new JLabel(layeredIcon);
int width = icon.getIconWidth();
int height = icon.getIconHeight();
int emptyIconWidth = EMPTY_ICON.getIconWidth();
int emptyIconHeight = EMPTY_ICON.getIconHeight();
if (width <= emptyIconWidth && height <= emptyIconHeight) {
layeredIcon.setIcon(disabled ? IconLoader.getDisabledIcon(icon) : icon, 1,
(emptyIconWidth - width) / 2,
(emptyIconHeight - height) / 2);
}
return new JLabel(layeredIcon);
}
@Override
public int compare(@NotNull Object o1, @NotNull Object o2) {
if (ChooseByNameBase.EXTRA_ELEM.equals(o1)) return 1;
if (ChooseByNameBase.EXTRA_ELEM.equals(o2)) return -1;
return ((MatchedValue)o1).compareTo((MatchedValue)o2);
}
@NotNull
public static AnActionEvent updateActionBeforeShow(@NotNull AnAction anAction, @NotNull DataContext dataContext) {
AnActionEvent event = AnActionEvent.createFromDataContext(ActionPlaces.ACTION_SEARCH, null, dataContext);
ActionUtil.performDumbAwareUpdate(anAction, event, false);
return event;
}
public static Color defaultActionForeground(boolean isSelected, @Nullable Presentation presentation) {
if (presentation != null && (!presentation.isEnabled() || !presentation.isVisible())) return UIUtil.getInactiveTextColor();
if (isSelected) return UIUtil.getListSelectionForeground();
return UIUtil.getListForeground();
}
@Override
@NotNull
public String[] getNames(boolean checkBoxState) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
@Override
@NotNull
public Object[] getElementsByName(String id, boolean checkBoxState, String pattern) {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
@NotNull
public String getGroupName(@NotNull OptionDescription description) {
String name = description.getGroupName();
if (name == null) name = myConfigurablesNames.getValue().get(description.getConfigurableId());
String settings = SystemInfo.isMac ? "Preferences" : "Settings";
if (name == null || name.equals(description.getHit())) return settings;
return settings + " > " + name;
}
@NotNull
Map<String, String> getConfigurablesNames() {
return myConfigurablesNames.getValue();
}
private void collectActions(@NotNull Map<AnAction, String> result, @NotNull ActionGroup group, @Nullable String containingGroupName) {
AnAction[] actions = group.getChildren(null);
includeGroup(result, group, actions, containingGroupName);
for (AnAction action : actions) {
if (action == null || action instanceof Separator) continue;
if (action instanceof ActionGroup) {
ActionGroup actionGroup = (ActionGroup)action;
String groupName = actionGroup.getTemplatePresentation().getText();
collectActions(result, actionGroup, getGroupName(StringUtil.isEmpty(groupName) || !actionGroup.isPopup() ? containingGroupName : groupName));
}
else {
String groupName = group.getTemplatePresentation().getText();
if (result.containsKey(action)) {
result.put(action, null);
}
else {
result.put(action, getGroupName(StringUtil.isEmpty(groupName) ? containingGroupName : groupName));
}
}
}
}
@Nullable
private static String getGroupName(@Nullable String groupName) {
if (groupName != null) {
Matcher matcher = INNER_GROUP_WITH_IDS.matcher(groupName);
if (matcher.matches()) return matcher.group(1);
}
return groupName;
}
private void includeGroup(@NotNull Map<AnAction, String> result,
@NotNull ActionGroup group,
@NotNull AnAction[] actions,
@Nullable String containingGroupName) {
boolean showGroup = true;
for (AnAction action : actions) {
if (myActionManager.getId(action) != null) {
showGroup = false;
break;
}
}
if (showGroup) {
result.put(group, getGroupName(containingGroupName));
}
}
@Override
@Nullable
public String getFullName(@NotNull Object element) {
return getElementName(element);
}
@NonNls
@Override
public String getHelpId() {
return "procedures.navigating.goto.action";
}
@Override
@NotNull
public String[] getSeparators() {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
@Nullable
@Override
public String getElementName(@NotNull Object mv) {
return ((MatchedValue) mv).getValueText();
}
protected MatchMode actionMatches(@NotNull String pattern, MinusculeMatcher matcher, @NotNull AnAction anAction) {
Presentation presentation = anAction.getTemplatePresentation();
String text = presentation.getText();
String description = presentation.getDescription();
String groupName = myActionGroups.get(anAction);
if (text != null && matcher.matches(text)) {
return MatchMode.NAME;
}
else if (description != null && !description.equals(text) && matcher.matches(description)) {
return MatchMode.DESCRIPTION;
}
if (text == null) {
return MatchMode.NONE;
}
if (matcher.matches(groupName + " " + text)) {
return anAction instanceof ToggleAction ? MatchMode.NAME : MatchMode.GROUP;
}
return matcher.matches(text + " " + groupName) ? MatchMode.GROUP : MatchMode.NONE;
}
@Nullable
protected Project getProject() {
return myProject;
}
protected Component getContextComponent() {
return myContextComponent;
}
@NotNull
public SortedSet<Object> sortItems(@NotNull Set<Object> elements) {
TreeSet<Object> objects = ContainerUtilRt.newTreeSet(this);
objects.addAll(elements);
return objects;
}
private void updateOnEdt(Runnable update) {
Semaphore semaphore = new Semaphore(1);
ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
ApplicationManager.getApplication().invokeLater(() -> {
try {
update.run();
}
finally {
semaphore.up();
}
}, myModality, __ -> indicator != null && indicator.isCanceled());
while (!semaphore.waitFor(10)) {
if (indicator != null && indicator.isCanceled()) {
// don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788
throw new ProcessCanceledException();
}
}
}
public enum MatchMode {
NONE, INTENTION, NAME, DESCRIPTION, GROUP, NON_MENU
}
@Override
public boolean willOpenEditor() {
return false;
}
@Override
public boolean useMiddleMatching() {
return true;
}
public static class ActionWrapper implements Comparable<ActionWrapper> {
@NotNull private final AnAction myAction;
@NotNull private final MatchMode myMode;
@Nullable private final String myGroupName;
private final DataContext myDataContext;
private final GotoActionModel myModel;
private volatile Presentation myPresentation;
public ActionWrapper(@NotNull AnAction action, @Nullable String groupName, @NotNull MatchMode mode, DataContext dataContext, GotoActionModel model) {
myAction = action;
myMode = mode;
myGroupName = groupName;
myDataContext = dataContext;
myModel = model;
}
@NotNull
public AnAction getAction() {
return myAction;
}
@NotNull
public MatchMode getMode() {
return myMode;
}
@Override
public int compareTo(@NotNull ActionWrapper o) {
int compared = myMode.compareTo(o.getMode());
if (compared != 0) return compared;
Presentation myPresentation = myAction.getTemplatePresentation();
Presentation oPresentation = o.getAction().getTemplatePresentation();
String myText = myPresentation.getText();
String oText = oPresentation.getText();
int byText = StringUtil.compare(StringUtil.trimEnd(myText, "..."), StringUtil.trimEnd(oText, "..."), true);
if (byText != 0) return byText;
int byTextLength = StringUtil.notNullize(myText).length() - StringUtil.notNullize(oText).length();
if (byTextLength != 0) return byTextLength;
int byGroup = Comparing.compare(myGroupName, o.myGroupName);
if (byGroup != 0) return byGroup;
int byDesc = StringUtil.compare(myPresentation.getDescription(), oPresentation.getDescription(), true);
if (byDesc != 0) return byDesc;
return 0;
}
public boolean isAvailable() {
Presentation presentation = getPresentation();
return presentation != null && presentation.isEnabledAndVisible();
}
public Presentation getPresentation() {
if (myPresentation != null) return myPresentation;
Runnable r = () -> myPresentation = updateActionBeforeShow(myAction, myDataContext).getPresentation();
if (ApplicationManager.getApplication().isDispatchThread()) {
r.run();
} else {
myModel.updateOnEdt(r);
}
return myPresentation;
}
private boolean hasPresentation() {
return myPresentation != null;
}
@Nullable
public String getGroupName() {
if (myAction instanceof ActionGroup && Comparing.equal(myAction.getTemplatePresentation().getText(), myGroupName)) return null;
return myGroupName;
}
public boolean isGroupAction() {
return myAction instanceof ActionGroup;
}
@Override
public boolean equals(Object obj) {
return obj instanceof ActionWrapper && compareTo((ActionWrapper)obj) == 0;
}
@Override
public int hashCode() {
String text = myAction.getTemplatePresentation().getText();
return text != null ? text.hashCode() : 0;
}
@Override
public String toString() {
return myAction.toString();
}
}
public static class GotoActionListCellRenderer extends DefaultListCellRenderer {
private final Function<OptionDescription, String> myGroupNamer;
public GotoActionListCellRenderer(Function<OptionDescription, String> groupNamer) {
myGroupNamer = groupNamer;
}
@NotNull
@Override
public Component getListCellRendererComponent(@NotNull JList list,
Object matchedValue,
int index, boolean isSelected, boolean cellHasFocus) {
boolean showIcon = UISettings.getInstance().getShowIconsInMenus();
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(JBUI.Borders.empty(2));
panel.setOpaque(true);
Color bg = UIUtil.getListBackground(isSelected);
panel.setBackground(bg);
SimpleColoredComponent nameComponent = new SimpleColoredComponent();
nameComponent.setBackground(bg);
panel.add(nameComponent, BorderLayout.CENTER);
if (matchedValue instanceof String) { //...
nameComponent.append((String)matchedValue, new SimpleTextAttributes(STYLE_PLAIN, defaultActionForeground(isSelected, null)));
if (showIcon) {
panel.add(new JBLabel(EMPTY_ICON), BorderLayout.WEST);
}
return panel;
}
Color groupFg = isSelected ? UIUtil.getListSelectionForeground() : UIUtil.getLabelDisabledForeground();
Object value = ((MatchedValue) matchedValue).value;
String pattern = ((MatchedValue)matchedValue).pattern;
Border eastBorder = JBUI.Borders.emptyRight(2);
if (value instanceof ActionWrapper) {
ActionWrapper actionWithParentGroup = (ActionWrapper)value;
AnAction anAction = actionWithParentGroup.getAction();
Presentation presentation = anAction.getTemplatePresentation();
boolean toggle = anAction instanceof ToggleAction;
String groupName = actionWithParentGroup.getAction() instanceof ApplyIntentionAction ? null : actionWithParentGroup.getGroupName();
Presentation actionPresentation = actionWithParentGroup.getPresentation();
Color fg = defaultActionForeground(isSelected, actionPresentation);
boolean disabled = actionPresentation != null && (!actionPresentation.isEnabled() || !actionPresentation.isVisible());
if (disabled) {
groupFg = UIUtil.getLabelDisabledForeground();
}
if (showIcon) {
Icon icon = presentation.getIcon();
panel.add(createIconLabel(icon, disabled), BorderLayout.WEST);
}
appendWithColoredMatches(nameComponent, getName(presentation.getText(), groupName, toggle), pattern, fg, isSelected);
panel.setToolTipText(presentation.getDescription());
Shortcut[] shortcuts = getActiveKeymapShortcuts(ActionManager.getInstance().getId(anAction)).getShortcuts();
String shortcutText = KeymapUtil.getPreferredShortcutText(
shortcuts);
if (StringUtil.isNotEmpty(shortcutText)) {
nameComponent.append(" " + shortcutText,
new SimpleTextAttributes(SimpleTextAttributes.STYLE_SMALLER | SimpleTextAttributes.STYLE_BOLD,
UIUtil.isUnderDarcula() ? groupFg : ColorUtil.shift(groupFg, 1.3)));
}
if (toggle) {
AnActionEvent event = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, ((ActionWrapper)value).myDataContext);
boolean selected = ((ToggleAction)anAction).isSelected(event);
addOnOffButton(panel, selected);
}
else {
if (groupName != null) {
JLabel groupLabel = new JLabel(groupName);
groupLabel.setBackground(bg);
groupLabel.setBorder(eastBorder);
groupLabel.setForeground(groupFg);
panel.add(groupLabel, BorderLayout.EAST);
}
}
}
else if (value instanceof OptionDescription) {
if (!isSelected && !(value instanceof BooleanOptionDescription)) {
Color descriptorBg = UIUtil.isUnderDarcula() ? ColorUtil.brighter(UIUtil.getListBackground(), 1) : LightColors.SLIGHTLY_GRAY;
panel.setBackground(descriptorBg);
nameComponent.setBackground(descriptorBg);
}
String hit = ((OptionDescription)value).getHit();
if (hit == null) {
hit = ((OptionDescription)value).getOption();
}
hit = StringUtil.unescapeXml(hit);
hit = hit.replace(" ", " "); // avoid extra spaces from mnemonics and xml conversion
String fullHit = hit;
hit = StringUtil.first(hit, 45, true);
Color fg = UIUtil.getListForeground(isSelected);
appendWithColoredMatches(nameComponent, hit.trim(), pattern, fg, isSelected);
if (showIcon) {
panel.add(new JLabel(EMPTY_ICON), BorderLayout.WEST);
}
panel.setToolTipText(fullHit);
if (value instanceof BooleanOptionDescription) {
boolean selected = ((BooleanOptionDescription)value).isOptionEnabled();
addOnOffButton(panel, selected);
}
else {
JLabel settingsLabel = new JLabel(myGroupNamer.fun((OptionDescription)value));
settingsLabel.setForeground(groupFg);
settingsLabel.setBackground(bg);
settingsLabel.setBorder(eastBorder);
panel.add(settingsLabel, BorderLayout.EAST);
}
}
return panel;
}
private static void addOnOffButton(@NotNull JPanel panel, boolean selected) {
OnOffButton button = new OnOffButton();
button.setSelected(selected);
panel.add(button, BorderLayout.EAST);
panel.setBorder(JBUI.Borders.empty(0, 2));
}
@NotNull
private static String getName(@Nullable String text, @Nullable String groupName, boolean toggle) {
return toggle && StringUtil.isNotEmpty(groupName)
? StringUtil.isNotEmpty(text) ? groupName + ": " + text
: groupName : StringUtil.notNullize(text);
}
private static void appendWithColoredMatches(SimpleColoredComponent nameComponent,
@NotNull String name,
@NotNull String pattern,
Color fg,
boolean selected) {
SimpleTextAttributes plain = new SimpleTextAttributes(STYLE_PLAIN, fg);
SimpleTextAttributes highlighted = new SimpleTextAttributes(null, fg, null, STYLE_SEARCH_MATCH);
List<TextRange> fragments = ContainerUtil.newArrayList();
if (selected) {
int matchStart = StringUtil.indexOfIgnoreCase(name, pattern, 0);
if (matchStart >= 0) {
fragments.add(TextRange.from(matchStart, pattern.length()));
}
}
SpeedSearchUtil.appendColoredFragments(nameComponent, name, fragments, plain, highlighted);
}
}
}
| do not convert empty icon into disabled one
(cherry picked from commit 129e442d2ecfd2b1b92bb047a0d47db805dd8629)
| platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java | do not convert empty icon into disabled one |
|
Java | apache-2.0 | 102f19892ac0618fd1e973dbe11b18d8d1d8f186 | 0 | getsocial-im/getsocial-android-sdk | /*
* Copyright 2015-2017 GetSocial B.V.
*
* 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 im.getsocial.demo.fragment;
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.InputType;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import im.getsocial.demo.adapter.MenuItem;
import im.getsocial.demo.utils.EditTextWOCopyPaste;
import im.getsocial.demo.utils.PixelUtils;
import im.getsocial.demo.utils.UserIdentityUtils;
import im.getsocial.sdk.GetSocial;
import im.getsocial.sdk.communities.IdentityProviderIds;
import im.getsocial.sdk.communities.UserUpdate;
import java.util.ArrayList;
import java.util.List;
import static com.squareup.picasso.Picasso.with;
public class UserManagementFragment extends BaseListFragment {
private static final int MAX_WIDTH = 500;
private static final int REQUEST_PICK_AVATAR = 0x1;
public UserManagementFragment() {
}
protected void invalidateUi() {
invalidateList();
_activityListener.invalidateUi();
}
@NonNull
protected List<MenuItem> createListData() {
final List<MenuItem> listData = new ArrayList<>();
listData.add(new MenuItem.Builder("Change Display Name").withAction(this::changeDisplayName).build());
listData.add(new MenuItem.Builder("Change User Avatar").withAction(this::changeUserAvatar).build());
listData.add(new MenuItem.Builder("Choose Avatar").withAction(() -> pickImageFromDevice(REQUEST_PICK_AVATAR)).build());
listData.add(new MenuItem.Builder("Add Facebook user identity").withAction(
() -> addFacebookUserIdentity(this::invalidateUi)
).withEnabledCheck(
() -> !GetSocial.getCurrentUser().getIdentities().containsKey(IdentityProviderIds.FACEBOOK)
).build()
);
listData.add(new MenuItem.Builder("Add Custom user identity")
.withAction(() -> addCustomUserIdentity(this::invalidateUi))
.withEnabledCheck(() -> !GetSocial.getCurrentUser().getIdentities().containsKey(CUSTOM_PROVIDER))
.build()
);
listData.add(new MenuItem.Builder("Remove Facebook user identity").withSubtitle("Log out from Facebook")
.withAction(this::removeFacebookUserIdentity)
.withEnabledCheck(() -> GetSocial.getCurrentUser().getIdentities().containsKey(IdentityProviderIds.FACEBOOK))
.build()
);
listData.add(new MenuItem.Builder("Remove Custom user identity")
.withAction(this::removeCustomUserIdentity)
.withEnabledCheck(() -> GetSocial.getCurrentUser().getIdentities().containsKey(CUSTOM_PROVIDER))
.build()
);
listData.add(new MenuItem.Builder("Add property").withAction(this::setPublicProperty).build());
listData.add(new MenuItem.Builder("Get property").withAction(this::getPublicProperty).build());
listData.add(new MenuItem.Builder("Increment property").withAction(this::incrementPublicProperty).build());
listData.add(new MenuItem.Builder("Decrement property").withAction(this::decrementPublicProperty).build());
listData.add(new MenuItem.Builder("Refresh").withAction(this::refreshUser).build());
listData.add(new MenuItem.Builder("Log out").withAction(this::logOut).build());
listData.add(MenuItem.builder("Reset without init").withAction(() -> GetSocial.reset(() -> {
_log.logInfoAndToast("User reset");
_activityListener.onBackPressed();
}, error -> {
_log.logErrorAndToast(error);
invalidateUi();
})).withEnabledCheck(GetSocial::isInitialized).build());
return listData;
}
@Override
protected void onImagePickedFromDevice(final Uri imageUri, final int requestCode) {
if (requestCode == REQUEST_PICK_AVATAR) {
with(getContext()).load(imageUri).resize(MAX_WIDTH, 0).memoryPolicy(MemoryPolicy.NO_CACHE)
.into(new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
setAvatarBitmap(bitmap);
}
@Override
public void onBitmapFailed(final Drawable errorDrawable) {
showAlert("Error", "Failed to load image");
}
@Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
}
});
}
}
private void setAvatarBitmap(final Bitmap bitmap) {
GetSocial.getCurrentUser().updateDetails(new UserUpdate().updateAvatar(bitmap), new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
bitmap.recycle();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Avatar has been changed successfully!", Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(), "Error changing avatar: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
});
}
private void getPublicProperty() {
final EditTextWOCopyPaste keyInput = new EditTextWOCopyPaste(getContext());
keyInput.setContentDescription("public_property_key");
keyInput.setLongClickable(false);
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final FrameLayout frameLayout = new FrameLayout(getContext());
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(keyInput);
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Property")
.setPositiveButton("OK", (dialogInterface, which) ->
Toast.makeText(
getContext(),
keyInput.getText().toString() + " = " + GetSocial.getCurrentUser().getPublicProperties().get(keyInput.getText().toString()),
Toast.LENGTH_SHORT
).show())
.setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel()).create().show();
}
private void setPublicProperty() {
final EditTextWOCopyPaste keyInput = new EditTextWOCopyPaste(getContext());
keyInput.setLongClickable(false);
final EditTextWOCopyPaste valInput = new EditTextWOCopyPaste(getContext());
valInput.setLongClickable(false);
keyInput.setHint("Key");
keyInput.setContentDescription("public_property_key");
valInput.setHint("Value");
valInput.setContentDescription("public_property_value");
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final LinearLayout frameLayout = new LinearLayout(getContext());
frameLayout.setOrientation(LinearLayout.VERTICAL);
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(keyInput);
frameLayout.addView(valInput);
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Property")
.setPositiveButton("OK", (dialogInterface, which) -> GetSocial.getCurrentUser().updateDetails(new UserUpdate().setPublicProperty(keyInput.getText().toString(), valInput.getText().toString()),
new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
dialogInterface.dismiss();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Public property has been changed successfully!",
Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(),
"Error changing public property: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
})).setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel()).create().show();
}
private void incrementPublicProperty() {
final EditTextWOCopyPaste keyInput = new EditTextWOCopyPaste(getContext());
keyInput.setLongClickable(false);
final EditTextWOCopyPaste valInput = new EditTextWOCopyPaste(getContext());
valInput.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
valInput.setLongClickable(false);
keyInput.setHint("Key");
keyInput.setContentDescription("public_property_key");
valInput.setHint("Value");
valInput.setContentDescription("increment");
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final LinearLayout frameLayout = new LinearLayout(getContext());
frameLayout.setOrientation(LinearLayout.VERTICAL);
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(keyInput);
frameLayout.addView(valInput);
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Property")
.setPositiveButton("OK", (dialogInterface, which) -> GetSocial.getCurrentUser().updateDetails(new UserUpdate().incrementPublicProperty(keyInput.getText().toString(), Double.parseDouble(valInput.getText().toString())),
new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
dialogInterface.dismiss();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Public property has been changed successfully!",
Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(),
"Error changing public property: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
})).setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel()).create().show();
}
private void decrementPublicProperty() {
final EditTextWOCopyPaste keyInput = new EditTextWOCopyPaste(getContext());
keyInput.setLongClickable(false);
final EditTextWOCopyPaste valInput = new EditTextWOCopyPaste(getContext());
valInput.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
valInput.setLongClickable(false);
keyInput.setHint("Key");
keyInput.setContentDescription("public_property_key");
valInput.setHint("Value");
valInput.setContentDescription("decrement");
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final LinearLayout frameLayout = new LinearLayout(getContext());
frameLayout.setOrientation(LinearLayout.VERTICAL);
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(keyInput);
frameLayout.addView(valInput);
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Property")
.setPositiveButton("OK", (dialogInterface, which) -> GetSocial.getCurrentUser().updateDetails(new UserUpdate().decrementPublicProperty(keyInput.getText().toString(), Double.parseDouble(valInput.getText().toString())),
new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
dialogInterface.dismiss();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Public property has been changed successfully!",
Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(),
"Error changing public property: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
})).setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel()).create().show();
}
private void refreshUser() {
GetSocial.getCurrentUser().refresh(() -> {
Toast.makeText(getContext(), "Current User has been refreshed successfully!",
Toast.LENGTH_SHORT).show();
}, (error) -> {
Toast.makeText(getContext(),
"Error refreshing current user: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
});
}
// region Presenter
private void changeUserAvatar() {
GetSocial.getCurrentUser().updateDetails(new UserUpdate().updateAvatarUrl(UserIdentityUtils.getRandomAvatar()), new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Avatar has been changed successfully!", Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(), "Error changing avatar: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
});
}
private void changeDisplayName() {
final EditTextWOCopyPaste displayNameInput = new EditTextWOCopyPaste(getContext());
displayNameInput.setLongClickable(false);
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final FrameLayout frameLayout = new FrameLayout(getContext());
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(displayNameInput);
displayNameInput.setText(UserIdentityUtils.getDisplayName());
displayNameInput.setSelection(displayNameInput.getText().length());
displayNameInput.setContentDescription("display_name_input");
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Display Name")
.setPositiveButton("OK", (dialogInterface, which) -> GetSocial.getCurrentUser().updateDetails(new UserUpdate().updateDisplayName(displayNameInput.getText().toString()),
new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
dialogInterface.dismiss();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Display name has been changed successfully!",
Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(),
"Error changing display name: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
})).setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel())
.create().show();
}
private void removeFacebookUserIdentity() {
removeUserIdentity(IdentityProviderIds.FACEBOOK);
disconnectFromFacebook();
}
private void removeCustomUserIdentity() {
removeUserIdentity(CUSTOM_PROVIDER);
}
private void logOut() {
showLoading("Log Out", "Wait...");
GetSocial.resetUser(() -> {
invalidateUi();
hideLoading();
Toast.makeText(getContext(), "User has been successfully logged out!", Toast.LENGTH_SHORT).show();
}, error -> {
hideLoading();
Toast.makeText(getContext(), "Failed to log out user, error: " + error.getMessage(),
Toast.LENGTH_SHORT).show();
});
}
// endregion
// region helpers
private void removeUserIdentity(final String providerId) {
GetSocial.getCurrentUser().removeIdentity(providerId, new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
invalidateUi();
_log.logInfoAndToast(String.format("Successfully removed user identity '%s'", providerId));
}
}, error -> {
_log.logErrorAndToast(String.format("Failed to remove user identity '%s', error: %s", providerId,
error.getMessage()));
});
}
@Override
public String getTitle() {
return "User Management";
}
@Override
public String getFragmentTag() {
return "usermanagement";
}
// endregion
}
| example/src/main/java/im/getsocial/demo/fragment/UserManagementFragment.java | /*
* Copyright 2015-2017 GetSocial B.V.
*
* 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 im.getsocial.demo.fragment;
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.InputType;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import im.getsocial.demo.adapter.MenuItem;
import im.getsocial.demo.utils.EditTextWOCopyPaste;
import im.getsocial.demo.utils.PixelUtils;
import im.getsocial.demo.utils.UserIdentityUtils;
import im.getsocial.sdk.GetSocial;
import im.getsocial.sdk.communities.IdentityProviderIds;
import im.getsocial.sdk.communities.UserUpdate;
import java.util.ArrayList;
import java.util.List;
import static com.squareup.picasso.Picasso.with;
public class UserManagementFragment extends BaseListFragment {
private static final int MAX_WIDTH = 500;
private static final int REQUEST_PICK_AVATAR = 0x1;
public UserManagementFragment() {
}
protected void invalidateUi() {
invalidateList();
_activityListener.invalidateUi();
}
@NonNull
protected List<MenuItem> createListData() {
final List<MenuItem> listData = new ArrayList<>();
listData.add(new MenuItem.Builder("Change Display Name").withAction(this::changeDisplayName).build());
listData.add(new MenuItem.Builder("Change User Avatar").withAction(this::changeUserAvatar).build());
listData.add(new MenuItem.Builder("Choose Avatar").withAction(() -> pickImageFromDevice(REQUEST_PICK_AVATAR)).build());
listData.add(new MenuItem.Builder("Add Facebook user identity").withAction(
() -> addFacebookUserIdentity(this::invalidateUi)
).withEnabledCheck(
() -> !GetSocial.getCurrentUser().getIdentities().containsKey(IdentityProviderIds.FACEBOOK)
).build()
);
listData.add(new MenuItem.Builder("Add Custom user identity")
.withAction(() -> addCustomUserIdentity(this::invalidateUi))
.withEnabledCheck(() -> !GetSocial.getCurrentUser().getIdentities().containsKey(CUSTOM_PROVIDER))
.build()
);
listData.add(new MenuItem.Builder("Remove Facebook user identity").withSubtitle("Log out from Facebook")
.withAction(this::removeFacebookUserIdentity)
.withEnabledCheck(() -> GetSocial.getCurrentUser().getIdentities().containsKey(IdentityProviderIds.FACEBOOK))
.build()
);
listData.add(new MenuItem.Builder("Remove Custom user identity")
.withAction(this::removeCustomUserIdentity)
.withEnabledCheck(() -> GetSocial.getCurrentUser().getIdentities().containsKey(CUSTOM_PROVIDER))
.build()
);
listData.add(new MenuItem.Builder("Add property").withAction(this::setPublicProperty).build());
listData.add(new MenuItem.Builder("Get property").withAction(this::getPublicProperty).build());
listData.add(new MenuItem.Builder("Increment property").withAction(this::incrementPublicProperty).build());
listData.add(new MenuItem.Builder("Decrement property").withAction(this::decrementPublicProperty).build());
listData.add(new MenuItem.Builder("Log out").withAction(this::logOut).build());
listData.add(MenuItem.builder("Reset without init").withAction(() -> GetSocial.reset(() -> {
_log.logInfoAndToast("User reset");
_activityListener.onBackPressed();
}, error -> {
_log.logErrorAndToast(error);
invalidateUi();
})).withEnabledCheck(GetSocial::isInitialized).build());
return listData;
}
@Override
protected void onImagePickedFromDevice(final Uri imageUri, final int requestCode) {
if (requestCode == REQUEST_PICK_AVATAR) {
with(getContext()).load(imageUri).resize(MAX_WIDTH, 0).memoryPolicy(MemoryPolicy.NO_CACHE)
.into(new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
setAvatarBitmap(bitmap);
}
@Override
public void onBitmapFailed(final Drawable errorDrawable) {
showAlert("Error", "Failed to load image");
}
@Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
}
});
}
}
private void setAvatarBitmap(final Bitmap bitmap) {
GetSocial.getCurrentUser().updateDetails(new UserUpdate().updateAvatar(bitmap), new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
bitmap.recycle();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Avatar has been changed successfully!", Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(), "Error changing avatar: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
});
}
private void getPublicProperty() {
final EditTextWOCopyPaste keyInput = new EditTextWOCopyPaste(getContext());
keyInput.setContentDescription("public_property_key");
keyInput.setLongClickable(false);
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final FrameLayout frameLayout = new FrameLayout(getContext());
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(keyInput);
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Property")
.setPositiveButton("OK", (dialogInterface, which) ->
Toast.makeText(
getContext(),
keyInput.getText().toString() + " = " + GetSocial.getCurrentUser().getPublicProperties().get(keyInput.getText().toString()),
Toast.LENGTH_SHORT
).show())
.setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel()).create().show();
}
private void setPublicProperty() {
final EditTextWOCopyPaste keyInput = new EditTextWOCopyPaste(getContext());
keyInput.setLongClickable(false);
final EditTextWOCopyPaste valInput = new EditTextWOCopyPaste(getContext());
valInput.setLongClickable(false);
keyInput.setHint("Key");
keyInput.setContentDescription("public_property_key");
valInput.setHint("Value");
valInput.setContentDescription("public_property_value");
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final LinearLayout frameLayout = new LinearLayout(getContext());
frameLayout.setOrientation(LinearLayout.VERTICAL);
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(keyInput);
frameLayout.addView(valInput);
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Property")
.setPositiveButton("OK", (dialogInterface, which) -> GetSocial.getCurrentUser().updateDetails(new UserUpdate().setPublicProperty(keyInput.getText().toString(), valInput.getText().toString()),
new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
dialogInterface.dismiss();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Public property has been changed successfully!",
Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(),
"Error changing public property: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
})).setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel()).create().show();
}
private void incrementPublicProperty() {
final EditTextWOCopyPaste keyInput = new EditTextWOCopyPaste(getContext());
keyInput.setLongClickable(false);
final EditTextWOCopyPaste valInput = new EditTextWOCopyPaste(getContext());
valInput.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
valInput.setLongClickable(false);
keyInput.setHint("Key");
keyInput.setContentDescription("public_property_key");
valInput.setHint("Value");
valInput.setContentDescription("increment");
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final LinearLayout frameLayout = new LinearLayout(getContext());
frameLayout.setOrientation(LinearLayout.VERTICAL);
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(keyInput);
frameLayout.addView(valInput);
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Property")
.setPositiveButton("OK", (dialogInterface, which) -> GetSocial.getCurrentUser().updateDetails(new UserUpdate().incrementPublicProperty(keyInput.getText().toString(), Double.parseDouble(valInput.getText().toString())),
new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
dialogInterface.dismiss();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Public property has been changed successfully!",
Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(),
"Error changing public property: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
})).setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel()).create().show();
}
private void decrementPublicProperty() {
final EditTextWOCopyPaste keyInput = new EditTextWOCopyPaste(getContext());
keyInput.setLongClickable(false);
final EditTextWOCopyPaste valInput = new EditTextWOCopyPaste(getContext());
valInput.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
valInput.setLongClickable(false);
keyInput.setHint("Key");
keyInput.setContentDescription("public_property_key");
valInput.setHint("Value");
valInput.setContentDescription("decrement");
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final LinearLayout frameLayout = new LinearLayout(getContext());
frameLayout.setOrientation(LinearLayout.VERTICAL);
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(keyInput);
frameLayout.addView(valInput);
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Property")
.setPositiveButton("OK", (dialogInterface, which) -> GetSocial.getCurrentUser().updateDetails(new UserUpdate().decrementPublicProperty(keyInput.getText().toString(), Double.parseDouble(valInput.getText().toString())),
new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
dialogInterface.dismiss();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Public property has been changed successfully!",
Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(),
"Error changing public property: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
})).setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel()).create().show();
}
// region Presenter
private void changeUserAvatar() {
GetSocial.getCurrentUser().updateDetails(new UserUpdate().updateAvatarUrl(UserIdentityUtils.getRandomAvatar()), new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Avatar has been changed successfully!", Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(), "Error changing avatar: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
});
}
private void changeDisplayName() {
final EditTextWOCopyPaste displayNameInput = new EditTextWOCopyPaste(getContext());
displayNameInput.setLongClickable(false);
final int _8dp = PixelUtils.dp2px(getContext(), 8);
final FrameLayout frameLayout = new FrameLayout(getContext());
frameLayout.setPadding(_8dp, _8dp, _8dp, _8dp);
frameLayout.addView(displayNameInput);
displayNameInput.setText(UserIdentityUtils.getDisplayName());
displayNameInput.setSelection(displayNameInput.getText().length());
displayNameInput.setContentDescription("display_name_input");
new AlertDialog.Builder(getContext()).setView(frameLayout).setTitle("User Display Name")
.setPositiveButton("OK", (dialogInterface, which) -> GetSocial.getCurrentUser().updateDetails(new UserUpdate().updateDisplayName(displayNameInput.getText().toString()),
new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
dialogInterface.dismiss();
_activityListener.invalidateUi();
Toast.makeText(getContext(), "Display name has been changed successfully!",
Toast.LENGTH_SHORT).show();
}
}, error -> {
Toast.makeText(getContext(),
"Error changing display name: \n" + error.getMessage(),
Toast.LENGTH_SHORT).show();
})).setNegativeButton("Cancel", (dialogInterface, which) -> dialogInterface.cancel())
.create().show();
}
private void removeFacebookUserIdentity() {
removeUserIdentity(IdentityProviderIds.FACEBOOK);
disconnectFromFacebook();
}
private void removeCustomUserIdentity() {
removeUserIdentity(CUSTOM_PROVIDER);
}
private void logOut() {
showLoading("Log Out", "Wait...");
GetSocial.resetUser(() -> {
invalidateUi();
hideLoading();
Toast.makeText(getContext(), "User has been successfully logged out!", Toast.LENGTH_SHORT).show();
}, error -> {
hideLoading();
Toast.makeText(getContext(), "Failed to log out user, error: " + error.getMessage(),
Toast.LENGTH_SHORT).show();
});
}
// endregion
// region helpers
private void removeUserIdentity(final String providerId) {
GetSocial.getCurrentUser().removeIdentity(providerId, new SafeCompletionCallback() {
@Override
public void onSafeSuccess() {
invalidateUi();
_log.logInfoAndToast(String.format("Successfully removed user identity '%s'", providerId));
}
}, error -> {
_log.logErrorAndToast(String.format("Failed to remove user identity '%s', error: %s", providerId,
error.getMessage()));
});
}
@Override
public String getTitle() {
return "User Management";
}
@Override
public String getFragmentTag() {
return "usermanagement";
}
// endregion
}
| Release demo app for GetSocial SDK version 7.4.5
| example/src/main/java/im/getsocial/demo/fragment/UserManagementFragment.java | Release demo app for GetSocial SDK version 7.4.5 |
|
Java | apache-2.0 | ba9c83c41cbb110d0ef79120691aba3bc26ad6c8 | 0 | cuba-platform/cuba,cuba-platform/cuba,dimone-kun/cuba,dimone-kun/cuba,cuba-platform/cuba,dimone-kun/cuba | /*
* Copyright (c) 2008 Haulmont Technology Ltd. All Rights Reserved.
* Haulmont Technology proprietary and confidential.
* Use is subject to license terms.
* Author: Nikolay Gorodnov
* Created: 06.08.2010 15:08:26
*
* $Id$
*/
package com.haulmont.cuba.toolkit.gwt.client.ui;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.*;
import com.vaadin.terminal.gwt.client.ui.VPanel;
public class VGroupBox extends VPanel {
public static final String CLASSNAME = "group-box";
private int contentNodeBorderPaddingsHor = -1;
private int contentNodeBorderPaddingsVer = -1;
protected Element expander;
protected boolean expanded;
protected boolean collapsable;
protected Element descriptionNode;
protected Element fieldset;
protected Element legend;
@Override
protected void constructDOM() {
fieldset = DOM.createFieldSet();
legend = DOM.createLegend();
// captionNode = DOM.createDiv();
expander = DOM.createDiv();
// captionText = DOM.createSpan();
descriptionNode = DOM.createDiv();
// bottomDecoration = DOM.createDiv();
// contentNode = DOM.createDiv();
captionNode.setClassName(CLASSNAME + "-caption");
descriptionNode.setClassName(CLASSNAME + "-description");
contentNode.setClassName(CLASSNAME + "-content");
bottomDecoration.setClassName(CLASSNAME + "-deco");
captionNode.appendChild(expander);
captionNode.appendChild(captionText);
legend.appendChild(captionNode);
fieldset.appendChild(legend);
fieldset.appendChild(descriptionNode);
fieldset.appendChild(contentNode);
fieldset.appendChild(bottomDecoration);
getElement().appendChild(fieldset);
setStyleName(CLASSNAME);
DOM.sinkEvents(getElement(), Event.ONKEYDOWN);
DOM.sinkEvents(contentNode, Event.ONSCROLL);
DOM.sinkEvents(expander, Event.ONCLICK);
contentNode.getStyle().setProperty("position", "relative");
getElement().getStyle().setProperty("overflow", "hidden");
}
@Override
protected void renderContent(UIDL uidl) {
//do nothing
}
@Override
protected void renderDOM(UIDL uidl) {
if (uidl.hasAttribute("caption")
&& !uidl.getStringAttribute("caption").equals("")) {
setCaption(uidl.getStringAttribute("caption"));
} else {
setCaption("");
}
if (uidl.hasAttribute("description")
&& !uidl.getStringAttribute("description").equals("")) {
setDescription(uidl.getStringAttribute("description"));
} else {
setDescription("");
}
}
private void setDescription(String text) {
DOM.setInnerText(descriptionNode, text);
}
@Override
public void updateFromUIDL(UIDL uidl) {
super.updateFromUIDL(uidl);
if (!uidl.hasAttribute("caption") || uidl.getStringAttribute("caption").equals("")) {
addStyleDependentName("nocaption");
} else {
removeStyleDependentName("nocaption");
}
if (!uidl.hasAttribute("description") || uidl.getStringAttribute("description").equals("")) {
addStyleDependentName("nodescription");
} else {
removeStyleDependentName("nodescription");
}
collapsable = uidl.getBooleanAttribute("collapsable");
if (collapsable) {
DOM.setStyleAttribute(expander, "display", "");
removeStyleDependentName("nocollapsable");
} else {
addStyleDependentName("nocollapsable");
DOM.setStyleAttribute(expander, "display", "none");
}
if (uidl.getBooleanAttribute("expanded") != expanded) {
toggleExpand();
}
//render content
final UIDL layoutUidl = uidl.getChildUIDL(0);
if (layoutUidl != null) {
final Paintable newLayout = client.getPaintable(layoutUidl);
if (newLayout != layout) {
if (layout != null) {
client.unregisterPaintable(layout);
}
setWidget((Widget) newLayout);
layout = newLayout;
}
layout.updateFromUIDL(layoutUidl, client);
}
detectContainerBorders();
}
protected void toggleExpand() {
expanded = !expanded;
if (expanded) {
captionNode.addClassName("expanded");
} else {
captionNode.removeClassName("expanded");
}
}
@Override
protected int getCaptionPaddingHorizontal() {
return 0;
}
@Override
protected void detectContainerBorders() {
if (isAttached()) {
String oldWidth = DOM.getStyleAttribute(contentNode, "width");
String oldHeight = DOM.getStyleAttribute(contentNode, "height");
DOM.setStyleAttribute(contentNode, "overflow", "hidden");
DOM.setStyleAttribute(contentNode, "width", "0px");
DOM.setStyleAttribute(contentNode, "height", "0px");
borderPaddingHorizontal = contentNodeBorderPaddingsHor = contentNode.getOffsetWidth();
borderPaddingVertical = contentNodeBorderPaddingsVer = contentNode.getOffsetHeight();
DOM.setStyleAttribute(contentNode, "width", "");
DOM.setStyleAttribute(contentNode, "height", "");
borderPaddingHorizontal += (fieldset.getOffsetWidth() - contentNode.getOffsetWidth());
borderPaddingVertical += (fieldset.getOffsetHeight() - contentNode.getOffsetHeight());
DOM.setStyleAttribute(contentNode, "width", oldWidth);
DOM.setStyleAttribute(contentNode, "height", oldHeight);
DOM.setStyleAttribute(contentNode, "overflow", "auto");
}
}
protected int getContentNodeBorderPaddingsWidth() {
if (isAttached()) {
if (contentNodeBorderPaddingsHor < 0) {
detectContainerBorders();
}
return contentNodeBorderPaddingsHor;
}
return 0;
}
protected int getContentNodeBorderPaddingsHeight() {
if (isAttached()) {
if (contentNodeBorderPaddingsVer < 0) {
detectContainerBorders();
}
return contentNodeBorderPaddingsVer;
}
return 0;
}
@Override
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int h = 0;
if (width != null && !width.equals("")) {
w = contentNode.getOffsetWidth() - getContentNodeBorderPaddingsWidth();
if (w < 0) {
w = 0;
}
}
if (height != null && !height.equals("")) {
h = contentNode.getOffsetHeight() - getContentNodeBorderPaddingsHeight();
if (h < 0) {
h = 0;
}
}
return new RenderSpace(w, h, true);
}
@Override
public void runHacks(boolean runGeckoFix) {
client.runDescendentsLayout(this);
Util.runWebkitOverflowAutoFix(contentNode);
}
@Override
public void onBrowserEvent(Event event) {
if (DOM.eventGetType(event) == Event.ONCLICK && DOM.eventGetTarget(event) == expander) {
toggleExpand();
if (collapsable) {
if (expanded) {
client.updateVariable(id, "expand", true, true);
} else {
client.updateVariable(id, "collapse", true, true);
}
}
DOM.eventCancelBubble(event, true);
} else {
super.onBrowserEvent(event);
}
}
}
| modules/web-toolkit/src/com/haulmont/cuba/toolkit/gwt/client/ui/VGroupBox.java | /*
* Copyright (c) 2008 Haulmont Technology Ltd. All Rights Reserved.
* Haulmont Technology proprietary and confidential.
* Use is subject to license terms.
* Author: Nikolay Gorodnov
* Created: 06.08.2010 15:08:26
*
* $Id$
*/
package com.haulmont.cuba.toolkit.gwt.client.ui;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.FieldSetElement;
import com.google.gwt.dom.client.LegendElement;
import com.google.gwt.event.dom.client.TouchStartEvent;
import com.google.gwt.event.dom.client.TouchStartHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.*;
import com.vaadin.terminal.gwt.client.ui.VPanel;
/**
* VGroupBox
* <br/>
* [Need rewrite]
*/
public class VGroupBox extends VPanel {
public static final String CLASSNAME = "group-box";
private int contentNodeBorderPaddingsHor = -1;
private int contentNodeBorderPaddingsVer = -1;
protected boolean expanded;
protected boolean collapsable;
protected Element descriptionNode;
protected Element expander;
protected FieldSetElement fieldset;
protected DivElement legend;
public VGroupBox() {
}
@Override
protected void constructDOM() {
// DivElement captionWrap = Document.get().createDivElement();
legend = Document.get().createDivElement();
fieldset = Document.get().createFieldSetElement();
expander = DOM.createDiv();
descriptionNode = DOM.createDiv();
captionNode.setClassName(CLASSNAME + "-caption");
descriptionNode.setClassName(CLASSNAME + "-description");
contentNode.setClassName(CLASSNAME + "-content");
bottomDecoration.setClassName(CLASSNAME + "-deco");
captionNode.appendChild(expander);
captionNode.appendChild(captionText);
legend.appendChild(captionNode);
fieldset.appendChild(legend);
fieldset.appendChild(descriptionNode);
fieldset.appendChild(contentNode);
fieldset.appendChild(bottomDecoration);
getElement().appendChild(fieldset);
setStyleName(CLASSNAME);
DOM.sinkEvents(getElement(), Event.ONKEYDOWN);
DOM.sinkEvents(contentNode, Event.ONSCROLL);
DOM.sinkEvents(expander, Event.ONCLICK);
contentNode.getStyle().setProperty("position", "relative");
getElement().getStyle().setProperty("overflow", "hidden");
}
@Override
protected void renderContent(UIDL uidl) {
//do nothing
}
@Override
protected void renderDOM(UIDL uidl) {
if (uidl.hasAttribute("caption")
&& !uidl.getStringAttribute("caption").equals("")) {
setCaption(uidl.getStringAttribute("caption"));
} else {
setCaption("");
}
if (uidl.hasAttribute("description")
&& !uidl.getStringAttribute("description").equals("")) {
setDescription(uidl.getStringAttribute("description"));
} else {
setDescription("");
}
}
private void setDescription(String text) {
DOM.setInnerText(descriptionNode, text);
}
@Override
public void updateFromUIDL(UIDL uidl) {
super.updateFromUIDL((UIDL) uidl);
if (!uidl.hasAttribute("caption") || uidl.getStringAttribute("caption").equals("")) {
addStyleDependentName("nocaption");
} else {
removeStyleDependentName("nocaption");
}
if (!uidl.hasAttribute("description") || uidl.getStringAttribute("description").equals("")) {
addStyleDependentName("nodescription");
} else {
removeStyleDependentName("nodescription");
}
collapsable = uidl.getBooleanAttribute("collapsable");
if (collapsable) {
DOM.setStyleAttribute(expander, "display", "");
removeStyleDependentName("nocollapsable");
} else {
addStyleDependentName("nocollapsable");
DOM.setStyleAttribute(expander, "display", "none");
}
if (uidl.getBooleanAttribute("expanded") != expanded) {
toggleExpand();
}
//render content
final UIDL layoutUidl = uidl.getChildUIDL(0);
if (layoutUidl != null) {
final Paintable newLayout = client.getPaintable(layoutUidl);
if (newLayout != layout) {
if (layout != null) {
client.unregisterPaintable(layout);
}
setWidget((Widget) newLayout);
layout = newLayout;
}
layout.updateFromUIDL(layoutUidl, client);
}
detectContainerBorders();
}
protected void toggleExpand() {
expanded = !expanded;
if (expanded) {
captionNode.addClassName("expanded");
} else {
captionNode.removeClassName("expanded");
}
}
@Override
protected int getCaptionPaddingHorizontal() {
return 0;
}
@Override
protected void detectContainerBorders() {
if (isAttached()) {
String oldWidth = DOM.getStyleAttribute(contentNode, "width");
String oldHeight = DOM.getStyleAttribute(contentNode, "height");
DOM.setStyleAttribute(contentNode, "overflow", "hidden");
DOM.setStyleAttribute(contentNode, "width", "0px");
DOM.setStyleAttribute(contentNode, "height", "0px");
borderPaddingHorizontal = contentNodeBorderPaddingsHor = contentNode.getOffsetWidth();
borderPaddingVertical = contentNodeBorderPaddingsVer = contentNode.getOffsetHeight();
DOM.setStyleAttribute(contentNode, "width", "");
DOM.setStyleAttribute(contentNode, "height", "");
borderPaddingHorizontal += (fieldset.getOffsetWidth() - contentNode.getOffsetWidth());
borderPaddingVertical += (fieldset.getOffsetHeight() - contentNode.getOffsetHeight());
DOM.setStyleAttribute(contentNode, "width", oldWidth);
DOM.setStyleAttribute(contentNode, "height", oldHeight);
DOM.setStyleAttribute(contentNode, "overflow", "auto");
}
}
protected int getContentNodeBorderPaddingsWidth() {
if (isAttached()) {
if (contentNodeBorderPaddingsHor < 0) {
detectContainerBorders();
}
return contentNodeBorderPaddingsHor;
}
return 0;
}
protected int getContentNodeBorderPaddingsHeight() {
if (isAttached()) {
if (contentNodeBorderPaddingsVer < 0) {
detectContainerBorders();
}
return contentNodeBorderPaddingsVer;
}
return 0;
}
@Override
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int h = 0;
if (width != null && !width.equals("")) {
w = contentNode.getOffsetWidth() - getContentNodeBorderPaddingsWidth();
if (w < 0) {
w = 0;
}
}
if (height != null && !height.equals("")) {
h = contentNode.getOffsetHeight() - getContentNodeBorderPaddingsHeight();
if (h < 0) {
h = 0;
}
}
return new RenderSpace(w, h, true);
}
@Override
public void runHacks(boolean runGeckoFix) {
client.runDescendentsLayout(this);
Util.runWebkitOverflowAutoFix(contentNode);
}
@Override
public void onBrowserEvent(Event event) {
if (DOM.eventGetType(event) == Event.ONCLICK && DOM.eventGetTarget(event) == expander) {
toggleExpand();
if (collapsable) {
if (expanded) {
client.updateVariable(id, "expand", true, true);
} else {
client.updateVariable(id, "collapse", true, true);
}
}
DOM.eventCancelBubble(event, true);
} else {
super.onBrowserEvent(event);
}
}
}
| GroupBox fixed
| modules/web-toolkit/src/com/haulmont/cuba/toolkit/gwt/client/ui/VGroupBox.java | GroupBox fixed |
|
Java | apache-2.0 | f5733769b96e3a4847ef86334662f60fc09b54e1 | 0 | allotria/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,semonte/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,signed/intellij-community,da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,signed/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,semonte/intellij-community,signed/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,asedunov/intellij-community,da1z/intellij-community,fitermay/intellij-community,fitermay/intellij-community,da1z/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,da1z/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,youdonghai/intellij-community,allotria/intellij-community,allotria/intellij-community,suncycheng/intellij-community,signed/intellij-community,da1z/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,xfournet/intellij-community,apixandru/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,allotria/intellij-community,FHannes/intellij-community,signed/intellij-community,allotria/intellij-community,ibinti/intellij-community,ibinti/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,hurricup/intellij-community,xfournet/intellij-community,allotria/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,ibinti/intellij-community,da1z/intellij-community,da1z/intellij-community,suncycheng/intellij-community,signed/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,vvv1559/intellij-community,semonte/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,semonte/intellij-community,FHannes/intellij-community,fitermay/intellij-community,da1z/intellij-community,apixandru/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,semonte/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ibinti/intellij-community,signed/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,semonte/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,fitermay/intellij-community,apixandru/intellij-community,asedunov/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,asedunov/intellij-community,fitermay/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,hurricup/intellij-community,xfournet/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,allotria/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,hurricup/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ibinti/intellij-community,fitermay/intellij-community,xfournet/intellij-community,allotria/intellij-community,semonte/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,da1z/intellij-community,FHannes/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,signed/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.statistics;
import com.intellij.internal.statistic.AbstractApplicationUsagesCollector;
import com.intellij.internal.statistic.CollectUsagesException;
import com.intellij.internal.statistic.StatisticsUtilKt;
import com.intellij.internal.statistic.beans.GroupDescriptor;
import com.intellij.internal.statistic.beans.UsageDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsKey;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.vcs.log.VcsLogProvider;
import com.intellij.vcs.log.data.DataPack;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.graph.PermanentGraph;
import com.intellij.vcs.log.impl.VcsProjectLog;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import static java.util.Arrays.asList;
@SuppressWarnings("StringToUpperCaseOrToLowerCaseWithoutLocale")
public class VcsLogRepoSizeCollector extends AbstractApplicationUsagesCollector {
public static final GroupDescriptor ID = GroupDescriptor.create("VCS Log 2");
@NotNull
@Override
public Set<UsageDescriptor> getProjectUsages(@NotNull Project project) throws CollectUsagesException {
VcsProjectLog projectLog = VcsProjectLog.getInstance(project);
VcsLogData logData = projectLog.getDataManager();
if (logData != null) {
DataPack dataPack = logData.getDataPack();
if (dataPack.isFull()) {
PermanentGraph<Integer> permanentGraph = dataPack.getPermanentGraph();
MultiMap<VcsKey, VirtualFile> groupedRoots = groupRootsByVcs(dataPack.getLogProviders());
Set<UsageDescriptor> usages = ContainerUtil.newHashSet();
usages.add(StatisticsUtilKt.getCountingUsage("data.commit.count", permanentGraph.getAllCommits().size(),
asList(0, 1, 100, 1000, 10 * 1000, 100 * 1000, 500 * 1000)));
for (VcsKey vcs : groupedRoots.keySet()) {
usages.add(StatisticsUtilKt.getCountingUsage("data." + vcs.getName().toLowerCase() + ".root.count", groupedRoots.get(vcs).size(),
asList(0, 1, 2, 5, 8, 15, 30, 50, 100, 500, 1000)));
}
return usages;
}
}
return Collections.emptySet();
}
@NotNull
private static MultiMap<VcsKey, VirtualFile> groupRootsByVcs(@NotNull Map<VirtualFile, VcsLogProvider> providers) {
MultiMap<VcsKey, VirtualFile> result = MultiMap.create();
for (Map.Entry<VirtualFile, VcsLogProvider> entry : providers.entrySet()) {
VirtualFile root = entry.getKey();
VcsKey vcs = entry.getValue().getSupportedVcs();
result.putValue(vcs, root);
}
return result;
}
@NotNull
@Override
public GroupDescriptor getGroupId() {
return ID;
}
}
| platform/vcs-log/impl/src/com/intellij/vcs/log/statistics/VcsLogRepoSizeCollector.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.statistics;
import com.intellij.internal.statistic.AbstractApplicationUsagesCollector;
import com.intellij.internal.statistic.CollectUsagesException;
import com.intellij.internal.statistic.StatisticsUtilKt;
import com.intellij.internal.statistic.beans.GroupDescriptor;
import com.intellij.internal.statistic.beans.UsageDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsKey;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.vcs.log.VcsLogProvider;
import com.intellij.vcs.log.data.DataPack;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.graph.PermanentGraph;
import com.intellij.vcs.log.impl.VcsProjectLog;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import static java.util.Arrays.asList;
@SuppressWarnings("StringToUpperCaseOrToLowerCaseWithoutLocale")
public class VcsLogRepoSizeCollector extends AbstractApplicationUsagesCollector {
public static final GroupDescriptor ID = GroupDescriptor.create("VCS Log 2");
@NotNull
@Override
public Set<UsageDescriptor> getProjectUsages(@NotNull Project project) throws CollectUsagesException {
VcsProjectLog projectLog = VcsProjectLog.getInstance(project);
VcsLogData logData = projectLog.getDataManager();
if (logData != null) {
DataPack dataPack = logData.getDataPack();
if (dataPack.isFull()) {
PermanentGraph<Integer> permanentGraph = dataPack.getPermanentGraph();
MultiMap<VcsKey, VirtualFile> groupedRoots = groupRootsByVcs(dataPack.getLogProviders());
Set<UsageDescriptor> usages = ContainerUtil.newHashSet();
usages.add(StatisticsUtilKt.getCountingUsage("data.commit.count", permanentGraph.getAllCommits().size(),
asList(0, 1, 100, 1000, 10 * 1000, 100 * 1000, 500 * 1000)));
for (VcsKey vcs : groupedRoots.keySet()) {
usages.add(StatisticsUtilKt.getCountingUsage("data." + vcs.getName().toLowerCase() + ".root.count", groupedRoots.get(vcs).size(),
asList(0, 1, 2, 5, 8, 15, 30, 50, 100)));
}
return usages;
}
}
return Collections.emptySet();
}
@NotNull
private static MultiMap<VcsKey, VirtualFile> groupRootsByVcs(@NotNull Map<VirtualFile, VcsLogProvider> providers) {
MultiMap<VcsKey, VirtualFile> result = MultiMap.create();
for (Map.Entry<VirtualFile, VcsLogProvider> entry : providers.entrySet()) {
VirtualFile root = entry.getKey();
VcsKey vcs = entry.getValue().getSupportedVcs();
result.putValue(vcs, root);
}
return result;
}
@NotNull
@Override
public GroupDescriptor getGroupId() {
return ID;
}
}
| [vcs-log] enhance roots statistic
| platform/vcs-log/impl/src/com/intellij/vcs/log/statistics/VcsLogRepoSizeCollector.java | [vcs-log] enhance roots statistic |
|
Java | apache-2.0 | 0a689f9add213f50a7a4bbe3eb7abd05334f3c39 | 0 | lavajumper/bitcoinj-scrypt,danielmcclure/bitcoinj,HashEngineering/darkcoinj,tjth/bitcoinj-lotterycoin,yezune/darkcoinj,TrustPlus/trustpluscoinj,HashEngineering/maxcoinj,nikileshsa/bitcoinj,GroestlCoin/groestlcoinj,bitcoin-solutions/bitcoinj-alice,fsb4000/bitcoinj,yezune/darkcoinj,HashEngineering/namecoinj,HashEngineering/darkcoinj,HashEngineering/dimecoinj,DigiByte-Team/digibytej-alice,dexX7/bitcoinj,oscarguindzberg/bitcoinj,stonecoldpat/bitcoinj,HashEngineering/unobtaniumj,HashEngineering/dimecoinj,HashEngineering/unobtaniumj,peterdettman/bitcoinj,stafur/trustpluscoinj,HashEngineering/dashj,jife94/bitcoinj,wpstudio/blazecoinj,bitbandi/spreadcoinj,TheBlueMatt/bitcoinj,MikeHuntington/blackcoinj-new,you21979/bitcoinj,kris-davison/non-working-darkcoinj-fork,Coinomi/bitcoinj,HashEngineering/dashj,yenliangl/bitcoinj,TrustPlus/trustpluscoinj,langerhans/dogecoinj-alice,HashEngineering/myriadcoinj,kurtwalker/bitcoinj,jife94/bitcoinj,HashEngineering/groestlcoinj,MrDunne/bitcoinj,Qw0kka/creditsj,praus/multicoinj,you21979/bitcoinj,bitbandi/spreadcoinj,haxwell/bitcoinj,dldinternet/bitcoinj,tjth/bitcoinj-lotterycoin,jdojff/bitcoinj,HashEngineering/infinitecoinj,greenaddress/bitcoinj,dogecoin/libdohj,HashEngineering/digitalcoinj-mb,ahmedbodi/anycoinj,HashEngineering/frankoj,HashEngineering/digitalcoinj,bitbandi/spreadcoinj,you21979/bitcoinj,HashEngineering/quarkcoinj,tangyves/bitcoinj,HashEngineering/digitalcoinj,yezune/darkcoinj,Enigmachine/btcjwork2,HashEngineering/groestlcoinj,DigiByte-Team/digibytej-alice,Kangmo/bitcoinj,reddcoin-project/reddcoinj-pow,paulminer/bitcoinj,natzei/bitcoinj,stafur/trustpluscoinj,rootstock/bitcoinj,stonecoldpat/bitcoinj,HashEngineering/megacoinj,kmels/bitcoinj,reddcoin-project/reddcoinj-pow,HashEngineering/megacoinj,techsubodh/admin_tracker,hank/litecoinj,langerhans/dogecoinj-new,HashEngineering/anycoinj,peacekeeper/bitcoinj,peterdettman/bitcoinj,framewr/bitcoinj,Kefkius/groestlcoinj,TheBlueMatt/bitcoinj,paulmadore/woodcoinj,jjculber/defcoinj,HashEngineering/dashj,therightwaystudio/fork_bitcoinj,hank/litecoinj-new,FTraian/bitcoinj-uc,lavajumper/bitcoinj-scrypt,cannabiscoindev/cannabiscoinj,habibmasuro/smileycoinj,HashEngineering/maxcoinj,patricklodder/bitcoinj,HashEngineering/unobtaniumj,HashEngineering/namecoinj,HashEngineering/myriadcoinj,ahmedbodi/anycoinj,bitsquare/bitcoinj,UberPay/bitcoinj,AugieMillares/bitcoinj,tangyves/bitcoinj,GroestlCoin/groestlcoinj,patricklodder/libdohj,GroestlCoin/groestlcoinj,patricklodder/bitcoinj,hank/feathercoinj,ligi/bitcoinj,MonetaryUnit/monetaryunitj,reddcoin-project/reddcoinj-pow,Coinomi/bitcoinj,troggy/bitcoinj,cbeams/bitcoinj,cpacia/bitcoinj,techsubodh/admin_tracker,MintcoinCommunity/mintcoinj,bankonme/monetaryunitj,langerhans/bitcoinj-alice-hd,cannabiscoindev/cannabiscoinj,HashEngineering/darkcoinj,mrosseel/bitcoinj-old,blockchain/bitcoinj,stonecoldpat/bitcoinj,oscarguindzberg/bitcoinj,devrandom/bitcoinj,hughneale/bitcoinj,rnicoll/libdohj,DigiByte-Team/digibytej-alice,imsaguy/bitcoinj,marctrem/bitcoinj,HashEngineering/digitalcoinj,Kefkius/groestlcoinj,HashEngineering/maxcoinj,HashEngineering/myriadcoinj,veritaseum/bitcoinj,dcw312/bitcoinj,stafur/trustpluscoinj,PeterNSteinmetz/peternsteinmetz-bitcoinj,jdojff/bitcoinj,haxwell/bitcoinj,Coinomi/bitcoinj,Kefkius/groestlcoinj,natzei/bitcoinj,HashEngineering/quarkcoinj,schildbach/bitcoinj,Crypto-Expert/digitalcoinj,HashEngineering/dimecoinj,bitcoinj/bitcoinj,patricklodder/bitcoinj,fsb4000/bitcoinj,MonetaryUnit/monetaryunitj,VegasCoin/vegascoinj,tjth/bitcoinj-lotterycoin,sserrano44/bitcoinj-watcher-service,HashEngineering/megacoinj,HashEngineering/maxcoinj,cannabiscoindev/cannabiscoinj,keremhd/mintcoinj,kurtwalker/bitcoinj,rnicoll/altcoinj,janko33bd/bitcoinj,HashEngineering/mobilecashj,Kefkius/groestlcoinj,techsubodh/admin_tracker,monapu/monacoinj-multibit,HashEngineering/maxcoinj,bankonme/monetaryunitj,HashEngineering/quarkcoinj,devrandom/bitcoinj,kurtwalker/bitcoinj,VegasCoin/vegascoinj,ohac/sha1coinj,cannabiscoindev/cannabiscoinj,Kefkius/groestlcoinj,FTraian/bitcoinj-uc,HashEngineering/groestlcoinj,habibmasuro/litecoinj,jdojff/bitcoinj,kris-davison/non-working-darkcoinj-fork,szdx/bitcoinj,bitbandi/spreadcoinj,TrustPlus/trustpluscoinj,VegasCoin/vegascoinj,cpacia/bitcoinj,MintcoinCommunity/mintcoinj,MonetaryUnit/monetaryunitj,fsb4000/bitcoinj,jife94/bitcoinj,lavajumper/bitcoinj-scrypt,ahmedbodi/anycoinj,patricklodder/libdohj,RaviAjaibSingh/bitcoinj,funkshelper/bitcoinj,bitbandi/spreadcoinj,yenliangl/bitcoinj,akonring/bitcoinj_generous,HashEngineering/mobilecashj,HashEngineering/frankoj,haxwell/bitcoinj,janko33bd/bitcoinj,kmels/bitcoinj,yezune/darkcoinj,coinspark/sparkbit-bitcoinj,VishalRao/bitcoinj,veritaseum/bitcoinj,imzhuli/bitcoinj,TheBlueMatt/bitcoinj,cpacia/bitcoinj,rnicoll/bitcoinj,pelle/bitcoinj,FTraian/bitcoinj-uc,habibmasuro/smileycoinj,bitcoinj/bitcoinj,novitski/bitcoinj,Rimbit/rimbitj,bankonme/monetaryunitj,dalbelap/bitcoinj,DynamicCoinOrg/dmcJ,designsters/android-fork-bitcoinj,tangyves/bitcoinj,stafur/trustpluscoinj,HashEngineering/frankoj,habibmasuro/smileycoinj,strawpay/bitcoinj,devrandom/bitcoinj,kris-davison/non-working-darkcoinj-fork,HashEngineering/dashj,meeh420/anoncoinj,patricklodder/libdohj,MintcoinCommunity/mintcoinj,HashEngineering/mobilecashj,bitcoin-solutions/bitcoinj-alice,HashEngineering/namecoinj,veritaseum/bitcoinj,schildbach/bitcoinj,bitcoin-solutions/bitcoinj-alice | /**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.BlockStoreException;
import com.google.bitcoin.utils.EventListenerInvoker;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
/**
* A Peer handles the high level communication with a BitCoin node.
*
* <p>After making the connection with connect(), call run() to start the message handling loop.
*/
public class Peer {
private static final Logger log = LoggerFactory.getLogger(Peer.class);
public static final int CONNECT_TIMEOUT_MSEC = 60000;
private NetworkConnection conn;
private final NetworkParameters params;
// Whether the peer loop is supposed to be running or not. Set to false during shutdown so the peer loop
// knows to quit when the socket goes away.
private volatile boolean running;
private final BlockChain blockChain;
// When an API user explicitly requests a block or transaction from a peer, the InventoryItem is put here
// whilst waiting for the response. Synchronized on itself. Is not used for downloads Peer generates itself.
// TODO: Make this work for transactions as well.
private final List<GetDataFuture<Block>> pendingGetBlockFutures;
private PeerAddress address;
private List<PeerEventListener> eventListeners;
// Whether to try and download blocks and transactions from this peer. Set to false by PeerGroup if not the
// primary peer. This is to avoid redundant work and concurrency problems with downloading the same chain
// in parallel.
private boolean downloadData = true;
// The version data to announce to the other side of the connections we make: useful for setting our "user agent"
// equivalent and other things.
private VersionMessage versionMessage;
// A class that tracks recent transactions that have been broadcast across the network, counts how many
// peers announced them and updates the transaction confidence data. It is passed to each Peer.
private MemoryPool memoryPool;
// A time before which we only download block headers, after that point we download block bodies.
private long fastCatchupTimeSecs;
// Whether we are currently downloading headers only or block bodies. Defaults to true, if the fast catchup time
// is set AND our best block is before that date, switch to false until block headers beyond that point have been
// received at which point it gets set to true again. This isn't relevant unless downloadData is true.
private boolean downloadBlockBodies = true;
/**
* Construct a peer that reads/writes from the given block chain. Note that communication won't occur until
* you call connect(), which will set up a new NetworkConnection.
*
* @param bestHeight our current best chain height, to facilitate downloading
*/
public Peer(NetworkParameters params, PeerAddress address, int bestHeight, BlockChain blockChain) {
this(params, address, blockChain, new VersionMessage(params, bestHeight));
}
/**
* Construct a peer that reads/writes from the given block chain. Note that communication won't occur until
* you call connect(), which will set up a new NetworkConnection.
*
* @param ver The version data to announce to the other side.
*/
public Peer(NetworkParameters params, PeerAddress address, BlockChain blockChain, VersionMessage ver) {
this.params = params;
this.address = address;
this.blockChain = blockChain;
this.pendingGetBlockFutures = new ArrayList<GetDataFuture<Block>>();
this.eventListeners = new ArrayList<PeerEventListener>();
this.fastCatchupTimeSecs = params.genesisBlock.getTimeSeconds();
this.versionMessage = ver;
}
/**
* Construct a peer that reads/writes from the given block chain. Note that communication won't occur until
* you call connect(), which will set up a new NetworkConnection.
*/
public Peer(NetworkParameters params, PeerAddress address, BlockChain blockChain) {
this(params, address, 0, blockChain);
}
/**
* Construct a peer that uses the given, already connected network connection object.
*/
public Peer(NetworkParameters params, BlockChain blockChain, NetworkConnection connection) {
this(params, null, 0, blockChain);
this.conn = connection;
this.address = connection.getPeerAddress();
}
public synchronized void addEventListener(PeerEventListener listener) {
eventListeners.add(listener);
}
public synchronized boolean removeEventListener(PeerEventListener listener) {
return eventListeners.remove(listener);
}
/**
* Tells the peer to insert received transactions/transaction announcements into the given {@link MemoryPool}.
* This is normally done for you by the {@link PeerGroup} so you don't have to think about it. Transactions stored
* in a memory pool will have their confidence levels updated when a peer announces it, to reflect the greater
* likelyhood that the transaction is valid.
*
* @param pool A new pool or null to unlink.
*/
public synchronized void setMemoryPool(MemoryPool pool) {
memoryPool = pool;
}
@Override
public String toString() {
if (address == null) {
// User-provided NetworkConnection object.
return "Peer(NetworkConnection:" + conn + ")";
} else {
return "Peer(" + address.getAddr() + ":" + address.getPort() + ")";
}
}
/**
* Connects to the peer.
*
* @throws PeerException when there is a temporary problem with the peer and we should retry later
*/
public synchronized void connect() throws PeerException {
try {
conn = new TCPNetworkConnection(params, versionMessage);
conn.connect(address, CONNECT_TIMEOUT_MSEC);
} catch (IOException ex) {
throw new PeerException(ex);
} catch (ProtocolException ex) {
throw new PeerException(ex);
}
}
// For testing
void setConnection(NetworkConnection conn) {
this.conn = conn;
}
/**
* Runs in the peers network loop and manages communication with the peer.
*
* <p>connect() must be called first
*
* @throws PeerException when there is a temporary problem with the peer and we should retry later
*/
public void run() throws PeerException {
// This should be called in the network loop thread for this peer
if (conn == null)
throw new RuntimeException("please call connect() first");
running = true;
try {
while (running) {
Message m = conn.readMessage();
// Allow event listeners to filter the message stream. Listeners are allowed to drop messages by
// returning null.
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
m = listener.onPreMessageReceived(this, m);
if (m == null) break;
}
}
if (m == null) continue;
if (m instanceof InventoryMessage) {
processInv((InventoryMessage) m);
} else if (m instanceof Block) {
processBlock((Block) m);
} else if (m instanceof Transaction) {
processTransaction((Transaction) m);
} else if (m instanceof GetDataMessage) {
processGetData((GetDataMessage) m);
} else if (m instanceof AddressMessage) {
// We don't care about addresses of the network right now. But in future,
// we should save them in the wallet so we don't put too much load on the seed nodes and can
// properly explore the network.
} else if (m instanceof HeadersMessage) {
processHeaders((HeadersMessage) m);
} else if (m instanceof AlertMessage) {
processAlert((AlertMessage)m);
} else {
// TODO: Handle the other messages we can receive.
log.warn("Received unhandled message: {}", m);
}
}
} catch (IOException e) {
if (!running) {
// This exception was expected because we are tearing down the socket as part of quitting.
log.info("{}: Shutting down peer loop", address);
} else {
disconnect();
throw new PeerException(e);
}
} catch (ProtocolException e) {
disconnect();
throw new PeerException(e);
} catch (RuntimeException e) {
log.error("Unexpected exception in peer loop", e);
disconnect();
throw e;
}
disconnect();
}
private void processAlert(AlertMessage m) {
try {
if (m.isSignatureValid()) {
log.info("Received alert from peer {}: {}", toString(), m.getStatusBar());
} else {
log.warn("Received alert with invalid signature from peer {}: {}", toString(), m.getStatusBar());
}
} catch (Throwable t) {
// Signature checking can FAIL on Android platforms before Gingerbread apparently due to bugs in their
// BigInteger implementations! See issue 160 for discussion. As alerts are just optional and not that
// useful, we just swallow the error here.
log.error("Failed to check signature: bug in platform libraries?", t);
}
}
private void processHeaders(HeadersMessage m) throws IOException, ProtocolException {
// Runs in network loop thread for this peer.
//
// This method can run if a peer just randomly sends us a "headers" message (should never happen), or more
// likely when we've requested them as part of chain download using fast catchup. We need to add each block to
// the chain if it pre-dates the fast catchup time. If we go past it, we can stop processing the headers and
// request the full blocks from that point on instead.
Preconditions.checkState(!downloadBlockBodies, toString());
try {
for (int i = 0; i < m.getBlockHeaders().size(); i++) {
Block header = m.getBlockHeaders().get(i);
if (header.getTimeSeconds() < fastCatchupTimeSecs) {
if (blockChain.add(header)) {
// The block was successfully linked into the chain. Notify the user of our progress.
invokeOnBlocksDownloaded(header);
} else {
// This block is unconnected - we don't know how to get from it back to the genesis block yet.
// That must mean that the peer is buggy or malicious because we specifically requested for
// headers that are part of the best chain.
throw new ProtocolException("Got unconnected header from peer: " + header.getHashAsString());
}
} else {
log.info("Passed the fast catchup time, discarding {} headers and requesting full blocks",
m.getBlockHeaders().size() - i);
downloadBlockBodies = true;
blockChainDownload(header.getHash());
return;
}
}
// We added all headers in the message to the chain. Request some more if we got up to the limit, otherwise
// we are at the end of the chain.
if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS)
blockChainDownload(Sha256Hash.ZERO_HASH);
} catch (VerificationException e) {
log.warn("Block header verification failed", e);
} catch (ScriptException e) {
// There are no transactions and thus no scripts in these blocks, so this should never happen.
throw new RuntimeException(e);
}
}
private void processGetData(GetDataMessage getdata) throws IOException {
log.info("Received getdata message: {}", getdata.toString());
ArrayList<Message> items = new ArrayList<Message>();
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
List<Message> listenerItems = listener.getData(this, getdata);
if (listenerItems == null) continue;
items.addAll(listenerItems);
}
}
if (items.size() == 0) {
return;
}
log.info("Sending {} items gathered from listeners to peer", items.size());
for (Message item : items) {
sendMessage(item);
}
}
private void processTransaction(Transaction m) {
log.info("Received broadcast tx {}", m.getHashAsString());
if (memoryPool != null)
memoryPool.seen(m, getAddress());
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
listener.onTransaction(this, m);
}
}
}
private void processBlock(Block m) throws IOException {
log.debug("Received broadcast block {}", m.getHashAsString());
try {
// Was this block requested by getBlock()?
synchronized (pendingGetBlockFutures) {
for (int i = 0; i < pendingGetBlockFutures.size(); i++) {
GetDataFuture<Block> f = pendingGetBlockFutures.get(i);
if (f.getItem().hash.equals(m.getHash())) {
// Yes, it was. So pass it through the future.
f.setResult(m);
// Blocks explicitly requested don't get sent to the block chain.
pendingGetBlockFutures.remove(i);
return;
}
}
}
if (!downloadData) {
log.warn("Received block we did not ask for: {}", m.getHashAsString());
return;
}
// Otherwise it's a block sent to us because the peer thought we needed it, so add it to the block chain.
// This call will synchronize on blockChain.
if (blockChain.add(m)) {
// The block was successfully linked into the chain. Notify the user of our progress.
invokeOnBlocksDownloaded(m);
} else {
// This block is unconnected - we don't know how to get from it back to the genesis block yet. That
// must mean that there are blocks we are missing, so do another getblocks with a new block locator
// to ask the peer to send them to us. This can happen during the initial block chain download where
// the peer will only send us 500 at a time and then sends us the head block expecting us to request
// the others.
// TODO: Should actually request root of orphan chain here.
blockChainDownload(m.getHash());
}
} catch (VerificationException e) {
// We don't want verification failures to kill the thread.
log.warn("Block verification failed", e);
} catch (ScriptException e) {
// We don't want script failures to kill the thread.
log.warn("Script exception", e);
}
}
private void invokeOnBlocksDownloaded(final Block m) {
// It is possible for the peer block height difference to be negative when blocks have been solved and broadcast
// since the time we first connected to the peer. However, it's weird and unexpected to receive a callback
// with negative "blocks left" in this case, so we clamp to zero so the API user doesn't have to think about it.
final int blocksLeft = Math.max(0, getPeerBlockHeightDifference());
EventListenerInvoker.invoke(eventListeners, new EventListenerInvoker<PeerEventListener>() {
@Override
public void invoke(PeerEventListener listener) {
listener.onBlocksDownloaded(Peer.this, m, blocksLeft);
}
});
}
private void processInv(InventoryMessage inv) throws IOException {
// This should be called in the network loop thread for this peer.
List<InventoryItem> items = inv.getItems();
// Separate out the blocks and transactions, we'll handle them differently
List<InventoryItem> transactions = new LinkedList<InventoryItem>();
List<InventoryItem> blocks = new LinkedList<InventoryItem>();
for (InventoryItem item : items) {
switch (item.type) {
case Transaction: transactions.add(item); break;
case Block: blocks.add(item); break;
}
}
GetDataMessage getdata = new GetDataMessage(params);
Iterator<InventoryItem> it = transactions.iterator();
while (it.hasNext()) {
InventoryItem item = it.next();
if (memoryPool == null && downloadData) {
// If there's no memory pool only download transactions if we're configured to.
getdata.addItem(item);
} else {
// Only download the transaction if we are the first peer that saw it be advertised. Other peers will also
// see it be advertised in inv packets asynchronously, they co-ordinate via the memory pool. We could
// potentially download transactions faster by always asking every peer for a tx when advertised, as remote
// peers run at different speeds. However to conserve bandwidth on mobile devices we try to only download a
// transaction once. This means we can miss broadcasts if the peer disconnects between sending us an inv and
// sending us the transaction: currently we'll never try to re-fetch after a timeout.
if (memoryPool.maybeWasSeen(item.hash)) {
// Some other peer already announced this so don't download.
it.remove();
} else {
getdata.addItem(item);
}
memoryPool.seen(item.hash, this.getAddress());
}
}
if (blocks.size() > 0 && downloadData) {
Block topBlock = blockChain.getUnconnectedBlock();
Sha256Hash topHash = (topBlock != null ? topBlock.getHash() : null);
if (isNewBlockTickle(topHash, blocks)) {
// An inv with a single hash containing our most recent unconnected block is a special inv,
// it's kind of like a tickle from the peer telling us that it's time to download more blocks to catch up to
// the block chain. We could just ignore this and treat it as a regular inv but then we'd download the head
// block over and over again after each batch of 500 blocks, which is wasteful.
blockChainDownload(topHash);
return;
}
// Request the advertised blocks only if we're the download peer.
for (InventoryItem item : blocks) getdata.addItem(item);
}
if (!getdata.getItems().isEmpty()) {
// This will cause us to receive a bunch of block or tx messages.
conn.writeMessage(getdata);
}
}
/** A new block tickle is an inv with a hash containing the topmost block. */
private boolean isNewBlockTickle(Sha256Hash topHash, List<InventoryItem> items) {
return items.size() == 1 &&
items.get(0).type == InventoryItem.Type.Block &&
topHash != null &&
items.get(0).hash.equals(topHash);
}
/**
* Asks the connected peer for the block of the given hash, and returns a Future representing the answer.
* If you want the block right away and don't mind waiting for it, just call .get() on the result. Your thread
* will block until the peer answers. You can also use the Future object to wait with a timeout, or just check
* whether it's done later.
*
* @param blockHash Hash of the block you wareare requesting.
* @throws IOException
*/
public Future<Block> getBlock(Sha256Hash blockHash) throws IOException {
GetDataMessage getdata = new GetDataMessage(params);
InventoryItem inventoryItem = new InventoryItem(InventoryItem.Type.Block, blockHash);
getdata.addItem(inventoryItem);
GetDataFuture<Block> future = new GetDataFuture<Block>(inventoryItem);
// Add to the list of things we're waiting for. It's important this come before the network send to avoid
// race conditions.
synchronized (pendingGetBlockFutures) {
pendingGetBlockFutures.add(future);
}
conn.writeMessage(getdata);
return future;
}
/**
* When downloading the block chain, the bodies will be skipped for blocks created before the given date. Any
* transactions relevant to the wallet will therefore not be found, but if you know your wallet has no such
* transactions it doesn't matter and can save a lot of bandwidth and processing time. Note that the times of blocks
* isn't known until their headers are available and they are requested in chunks, so some headers may be downloaded
* twice using this scheme, but this optimization can still be a large win for newly created wallets.
*
* @param secondsSinceEpoch Time in seconds since the epoch or 0 to reset to always downloading block bodies.
*/
public void setFastCatchupTime(long secondsSinceEpoch) {
if (secondsSinceEpoch == 0) {
fastCatchupTimeSecs = params.genesisBlock.getTimeSeconds();
downloadBlockBodies = true;
} else {
fastCatchupTimeSecs = secondsSinceEpoch;
// If the given time is before the current chains head block time, then this has no effect (we already
// downloaded everything we need).
if (fastCatchupTimeSecs > blockChain.getChainHead().getHeader().getTimeSeconds()) {
downloadBlockBodies = false;
}
}
}
/**
* Links the given wallet to this peer. If you have multiple peers, you should use a {@link PeerGroup} to manage
* them and use the {@link PeerGroup#addWallet(Wallet)} method instead of registering the wallet with each peer
* independently, otherwise the wallet will receive duplicate notifications.
*/
public void addWallet(Wallet wallet) {
addEventListener(wallet.getPeerEventListener());
}
/** Unlinks the given wallet from peer. See {@link Peer#addWallet(Wallet)}. */
public void removeWallet(Wallet wallet) {
removeEventListener(wallet.getPeerEventListener());
}
// A GetDataFuture wraps the result of a getBlock or (in future) getTransaction so the owner of the object can
// decide whether to wait forever, wait for a short while or check later after doing other work.
private static class GetDataFuture<T extends Message> implements Future<T> {
private boolean cancelled;
private final InventoryItem item;
private final CountDownLatch latch;
private T result;
GetDataFuture(InventoryItem item) {
this.item = item;
this.latch = new CountDownLatch(1);
}
public boolean cancel(boolean b) {
// Cannot cancel a getdata - once sent, it's sent.
cancelled = true;
return false;
}
public boolean isCancelled() {
return cancelled;
}
public boolean isDone() {
return result != null || cancelled;
}
public T get() throws InterruptedException, ExecutionException {
latch.await();
return Preconditions.checkNotNull(result);
}
public T get(long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
if (!latch.await(l, timeUnit))
throw new TimeoutException();
return Preconditions.checkNotNull(result);
}
InventoryItem getItem() {
return item;
}
/** Called by the Peer when the result has arrived. Completes the task. */
void setResult(T result) {
// This should be called in the network loop thread for this peer
this.result = result;
// Now release the thread that is waiting. We don't need to synchronize here as the latch establishes
// a memory barrier.
latch.countDown();
}
}
/**
* Sends the given message on the peers network connection. Just uses {@link NetworkConnection#writeMessage(Message)}.
*/
public void sendMessage(Message m) throws IOException {
conn.writeMessage(m);
}
private void blockChainDownload(Sha256Hash toHash) throws IOException {
// This may run in ANY thread.
// The block chain download process is a bit complicated. Basically, we start with one or more blocks in a
// chain that we have from a previous session. We want to catch up to the head of the chain BUT we don't know
// where that chain is up to or even if the top block we have is even still in the chain - we
// might have got ourselves onto a fork that was later resolved by the network.
//
// To solve this, we send the peer a block locator which is just a list of block hashes. It contains the
// blocks we know about, but not all of them, just enough of them so the peer can figure out if we did end up
// on a fork and if so, what the earliest still valid block we know about is likely to be.
//
// Once it has decided which blocks we need, it will send us an inv with up to 500 block messages. We may
// have some of them already if we already have a block chain and just need to catch up. Once we request the
// last block, if there are still more to come it sends us an "inv" containing only the hash of the head
// block.
//
// That causes us to download the head block but then we find (in processBlock) that we can't connect
// it to the chain yet because we don't have the intermediate blocks. So we rerun this function building a
// new block locator describing where we're up to.
//
// The getblocks with the new locator gets us another inv with another bunch of blocks. We download them once
// again. This time when the peer sends us an inv with the head block, we already have it so we won't download
// it again - but we recognize this case as special and call back into blockChainDownload to continue the
// process.
//
// So this is a complicated process but it has the advantage that we can download a chain of enormous length
// in a relatively stateless manner and with constant memory usage.
//
// All this is made more complicated by the desire to skip downloading the bodies of blocks that pre-date the
// 'fast catchup time', which is usually set to the creation date of the earliest key in the wallet. Because
// we know there are no transactions using our keys before that date, we need only the headers. To do that we
// use the "getheaders" command. Once we find we've gone past the target date, we throw away the downloaded
// headers and then request the blocks from that point onwards. "getheaders" does not send us an inv, it just
// sends us the data we requested in a "headers" message.
// TODO: Block locators should be abstracted out rather than special cased here.
List<Sha256Hash> blockLocator = new ArrayList<Sha256Hash>(51);
// For now we don't do the exponential thinning as suggested here:
//
// https://en.bitcoin.it/wiki/Protocol_specification#getblocks
//
// This is because it requires scanning all the block chain headers, which is very slow. Instead we add the top
// 50 block headers. If there is a re-org deeper than that, we'll end up downloading the entire chain. We
// must always put the genesis block as the first entry.
BlockStore store = blockChain.getBlockStore();
StoredBlock cursor = blockChain.getChainHead();
log.info("blockChainDownload({}) current head = ", toHash.toString(), cursor);
for (int i = 50; cursor != null && i > 0; i--) {
blockLocator.add(cursor.getHeader().getHash());
try {
cursor = cursor.getPrev(store);
} catch (BlockStoreException e) {
log.error("Failed to walk the block chain whilst constructing a locator");
throw new RuntimeException(e);
}
}
// Only add the locator if we didn't already do so. If the chain is < 50 blocks we already reached it.
if (cursor != null) {
blockLocator.add(params.genesisBlock.getHash());
}
// The toHash field is set to zero already by the constructor. This is how we indicate "never stop".
if (downloadBlockBodies) {
GetBlocksMessage message = new GetBlocksMessage(params, blockLocator, toHash);
conn.writeMessage(message);
} else {
// Downloading headers for a while instead of full blocks.
GetHeadersMessage message = new GetHeadersMessage(params, blockLocator, toHash);
conn.writeMessage(message);
}
}
/**
* Starts an asynchronous download of the block chain. The chain download is deemed to be complete once we've
* downloaded the same number of blocks that the peer advertised having in its version handshake message.
*/
public void startBlockChainDownload() throws IOException {
setDownloadData(true);
// TODO: peer might still have blocks that we don't have, and even have a heavier
// chain even if the chain block count is lower.
if (getPeerBlockHeightDifference() >= 0) {
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
listener.onChainDownloadStarted(this, getPeerBlockHeightDifference());
}
}
// When we just want as many blocks as possible, we can set the target hash to zero.
blockChainDownload(Sha256Hash.ZERO_HASH);
}
}
/**
* Returns the difference between our best chain height and the peers, which can either be positive if we are
* behind the peer, or negative if the peer is ahead of us.
*/
public int getPeerBlockHeightDifference() {
// Chain will overflow signed int blocks in ~41,000 years.
int chainHeight = (int) conn.getVersionMessage().bestHeight;
// chainHeight should not be zero/negative because we shouldn't have given the user a Peer that is to another
// client-mode node, nor should it be unconnected. If that happens it means the user overrode us somewhere or
// there is a bug in the peer management code.
Preconditions.checkState(chainHeight > 0, "Connected to peer with zero/negative chain height", chainHeight);
return chainHeight - blockChain.getChainHead().getHeight();
}
/**
* Terminates the network connection and stops the message handling loop.
*
* <p>This does not wait for the loop to terminate.
*/
public synchronized void disconnect() {
log.debug("Disconnecting peer");
running = false;
try {
// This is the correct way to stop an IO bound loop
if (conn != null)
conn.shutdown();
} catch (IOException e) {
// Don't care about this.
}
}
/**
* Returns true if this peer will try and download things it is sent in "inv" messages. Normally you only need
* one peer to be downloading data. Defaults to true.
*/
public boolean getDownloadData() {
return downloadData;
}
/**
* If set to false, the peer won't try and fetch blocks and transactions it hears about. Normally, only one
* peer should download missing blocks. Defaults to true.
*/
public void setDownloadData(boolean downloadData) {
this.downloadData = downloadData;
}
/**
* @return the IP address and port of peer.
*/
public PeerAddress getAddress() {
return address;
}
/**
* @return various version numbers claimed by peer.
*/
public VersionMessage getVersionMessage() {
return conn.getVersionMessage();
}
/**
* @return the height of the best chain as claimed by peer.
*/
public long getBestHeight() {
return conn.getVersionMessage().bestHeight;
}
/**
* @return whether the peer is currently connected and the message loop is running.
*/
public boolean isConnected() {
return running;
}
}
| core/src/main/java/com/google/bitcoin/core/Peer.java | /**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.BlockStoreException;
import com.google.bitcoin.utils.EventListenerInvoker;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
/**
* A Peer handles the high level communication with a BitCoin node.
*
* <p>After making the connection with connect(), call run() to start the message handling loop.
*/
public class Peer {
private static final Logger log = LoggerFactory.getLogger(Peer.class);
public static final int CONNECT_TIMEOUT_MSEC = 60000;
private NetworkConnection conn;
private final NetworkParameters params;
// Whether the peer loop is supposed to be running or not. Set to false during shutdown so the peer loop
// knows to quit when the socket goes away.
private volatile boolean running;
private final BlockChain blockChain;
// When an API user explicitly requests a block or transaction from a peer, the InventoryItem is put here
// whilst waiting for the response. Synchronized on itself. Is not used for downloads Peer generates itself.
// TODO: Make this work for transactions as well.
private final List<GetDataFuture<Block>> pendingGetBlockFutures;
private PeerAddress address;
private List<PeerEventListener> eventListeners;
// Whether to try and download blocks and transactions from this peer. Set to false by PeerGroup if not the
// primary peer. This is to avoid redundant work and concurrency problems with downloading the same chain
// in parallel.
private boolean downloadData = true;
// The version data to announce to the other side of the connections we make: useful for setting our "user agent"
// equivalent and other things.
private VersionMessage versionMessage;
// A class that tracks recent transactions that have been broadcast across the network, counts how many
// peers announced them and updates the transaction confidence data. It is passed to each Peer.
private MemoryPool memoryPool;
// A time before which we only download block headers, after that point we download block bodies.
private long fastCatchupTimeSecs;
// Whether we are currently downloading headers only or block bodies. Defaults to true, if the fast catchup time
// is set AND our best block is before that date, switch to false until block headers beyond that point have been
// received at which point it gets set to true again. This isn't relevant unless downloadData is true.
private boolean downloadBlockBodies = true;
/**
* Construct a peer that reads/writes from the given block chain. Note that communication won't occur until
* you call connect(), which will set up a new NetworkConnection.
*
* @param bestHeight our current best chain height, to facilitate downloading
*/
public Peer(NetworkParameters params, PeerAddress address, int bestHeight, BlockChain blockChain) {
this(params, address, blockChain, new VersionMessage(params, bestHeight));
}
/**
* Construct a peer that reads/writes from the given block chain. Note that communication won't occur until
* you call connect(), which will set up a new NetworkConnection.
*
* @param ver The version data to announce to the other side.
*/
public Peer(NetworkParameters params, PeerAddress address, BlockChain blockChain, VersionMessage ver) {
this.params = params;
this.address = address;
this.blockChain = blockChain;
this.pendingGetBlockFutures = new ArrayList<GetDataFuture<Block>>();
this.eventListeners = new ArrayList<PeerEventListener>();
this.fastCatchupTimeSecs = params.genesisBlock.getTimeSeconds();
this.versionMessage = ver;
}
/**
* Construct a peer that reads/writes from the given block chain. Note that communication won't occur until
* you call connect(), which will set up a new NetworkConnection.
*/
public Peer(NetworkParameters params, PeerAddress address, BlockChain blockChain) {
this(params, address, 0, blockChain);
}
/**
* Construct a peer that uses the given, already connected network connection object.
*/
public Peer(NetworkParameters params, BlockChain blockChain, NetworkConnection connection) {
this(params, null, 0, blockChain);
this.conn = connection;
this.address = connection.getPeerAddress();
}
public synchronized void addEventListener(PeerEventListener listener) {
eventListeners.add(listener);
}
public synchronized boolean removeEventListener(PeerEventListener listener) {
return eventListeners.remove(listener);
}
/**
* Tells the peer to insert received transactions/transaction announcements into the given {@link MemoryPool}.
* This is normally done for you by the {@link PeerGroup} so you don't have to think about it. Transactions stored
* in a memory pool will have their confidence levels updated when a peer announces it, to reflect the greater
* likelyhood that the transaction is valid.
*
* @param pool A new pool or null to unlink.
*/
public synchronized void setMemoryPool(MemoryPool pool) {
memoryPool = pool;
}
@Override
public String toString() {
if (address == null) {
// User-provided NetworkConnection object.
return "Peer(NetworkConnection:" + conn + ")";
} else {
return "Peer(" + address.getAddr() + ":" + address.getPort() + ")";
}
}
/**
* Connects to the peer.
*
* @throws PeerException when there is a temporary problem with the peer and we should retry later
*/
public synchronized void connect() throws PeerException {
try {
conn = new TCPNetworkConnection(params, versionMessage);
conn.connect(address, CONNECT_TIMEOUT_MSEC);
} catch (IOException ex) {
throw new PeerException(ex);
} catch (ProtocolException ex) {
throw new PeerException(ex);
}
}
// For testing
void setConnection(NetworkConnection conn) {
this.conn = conn;
}
/**
* Runs in the peers network loop and manages communication with the peer.
*
* <p>connect() must be called first
*
* @throws PeerException when there is a temporary problem with the peer and we should retry later
*/
public void run() throws PeerException {
// This should be called in the network loop thread for this peer
if (conn == null)
throw new RuntimeException("please call connect() first");
running = true;
try {
while (running) {
Message m = conn.readMessage();
// Allow event listeners to filter the message stream. Listeners are allowed to drop messages by
// returning null.
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
m = listener.onPreMessageReceived(this, m);
if (m == null) break;
}
}
if (m == null) continue;
if (m instanceof InventoryMessage) {
processInv((InventoryMessage) m);
} else if (m instanceof Block) {
processBlock((Block) m);
} else if (m instanceof Transaction) {
processTransaction((Transaction) m);
} else if (m instanceof GetDataMessage) {
processGetData((GetDataMessage) m);
} else if (m instanceof AddressMessage) {
// We don't care about addresses of the network right now. But in future,
// we should save them in the wallet so we don't put too much load on the seed nodes and can
// properly explore the network.
} else if (m instanceof HeadersMessage) {
processHeaders((HeadersMessage) m);
} else if (m instanceof AlertMessage) {
processAlert((AlertMessage)m);
} else {
// TODO: Handle the other messages we can receive.
log.warn("Received unhandled message: {}", m);
}
}
} catch (IOException e) {
if (!running) {
// This exception was expected because we are tearing down the socket as part of quitting.
log.info("{}: Shutting down peer loop", address);
} else {
disconnect();
throw new PeerException(e);
}
} catch (ProtocolException e) {
disconnect();
throw new PeerException(e);
} catch (RuntimeException e) {
log.error("Unexpected exception in peer loop", e);
disconnect();
throw e;
}
disconnect();
}
private void processAlert(AlertMessage m) {
try {
if (m.isSignatureValid()) {
log.info("Received alert from peer {}: {}", toString(), m.getStatusBar());
} else {
log.warn("Received alert with invalid signature from peer {}: {}", toString(), m.getStatusBar());
}
} catch (Throwable t) {
// Signature checking can FAIL on Android platforms before Gingerbread apparently due to bugs in their
// BigInteger implementations! See issue 160 for discussion. As alerts are just optional and not that
// useful, we just swallow the error here.
log.error("Failed to check signature: bug in platform libraries?", t);
}
}
private void processHeaders(HeadersMessage m) throws IOException, ProtocolException {
// Runs in network loop thread for this peer.
//
// This method can run if a peer just randomly sends us a "headers" message (should never happen), or more
// likely when we've requested them as part of chain download using fast catchup. We need to add each block to
// the chain if it pre-dates the fast catchup time. If we go past it, we can stop processing the headers and
// request the full blocks from that point on instead.
Preconditions.checkState(!downloadBlockBodies);
try {
for (int i = 0; i < m.getBlockHeaders().size(); i++) {
Block header = m.getBlockHeaders().get(i);
if (header.getTimeSeconds() < fastCatchupTimeSecs) {
if (blockChain.add(header)) {
// The block was successfully linked into the chain. Notify the user of our progress.
invokeOnBlocksDownloaded(header);
} else {
// This block is unconnected - we don't know how to get from it back to the genesis block yet.
// That must mean that the peer is buggy or malicious because we specifically requested for
// headers that are part of the best chain.
throw new ProtocolException("Got unconnected header from peer: " + header.getHashAsString());
}
} else {
log.info("Passed the fast catchup time, discarding {} headers and requesting full blocks",
m.getBlockHeaders().size() - i);
downloadBlockBodies = true;
blockChainDownload(header.getHash());
return;
}
}
// We added all headers in the message to the chain. Request some more if we got up to the limit, otherwise
// we are at the end of the chain.
if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS)
blockChainDownload(Sha256Hash.ZERO_HASH);
} catch (VerificationException e) {
log.warn("Block header verification failed", e);
} catch (ScriptException e) {
// There are no transactions and thus no scripts in these blocks, so this should never happen.
throw new RuntimeException(e);
}
}
private void processGetData(GetDataMessage getdata) throws IOException {
log.info("Received getdata message: {}", getdata.toString());
ArrayList<Message> items = new ArrayList<Message>();
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
List<Message> listenerItems = listener.getData(this, getdata);
if (listenerItems == null) continue;
items.addAll(listenerItems);
}
}
if (items.size() == 0) {
return;
}
log.info("Sending {} items gathered from listeners to peer", items.size());
for (Message item : items) {
sendMessage(item);
}
}
private void processTransaction(Transaction m) {
log.info("Received broadcast tx {}", m.getHashAsString());
if (memoryPool != null)
memoryPool.seen(m, getAddress());
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
listener.onTransaction(this, m);
}
}
}
private void processBlock(Block m) throws IOException {
log.debug("Received broadcast block {}", m.getHashAsString());
try {
// Was this block requested by getBlock()?
synchronized (pendingGetBlockFutures) {
for (int i = 0; i < pendingGetBlockFutures.size(); i++) {
GetDataFuture<Block> f = pendingGetBlockFutures.get(i);
if (f.getItem().hash.equals(m.getHash())) {
// Yes, it was. So pass it through the future.
f.setResult(m);
// Blocks explicitly requested don't get sent to the block chain.
pendingGetBlockFutures.remove(i);
return;
}
}
}
if (!downloadData) {
log.warn("Received block we did not ask for: {}", m.getHashAsString());
return;
}
// Otherwise it's a block sent to us because the peer thought we needed it, so add it to the block chain.
// This call will synchronize on blockChain.
if (blockChain.add(m)) {
// The block was successfully linked into the chain. Notify the user of our progress.
invokeOnBlocksDownloaded(m);
} else {
// This block is unconnected - we don't know how to get from it back to the genesis block yet. That
// must mean that there are blocks we are missing, so do another getblocks with a new block locator
// to ask the peer to send them to us. This can happen during the initial block chain download where
// the peer will only send us 500 at a time and then sends us the head block expecting us to request
// the others.
// TODO: Should actually request root of orphan chain here.
blockChainDownload(m.getHash());
}
} catch (VerificationException e) {
// We don't want verification failures to kill the thread.
log.warn("Block verification failed", e);
} catch (ScriptException e) {
// We don't want script failures to kill the thread.
log.warn("Script exception", e);
}
}
private void invokeOnBlocksDownloaded(final Block m) {
// It is possible for the peer block height difference to be negative when blocks have been solved and broadcast
// since the time we first connected to the peer. However, it's weird and unexpected to receive a callback
// with negative "blocks left" in this case, so we clamp to zero so the API user doesn't have to think about it.
final int blocksLeft = Math.max(0, getPeerBlockHeightDifference());
EventListenerInvoker.invoke(eventListeners, new EventListenerInvoker<PeerEventListener>() {
@Override
public void invoke(PeerEventListener listener) {
listener.onBlocksDownloaded(Peer.this, m, blocksLeft);
}
});
}
private void processInv(InventoryMessage inv) throws IOException {
// This should be called in the network loop thread for this peer.
List<InventoryItem> items = inv.getItems();
// Separate out the blocks and transactions, we'll handle them differently
List<InventoryItem> transactions = new LinkedList<InventoryItem>();
List<InventoryItem> blocks = new LinkedList<InventoryItem>();
for (InventoryItem item : items) {
switch (item.type) {
case Transaction: transactions.add(item); break;
case Block: blocks.add(item); break;
}
}
GetDataMessage getdata = new GetDataMessage(params);
Iterator<InventoryItem> it = transactions.iterator();
while (it.hasNext()) {
InventoryItem item = it.next();
if (memoryPool == null && downloadData) {
// If there's no memory pool only download transactions if we're configured to.
getdata.addItem(item);
} else {
// Only download the transaction if we are the first peer that saw it be advertised. Other peers will also
// see it be advertised in inv packets asynchronously, they co-ordinate via the memory pool. We could
// potentially download transactions faster by always asking every peer for a tx when advertised, as remote
// peers run at different speeds. However to conserve bandwidth on mobile devices we try to only download a
// transaction once. This means we can miss broadcasts if the peer disconnects between sending us an inv and
// sending us the transaction: currently we'll never try to re-fetch after a timeout.
if (memoryPool.maybeWasSeen(item.hash)) {
// Some other peer already announced this so don't download.
it.remove();
} else {
getdata.addItem(item);
}
memoryPool.seen(item.hash, this.getAddress());
}
}
if (blocks.size() > 0 && downloadData) {
Block topBlock = blockChain.getUnconnectedBlock();
Sha256Hash topHash = (topBlock != null ? topBlock.getHash() : null);
if (isNewBlockTickle(topHash, blocks)) {
// An inv with a single hash containing our most recent unconnected block is a special inv,
// it's kind of like a tickle from the peer telling us that it's time to download more blocks to catch up to
// the block chain. We could just ignore this and treat it as a regular inv but then we'd download the head
// block over and over again after each batch of 500 blocks, which is wasteful.
blockChainDownload(topHash);
return;
}
// Request the advertised blocks only if we're the download peer.
for (InventoryItem item : blocks) getdata.addItem(item);
}
if (!getdata.getItems().isEmpty()) {
// This will cause us to receive a bunch of block or tx messages.
conn.writeMessage(getdata);
}
}
/** A new block tickle is an inv with a hash containing the topmost block. */
private boolean isNewBlockTickle(Sha256Hash topHash, List<InventoryItem> items) {
return items.size() == 1 &&
items.get(0).type == InventoryItem.Type.Block &&
topHash != null &&
items.get(0).hash.equals(topHash);
}
/**
* Asks the connected peer for the block of the given hash, and returns a Future representing the answer.
* If you want the block right away and don't mind waiting for it, just call .get() on the result. Your thread
* will block until the peer answers. You can also use the Future object to wait with a timeout, or just check
* whether it's done later.
*
* @param blockHash Hash of the block you wareare requesting.
* @throws IOException
*/
public Future<Block> getBlock(Sha256Hash blockHash) throws IOException {
GetDataMessage getdata = new GetDataMessage(params);
InventoryItem inventoryItem = new InventoryItem(InventoryItem.Type.Block, blockHash);
getdata.addItem(inventoryItem);
GetDataFuture<Block> future = new GetDataFuture<Block>(inventoryItem);
// Add to the list of things we're waiting for. It's important this come before the network send to avoid
// race conditions.
synchronized (pendingGetBlockFutures) {
pendingGetBlockFutures.add(future);
}
conn.writeMessage(getdata);
return future;
}
/**
* When downloading the block chain, the bodies will be skipped for blocks created before the given date. Any
* transactions relevant to the wallet will therefore not be found, but if you know your wallet has no such
* transactions it doesn't matter and can save a lot of bandwidth and processing time. Note that the times of blocks
* isn't known until their headers are available and they are requested in chunks, so some headers may be downloaded
* twice using this scheme, but this optimization can still be a large win for newly created wallets.
*
* @param secondsSinceEpoch Time in seconds since the epoch or 0 to reset to always downloading block bodies.
*/
public void setFastCatchupTime(long secondsSinceEpoch) {
if (secondsSinceEpoch == 0) {
fastCatchupTimeSecs = params.genesisBlock.getTimeSeconds();
downloadBlockBodies = true;
} else {
fastCatchupTimeSecs = secondsSinceEpoch;
// If the given time is before the current chains head block time, then this has no effect (we already
// downloaded everything we need).
if (fastCatchupTimeSecs > blockChain.getChainHead().getHeader().getTimeSeconds()) {
downloadBlockBodies = false;
}
}
}
/**
* Links the given wallet to this peer. If you have multiple peers, you should use a {@link PeerGroup} to manage
* them and use the {@link PeerGroup#addWallet(Wallet)} method instead of registering the wallet with each peer
* independently, otherwise the wallet will receive duplicate notifications.
*/
public void addWallet(Wallet wallet) {
addEventListener(wallet.getPeerEventListener());
}
/** Unlinks the given wallet from peer. See {@link Peer#addWallet(Wallet)}. */
public void removeWallet(Wallet wallet) {
removeEventListener(wallet.getPeerEventListener());
}
// A GetDataFuture wraps the result of a getBlock or (in future) getTransaction so the owner of the object can
// decide whether to wait forever, wait for a short while or check later after doing other work.
private static class GetDataFuture<T extends Message> implements Future<T> {
private boolean cancelled;
private final InventoryItem item;
private final CountDownLatch latch;
private T result;
GetDataFuture(InventoryItem item) {
this.item = item;
this.latch = new CountDownLatch(1);
}
public boolean cancel(boolean b) {
// Cannot cancel a getdata - once sent, it's sent.
cancelled = true;
return false;
}
public boolean isCancelled() {
return cancelled;
}
public boolean isDone() {
return result != null || cancelled;
}
public T get() throws InterruptedException, ExecutionException {
latch.await();
return Preconditions.checkNotNull(result);
}
public T get(long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
if (!latch.await(l, timeUnit))
throw new TimeoutException();
return Preconditions.checkNotNull(result);
}
InventoryItem getItem() {
return item;
}
/** Called by the Peer when the result has arrived. Completes the task. */
void setResult(T result) {
// This should be called in the network loop thread for this peer
this.result = result;
// Now release the thread that is waiting. We don't need to synchronize here as the latch establishes
// a memory barrier.
latch.countDown();
}
}
/**
* Sends the given message on the peers network connection. Just uses {@link NetworkConnection#writeMessage(Message)}.
*/
public void sendMessage(Message m) throws IOException {
conn.writeMessage(m);
}
private void blockChainDownload(Sha256Hash toHash) throws IOException {
// This may run in ANY thread.
// The block chain download process is a bit complicated. Basically, we start with one or more blocks in a
// chain that we have from a previous session. We want to catch up to the head of the chain BUT we don't know
// where that chain is up to or even if the top block we have is even still in the chain - we
// might have got ourselves onto a fork that was later resolved by the network.
//
// To solve this, we send the peer a block locator which is just a list of block hashes. It contains the
// blocks we know about, but not all of them, just enough of them so the peer can figure out if we did end up
// on a fork and if so, what the earliest still valid block we know about is likely to be.
//
// Once it has decided which blocks we need, it will send us an inv with up to 500 block messages. We may
// have some of them already if we already have a block chain and just need to catch up. Once we request the
// last block, if there are still more to come it sends us an "inv" containing only the hash of the head
// block.
//
// That causes us to download the head block but then we find (in processBlock) that we can't connect
// it to the chain yet because we don't have the intermediate blocks. So we rerun this function building a
// new block locator describing where we're up to.
//
// The getblocks with the new locator gets us another inv with another bunch of blocks. We download them once
// again. This time when the peer sends us an inv with the head block, we already have it so we won't download
// it again - but we recognize this case as special and call back into blockChainDownload to continue the
// process.
//
// So this is a complicated process but it has the advantage that we can download a chain of enormous length
// in a relatively stateless manner and with constant memory usage.
//
// All this is made more complicated by the desire to skip downloading the bodies of blocks that pre-date the
// 'fast catchup time', which is usually set to the creation date of the earliest key in the wallet. Because
// we know there are no transactions using our keys before that date, we need only the headers. To do that we
// use the "getheaders" command. Once we find we've gone past the target date, we throw away the downloaded
// headers and then request the blocks from that point onwards. "getheaders" does not send us an inv, it just
// sends us the data we requested in a "headers" message.
log.info("blockChainDownload({})", toHash.toString());
// TODO: Block locators should be abstracted out rather than special cased here.
List<Sha256Hash> blockLocator = new ArrayList<Sha256Hash>(51);
// For now we don't do the exponential thinning as suggested here:
//
// https://en.bitcoin.it/wiki/Protocol_specification#getblocks
//
// This is because it requires scanning all the block chain headers, which is very slow. Instead we add the top
// 50 block headers. If there is a re-org deeper than that, we'll end up downloading the entire chain. We
// must always put the genesis block as the first entry.
BlockStore store = blockChain.getBlockStore();
StoredBlock cursor = blockChain.getChainHead();
for (int i = 50; cursor != null && i > 0; i--) {
blockLocator.add(cursor.getHeader().getHash());
try {
cursor = cursor.getPrev(store);
} catch (BlockStoreException e) {
log.error("Failed to walk the block chain whilst constructing a locator");
throw new RuntimeException(e);
}
}
// Only add the locator if we didn't already do so. If the chain is < 50 blocks we already reached it.
if (cursor != null) {
blockLocator.add(params.genesisBlock.getHash());
}
// The toHash field is set to zero already by the constructor. This is how we indicate "never stop".
if (downloadBlockBodies) {
GetBlocksMessage message = new GetBlocksMessage(params, blockLocator, toHash);
conn.writeMessage(message);
} else {
// Downloading headers for a while instead of full blocks.
GetHeadersMessage message = new GetHeadersMessage(params, blockLocator, toHash);
conn.writeMessage(message);
}
}
/**
* Starts an asynchronous download of the block chain. The chain download is deemed to be complete once we've
* downloaded the same number of blocks that the peer advertised having in its version handshake message.
*/
public void startBlockChainDownload() throws IOException {
setDownloadData(true);
// TODO: peer might still have blocks that we don't have, and even have a heavier
// chain even if the chain block count is lower.
if (getPeerBlockHeightDifference() >= 0) {
for (PeerEventListener listener : eventListeners) {
synchronized (listener) {
listener.onChainDownloadStarted(this, getPeerBlockHeightDifference());
}
}
// When we just want as many blocks as possible, we can set the target hash to zero.
blockChainDownload(Sha256Hash.ZERO_HASH);
}
}
/**
* Returns the difference between our best chain height and the peers, which can either be positive if we are
* behind the peer, or negative if the peer is ahead of us.
*/
public int getPeerBlockHeightDifference() {
// Chain will overflow signed int blocks in ~41,000 years.
int chainHeight = (int) conn.getVersionMessage().bestHeight;
// chainHeight should not be zero/negative because we shouldn't have given the user a Peer that is to another
// client-mode node, nor should it be unconnected. If that happens it means the user overrode us somewhere or
// there is a bug in the peer management code.
Preconditions.checkState(chainHeight > 0, "Connected to peer with zero/negative chain height", chainHeight);
return chainHeight - blockChain.getChainHead().getHeight();
}
/**
* Terminates the network connection and stops the message handling loop.
*
* <p>This does not wait for the loop to terminate.
*/
public synchronized void disconnect() {
log.debug("Disconnecting peer");
running = false;
try {
// This is the correct way to stop an IO bound loop
if (conn != null)
conn.shutdown();
} catch (IOException e) {
// Don't care about this.
}
}
/**
* Returns true if this peer will try and download things it is sent in "inv" messages. Normally you only need
* one peer to be downloading data. Defaults to true.
*/
public boolean getDownloadData() {
return downloadData;
}
/**
* If set to false, the peer won't try and fetch blocks and transactions it hears about. Normally, only one
* peer should download missing blocks. Defaults to true.
*/
public void setDownloadData(boolean downloadData) {
this.downloadData = downloadData;
}
/**
* @return the IP address and port of peer.
*/
public PeerAddress getAddress() {
return address;
}
/**
* @return various version numbers claimed by peer.
*/
public VersionMessage getVersionMessage() {
return conn.getVersionMessage();
}
/**
* @return the height of the best chain as claimed by peer.
*/
public long getBestHeight() {
return conn.getVersionMessage().bestHeight;
}
/**
* @return whether the peer is currently connected and the message loop is running.
*/
public boolean isConnected() {
return running;
}
}
| Add some debug logging to Peer. Updates issue 199.
| core/src/main/java/com/google/bitcoin/core/Peer.java | Add some debug logging to Peer. Updates issue 199. |
|
Java | apache-2.0 | 98d720a1e33f6aa496cef9a731c58d6ef6ae6e7b | 0 | dimbleby/JGroups,vjuranek/JGroups,deepnarsay/JGroups,Sanne/JGroups,dimbleby/JGroups,belaban/JGroups,ibrahimshbat/JGroups,ligzy/JGroups,danberindei/JGroups,rhusar/JGroups,ibrahimshbat/JGroups,rpelisse/JGroups,dimbleby/JGroups,pferraro/JGroups,tristantarrant/JGroups,pruivo/JGroups,TarantulaTechnology/JGroups,kedzie/JGroups,kedzie/JGroups,deepnarsay/JGroups,Sanne/JGroups,pruivo/JGroups,TarantulaTechnology/JGroups,slaskawi/JGroups,ibrahimshbat/JGroups,vjuranek/JGroups,slaskawi/JGroups,kedzie/JGroups,ligzy/JGroups,slaskawi/JGroups,rhusar/JGroups,TarantulaTechnology/JGroups,tristantarrant/JGroups,ligzy/JGroups,ibrahimshbat/JGroups,rpelisse/JGroups,vjuranek/JGroups,rpelisse/JGroups,pferraro/JGroups,danberindei/JGroups,deepnarsay/JGroups,pferraro/JGroups,belaban/JGroups,rvansa/JGroups,Sanne/JGroups,pruivo/JGroups,belaban/JGroups,rhusar/JGroups,rvansa/JGroups,danberindei/JGroups |
package org.jgroups.stack;
import org.jgroups.Event;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.annotations.DeprecatedProperty;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.Property;
import org.jgroups.jmx.ResourceDMBean;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.protocols.TP;
import org.jgroups.util.SocketFactory;
import org.jgroups.util.ThreadFactory;
import org.jgroups.util.Util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* The Protocol class provides a set of common services for protocol layers. Each layer has to
* be a subclass of Protocol and override a number of methods (typically just <code>up()</code>,
* <code>down()</code> and <code>getName()</code>. Layers are stacked in a certain order to form
* a protocol stack. <a href=org.jgroups.Event.html>Events</a> are passed from lower
* layers to upper ones and vice versa. E.g. a Message received by the UDP layer at the bottom
* will be passed to its higher layer as an Event. That layer will in turn pass the Event to
* its layer and so on, until a layer handles the Message and sends a response or discards it,
* the former resulting in another Event being passed down the stack.
* <p/>
* The important thing to bear in mind is that Events have to passed on between layers in FIFO
* order which is guaranteed by the Protocol implementation and must be guranteed by subclasses
* implementing their on Event queuing.<p>
* <b>Note that each class implementing interface Protocol MUST provide an empty, public
* constructor !</b>
*
* @author Bela Ban
*/
@DeprecatedProperty(names={"down_thread","down_thread_prio","up_thread","up_thread_prio"})
public abstract class Protocol {
protected Protocol up_prot=null, down_prot=null;
protected ProtocolStack stack=null;
@Property(description="Determines whether to collect statistics (and expose them via JMX). Default is true",writable=true)
protected boolean stats=true;
@Property(description="Enables ergonomics: dynamically find the best values for properties at runtime")
protected boolean ergonomics=true;
/** The name of the protocol. Is by default set to the protocol's classname. This property should rarely need to
* be set, e.g. only in cases where we want to create more than 1 protocol of the same class in the same stack */
@Property(name="name",description="Give the protocol a different name if needed so we can have multiple " +
"instances of it in the same stack (deprecated)",writable=false)
@Deprecated
protected String name=getClass().getSimpleName();
@Property(description="Give the protocol a different ID if needed so we can have multiple " +
"instances of it in the same stack",writable=true)
protected short id=ClassConfigurator.getProtocolId(getClass());
protected final Log log=LogFactory.getLog(this.getClass());
/**
* Sets the level of a logger. This method is used to dynamically change the logging level of a
* running system, e.g. via JMX. The appender of a level needs to exist.
* @param level The new level. Valid values are "fatal", "error", "warn", "info", "debug", "trace"
* (capitalization not relevant)
*/
@Property(name="level", description="Sets the logger level (see javadocs)")
public void setLevel(String level) {
log.setLevel(level);
}
public String getLevel() {
return log.getLevel();
}
public boolean isErgonomics() {
return ergonomics;
}
public void setErgonomics(boolean ergonomics) {
this.ergonomics=ergonomics;
}
/**
* Configures the protocol initially. A configuration string consists of name=value
* items, separated by a ';' (semicolon), e.g.:<pre>
* "loopback=false;unicast_inport=4444"
* </pre>
* @deprecated The properties are now set through the @Property annotation on the attribute or setter
*/
protected boolean setProperties(Properties props) {
throw new UnsupportedOperationException("deprecated; use a setter instead");
}
/**
* Sets a property
* @param key
* @param val
* @deprecated Use the corresponding setter instead
*/
public void setProperty(String key, String val) {
throw new UnsupportedOperationException("deprecated; use a setter instead");
}
/** Called by Configurator. Removes 2 properties which are used by the Protocol directly and then
* calls setProperties(), which might invoke the setProperties() method of the actual protocol instance.
* @deprecated Use a setter instead
*/
public boolean setPropertiesInternal(Properties props) {
throw new UnsupportedOperationException("use a setter instead");
}
public Protocol setValues(Map<String,Object> values) {
if(values == null)
return this;
for(Map.Entry<String,Object> entry: values.entrySet()) {
String attrname=entry.getKey();
Object value=entry.getValue();
Field field=Util.getField(getClass(), attrname);
if(field != null) {
Configurator.setField(field, this, value);
}
}
return this;
}
public Protocol setValue(String name, Object value) {
if(name == null || value == null)
return this;
Field field=Util.getField(getClass(), name);
if(field != null) {
Configurator.setField(field, this, value);
}
return this;
}
/**
* @return
* @deprecated Use a getter to get the actual instance variable
*/
public Properties getProperties() {
if(log.isWarnEnabled())
log.warn("deprecated feature: please use a setter instead");
return new Properties();
}
public ProtocolStack getProtocolStack(){
return stack;
}
/**
* After configuring the protocol itself from the properties defined in the XML config, a protocol might have
* additional objects which need to be configured. This callback allows a protocol developer to configure those
* other objects. This call is guaranteed to be invoked <em>after</em> the protocol itself has
* been configured. See AUTH for an example.
* @return
*/
protected List<Object> getConfigurableObjects() {
return null;
}
protected TP getTransport() {
Protocol retval=this;
while(retval != null && retval.down_prot != null) {
retval=retval.down_prot;
}
return (TP)retval;
}
/** Supposed to be overwritten by subclasses. Usually the transport returns a valid non-null thread factory, but
* thread factories can also be created by individual protocols
* @return
*/
public ThreadFactory getThreadFactory() {
return down_prot != null? down_prot.getThreadFactory(): null;
}
/**
* Returns the SocketFactory associated with this protocol, if overridden in a subclass, or passes the call down
* @return SocketFactory
*/
public SocketFactory getSocketFactory() {
return down_prot != null? down_prot.getSocketFactory() : null;
}
/**
* Sets a SocketFactory. Socket factories are typically provided by the transport ({@link org.jgroups.protocols.TP})
* or {@link org.jgroups.protocols.TP.ProtocolAdapter}
* @param factory
*/
public void setSocketFactory(SocketFactory factory) {
if(down_prot != null)
down_prot.setSocketFactory(factory);
}
/** @deprecated up_thread was removed
* @return false by default
*/
public boolean upThreadEnabled() {
return false;
}
/**
* @deprecated down thread was removed
* @return boolean False by default
*/
public boolean downThreadEnabled() {
return false;
}
public boolean statsEnabled() {
return stats;
}
public void enableStats(boolean flag) {
stats=flag;
}
public void resetStats() {
;
}
public String printStats() {
return null;
}
public Map<String,Object> dumpStats() {
HashMap<String,Object> map=new HashMap<String,Object>();
for(Class<?> clazz=this.getClass();clazz != null;clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(Field field: fields) {
if(field.isAnnotationPresent(ManagedAttribute.class) ||
(field.isAnnotationPresent(Property.class) && field.getAnnotation(Property.class).exposeAsManagedAttribute())) {
String attributeName=field.getName();
try {
field.setAccessible(true);
Object value=field.get(this);
map.put(attributeName, value != null? value.toString() : null);
}
catch(Exception e) {
log.warn("Could not retrieve value of attribute (field) " + attributeName,e);
}
}
}
Method[] methods=this.getClass().getMethods();
for(Method method: methods) {
if(method.isAnnotationPresent(ManagedAttribute.class) ||
(method.isAnnotationPresent(Property.class) && method.getAnnotation(Property.class).exposeAsManagedAttribute())) {
String method_name=method.getName();
if(method_name.startsWith("is") || method_name.startsWith("get")) {
try {
Object value=method.invoke(this);
String attributeName=Util.methodNameToAttributeName(method_name);
map.put(attributeName, value != null? value.toString() : null);
}
catch(Exception e) {
log.warn("Could not retrieve value of attribute (method) " + method_name,e);
}
}
else if(method_name.startsWith("set")) {
String stem=method_name.substring(3);
Method getter=ResourceDMBean.findGetter(getClass(), stem);
if(getter != null) {
try {
Object value=getter.invoke(this);
String attributeName=Util.methodNameToAttributeName(method_name);
map.put(attributeName, value != null? value.toString() : null);
}
catch(Exception e) {
log.warn("Could not retrieve value of attribute (method) " + method_name, e);
}
}
}
}
}
}
return map;
}
/**
* Called after instance has been created (null constructor) and before protocol is started.
* Properties are already set. Other protocols are not yet connected and events cannot yet be sent.
* @exception Exception Thrown if protocol cannot be initialized successfully. This will cause the
* ProtocolStack to fail, so the channel constructor will throw an exception
*/
public void init() throws Exception {
}
/**
* This method is called on a {@link org.jgroups.Channel#connect(String)}. Starts work.
* Protocols are connected and queues are ready to receive events.
* Will be called <em>from bottom to top</em>. This call will replace
* the <b>START</b> and <b>START_OK</b> events.
* @exception Exception Thrown if protocol cannot be started successfully. This will cause the ProtocolStack
* to fail, so {@link org.jgroups.Channel#connect(String)} will throw an exception
*/
public void start() throws Exception {
}
/**
* This method is called on a {@link org.jgroups.Channel#disconnect()}. Stops work (e.g. by closing multicast socket).
* Will be called <em>from top to bottom</em>. This means that at the time of the method invocation the
* neighbor protocol below is still working. This method will replace the
* <b>STOP</b>, <b>STOP_OK</b>, <b>CLEANUP</b> and <b>CLEANUP_OK</b> events. The ProtocolStack guarantees that
* when this method is called all messages in the down queue will have been flushed
*/
public void stop() {
}
/**
* This method is called on a {@link org.jgroups.Channel#close()}.
* Does some cleanup; after the call the VM will terminate
*/
public void destroy() {
}
/** List of events that are required to be answered by some layer above.
@return Vector (of Integers) */
public Vector<Integer> requiredUpServices() {
return null;
}
/** List of events that are required to be answered by some layer below.
@return Vector (of Integers) */
public Vector<Integer> requiredDownServices() {
return null;
}
/** List of events that are provided to layers above (they will be handled when sent down from
above).
@return Vector (of Integers) */
public Vector<Integer> providedUpServices() {
return null;
}
/** List of events that are provided to layers below (they will be handled when sent down from
below).
@return Vector<Integer (of Integers) */
public Vector<Integer> providedDownServices() {
return null;
}
/** All protocol names have to be unique ! */
public String getName() {
return getClass().getSimpleName();
}
public short getId() {
return id;
}
public void setId(short id) {
this.id=id;
}
public Protocol getUpProtocol() {
return up_prot;
}
public Protocol getDownProtocol() {
return down_prot;
}
public void setUpProtocol(Protocol up_prot) {
this.up_prot=up_prot;
}
public void setDownProtocol(Protocol down_prot) {
this.down_prot=down_prot;
}
public void setProtocolStack(ProtocolStack stack) {
this.stack=stack;
}
/**
* An event was received from the layer below. Usually the current layer will want to examine
* the event type and - depending on its type - perform some computation
* (e.g. removing headers from a MSG event type, or updating the internal membership list
* when receiving a VIEW_CHANGE event).
* Finally the event is either a) discarded, or b) an event is sent down
* the stack using <code>down_prot.down()</code> or c) the event (or another event) is sent up
* the stack using <code>up_prot.up()</code>.
*/
public Object up(Event evt) {
return up_prot.up(evt);
}
/**
* An event is to be sent down the stack. The layer may want to examine its type and perform
* some action on it, depending on the event's type. If the event is a message MSG, then
* the layer may need to add a header to it (or do nothing at all) before sending it down
* the stack using <code>down_prot.down()</code>. In case of a GET_ADDRESS event (which tries to
* retrieve the stack's address from one of the bottom layers), the layer may need to send
* a new response event back up the stack using <code>up_prot.up()</code>.
*/
public Object down(Event evt) {
return down_prot.down(evt);
}
}
| src/org/jgroups/stack/Protocol.java |
package org.jgroups.stack;
import org.jgroups.Event;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.annotations.DeprecatedProperty;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.Property;
import org.jgroups.jmx.ResourceDMBean;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.protocols.TP;
import org.jgroups.util.SocketFactory;
import org.jgroups.util.ThreadFactory;
import org.jgroups.util.Util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* The Protocol class provides a set of common services for protocol layers. Each layer has to
* be a subclass of Protocol and override a number of methods (typically just <code>up()</code>,
* <code>down()</code> and <code>getName()</code>. Layers are stacked in a certain order to form
* a protocol stack. <a href=org.jgroups.Event.html>Events</a> are passed from lower
* layers to upper ones and vice versa. E.g. a Message received by the UDP layer at the bottom
* will be passed to its higher layer as an Event. That layer will in turn pass the Event to
* its layer and so on, until a layer handles the Message and sends a response or discards it,
* the former resulting in another Event being passed down the stack.
* <p/>
* The important thing to bear in mind is that Events have to passed on between layers in FIFO
* order which is guaranteed by the Protocol implementation and must be guranteed by subclasses
* implementing their on Event queuing.<p>
* <b>Note that each class implementing interface Protocol MUST provide an empty, public
* constructor !</b>
*
* @author Bela Ban
*/
@DeprecatedProperty(names={"down_thread","down_thread_prio","up_thread","up_thread_prio"})
public abstract class Protocol {
protected Protocol up_prot=null, down_prot=null;
protected ProtocolStack stack=null;
@Property(description="Determines whether to collect statistics (and expose them via JMX). Default is true",writable=true)
protected boolean stats=true;
@Property(description="Enables ergonomics: dynamically find the best values for properties at runtime")
protected boolean ergonomics=true;
/** The name of the protocol. Is by default set to the protocol's classname. This property should rarely need to
* be set, e.g. only in cases where we want to create more than 1 protocol of the same class in the same stack */
@Property(name="name",description="Give the protocol a different name if needed so we can have multiple " +
"instances of it in the same stack",writable=false)
protected String name=getClass().getSimpleName();
@Property(description="Give the protocol a different ID if needed so we can have multiple " +
"instances of it in the same stack",writable=true)
protected short id=ClassConfigurator.getProtocolId(getClass());
protected final Log log=LogFactory.getLog(this.getClass());
/**
* Sets the level of a logger. This method is used to dynamically change the logging level of a
* running system, e.g. via JMX. The appender of a level needs to exist.
* @param level The new level. Valid values are "fatal", "error", "warn", "info", "debug", "trace"
* (capitalization not relevant)
*/
@Property(name="level", description="Sets the logger level (see javadocs)")
public void setLevel(String level) {
log.setLevel(level);
}
public String getLevel() {
return log.getLevel();
}
public boolean isErgonomics() {
return ergonomics;
}
public void setErgonomics(boolean ergonomics) {
this.ergonomics=ergonomics;
}
/**
* Configures the protocol initially. A configuration string consists of name=value
* items, separated by a ';' (semicolon), e.g.:<pre>
* "loopback=false;unicast_inport=4444"
* </pre>
* @deprecated The properties are now set through the @Property annotation on the attribute or setter
*/
protected boolean setProperties(Properties props) {
throw new UnsupportedOperationException("deprecated; use a setter instead");
}
/**
* Sets a property
* @param key
* @param val
* @deprecated Use the corresponding setter instead
*/
public void setProperty(String key, String val) {
throw new UnsupportedOperationException("deprecated; use a setter instead");
}
/** Called by Configurator. Removes 2 properties which are used by the Protocol directly and then
* calls setProperties(), which might invoke the setProperties() method of the actual protocol instance.
* @deprecated Use a setter instead
*/
public boolean setPropertiesInternal(Properties props) {
throw new UnsupportedOperationException("use a setter instead");
}
public Protocol setValues(Map<String,Object> values) {
if(values == null)
return this;
for(Map.Entry<String,Object> entry: values.entrySet()) {
String attrname=entry.getKey();
Object value=entry.getValue();
Field field=Util.getField(getClass(), attrname);
if(field != null) {
Configurator.setField(field, this, value);
}
}
return this;
}
public Protocol setValue(String name, Object value) {
if(name == null || value == null)
return this;
Field field=Util.getField(getClass(), name);
if(field != null) {
Configurator.setField(field, this, value);
}
return this;
}
/**
* @return
* @deprecated Use a getter to get the actual instance variable
*/
public Properties getProperties() {
if(log.isWarnEnabled())
log.warn("deprecated feature: please use a setter instead");
return new Properties();
}
public ProtocolStack getProtocolStack(){
return stack;
}
/**
* After configuring the protocol itself from the properties defined in the XML config, a protocol might have
* additional objects which need to be configured. This callback allows a protocol developer to configure those
* other objects. This call is guaranteed to be invoked <em>after</em> the protocol itself has
* been configured. See AUTH for an example.
* @return
*/
protected List<Object> getConfigurableObjects() {
return null;
}
protected TP getTransport() {
Protocol retval=this;
while(retval != null && retval.down_prot != null) {
retval=retval.down_prot;
}
return (TP)retval;
}
/** Supposed to be overwritten by subclasses. Usually the transport returns a valid non-null thread factory, but
* thread factories can also be created by individual protocols
* @return
*/
public ThreadFactory getThreadFactory() {
return down_prot != null? down_prot.getThreadFactory(): null;
}
/**
* Returns the SocketFactory associated with this protocol, if overridden in a subclass, or passes the call down
* @return SocketFactory
*/
public SocketFactory getSocketFactory() {
return down_prot != null? down_prot.getSocketFactory() : null;
}
/**
* Sets a SocketFactory. Socket factories are typically provided by the transport ({@link org.jgroups.protocols.TP})
* or {@link org.jgroups.protocols.TP.ProtocolAdapter}
* @param factory
*/
public void setSocketFactory(SocketFactory factory) {
if(down_prot != null)
down_prot.setSocketFactory(factory);
}
/** @deprecated up_thread was removed
* @return false by default
*/
public boolean upThreadEnabled() {
return false;
}
/**
* @deprecated down thread was removed
* @return boolean False by default
*/
public boolean downThreadEnabled() {
return false;
}
public boolean statsEnabled() {
return stats;
}
public void enableStats(boolean flag) {
stats=flag;
}
public void resetStats() {
;
}
public String printStats() {
return null;
}
public Map<String,Object> dumpStats() {
HashMap<String,Object> map=new HashMap<String,Object>();
for(Class<?> clazz=this.getClass();clazz != null;clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(Field field: fields) {
if(field.isAnnotationPresent(ManagedAttribute.class) ||
(field.isAnnotationPresent(Property.class) && field.getAnnotation(Property.class).exposeAsManagedAttribute())) {
String attributeName=field.getName();
try {
field.setAccessible(true);
Object value=field.get(this);
map.put(attributeName, value != null? value.toString() : null);
}
catch(Exception e) {
log.warn("Could not retrieve value of attribute (field) " + attributeName,e);
}
}
}
Method[] methods=this.getClass().getMethods();
for(Method method: methods) {
if(method.isAnnotationPresent(ManagedAttribute.class) ||
(method.isAnnotationPresent(Property.class) && method.getAnnotation(Property.class).exposeAsManagedAttribute())) {
String method_name=method.getName();
if(method_name.startsWith("is") || method_name.startsWith("get")) {
try {
Object value=method.invoke(this);
String attributeName=Util.methodNameToAttributeName(method_name);
map.put(attributeName, value != null? value.toString() : null);
}
catch(Exception e) {
log.warn("Could not retrieve value of attribute (method) " + method_name,e);
}
}
else if(method_name.startsWith("set")) {
String stem=method_name.substring(3);
Method getter=ResourceDMBean.findGetter(getClass(), stem);
if(getter != null) {
try {
Object value=getter.invoke(this);
String attributeName=Util.methodNameToAttributeName(method_name);
map.put(attributeName, value != null? value.toString() : null);
}
catch(Exception e) {
log.warn("Could not retrieve value of attribute (method) " + method_name, e);
}
}
}
}
}
}
return map;
}
/**
* Called after instance has been created (null constructor) and before protocol is started.
* Properties are already set. Other protocols are not yet connected and events cannot yet be sent.
* @exception Exception Thrown if protocol cannot be initialized successfully. This will cause the
* ProtocolStack to fail, so the channel constructor will throw an exception
*/
public void init() throws Exception {
}
/**
* This method is called on a {@link org.jgroups.Channel#connect(String)}. Starts work.
* Protocols are connected and queues are ready to receive events.
* Will be called <em>from bottom to top</em>. This call will replace
* the <b>START</b> and <b>START_OK</b> events.
* @exception Exception Thrown if protocol cannot be started successfully. This will cause the ProtocolStack
* to fail, so {@link org.jgroups.Channel#connect(String)} will throw an exception
*/
public void start() throws Exception {
}
/**
* This method is called on a {@link org.jgroups.Channel#disconnect()}. Stops work (e.g. by closing multicast socket).
* Will be called <em>from top to bottom</em>. This means that at the time of the method invocation the
* neighbor protocol below is still working. This method will replace the
* <b>STOP</b>, <b>STOP_OK</b>, <b>CLEANUP</b> and <b>CLEANUP_OK</b> events. The ProtocolStack guarantees that
* when this method is called all messages in the down queue will have been flushed
*/
public void stop() {
}
/**
* This method is called on a {@link org.jgroups.Channel#close()}.
* Does some cleanup; after the call the VM will terminate
*/
public void destroy() {
}
/** List of events that are required to be answered by some layer above.
@return Vector (of Integers) */
public Vector<Integer> requiredUpServices() {
return null;
}
/** List of events that are required to be answered by some layer below.
@return Vector (of Integers) */
public Vector<Integer> requiredDownServices() {
return null;
}
/** List of events that are provided to layers above (they will be handled when sent down from
above).
@return Vector (of Integers) */
public Vector<Integer> providedUpServices() {
return null;
}
/** List of events that are provided to layers below (they will be handled when sent down from
below).
@return Vector<Integer (of Integers) */
public Vector<Integer> providedDownServices() {
return null;
}
/** All protocol names have to be unique ! */
public String getName() {
return name;
}
public short getId() {
return id;
}
public void setId(short id) {
this.id=id;
}
public Protocol getUpProtocol() {
return up_prot;
}
public Protocol getDownProtocol() {
return down_prot;
}
public void setUpProtocol(Protocol up_prot) {
this.up_prot=up_prot;
}
public void setDownProtocol(Protocol down_prot) {
this.down_prot=down_prot;
}
public void setProtocolStack(ProtocolStack stack) {
this.stack=stack;
}
/**
* An event was received from the layer below. Usually the current layer will want to examine
* the event type and - depending on its type - perform some computation
* (e.g. removing headers from a MSG event type, or updating the internal membership list
* when receiving a VIEW_CHANGE event).
* Finally the event is either a) discarded, or b) an event is sent down
* the stack using <code>down_prot.down()</code> or c) the event (or another event) is sent up
* the stack using <code>up_prot.up()</code>.
*/
public Object up(Event evt) {
return up_prot.up(evt);
}
/**
* An event is to be sent down the stack. The layer may want to examine its type and perform
* some action on it, depending on the event's type. If the event is a message MSG, then
* the layer may need to add a header to it (or do nothing at all) before sending it down
* the stack using <code>down_prot.down()</code>. In case of a GET_ADDRESS event (which tries to
* retrieve the stack's address from one of the bottom layers), the layer may need to send
* a new response event back up the stack using <code>up_prot.up()</code>.
*/
public Object down(Event evt) {
return down_prot.down(evt);
}
}
| deprecated name
| src/org/jgroups/stack/Protocol.java | deprecated name |
|
Java | apache-2.0 | error: pathspec 'ListenerList.java' did not match any file(s) known to git
| 936e11073bb040b801e91d683f3875413f6d0747 | 1 | radium226/maven-github-wagon,radium226/maven-github-wagon | package com.github.radium.maven;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class ListenerList<T> {
final private static Logger LOGGER = LoggerFactory.getLogger(ListenerList.class);
private Set<T> listeners = Sets.newHashSet();
private Class<T> listenerClass;
private ListenerList(Class<T> listenerClass) {
super();
this.listenerClass = listenerClass;
}
public static <T> ListenerList<T> of(Class<T> listenerClass) {
return new ListenerList<T>(listenerClass);
}
public boolean add(T listener) {
return listeners.add(listener);
}
public boolean remove(T listener) {
return listeners.remove(listener);
}
public boolean contains(T listener) {
return listeners.contains(listener);
}
public void fire(String methodName, Object... parameters) {
for (T listener : listeners) {
try {
Class<?>[] parameterTypes = Lists.transform(Arrays.asList(parameters), new Function<Object, Class<?>>() {
@Override
public Class<?> apply(Object parameter) {
Class<?> type = parameter.getClass();
return type;
}
}).toArray(new Class<?>[0]);
Method method = listenerClass.getMethod(methodName, parameterTypes);
method.invoke(listener, parameters);
} catch (IllegalAccessException e) {
LOGGER.warn("Unable to invoke {}", methodName, e);
} catch (SecurityException e) {
LOGGER.warn("Unable to invoke {}", methodName, e);
} catch (NoSuchMethodException e) {
LOGGER.warn("Unable to invoke {}", methodName, e);
} catch (IllegalArgumentException e) {
LOGGER.warn("Unable to invoke {}", methodName, e);
} catch (InvocationTargetException e) {
LOGGER.warn("Unable to invoke {}", methodName, e);
}
}
}
}
| ListenerList.java | Create ListenerList.java | ListenerList.java | Create ListenerList.java |
|
Java | apache-2.0 | error: pathspec 'src/util/UtilHelper.java' did not match any file(s) known to git
| 843d08b26fb3800c925bc13c76c25dadf1858a47 | 1 | MINDS-i/Dashboard,MINDS-i/Dashboard,MINDS-i/Dashboard | package com.util;
import java.util.*;
/**
* @author Chris Park @ Infinetix Corp
* Date: 4-21-21
* Description: Singletone class containing useful utility functions for
* Minds-i Dashboard specific functionality and calculations.
*/
public class UtilHelper {
private static UtilHelper utilHelperInstance = null;
private static final double EARTH_RADIUS = 6371.00;
private static final double FEET_PER_KM = 3280.84;
/**
* Constructor (Private, accessed by getInstance
*/
private UtilHelper() {
}
/**
* Returns the singleton instance of this class to be used system wide.
* @return The UtilHelper instance.
*/
public static UtilHelper getInstance() {
if(utilHelperInstance == null) {
utilHelperInstance = new UtilHelper();
}
return utilHelperInstance;
}
/**
* Computes the distance in km between to points on the surface of a sphere.
* @param lat1 - First latitude coordinate
* @param lon1 - First longitude coordinate
* @param lat2 - Second latitude coordinate
* @param lon2 - Second longitude coordinate
* @return - Distance between coordinates in km
*/
public double haversine(double lat1, double lon1,
double lat2, double lon2) {
//Calculate distance between Lats and Longs
double distLat = Math.toRadians(lat2 - lat1);
double distLon = Math.toRadians(lon2 - lon1);
//Convert to Radians
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
//Use Formula
double a = (Math.pow(Math.sin(distLat / 2), 2) +
(Math.pow(Math.sin(distLon / 2), 2) *
Math.cos(lat1) *
Math.cos(lat2)));
double c = (2 * Math.asin(Math.sqrt(a)));
return EARTH_RADIUS * c;
}
/**
* Converts kilometer to feet.
* @param km - distance in km to convert
* @return - distance in feet.
*/
public double kmToFeet(double km) {
return (km * FEET_PER_KM);
}
}
| src/util/UtilHelper.java | Create UtilHelper.java
Add functions:
-Calculate spherical distance between two coordinates
-Convert km to feet
| src/util/UtilHelper.java | Create UtilHelper.java |
|
Java | apache-2.0 | error: pathspec 'test/models/AttachmentTest.java' did not match any file(s) known to git
| 349b0529a25ea1663729eee9b4a0984002ead7cb | 1 | bloodybear/yona,ihoneymon/yobi,Limseunghwan/oss,doortts/forked-for-history,bloodybear/yona,bloodybear/yona,doortts/forked-for-history,naver/yobi,ahb0327/yobi,bloodybear/yona,ChangsungKim/TestRepository01,yona-projects/yona,ahb0327/yobi,oolso/yobi,Limseunghwan/oss,ChangsungKim/TestRepository01,ihoneymon/yobi,doortts/fork-yobi,oolso/yobi,violetag/demo,brainagenet/yobi,ihoneymon/yobi,yona-projects/yona,oolso/yobi,yona-projects/yona,brainagenet/yobi,violetag/demo,ahb0327/yobi,doortts/fork-yobi,yona-projects/yona,naver/yobi,doortts/fork-yobi,naver/yobi,brainagenet/yobi,Limseunghwan/oss,doortts/fork-yobi,doortts/forked-for-history | package models;
import static org.fest.assertions.Assertions.assertThat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import models.enumeration.Resource;
import org.junit.Before;
import org.junit.Test;
public class AttachmentTest extends ModelTest<Attachment> {
@Before
public void before() {
Attachment.setUploadDirectory("resources/test/uploads");
}
@Test
public void testSaveInUserTemporaryArea() throws IOException, NoSuchAlgorithmException {
// Given
File file = createFileWithContents("foo.txt", "Hello".getBytes());
// When
Attachment attach = new Attachment();
attach.storeInUserTemporaryArea(0L, file, "bar.txt");
FileInputStream is = new FileInputStream(attach.getFile());
byte[] b = new byte[1024];
int length = is.read(b);
is.close();
// Then
assertThat(attach.name).isEqualTo("bar.txt");
assertThat(attach.mimeType).isEqualTo("text/plain");
assertThat(new String(b, 0, length)).isEqualTo(new String("Hello"));
}
public void testAttachFiles() throws IOException, NoSuchAlgorithmException {
// Given
File foo = createFileWithContents("foo.txt", "Hello".getBytes());
File bar = createFileWithContents("bar.html", "<p>Bye</p>".getBytes());
// When
new Attachment().storeInUserTemporaryArea(0L, foo, "foo.txt");
new Attachment().storeInUserTemporaryArea(0L, bar, "bar.html");
Attachment.attachFiles(0L, 0L, Resource.ISSUE_POST, 1L);
List<Attachment> attachedFiles = Attachment.findByContainer(Resource.ISSUE_POST, 1L);
// Then
assertThat(attachedFiles.size()).isEqualTo(2);
assertThat(attachedFiles.get(0).name).isEqualTo("foo.txt");
assertThat(attachedFiles.get(0).mimeType).isEqualTo("text/plain");
assertThat(attachedFiles.get(1).name).isEqualTo("bar.html");
assertThat(attachedFiles.get(1).mimeType).isEqualTo("text/html");
}
public File createFileWithContents(String name, byte[] contents) throws IOException, FileNotFoundException {
File tempFile = java.io.File.createTempFile(name, null);
tempFile.deleteOnExit();
FileOutputStream os = new FileOutputStream(tempFile);
os.write(contents);
os.close();
return tempFile;
}
} | test/models/AttachmentTest.java | uploader: Add missed test should be in 9aed8db.
| test/models/AttachmentTest.java | uploader: Add missed test should be in 9aed8db. |
|
Java | apache-2.0 | error: pathspec 'src/ext/wyone/core/TypeChecker.java' did not match any file(s) known to git
| a54b5fbe31bab209e62a68ac375f68bdf833f93e | 1 | hjwylde/whiley-compiler,Whiley/WhileyCompiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler | package wyone.core;
import java.util.*;
import static wyone.core.Expr.*;
import static wyone.core.SpecFile.*;
import wyil.util.*;
import static wyil.util.SyntaxError.*;
public class TypeChecker {
private String filename;
public void check(SpecFile spec) {
filename = spec.filename;
for(Decl d : spec.declarations) {
if(d instanceof RewriteDecl) {
check((RewriteDecl)d);
}
}
}
public void check(RewriteDecl rd) {
HashMap<String,Type> environment = new HashMap<String,Type>();
for(Pair<TypeDecl,String> td : rd.types){
environment.put(td.second(), td.first().type);
}
for(RuleDecl rule : rd.rules) {
check(rule,environment);
}
}
public void check(RuleDecl rule, HashMap<String,Type> environment) {
for(Pair<String,Expr> let : rule.lets) {
environment.put(let.first(), resolve(let.second(),environment));
}
resolve(rule.condition,environment);
}
protected Type resolve(Expr e, HashMap<String,Type> environment) {
try {
if (e instanceof Constant) {
return resolve((Constant) e, environment);
} else if (e instanceof Variable) {
return resolve((Variable) e, environment);
} else if (e instanceof UnOp) {
return resolve((UnOp) e, environment);
} else if (e instanceof Invoke) {
return resolve((Invoke) e, environment);
} else if (e instanceof BinOp) {
return resolve((BinOp) e, environment);
} else if (e instanceof NaryOp) {
return resolve((NaryOp) e, environment);
} else if (e instanceof RecordGen) {
return resolve((RecordGen) e, environment);
} else if (e instanceof RecordAccess) {
return resolve((RecordAccess) e, environment);
} else if (e instanceof DictionaryGen) {
return resolve((DictionaryGen) e, environment);
} else if (e instanceof TupleGen) {
return resolve((TupleGen) e, environment);
} else {
syntaxError("unknown expression encountered", filename, e);
}
} catch (SyntaxError se) {
throw se;
} catch (Exception ex) {
syntaxError("internal failure", filename, e, ex);
}
return null;
}
protected Type resolve(Constant c, HashMap<String,Type> environment) {
Object v = c.value;
if (v instanceof Boolean) {
return Type.T_BOOL;
} else if (v instanceof Character) {
return Type.T_CHAR;
} else if (v instanceof Integer) {
return Type.T_INT;
} else if (v instanceof Double) {
return Type.T_REAL;
} else if (v instanceof String) {
return Type.T_STRING;
}
syntaxError("unknown constant encountered (" + v.getClass().getName() + ")", filename, c);
return null;
}
protected Type resolve(FunConst c, HashMap<String,Type> environment)
throws ResolveError {
ModuleID mid = c.attribute(Attribute.Module.class).module;
ArrayList<Type> types = new ArrayList<Type>();
for (UnresolvedType ut : c.paramTypes) {
types.add(resolve(ut));
}
NameID nid = new NameID(mid, c.name);
return bindFunction(nid, types, c);
}
protected Type resolve(Variable v, HashMap<String,Type> environment)
throws ResolveError {
Type v_t = environment.get(v.var);
if (v_t != null) {
return v_t;
}
// Not a variable, but could be a constant
Attribute.Module mattr = v.attribute(Attribute.Module.class);
if (mattr != null) {
Expr constant = constants.get(new NameID(mattr.module, v.var));
return resolve(constant, environment);
}
syntaxError("variable not defined", filename, v);
return null;
}
protected Type resolve(Invoke ivk, HashMap<String,Type> environment) {
// First, we look for a local variable with the matching name
Type t = environment.get(ivk.name);
if (t instanceof Type.Fun) {
Type.Fun ft = (Type.Fun) t;
if (ivk.arguments.size() != ft.params.size()) {
syntaxError("incorrect arguments for function call", filename, ivk);
}
for (int i = 0; i != ft.params.size(); ++i) {
Expr arg = ivk.arguments.get(i);
Type pt = ft.params.get(i);
Type at = resolve(arg, environment);
checkSubtype(pt, at, arg);
}
ivk.indirect = true;
return ft.ret;
} else {
ArrayList<Type> types = new ArrayList<Type>();
for (Expr arg : ivk.arguments) {
Type arg_t = resolve(arg, environment);
types.add(arg_t);
}
// Second, we assume it's not a local variable and look outside the
// scope.
try {
// FIXME: when putting name spacing back in, we'll need to fix this.
ModuleID mid = ivk.attribute(Attribute.Module.class).module;
NameID nid = new NameID(mid, ivk.name);
Type.Fun funtype = bindFunction(nid, types, ivk);
// now, update the invoke
ivk.attributes().add(new Attribute.FunType(funtype));
return funtype.ret;
} catch (ResolveError ex) {
syntaxError(ex.getMessage(), filename, ivk);
return null; // unreachable
}
}
}
/**
* Bind function is responsible for determining the true type of a method or
* function being invoked. To do this, it must find the function/method with
* the most precise type that matches the argument types. *
*
* @param nid
* @param receiver
* @param paramTypes
* @param elem
* @return
* @throws ResolveError
*/
protected Type.Fun bindFunction(NameID nid, List<Type> paramTypes,
SyntacticElement elem) throws ResolveError {
Type receiver = null; // dummy
Type.Fun target = Type.T_FUN(null, Type.T_ANY, paramTypes);
Type.Fun candidate = null;
List<Type.Fun> targets = lookupMethod(nid);
for (Type.Fun ft : targets) {
Type funrec = ft.receiver;
if (receiver == funrec
|| (receiver != null && funrec != null && Type.isSubtype(funrec,
receiver))) {
// receivers match up OK ...
if (ft.params.size() == paramTypes.size() && paramSubtypes(ft, target)
&& (candidate == null || paramSubtypes(candidate, ft))) {
candidate = ft;
}
}
}
// Check whether we actually found something. If not, print a useful
// error message.
if (candidate == null) {
String msg = "no match for " + nid.name() + parameterString(paramTypes);
boolean firstTime = true;
int count = 0;
for (Type.Fun ft : targets) {
if (firstTime) {
msg += "\n\tfound: " + nid.name() + parameterString(ft.params);
} else {
msg += "\n\tand: " + nid.name() + parameterString(ft.params);
}
if (++count < targets.size()) {
msg += ",";
}
}
syntaxError(msg + "\n", filename, elem);
}
return candidate;
}
private boolean paramSubtypes(Type.Fun f1, Type.Fun f2) {
List<Type> f1_params = f1.params;
List<Type> f2_params = f2.params;
if (f1_params.size() == f2_params.size()) {
for (int i = 0; i != f1_params.size(); ++i) {
if (!Type.isSubtype(f1_params.get(i), f2_params.get(i))) {
return false;
}
}
return true;
}
return false;
}
private String parameterString(List<Type> paramTypes) {
String paramStr = "(";
boolean firstTime = true;
for (Type t : paramTypes) {
if (!firstTime) {
paramStr += ",";
}
firstTime = false;
paramStr += Type.toShortString(t);
}
return paramStr + ")";
}
protected List<Type.Fun> lookupMethod(NameID nid) throws ResolveError {
List<Type.Fun> matches = functions.get(nid);
if (matches == null) {
Module m = loader.loadModule(nid.module());
List<FunDecl> fmatches = m.functions(nid.name());
matches = new ArrayList<Type.Fun>();
for (FunDecl fd : fmatches) {
partResolve(m.id(), fd);
matches.add(fd.attribute(Attribute.FunType.class).type);
}
}
return matches;
}
protected Type resolve(UnOp uop, HashMap<String,Type> environment) throws ResolveError {
Type t = resolve(uop.mhs, environment);
switch (uop.op) {
case LENGTHOF:
checkSubtype(Type.T_SET(Type.T_ANY), t, uop.mhs);
Type.SetList sl = (Type.SetList) t;
return sl.element();
case NEG:
checkSubtype(Type.T_REAL, t, uop.mhs);
return t;
case NOT:
checkSubtype(Type.T_BOOL, t, uop.mhs);
return t;
}
syntaxError("unknown unary expression encountered", filename, uop);
return null;
}
protected Type resolve(BinOp bop, HashMap<String,Type> environment)
throws ResolveError {
Type lhs_t = resolve(bop.lhs, environment);
Type rhs_t = resolve(bop.rhs, environment);
// FIXME: really need to add coercions somehow
switch (bop.op) {
case ADD: {
if (Type.isSubtype(Type.T_SET(Type.T_ANY), lhs_t)
|| Type.isSubtype(Type.T_SET(Type.T_ANY), rhs_t)) {
checkSubtype(Type.T_SET(Type.T_ANY), lhs_t, bop.lhs);
checkSubtype(Type.T_SET(Type.T_ANY), rhs_t, bop.rhs);
// need to update operation
bop.op = BOp.UNION;
return Type.leastUpperBound(lhs_t, rhs_t);
}
}
case SUB:
case DIV:
case MUL: {
checkSubtype(Type.T_REAL, lhs_t, bop.lhs);
checkSubtype(Type.T_REAL, rhs_t, bop.rhs);
return Type.leastUpperBound(lhs_t, rhs_t);
}
case EQ:
case NEQ: {
Type lub = Type.greatestLowerBound(lhs_t, rhs_t);
if(lub == Type.T_VOID) {
syntaxError("incomparable types: " + lhs_t + ", " + rhs_t,filename,bop);
}
return Type.T_BOOL;
}
case LT:
case LTEQ:
case GT:
case GTEQ: {
checkSubtype(Type.T_REAL, lhs_t, bop.lhs);
checkSubtype(Type.T_REAL, rhs_t, bop.rhs);
return Type.T_BOOL;
}
case AND:
case OR: {
checkSubtype(Type.T_BOOL, lhs_t, bop.lhs);
checkSubtype(Type.T_BOOL, rhs_t, bop.rhs);
return Type.T_BOOL;
}
}
syntaxError("unknown binary expression encountered", filename, bop);
return null;
}
protected Type resolve(NaryOp nop, HashMap<String,Type> environment) {
if (nop.op == NOp.SUBLIST) {
Expr src = nop.arguments.get(0);
Expr start = nop.arguments.get(1);
Expr end = nop.arguments.get(2);
Type src_t = resolve(src, environment);
Type start_t = resolve(start, environment);
Type end_t = resolve(end, environment);
checkSubtype(Type.T_LIST(Type.T_ANY), src_t, src);
checkSubtype(Type.T_INT, start_t, start);
checkSubtype(Type.T_INT, end_t, end);
return src_t;
} else {
// Must be a set or list generator
Type lub = Type.T_VOID;
for (Expr e : nop.arguments) {
Type t = resolve(e, environment);
lub = Type.leastUpperBound(lub, t);
}
if (nop.op == NOp.SETGEN) {
return Type.T_SET(lub);
} else {
return Type.T_LIST(lub);
}
}
}
protected Type resolve(RecordGen rg, HashMap<String,Type> environment) {
HashMap<String, Type> types = new HashMap<String, Type>();
for (Map.Entry<String, Expr> f : rg.fields.entrySet()) {
Type t = resolve(f.getValue(), environment);
types.put(f.getKey(), t);
}
return Type.T_RECORD(types);
}
protected Type resolve(RecordAccess ra, HashMap<String,Type> environment) {
Type src = resolve(ra.lhs, environment);
Type.Record ert = Type.effectiveRecordType(src);
if (ert == null) {
syntaxError("expected record type, got " + src, filename, ra.lhs);
}
Type t = ert.types.get(ra.name);
if (t == null) {
syntaxError("no such field in type: " + ert, filename, ra);
}
return t;
}
protected Type resolve(DictionaryGen rg, HashMap<String,Type> environment) {
Type keyType = Type.T_VOID;
Type valueType = Type.T_VOID;
for (Pair<Expr, Expr> p : rg.pairs) {
Type kt = resolve(p.first(), environment);
Type vt = resolve(p.second(), environment);
keyType = Type.leastUpperBound(keyType, kt);
valueType = Type.leastUpperBound(valueType, vt);
}
return Type.T_DICTIONARY(keyType, valueType);
}
protected Type resolve(Access ra, HashMap<String,Type> environment) {
Type src = resolve(ra.src, environment);
Type idx = resolve(ra.index, environment);
Type.Dictionary edt = Type.effectiveDictionaryType(src);
if (edt == null) {
syntaxError("expected dictionary or list type, got " + src, filename,
ra.src);
}
checkSubtype(edt.key, idx, ra.index);
return edt.value;
}
protected Type resolve(TupleGen rg, HashMap<String,Type> environment) {
HashMap<String, Type> types = new HashMap<String, Type>();
// FIXME: add proper support for tuple types.
int idx = 0;
for (Expr e : rg.fields) {
Type t = resolve(e, environment);
types.put("$" + idx++, t);
}
return Type.T_RECORD(types);
}
}
| src/ext/wyone/core/TypeChecker.java | Minor updates working on type checker.
| src/ext/wyone/core/TypeChecker.java | Minor updates working on type checker. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.