repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
raviagarwal7/buck
src/com/facebook/buck/model/ImmediateDirectoryBuildTargetPattern.java
2490
/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.model; import com.facebook.buck.io.MorePaths; import com.google.common.base.Objects; import java.nio.file.Path; import javax.annotation.Nullable; /** * A pattern matches build targets that are all in the same directory. */ public class ImmediateDirectoryBuildTargetPattern implements BuildTargetPattern { private final Path cellPath; private final Path pathWithinCell; /** * @param pathWithinCell The base path of all valid build targets. It is expected to * match the value returned from a {@link BuildTarget#getBasePath()} call. */ public ImmediateDirectoryBuildTargetPattern(Path cellPath, Path pathWithinCell) { this.cellPath = cellPath; this.pathWithinCell = pathWithinCell; } /** * @return true if the given target not null and has the same basePathWithSlash, * otherwise return false. */ @Override public boolean apply(@Nullable BuildTarget target) { if (target == null) { return false; } return Objects.equal(this.cellPath, target.getCellPath()) && Objects.equal(this.pathWithinCell, target.getBasePath()); } @Override public String getCellFreeRepresentation() { return "//" + MorePaths.pathWithUnixSeparators(pathWithinCell) + ":"; } @Override public boolean equals(Object o) { if (!(o instanceof ImmediateDirectoryBuildTargetPattern)) { return false; } ImmediateDirectoryBuildTargetPattern that = (ImmediateDirectoryBuildTargetPattern) o; return Objects.equal(this.cellPath, that.cellPath) && Objects.equal(this.pathWithinCell, that.pathWithinCell); } @Override public int hashCode() { return Objects.hashCode(cellPath, pathWithinCell); } @Override public String toString() { return "+" + cellPath.getFileName().toString() + "//" + pathWithinCell.toString() + ":"; } }
apache-2.0
dhalperi/beam
sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/MapElements.java
5738
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.transforms; import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.Nullable; import org.apache.beam.sdk.transforms.display.DisplayData; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.TypeDescriptor; /** * {@code PTransform}s for mapping a simple function over the elements of a {@link PCollection}. */ public class MapElements<InputT, OutputT> extends PTransform<PCollection<? extends InputT>, PCollection<OutputT>> { /** * Temporarily stores the argument of {@link #into(TypeDescriptor)} until combined with the * argument of {@link #via(SerializableFunction)} into the fully-specified {@link #fn}. Stays null * if constructed using {@link #via(SimpleFunction)} directly. */ @Nullable private final transient TypeDescriptor<OutputT> outputType; /** * Non-null on a fully specified transform - is null only when constructed using {@link * #into(TypeDescriptor)}, until the fn is specified using {@link #via(SerializableFunction)}. */ @Nullable private final SimpleFunction<InputT, OutputT> fn; private final DisplayData.ItemSpec<?> fnClassDisplayData; private MapElements( @Nullable SimpleFunction<InputT, OutputT> fn, @Nullable TypeDescriptor<OutputT> outputType, @Nullable Class<?> fnClass) { this.fn = fn; this.outputType = outputType; this.fnClassDisplayData = DisplayData.item("mapFn", fnClass).withLabel("Map Function"); } /** * For a {@code SimpleFunction<InputT, OutputT>} {@code fn}, returns a {@code PTransform} that * takes an input {@code PCollection<InputT>} and returns a {@code PCollection<OutputT>} * containing {@code fn.apply(v)} for every element {@code v} in the input. * * <p>This overload is intended primarily for use in Java 7. In Java 8, the overload * {@link #via(SerializableFunction)} supports use of lambda for greater concision. * * <p>Example of use in Java 7: * <pre>{@code * PCollection<String> words = ...; * PCollection<Integer> wordsPerLine = words.apply(MapElements.via( * new SimpleFunction<String, Integer>() { * public Integer apply(String word) { * return word.length(); * } * })); * }</pre> */ public static <InputT, OutputT> MapElements<InputT, OutputT> via( final SimpleFunction<InputT, OutputT> fn) { return new MapElements<>(fn, null, fn.getClass()); } /** * Returns a new {@link MapElements} transform with the given type descriptor for the output * type, but the mapping function yet to be specified using {@link #via(SerializableFunction)}. */ public static <OutputT> MapElements<?, OutputT> into(final TypeDescriptor<OutputT> outputType) { return new MapElements<>(null, outputType, null); } /** * For a {@code SerializableFunction<InputT, OutputT>} {@code fn} and output type descriptor, * returns a {@code PTransform} that takes an input {@code PCollection<InputT>} and returns a * {@code PCollection<OutputT>} containing {@code fn.apply(v)} for every element {@code v} in the * input. * * <p>Example of use in Java 8: * * <pre>{@code * PCollection<Integer> wordLengths = words.apply( * MapElements.into(TypeDescriptors.integers()) * .via((String word) -> word.length())); * }</pre> * * <p>In Java 7, the overload {@link #via(SimpleFunction)} is more concise as the output type * descriptor need not be provided. */ public <NewInputT> MapElements<NewInputT, OutputT> via( SerializableFunction<NewInputT, OutputT> fn) { return new MapElements<>( SimpleFunction.fromSerializableFunctionWithOutputType(fn, outputType), null, fn.getClass()); } @Override public PCollection<OutputT> expand(PCollection<? extends InputT> input) { checkNotNull(fn, "Must specify a function on MapElements using .via()"); return input.apply( "Map", ParDo.of( new DoFn<InputT, OutputT>() { @ProcessElement public void processElement(ProcessContext c) { c.output(fn.apply(c.element())); } @Override public void populateDisplayData(DisplayData.Builder builder) { builder.delegate(MapElements.this); } @Override public TypeDescriptor<InputT> getInputTypeDescriptor() { return fn.getInputTypeDescriptor(); } @Override public TypeDescriptor<OutputT> getOutputTypeDescriptor() { return fn.getOutputTypeDescriptor(); } })); } @Override public void populateDisplayData(DisplayData.Builder builder) { super.populateDisplayData(builder); builder .include("mapFn", fn) .add(fnClassDisplayData); } }
apache-2.0
ern/elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectProcessFactory.java
2047
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.ml.job.process.autodetect; import org.elasticsearch.xpack.core.ml.job.config.Job; import org.elasticsearch.xpack.ml.job.process.autodetect.params.AutodetectParams; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; /** * Factory interface for creating implementations of {@link AutodetectProcess} */ public interface AutodetectProcessFactory { /** * Create an implementation of {@link AutodetectProcess} * * @param job Job configuration for the analysis process * @param autodetectParams Autodetect parameters including The model snapshot to restore from * and the quantiles to push to the native process * @param executorService Executor service used to start the async tasks a job needs to operate the analytical process * @param onProcessCrash Callback to execute if the process stops unexpectedly * @return The process */ default AutodetectProcess createAutodetectProcess(Job job, AutodetectParams autodetectParams, ExecutorService executorService, Consumer<String> onProcessCrash) { return createAutodetectProcess(job.getId(), job, autodetectParams, executorService, onProcessCrash); } AutodetectProcess createAutodetectProcess(String pipelineId, Job job, AutodetectParams autodetectParams, ExecutorService executorService, Consumer<String> onProcessCrash); }
apache-2.0
jirmauritz/perun
perun-base/src/main/java/cz/metacentrum/perun/core/api/exceptions/rt/FacilityNotExistsRuntimeException.java
607
package cz.metacentrum.perun.core.api.exceptions.rt; @SuppressWarnings("serial") public class FacilityNotExistsRuntimeException extends EntityNotExistsRuntimeException { private String userId; public FacilityNotExistsRuntimeException() { super(); } public FacilityNotExistsRuntimeException(String userId) { super(); this.userId = userId; } public FacilityNotExistsRuntimeException(Throwable cause) { super(cause); } public FacilityNotExistsRuntimeException(Throwable cause, String userId) { super(cause); this.userId = userId; } public String getUserId() { return userId; } }
bsd-2-clause
OpenGrabeso/jmonkeyengine
jme3-networking/src/main/java/com/jme3/network/service/rpc/RpcConnection.java
10206
/* * Copyright (c) 2015 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.network.service.rpc; import com.jme3.network.MessageConnection; import com.jme3.network.service.rpc.msg.RpcCallMessage; import com.jme3.network.service.rpc.msg.RpcResponseMessage; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; /** * Wraps a message connection to provide RPC call support. This * is used internally by the RpcClientService and RpcHostedService to manage * network messaging. * * @author Paul Speed */ public class RpcConnection { static final Logger log = Logger.getLogger(RpcConnection.class.getName()); /** * The underlying connection upon which RPC call messages are sent * and RPC response messages are received. It can be a Client or * a HostedConnection depending on the mode of the RPC service. */ private MessageConnection connection; /** * The objectId index of RpcHandler objects that are used to perform the * RPC calls for a particular object. */ private Map<Short, RpcHandler> handlers = new ConcurrentHashMap<Short, RpcHandler>(); /** * Provides unique messages IDs for outbound synchronous call * messages. These are then used in the responses index to * locate the proper ResponseHolder objects. */ private AtomicLong sequenceNumber = new AtomicLong(); /** * Tracks the ResponseHolder objects for sent message IDs. When the * response is received, the appropriate handler is found here and the * response or error set, thus releasing the waiting caller. */ private Map<Long, ResponseHolder> responses = new ConcurrentHashMap<Long, ResponseHolder>(); /** * Creates a new RpcConnection for the specified network connection. */ public RpcConnection( MessageConnection connection ) { this.connection = connection; } /** * Clears any pending synchronous calls causing them to * throw an exception with the message "Closing connection". */ public void close() { // Let any pending waits go free for( ResponseHolder holder : responses.values() ) { holder.release(); } } /** * Performs a remote procedure call with the specified arguments and waits * for the response. Both the outbound message and inbound response will * be sent on the specified channel. */ public Object callAndWait( byte channel, short objId, short procId, Object... args ) { RpcCallMessage msg = new RpcCallMessage(sequenceNumber.getAndIncrement(), channel, objId, procId, args); // Need to register an object so we can wait for the response. // ...before we send it. Just in case. ResponseHolder holder = new ResponseHolder(msg); responses.put(msg.getMessageId(), holder); if( log.isLoggable(Level.FINEST) ) { log.log(Level.FINEST, "Sending:{0} on channel:{1}", new Object[]{msg, channel}); } // Prevent non-async messages from being send as UDP // because there is a high probabilty that this would block // forever waiting for a response. For async calls it's ok // so it doesn't do the check. if( channel >= 0 ) { connection.send(channel, msg); } else { connection.send(msg); } return holder.getResponse(); } /** * Performs a remote procedure call with the specified arguments but does * not wait for a response. The outbound message is sent on the specified channel. * There is no inbound response message. */ public void callAsync( byte channel, short objId, short procId, Object... args ) { RpcCallMessage msg = new RpcCallMessage(-1, channel, objId, procId, args); if( log.isLoggable(Level.FINEST) ) { log.log(Level.FINEST, "Sending:{0} on channel:{1}", new Object[]{msg, channel}); } connection.send(channel, msg); } /** * Register a handler that can be called by the other end * of the connection using the specified object ID. Only one * handler per object ID can be registered at any given time, * though the same handler can be registered for multiple object * IDs. */ public void registerHandler( short objId, RpcHandler handler ) { handlers.put(objId, handler); } /** * Removes a previously registered handler for the specified * object ID. */ public void removeHandler( short objId, RpcHandler handler ) { RpcHandler removing = handlers.get(objId); if( handler != removing ) { throw new IllegalArgumentException("Handler not registered for object ID:" + objId + ", handler:" + handler ); } handlers.remove(objId); } protected void send( byte channel, RpcResponseMessage msg ) { if( channel >= 0 ) { connection.send(channel, msg); } else { connection.send(msg); } } /** * Called internally when an RpcCallMessage is received from * the remote connection. */ public void handleMessage( RpcCallMessage msg ) { if( log.isLoggable(Level.FINEST) ) { log.log(Level.FINEST, "handleMessage({0})", msg); } RpcHandler handler = handlers.get(msg.getObjectId()); try { if( handler == null ) { throw new RuntimeException("Handler not found for objectID:" + msg.getObjectId()); } Object result = handler.call(this, msg.getObjectId(), msg.getProcedureId(), msg.getArguments()); if( !msg.isAsync() ) { send(msg.getChannel(), new RpcResponseMessage(msg.getMessageId(), result)); } } catch( Exception e ) { if( !msg.isAsync() ) { send(msg.getChannel(), new RpcResponseMessage(msg.getMessageId(), e)); } else { log.log(Level.SEVERE, "Error invoking async call for:" + msg, e); } } } /** * Called internally when an RpcResponseMessage is received from * the remote connection. */ public void handleMessage( RpcResponseMessage msg ) { if( log.isLoggable(Level.FINEST) ) { log.log(Level.FINEST, "handleMessage({0})", msg); } ResponseHolder holder = responses.remove(msg.getMessageId()); if( holder == null ) { return; } holder.setResponse(msg); } /** * Sort of like a Future, holds a locked reference to a response * until the remote call has completed and returned a response. */ private class ResponseHolder { private Object response; private String error; private RpcCallMessage msg; boolean received = false; public ResponseHolder( RpcCallMessage msg ) { this.msg = msg; } public synchronized void setResponse( RpcResponseMessage msg ) { this.response = msg.getResult(); this.error = msg.getError(); this.received = true; notifyAll(); } public synchronized Object getResponse() { try { while(!received) { wait(); } } catch( InterruptedException e ) { throw new RuntimeException("Interrupted waiting for respone to:" + msg, e); } if( error != null ) { throw new RuntimeException("Error calling remote procedure:" + msg + "\n" + error); } return response; } public synchronized void release() { if( received ) { return; } // Else signal an error for the callers this.error = "Closing connection"; this.received = true; } } }
bsd-3-clause
carsonreinke/mozu-java-sdk
src/main/java/com/mozu/api/security/AuthenticationProfile.java
1463
package com.mozu.api.security; import java.util.List; import com.mozu.api.contracts.core.UserProfile; import com.mozu.api.contracts.customer.CustomerAccount; public class AuthenticationProfile { private AuthTicket authTicket; private List<Scope> authorizedScopes; private Scope activeScope; private UserProfile userProfile; public AuthenticationProfile () { } public AuthenticationProfile (AuthTicket authTicket, List<Scope> authorizedScope, Scope activeScope, UserProfile userProfile) { this.authTicket = authTicket; this.authorizedScopes = authorizedScope; this.activeScope = activeScope; this.userProfile = userProfile; } public AuthTicket getAuthTicket() { return authTicket; } public void setAuthTicket(AuthTicket authTicket) { this.authTicket = authTicket; } public List<Scope> getAuthorizedScopes() { return authorizedScopes; } public void setAuthorizedScopes(List<Scope> authorizedScopes) { this.authorizedScopes = authorizedScopes; } public Scope getActiveScope() { return activeScope; } public void setActiveScope(Scope activeScope) { this.activeScope = activeScope; } public UserProfile getUserProfile() { return userProfile; } public void setUserProfile(UserProfile userProfile) { this.userProfile = userProfile; } }
mit
shiwalimohan/RLInfiniteMario
system/codecs/Java/src/org/rlcommunity/rlglue/codec/taskspec/ranges/AbstractRange.java
4976
/* * Copyright 2008 Brian Tanner * http://bt-recordbook.googlecode.com/ * brian@tannerpages.com * http://brian.tannerpages.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rlcommunity.rlglue.codec.taskspec.ranges; import java.util.StringTokenizer; /** * * @author Brian Tanner */ public abstract class AbstractRange { private String minSpecial = "NONE"; private String maxSpecial = "NONE"; private int howMany = 1; public AbstractRange(int howMany) { this.howMany = howMany; } public AbstractRange(String rangeString) { //Now get a string that has either 2 or 3 tokens ... either num low high or low high StringTokenizer rangeTokenizer = new StringTokenizer(rangeString); if (rangeTokenizer.countTokens() == 3) { howMany = Integer.parseInt(rangeTokenizer.nextToken()); } String firstHalf = rangeTokenizer.nextToken(); String secondHalf = rangeTokenizer.nextToken(); parseSpecialMin(firstHalf); if (!hasSpecialMinStatus()) { parseMin(firstHalf); } parseSpecialMax(secondHalf); if (!hasSpecialMaxStatus()) { parseMax(secondHalf); } } public int getHowMany() { return howMany; } public String getMinSpecialStatus() { return minSpecial; } public String getMaxSpecialStatus() { return maxSpecial; } protected abstract void parseMin(String minString); protected abstract void parseMax(String maxString); public boolean hasSpecialMinStatus() { return !minSpecial.equals("NONE"); } public boolean hasSpecialMaxStatus() { return !maxSpecial.equals("NONE"); } protected void parseSpecialMax(String secondHalf) { for (String thisSpecialValue : AbstractRange.specialValues) { if (secondHalf.equals(thisSpecialValue)) { maxSpecial = thisSpecialValue; } } } protected void parseSpecialMin(String firstHalf) { for (String thisSpecialValue : AbstractRange.specialValues) { if (firstHalf.equals(thisSpecialValue)) { minSpecial = thisSpecialValue; } } } public void setMaxInf() { maxSpecial = "POSINF"; } public void setMinNegInf() { minSpecial = "NEGINF"; } public void setMinUnspecified() { minSpecial = "UNSPEC"; } public void setMaxUnspecified() { maxSpecial = "UNSPEC"; } public boolean getMinInf() { return minSpecial.equals("POSINF"); } public boolean getMinNegInf() { return minSpecial.equals("NEGINF"); } public boolean getMinUnspecified() { return minSpecial.equals("UNSPEC"); } public boolean getMaxInf() { return maxSpecial.equals("POSINF"); } public boolean getMaxNegInf() { return maxSpecial.equals("NEGINF"); } public boolean getMaxUnspecified() { return maxSpecial.equals("UNSPEC"); } /** * Override this is descendant classes and only use super method if min is special. * @return The minimum value special status as a string (one of NEGINF, POSINF, UNSPEC, NONE */ public String getMinAsString() { return minSpecial; } /** * Override this is descendant classes and only use super method if max is special. * @return The maximum value special status as a string (one of NEGINF, POSINF, UNSPEC, NONE */ public String getMaxAsString() { return maxSpecial; } public String toTaskSpec() { StringBuilder SB = new StringBuilder(); SB.append(" ("); if (getHowMany() > 1) { SB.append(getHowMany()); SB.append(" "); } SB.append(getMinAsString()); SB.append(" "); SB.append(getMaxAsString()); SB.append(") "); return SB.toString(); } //wRITE A SANITY CEHCK public static final String specialValues[] = new String[]{"UNSPEC", "NEGINF", "POSINF"}; /** * Useful if a subclass has its value set after initially not being set. */ protected void setMaxSpecified() { maxSpecial = "NONE"; } /** * Useful if a subclass has its value set after initially not being set. */ protected void setMinSpecified() { minSpecial = "NONE"; } }
gpl-2.0
Puja-Mishra/Android_FreeChat
Telegram-master/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java
54869
/* * This is the source code of Telegram for Android v. 3.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2016. */ package org.telegram.ui.Adapters; import android.content.Context; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLitePreparedStatement; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.query.SearchQuery; import org.telegram.messenger.support.widget.LinearLayoutManager; import org.telegram.messenger.support.widget.RecyclerView; import org.telegram.messenger.FileLog; import org.telegram.messenger.R; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.Cells.DialogCell; import org.telegram.ui.Cells.GreySectionCell; import org.telegram.ui.Cells.HashtagSearchCell; import org.telegram.ui.Cells.HintDialogCell; import org.telegram.ui.Cells.LoadingCell; import org.telegram.ui.Cells.ProfileSearchCell; import org.telegram.ui.Components.RecyclerListView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; public class DialogsSearchAdapter extends BaseSearchAdapterRecycler { private Context mContext; private Timer searchTimer; private ArrayList<TLObject> searchResult = new ArrayList<>(); private ArrayList<CharSequence> searchResultNames = new ArrayList<>(); private ArrayList<MessageObject> searchResultMessages = new ArrayList<>(); private ArrayList<String> searchResultHashtags = new ArrayList<>(); private String lastSearchText; private int reqId = 0; private int lastReqId; private DialogsSearchAdapterDelegate delegate; private int needMessagesSearch; private boolean messagesSearchEndReached; private String lastMessagesSearchString; private int lastSearchId = 0; private int dialogsType; private ArrayList<RecentSearchObject> recentSearchObjects = new ArrayList<>(); private HashMap<Long, RecentSearchObject> recentSearchObjectsById = new HashMap<>(); private class Holder extends RecyclerView.ViewHolder { public Holder(View itemView) { super(itemView); } } private class DialogSearchResult { public TLObject object; public int date; public CharSequence name; } protected static class RecentSearchObject { TLObject object; int date; long did; } public interface DialogsSearchAdapterDelegate { void searchStateChanged(boolean searching); void didPressedOnSubDialog(int did); void needRemoveHint(int did); } private class CategoryAdapterRecycler extends RecyclerView.Adapter { public void setIndex(int value) { notifyDataSetChanged(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = new HintDialogCell(mContext); view.setLayoutParams(new RecyclerView.LayoutParams(AndroidUtilities.dp(80), AndroidUtilities.dp(100))); return new Holder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { HintDialogCell cell = (HintDialogCell) holder.itemView; TLRPC.TL_topPeer peer = SearchQuery.hints.get(position); TLRPC.TL_dialog dialog = new TLRPC.TL_dialog(); TLRPC.Chat chat = null; TLRPC.User user = null; int did = 0; if (peer.peer.user_id != 0) { did = peer.peer.user_id; user = MessagesController.getInstance().getUser(peer.peer.user_id); } else if (peer.peer.channel_id != 0) { did = -peer.peer.channel_id; chat = MessagesController.getInstance().getChat(peer.peer.channel_id); } else if (peer.peer.chat_id != 0) { did = -peer.peer.chat_id; chat = MessagesController.getInstance().getChat(peer.peer.chat_id); } cell.setTag(did); String name = ""; if (user != null) { name = ContactsController.formatName(user.first_name, user.last_name); } else if (chat != null) { name = chat.title; } cell.setDialog(did, true, name); } @Override public int getItemCount() { return SearchQuery.hints.size(); } } public DialogsSearchAdapter(Context context, int messagesSearch, int type) { mContext = context; needMessagesSearch = messagesSearch; dialogsType = type; loadRecentSearch(); SearchQuery.loadHints(true); } public void setDelegate(DialogsSearchAdapterDelegate delegate) { this.delegate = delegate; } public boolean isMessagesSearchEndReached() { return messagesSearchEndReached; } public void loadMoreSearchMessages() { searchMessagesInternal(lastMessagesSearchString); } public String getLastSearchString() { return lastMessagesSearchString; } private void searchMessagesInternal(final String query) { if (needMessagesSearch == 0 || (lastMessagesSearchString == null || lastMessagesSearchString.length() == 0) && (query == null || query.length() == 0)) { return; } if (reqId != 0) { ConnectionsManager.getInstance().cancelRequest(reqId, true); reqId = 0; } if (query == null || query.length() == 0) { searchResultMessages.clear(); lastReqId = 0; lastMessagesSearchString = null; notifyDataSetChanged(); if (delegate != null) { delegate.searchStateChanged(false); } return; } final TLRPC.TL_messages_searchGlobal req = new TLRPC.TL_messages_searchGlobal(); req.limit = 20; req.q = query; if (lastMessagesSearchString != null && query.equals(lastMessagesSearchString) && !searchResultMessages.isEmpty()) { MessageObject lastMessage = searchResultMessages.get(searchResultMessages.size() - 1); req.offset_id = lastMessage.getId(); req.offset_date = lastMessage.messageOwner.date; int id; if (lastMessage.messageOwner.to_id.channel_id != 0) { id = -lastMessage.messageOwner.to_id.channel_id; } else if (lastMessage.messageOwner.to_id.chat_id != 0) { id = -lastMessage.messageOwner.to_id.chat_id; } else { id = lastMessage.messageOwner.to_id.user_id; } req.offset_peer = MessagesController.getInputPeer(id); } else { req.offset_date = 0; req.offset_id = 0; req.offset_peer = new TLRPC.TL_inputPeerEmpty(); } lastMessagesSearchString = query; final int currentReqId = ++lastReqId; if (delegate != null) { delegate.searchStateChanged(true); } reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (currentReqId == lastReqId) { if (error == null) { TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); MessagesController.getInstance().putUsers(res.users, false); MessagesController.getInstance().putChats(res.chats, false); if (req.offset_id == 0) { searchResultMessages.clear(); } for (int a = 0; a < res.messages.size(); a++) { TLRPC.Message message = res.messages.get(a); searchResultMessages.add(new MessageObject(message, null, false)); long dialog_id = MessageObject.getDialogId(message); ConcurrentHashMap<Long, Integer> read_max = message.out ? MessagesController.getInstance().dialogs_read_outbox_max : MessagesController.getInstance().dialogs_read_inbox_max; Integer value = read_max.get(dialog_id); if (value == null) { value = MessagesStorage.getInstance().getDialogReadMax(message.out, dialog_id); read_max.put(dialog_id, value); } message.unread = value < message.id; } messagesSearchEndReached = res.messages.size() != 20; notifyDataSetChanged(); } } if (delegate != null) { delegate.searchStateChanged(false); } reqId = 0; } }); } }, ConnectionsManager.RequestFlagFailOnServerErrors); } public boolean hasRecentRearch() { return !recentSearchObjects.isEmpty() || !SearchQuery.hints.isEmpty(); } public boolean isRecentSearchDisplayed() { return needMessagesSearch != 2 && (lastSearchText == null || lastSearchText.length() == 0) && (!recentSearchObjects.isEmpty() || !SearchQuery.hints.isEmpty()); } public void loadRecentSearch() { MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { try { SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized("SELECT did, date FROM search_recent WHERE 1"); ArrayList<Integer> usersToLoad = new ArrayList<>(); ArrayList<Integer> chatsToLoad = new ArrayList<>(); ArrayList<Integer> encryptedToLoad = new ArrayList<>(); ArrayList<TLRPC.User> encUsers = new ArrayList<>(); final ArrayList<RecentSearchObject> arrayList = new ArrayList<>(); final HashMap<Long, RecentSearchObject> hashMap = new HashMap<>(); while (cursor.next()) { long did = cursor.longValue(0); boolean add = false; int lower_id = (int) did; int high_id = (int) (did >> 32); if (lower_id != 0) { if (high_id == 1) { if (dialogsType == 0 && !chatsToLoad.contains(lower_id)) { chatsToLoad.add(lower_id); add = true; } } else { if (lower_id > 0) { if (dialogsType != 2 && !usersToLoad.contains(lower_id)) { usersToLoad.add(lower_id); add = true; } } else { if (!chatsToLoad.contains(-lower_id)) { chatsToLoad.add(-lower_id); add = true; } } } } else if (dialogsType == 0) { if (!encryptedToLoad.contains(high_id)) { encryptedToLoad.add(high_id); add = true; } } if (add) { RecentSearchObject recentSearchObject = new RecentSearchObject(); recentSearchObject.did = did; recentSearchObject.date = cursor.intValue(1); arrayList.add(recentSearchObject); hashMap.put(recentSearchObject.did, recentSearchObject); } } cursor.dispose(); ArrayList<TLRPC.User> users = new ArrayList<>(); if (!encryptedToLoad.isEmpty()) { ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<>(); MessagesStorage.getInstance().getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, usersToLoad); for (int a = 0; a < encryptedChats.size(); a++) { hashMap.get((long) encryptedChats.get(a).id << 32).object = encryptedChats.get(a); } } if (!chatsToLoad.isEmpty()) { ArrayList<TLRPC.Chat> chats = new ArrayList<>(); MessagesStorage.getInstance().getChatsInternal(TextUtils.join(",", chatsToLoad), chats); for (int a = 0; a < chats.size(); a++) { TLRPC.Chat chat = chats.get(a); long did; if (chat.id > 0) { did = -chat.id; } else { did = AndroidUtilities.makeBroadcastId(chat.id); } if (chat.migrated_to != null) { RecentSearchObject recentSearchObject = hashMap.remove(did); if (recentSearchObject != null) { arrayList.remove(recentSearchObject); } } else { hashMap.get(did).object = chat; } } } if (!usersToLoad.isEmpty()) { MessagesStorage.getInstance().getUsersInternal(TextUtils.join(",", usersToLoad), users); for (int a = 0; a < users.size(); a++) { TLRPC.User user = users.get(a); RecentSearchObject recentSearchObject = hashMap.get((long) user.id); if (recentSearchObject != null) { recentSearchObject.object = user; } } } Collections.sort(arrayList, new Comparator<RecentSearchObject>() { @Override public int compare(RecentSearchObject lhs, RecentSearchObject rhs) { if (lhs.date < rhs.date) { return 1; } else if (lhs.date > rhs.date) { return -1; } else { return 0; } } }); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { setRecentSearch(arrayList, hashMap); } }); } catch (Exception e) { FileLog.e("tmessages", e); } } }); } public void putRecentSearch(final long did, TLObject object) { RecentSearchObject recentSearchObject = recentSearchObjectsById.get(did); if (recentSearchObject == null) { recentSearchObject = new RecentSearchObject(); recentSearchObjectsById.put(did, recentSearchObject); } else { recentSearchObjects.remove(recentSearchObject); } recentSearchObjects.add(0, recentSearchObject); recentSearchObject.did = did; recentSearchObject.object = object; recentSearchObject.date = (int) (System.currentTimeMillis() / 1000); notifyDataSetChanged(); MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { try { SQLitePreparedStatement state = MessagesStorage.getInstance().getDatabase().executeFast("REPLACE INTO search_recent VALUES(?, ?)"); state.requery(); state.bindLong(1, did); state.bindInteger(2, (int) (System.currentTimeMillis() / 1000)); state.step(); state.dispose(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); } public void clearRecentSearch() { recentSearchObjectsById = new HashMap<>(); recentSearchObjects = new ArrayList<>(); notifyDataSetChanged(); MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { try { MessagesStorage.getInstance().getDatabase().executeFast("DELETE FROM search_recent WHERE 1").stepThis().dispose(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); } private void setRecentSearch(ArrayList<RecentSearchObject> arrayList, HashMap<Long, RecentSearchObject> hashMap) { recentSearchObjects = arrayList; recentSearchObjectsById = hashMap; for (int a = 0; a < recentSearchObjects.size(); a++) { RecentSearchObject recentSearchObject = recentSearchObjects.get(a); if (recentSearchObject.object instanceof TLRPC.User) { MessagesController.getInstance().putUser((TLRPC.User) recentSearchObject.object, true); } else if (recentSearchObject.object instanceof TLRPC.Chat) { MessagesController.getInstance().putChat((TLRPC.Chat) recentSearchObject.object, true); } else if (recentSearchObject.object instanceof TLRPC.EncryptedChat) { MessagesController.getInstance().putEncryptedChat((TLRPC.EncryptedChat) recentSearchObject.object, true); } } notifyDataSetChanged(); } private void searchDialogsInternal(final String query, final int searchId) { if (needMessagesSearch == 2) { return; } MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { try { String search1 = query.trim().toLowerCase(); if (search1.length() == 0) { lastSearchId = -1; updateSearchResults(new ArrayList<TLObject>(), new ArrayList<CharSequence>(), new ArrayList<TLRPC.User>(), lastSearchId); return; } String search2 = LocaleController.getInstance().getTranslitString(search1); if (search1.equals(search2) || search2.length() == 0) { search2 = null; } String search[] = new String[1 + (search2 != null ? 1 : 0)]; search[0] = search1; if (search2 != null) { search[1] = search2; } ArrayList<Integer> usersToLoad = new ArrayList<>(); ArrayList<Integer> chatsToLoad = new ArrayList<>(); ArrayList<Integer> encryptedToLoad = new ArrayList<>(); ArrayList<TLRPC.User> encUsers = new ArrayList<>(); int resultCount = 0; HashMap<Long, DialogSearchResult> dialogsResult = new HashMap<>(); SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized("SELECT did, date FROM dialogs ORDER BY date DESC LIMIT 400"); while (cursor.next()) { long id = cursor.longValue(0); DialogSearchResult dialogSearchResult = new DialogSearchResult(); dialogSearchResult.date = cursor.intValue(1); dialogsResult.put(id, dialogSearchResult); int lower_id = (int) id; int high_id = (int) (id >> 32); if (lower_id != 0) { if (high_id == 1) { if (dialogsType == 0 && !chatsToLoad.contains(lower_id)) { chatsToLoad.add(lower_id); } } else { if (lower_id > 0) { if (dialogsType != 2 && !usersToLoad.contains(lower_id)) { usersToLoad.add(lower_id); } } else { if (!chatsToLoad.contains(-lower_id)) { chatsToLoad.add(-lower_id); } } } } else if (dialogsType == 0) { if (!encryptedToLoad.contains(high_id)) { encryptedToLoad.add(high_id); } } } cursor.dispose(); if (!usersToLoad.isEmpty()) { cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, status, name FROM users WHERE uid IN(%s)", TextUtils.join(",", usersToLoad))); while (cursor.next()) { String name = cursor.stringValue(2); String tName = LocaleController.getInstance().getTranslitString(name); if (name.equals(tName)) { tName = null; } String username = null; int usernamePos = name.lastIndexOf(";;;"); if (usernamePos != -1) { username = name.substring(usernamePos + 3); } int found = 0; for (String q : search) { if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) { found = 1; } else if (username != null && username.startsWith(q)) { found = 2; } if (found != 0) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { TLRPC.User user = TLRPC.User.TLdeserialize(data, data.readInt32(false), false); data.reuse(); DialogSearchResult dialogSearchResult = dialogsResult.get((long) user.id); if (user.status != null) { user.status.expires = cursor.intValue(1); } if (found == 1) { dialogSearchResult.name = AndroidUtilities.generateSearchName(user.first_name, user.last_name, q); } else { dialogSearchResult.name = AndroidUtilities.generateSearchName("@" + user.username, null, "@" + q); } dialogSearchResult.object = user; resultCount++; } break; } } } cursor.dispose(); } if (!chatsToLoad.isEmpty()) { cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, name FROM chats WHERE uid IN(%s)", TextUtils.join(",", chatsToLoad))); while (cursor.next()) { String name = cursor.stringValue(1); String tName = LocaleController.getInstance().getTranslitString(name); if (name.equals(tName)) { tName = null; } for (String q : search) { if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { TLRPC.Chat chat = TLRPC.Chat.TLdeserialize(data, data.readInt32(false), false); data.reuse(); if (!(chat == null || chat.deactivated || ChatObject.isChannel(chat) && ChatObject.isNotInChat(chat))) { long dialog_id; if (chat.id > 0) { dialog_id = -chat.id; } else { dialog_id = AndroidUtilities.makeBroadcastId(chat.id); } DialogSearchResult dialogSearchResult = dialogsResult.get(dialog_id); dialogSearchResult.name = AndroidUtilities.generateSearchName(chat.title, null, q); dialogSearchResult.object = chat; resultCount++; } } break; } } } cursor.dispose(); } if (!encryptedToLoad.isEmpty()) { cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT q.data, u.name, q.user, q.g, q.authkey, q.ttl, u.data, u.status, q.layer, q.seq_in, q.seq_out, q.use_count, q.exchange_id, q.key_date, q.fprint, q.fauthkey, q.khash, q.in_seq_no FROM enc_chats as q INNER JOIN users as u ON q.user = u.uid WHERE q.uid IN(%s)", TextUtils.join(",", encryptedToLoad))); while (cursor.next()) { String name = cursor.stringValue(1); String tName = LocaleController.getInstance().getTranslitString(name); if (name.equals(tName)) { tName = null; } String username = null; int usernamePos = name.lastIndexOf(";;;"); if (usernamePos != -1) { username = name.substring(usernamePos + 2); } int found = 0; for (int a = 0; a < search.length; a++) { String q = search[a]; if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) { found = 1; } else if (username != null && username.startsWith(q)) { found = 2; } if (found != 0) { TLRPC.EncryptedChat chat = null; TLRPC.User user = null; NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { chat = TLRPC.EncryptedChat.TLdeserialize(data, data.readInt32(false), false); data.reuse(); } data = cursor.byteBufferValue(6); if (data != null) { user = TLRPC.User.TLdeserialize(data, data.readInt32(false), false); data.reuse(); } if (chat != null && user != null) { DialogSearchResult dialogSearchResult = dialogsResult.get((long) chat.id << 32); chat.user_id = cursor.intValue(2); chat.a_or_b = cursor.byteArrayValue(3); chat.auth_key = cursor.byteArrayValue(4); chat.ttl = cursor.intValue(5); chat.layer = cursor.intValue(8); chat.seq_in = cursor.intValue(9); chat.seq_out = cursor.intValue(10); int use_count = cursor.intValue(11); chat.key_use_count_in = (short) (use_count >> 16); chat.key_use_count_out = (short) (use_count); chat.exchange_id = cursor.longValue(12); chat.key_create_date = cursor.intValue(13); chat.future_key_fingerprint = cursor.longValue(14); chat.future_auth_key = cursor.byteArrayValue(15); chat.key_hash = cursor.byteArrayValue(16); chat.in_seq_no = cursor.intValue(17); if (user.status != null) { user.status.expires = cursor.intValue(7); } if (found == 1) { dialogSearchResult.name = AndroidUtilities.replaceTags("<c#ff00a60e>" + ContactsController.formatName(user.first_name, user.last_name) + "</c>"); } else { dialogSearchResult.name = AndroidUtilities.generateSearchName("@" + user.username, null, "@" + q); } dialogSearchResult.object = chat; encUsers.add(user); resultCount++; } break; } } } cursor.dispose(); } ArrayList<DialogSearchResult> searchResults = new ArrayList<>(resultCount); for (DialogSearchResult dialogSearchResult : dialogsResult.values()) { if (dialogSearchResult.object != null && dialogSearchResult.name != null) { searchResults.add(dialogSearchResult); } } Collections.sort(searchResults, new Comparator<DialogSearchResult>() { @Override public int compare(DialogSearchResult lhs, DialogSearchResult rhs) { if (lhs.date < rhs.date) { return 1; } else if (lhs.date > rhs.date) { return -1; } return 0; } }); ArrayList<TLObject> resultArray = new ArrayList<>(); ArrayList<CharSequence> resultArrayNames = new ArrayList<>(); for (int a = 0; a < searchResults.size(); a++) { DialogSearchResult dialogSearchResult = searchResults.get(a); resultArray.add(dialogSearchResult.object); resultArrayNames.add(dialogSearchResult.name); } if (dialogsType != 2) { cursor = MessagesStorage.getInstance().getDatabase().queryFinalized("SELECT u.data, u.status, u.name, u.uid FROM users as u INNER JOIN contacts as c ON u.uid = c.uid"); while (cursor.next()) { int uid = cursor.intValue(3); if (dialogsResult.containsKey((long) uid)) { continue; } String name = cursor.stringValue(2); String tName = LocaleController.getInstance().getTranslitString(name); if (name.equals(tName)) { tName = null; } String username = null; int usernamePos = name.lastIndexOf(";;;"); if (usernamePos != -1) { username = name.substring(usernamePos + 3); } int found = 0; for (String q : search) { if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) { found = 1; } else if (username != null && username.startsWith(q)) { found = 2; } if (found != 0) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { TLRPC.User user = TLRPC.User.TLdeserialize(data, data.readInt32(false), false); data.reuse(); if (user.status != null) { user.status.expires = cursor.intValue(1); } if (found == 1) { resultArrayNames.add(AndroidUtilities.generateSearchName(user.first_name, user.last_name, q)); } else { resultArrayNames.add(AndroidUtilities.generateSearchName("@" + user.username, null, "@" + q)); } resultArray.add(user); } break; } } } cursor.dispose(); } updateSearchResults(resultArray, resultArrayNames, encUsers, searchId); } catch (Exception e) { FileLog.e("tmessages", e); } } }); } private void updateSearchResults(final ArrayList<TLObject> result, final ArrayList<CharSequence> names, final ArrayList<TLRPC.User> encUsers, final int searchId) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (searchId != lastSearchId) { return; } for (int a = 0; a < result.size(); a++) { TLObject obj = result.get(a); if (obj instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) obj; MessagesController.getInstance().putUser(user, true); } else if (obj instanceof TLRPC.Chat) { TLRPC.Chat chat = (TLRPC.Chat) obj; MessagesController.getInstance().putChat(chat, true); } else if (obj instanceof TLRPC.EncryptedChat) { TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) obj; MessagesController.getInstance().putEncryptedChat(chat, true); } } MessagesController.getInstance().putUsers(encUsers, true); searchResult = result; searchResultNames = names; notifyDataSetChanged(); } }); } public boolean isGlobalSearch(int i) { return i > searchResult.size() && i <= globalSearch.size() + searchResult.size(); } @Override public void clearRecentHashtags() { super.clearRecentHashtags(); searchResultHashtags.clear(); notifyDataSetChanged(); } @Override protected void setHashtags(ArrayList<HashtagObject> arrayList, HashMap<String, HashtagObject> hashMap) { super.setHashtags(arrayList, hashMap); for (int a = 0; a < arrayList.size(); a++) { searchResultHashtags.add(arrayList.get(a).hashtag); } if (delegate != null) { delegate.searchStateChanged(false); } notifyDataSetChanged(); } public void searchDialogs(final String query) { if (query != null && lastSearchText != null && query.equals(lastSearchText)) { return; } lastSearchText = query; try { if (searchTimer != null) { searchTimer.cancel(); searchTimer = null; } } catch (Exception e) { FileLog.e("tmessages", e); } if (query == null || query.length() == 0) { hashtagsLoadedFromDb = false; searchResult.clear(); searchResultNames.clear(); searchResultHashtags.clear(); if (needMessagesSearch != 2) { queryServerSearch(null, true); } searchMessagesInternal(null); notifyDataSetChanged(); } else { if (needMessagesSearch != 2 && (query.startsWith("#") && query.length() == 1)) { messagesSearchEndReached = true; if (!hashtagsLoadedFromDb) { loadRecentHashtags(); if (delegate != null) { delegate.searchStateChanged(true); } notifyDataSetChanged(); return; } searchResultMessages.clear(); searchResultHashtags.clear(); for (int a = 0; a < hashtags.size(); a++) { searchResultHashtags.add(hashtags.get(a).hashtag); } if (delegate != null) { delegate.searchStateChanged(false); } notifyDataSetChanged(); return; } else { searchResultHashtags.clear(); notifyDataSetChanged(); } final int searchId = ++lastSearchId; searchTimer = new Timer(); searchTimer.schedule(new TimerTask() { @Override public void run() { try { cancel(); searchTimer.cancel(); searchTimer = null; } catch (Exception e) { FileLog.e("tmessages", e); } searchDialogsInternal(query, searchId); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (needMessagesSearch != 2) { queryServerSearch(query, true); } searchMessagesInternal(query); } }); } }, 200, 300); } } @Override public int getItemCount() { if (isRecentSearchDisplayed()) { return (!recentSearchObjects.isEmpty() ? recentSearchObjects.size() + 1 : 0) + (!SearchQuery.hints.isEmpty() ? 2 : 0); } if (!searchResultHashtags.isEmpty()) { return searchResultHashtags.size() + 1; } int count = searchResult.size(); int globalCount = globalSearch.size(); int messagesCount = searchResultMessages.size(); if (globalCount != 0) { count += globalCount + 1; } if (messagesCount != 0) { count += messagesCount + 1 + (messagesSearchEndReached ? 0 : 1); } return count; } public Object getItem(int i) { if (isRecentSearchDisplayed()) { int offset = (!SearchQuery.hints.isEmpty() ? 2 : 0); if (i > offset && i - 1 - offset < recentSearchObjects.size()) { TLObject object = recentSearchObjects.get(i - 1 - offset).object; if (object instanceof TLRPC.User) { TLRPC.User user = MessagesController.getInstance().getUser(((TLRPC.User) object).id); if (user != null) { object = user; } } else if (object instanceof TLRPC.Chat) { TLRPC.Chat chat = MessagesController.getInstance().getChat(((TLRPC.Chat) object).id); if (chat != null) { object = chat; } } return object; } else { return null; } } if (!searchResultHashtags.isEmpty()) { if (i > 0) { return searchResultHashtags.get(i - 1); } else { return null; } } int localCount = searchResult.size(); int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1; int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1; if (i >= 0 && i < localCount) { return searchResult.get(i); } else if (i > localCount && i < globalCount + localCount) { return globalSearch.get(i - localCount - 1); } else if (i > globalCount + localCount && i < globalCount + localCount + messagesCount) { return searchResultMessages.get(i - localCount - globalCount - 1); } return null; } @Override public long getItemId(int i) { return i; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = null; switch (viewType) { case 0: view = new ProfileSearchCell(mContext); view.setBackgroundResource(R.drawable.list_selector); break; case 1: view = new GreySectionCell(mContext); break; case 2: view = new DialogCell(mContext); break; case 3: view = new LoadingCell(mContext); break; case 4: view = new HashtagSearchCell(mContext); break; case 5: RecyclerListView horizontalListView = new RecyclerListView(mContext) { @Override public boolean onInterceptTouchEvent(MotionEvent e) { if (getParent() != null && getParent().getParent() != null) { getParent().getParent().requestDisallowInterceptTouchEvent(true); } return super.onInterceptTouchEvent(e); } }; horizontalListView.setTag(9); horizontalListView.setItemAnimator(null); horizontalListView.setLayoutAnimation(null); LinearLayoutManager layoutManager = new LinearLayoutManager(mContext) { @Override public boolean supportsPredictiveItemAnimations() { return false; } }; layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); horizontalListView.setLayoutManager(layoutManager); //horizontalListView.setDisallowInterceptTouchEvents(true); horizontalListView.setAdapter(new CategoryAdapterRecycler()); horizontalListView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() { @Override public void onItemClick(View view, int position) { if (delegate != null) { delegate.didPressedOnSubDialog((Integer) view.getTag()); } } }); horizontalListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() { @Override public boolean onItemClick(View view, int position) { if (delegate != null) { delegate.needRemoveHint((Integer) view.getTag()); } return true; } }); view = horizontalListView; } if (viewType == 5) { view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(100))); } else { view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); } return new Holder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { switch (holder.getItemViewType()) { case 0: { ProfileSearchCell cell = (ProfileSearchCell) holder.itemView; TLRPC.User user = null; TLRPC.Chat chat = null; TLRPC.EncryptedChat encryptedChat = null; CharSequence username = null; CharSequence name = null; boolean isRecent = false; String un = null; Object obj = getItem(position); if (obj instanceof TLRPC.User) { user = (TLRPC.User) obj; un = user.username; } else if (obj instanceof TLRPC.Chat) { chat = MessagesController.getInstance().getChat(((TLRPC.Chat) obj).id); if (chat == null) { chat = (TLRPC.Chat) obj; } un = chat.username; } else if (obj instanceof TLRPC.EncryptedChat) { encryptedChat = MessagesController.getInstance().getEncryptedChat(((TLRPC.EncryptedChat) obj).id); user = MessagesController.getInstance().getUser(encryptedChat.user_id); } if (isRecentSearchDisplayed()) { isRecent = true; cell.useSeparator = position != getItemCount() - 1; } else { int localCount = searchResult.size(); int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1; cell.useSeparator = (position != getItemCount() - 1 && position != localCount - 1 && position != localCount + globalCount - 1); if (position < searchResult.size()) { name = searchResultNames.get(position); if (name != null && user != null && user.username != null && user.username.length() > 0) { if (name.toString().startsWith("@" + user.username)) { username = name; name = null; } } } else if (position > searchResult.size() && un != null) { String foundUserName = lastFoundUsername; if (foundUserName.startsWith("@")) { foundUserName = foundUserName.substring(1); } try { username = AndroidUtilities.replaceTags(String.format("<c#ff4d83b3>@%s</c>%s", un.substring(0, foundUserName.length()), un.substring(foundUserName.length()))); } catch (Exception e) { username = un; FileLog.e("tmessages", e); } } } cell.setData(user != null ? user : chat, encryptedChat, name, username, isRecent); break; } case 1: { GreySectionCell cell = (GreySectionCell) holder.itemView; if (isRecentSearchDisplayed()) { int offset = (!SearchQuery.hints.isEmpty() ? 2 : 0); if (position < offset) { cell.setText(LocaleController.getString("ChatHints", R.string.ChatHints).toUpperCase()); } else { cell.setText(LocaleController.getString("Recent", R.string.Recent).toUpperCase()); } } else if (!searchResultHashtags.isEmpty()) { cell.setText(LocaleController.getString("Hashtags", R.string.Hashtags).toUpperCase()); } else if (!globalSearch.isEmpty() && position == searchResult.size()) { cell.setText(LocaleController.getString("GlobalSearch", R.string.GlobalSearch)); } else { cell.setText(LocaleController.getString("SearchMessages", R.string.SearchMessages)); } break; } case 2: { DialogCell cell = (DialogCell) holder.itemView; cell.useSeparator = (position != getItemCount() - 1); MessageObject messageObject = (MessageObject)getItem(position); cell.setDialog(messageObject.getDialogId(), messageObject, messageObject.messageOwner.date); break; } case 3: { break; } case 4: { HashtagSearchCell cell = (HashtagSearchCell) holder.itemView; cell.setText(searchResultHashtags.get(position - 1)); cell.setNeedDivider(position != searchResultHashtags.size()); break; } case 5: { RecyclerListView recyclerListView = (RecyclerListView) holder.itemView; ((CategoryAdapterRecycler) recyclerListView.getAdapter()).setIndex(position / 2); break; } } } @Override public int getItemViewType(int i) { if (isRecentSearchDisplayed()) { int offset = (!SearchQuery.hints.isEmpty() ? 2 : 0); if (i <= offset) { if (i == offset || i % 2 == 0) { return 1; } else { return 5; } } return 0; } if (!searchResultHashtags.isEmpty()) { return i == 0 ? 1 : 4; } int localCount = searchResult.size(); int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1; int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1; if (i >= 0 && i < localCount || i > localCount && i < globalCount + localCount) { return 0; } else if (i > globalCount + localCount && i < globalCount + localCount + messagesCount) { return 2; } else if (messagesCount != 0 && i == globalCount + localCount + messagesCount) { return 3; } return 1; } }
gpl-2.0
md-5/jdk10
src/jdk.jdi/share/classes/com/sun/jdi/connect/spi/ClosedConnectionException.java
2542
/* * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.jdi.connect.spi; /** * This exception may be thrown as a result of an asynchronous * close of a {@link Connection} while an I/O operation is * in progress. * * <p> When a thread is blocked in {@link Connection#readPacket * readPacket} waiting for packet from a target VM the * {@link Connection} may be closed asynchronous by another * thread invokving the {@link Connection#close close} method. * When this arises the thread in readPacket will throw this * exception. Similiarly when a thread is blocked in * {@link Connection#writePacket} the Connection may be closed. * When this occurs the thread in writePacket will throw * this exception. * * @see Connection#readPacket * @see Connection#writePacket * * @since 1.5 */ public class ClosedConnectionException extends java.io.IOException { private static final long serialVersionUID = 3877032124297204774L; /** * Constructs a {@code ClosedConnectionException} with no detail * message. */ public ClosedConnectionException() { } /** * Constructs a {@code ClosedConnectionException} with the * specified detail message. * * @param message the detail message pertaining to this exception. */ public ClosedConnectionException(String message) { super(message); } }
gpl-2.0
newtonker/weiciyuan
src/org/qii/weiciyuan/support/database/DraftDBManager.java
7845
package org.qii.weiciyuan.support.database; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import com.google.gson.Gson; import org.qii.weiciyuan.bean.CommentBean; import org.qii.weiciyuan.bean.GeoBean; import org.qii.weiciyuan.bean.MessageBean; import org.qii.weiciyuan.support.database.draftbean.*; import org.qii.weiciyuan.support.database.table.DraftTable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; /** * User: qii * Date: 12-10-21 */ public class DraftDBManager { private static DraftDBManager singleton = null; private SQLiteDatabase wsd = null; private SQLiteDatabase rsd = null; private DraftDBManager() { } public static DraftDBManager getInstance() { if (singleton == null) { DatabaseHelper databaseHelper = DatabaseHelper.getInstance(); SQLiteDatabase wsd = databaseHelper.getWritableDatabase(); SQLiteDatabase rsd = databaseHelper.getReadableDatabase(); singleton = new DraftDBManager(); singleton.wsd = wsd; singleton.rsd = rsd; } return singleton; } public void insertStatus(String content, GeoBean gps, String pic, String accountId) { ContentValues cv = new ContentValues(); cv.put(DraftTable.CONTENT, content); cv.put(DraftTable.ACCOUNTID, accountId); if (gps != null) cv.put(DraftTable.GPS, new Gson().toJson(gps)); if (!TextUtils.isEmpty(pic)) cv.put(DraftTable.PIC, pic); cv.put(DraftTable.TYPE, DraftTable.TYPE_WEIBO); wsd.insert(DraftTable.TABLE_NAME, DraftTable.ID, cv); } public void insertRepost(String content, MessageBean messageBean, String accountId) { ContentValues cv = new ContentValues(); cv.put(DraftTable.CONTENT, content); cv.put(DraftTable.ACCOUNTID, accountId); cv.put(DraftTable.JSONDATA, new Gson().toJson(messageBean)); cv.put(DraftTable.TYPE, DraftTable.TYPE_REPOST); wsd.insert(DraftTable.TABLE_NAME, DraftTable.ID, cv); } public void insertComment(String content, MessageBean messageBean, String accountId) { ContentValues cv = new ContentValues(); cv.put(DraftTable.CONTENT, content); cv.put(DraftTable.ACCOUNTID, accountId); cv.put(DraftTable.JSONDATA, new Gson().toJson(messageBean)); cv.put(DraftTable.TYPE, DraftTable.TYPE_COMMENT); wsd.insert(DraftTable.TABLE_NAME, DraftTable.ID, cv); } public void insertReply(String content, CommentBean commentBean, String accountId) { ContentValues cv = new ContentValues(); cv.put(DraftTable.CONTENT, content); cv.put(DraftTable.ACCOUNTID, accountId); cv.put(DraftTable.JSONDATA, new Gson().toJson(commentBean)); cv.put(DraftTable.TYPE, DraftTable.TYPE_REPLY); wsd.insert(DraftTable.TABLE_NAME, DraftTable.ID, cv); } public List<DraftListViewItemBean> getDraftList(String accountId) { Gson gson = new Gson(); List<DraftListViewItemBean> result = new ArrayList<DraftListViewItemBean>(); String sql = "select * from " + DraftTable.TABLE_NAME + " where " + DraftTable.ACCOUNTID + " = " + accountId + " order by " + DraftTable.ID + " desc"; Cursor c = rsd.rawQuery(sql, null); while (c.moveToNext()) { DraftListViewItemBean item = new DraftListViewItemBean(); int type = c.getInt(c.getColumnIndex(DraftTable.TYPE)); item.setType(type); item.setId(c.getString(c.getColumnIndex(DraftTable.ID))); String content; switch (type) { case DraftTable.TYPE_WEIBO: content = c.getString(c.getColumnIndex(DraftTable.CONTENT)); StatusDraftBean bean = new StatusDraftBean(); bean.setId(c.getString(c.getColumnIndex(DraftTable.ID))); bean.setContent(content); bean.setAccountId(accountId); String gpsJson = c.getString(c.getColumnIndex(DraftTable.GPS)); if (!TextUtils.isEmpty(gpsJson)) { bean.setGps(new Gson().fromJson(gpsJson, GeoBean.class)); } bean.setPic(c.getString(c.getColumnIndex(DraftTable.PIC))); item.setStatusDraftBean(bean); result.add(item); break; case DraftTable.TYPE_REPOST: content = c.getString(c.getColumnIndex(DraftTable.CONTENT)); RepostDraftBean repostDraftBean = new RepostDraftBean(); repostDraftBean.setId(c.getString(c.getColumnIndex(DraftTable.ID))); repostDraftBean.setContent(content); repostDraftBean.setAccountId(accountId); MessageBean messageBean = gson.fromJson(c.getString(c.getColumnIndex(DraftTable.JSONDATA)), MessageBean.class); repostDraftBean.setMessageBean(messageBean); item.setRepostDraftBean(repostDraftBean); result.add(item); break; case DraftTable.TYPE_COMMENT: content = c.getString(c.getColumnIndex(DraftTable.CONTENT)); CommentDraftBean commentDraftBean = new CommentDraftBean(); commentDraftBean.setId(c.getString(c.getColumnIndex(DraftTable.ID))); commentDraftBean.setContent(content); commentDraftBean.setAccountId(accountId); MessageBean commentMessageBean = gson.fromJson(c.getString(c.getColumnIndex(DraftTable.JSONDATA)), MessageBean.class); commentDraftBean.setMessageBean(commentMessageBean); item.setCommentDraftBean(commentDraftBean); result.add(item); break; case DraftTable.TYPE_REPLY: content = c.getString(c.getColumnIndex(DraftTable.CONTENT)); ReplyDraftBean replyDraftBean = new ReplyDraftBean(); replyDraftBean.setId(c.getString(c.getColumnIndex(DraftTable.ID))); replyDraftBean.setContent(content); replyDraftBean.setAccountId(accountId); CommentBean commentBean = gson.fromJson(c.getString(c.getColumnIndex(DraftTable.JSONDATA)), CommentBean.class); replyDraftBean.setCommentBean(commentBean); item.setReplyDraftBean(replyDraftBean); result.add(item); break; } } c.close(); return result; } public List<DraftListViewItemBean> removeAndGet(Set<String> checkedItemPosition, String acountId) { String[] args = checkedItemPosition.toArray(new String[0]); String asString = Arrays.toString(args); asString = asString.replace("[", "("); asString = asString.replace("]", ")"); String sql = "delete from " + DraftTable.TABLE_NAME + " where " + DraftTable.ID + " in " + asString; wsd.execSQL(sql); return getDraftList(acountId); } public void remove(String id) { String sql = "delete from " + DraftTable.TABLE_NAME + " where " + DraftTable.ID + " = " + id; wsd.execSQL(sql); } }
gpl-3.0
siosio/intellij-community
platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/popup/WarnOnDeletion.java
1934
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.diff.impl.dir.actions.popup; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.ToggleAction; import com.intellij.openapi.diff.impl.dir.DirDiffTableModel; import com.intellij.openapi.project.DumbAware; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; /** * @author Konstantin Bulenkov */ public class WarnOnDeletion extends ToggleAction implements DumbAware { private static final @NonNls String PROPERTY_NAME = "dir.diff.do.not.show.warnings.when.deleting"; @Override public boolean isSelected(@NotNull AnActionEvent e) { return isWarnWhenDeleteItems(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { setWarnWhenDeleteItems(state); } @Override public void update(@NotNull AnActionEvent e) { final DirDiffTableModel model = SetOperationToBase.getModel(e); e.getPresentation().setEnabled(model != null && model.isOperationsEnabled()); } public static boolean isWarnWhenDeleteItems() { return PropertiesComponent.getInstance().getBoolean(PROPERTY_NAME); } public static void setWarnWhenDeleteItems(boolean warn) { PropertiesComponent.getInstance().setValue(PROPERTY_NAME, warn); } }
apache-2.0
jomarko/kie-wb-common
kie-wb-common-forms/kie-wb-common-forms-commons/kie-wb-common-forms-crud-component/src/test/java/org/kie/workbench/common/forms/crud/client/component/mock/CrudComponentMock.java
1615
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.forms.crud.client.component.mock; import org.jboss.errai.ui.client.local.spi.TranslationService; import org.kie.workbench.common.forms.crud.client.component.CrudComponent; import org.kie.workbench.common.forms.crud.client.component.formDisplay.embedded.EmbeddedFormDisplayer; import org.kie.workbench.common.forms.crud.client.component.formDisplay.modal.ModalFormDisplayer; public class CrudComponentMock<MODEL, FORM_MODEL> extends CrudComponent<MODEL, FORM_MODEL> { public CrudComponentMock(final CrudComponentView<MODEL, FORM_MODEL> view, final EmbeddedFormDisplayer embeddedFormDisplayer, final ModalFormDisplayer modalFormDisplayer, final TranslationService translationService) { super(view, embeddedFormDisplayer, modalFormDisplayer, translationService); } @Override public void refresh() { } }
apache-2.0
Kreolwolf1/Elastic
src/main/java/org/elasticsearch/action/deletebyquery/package-info.java
889
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Delete by query action. */ package org.elasticsearch.action.deletebyquery;
apache-2.0
honestrock/light-admin
lightadmin-sandbox/src/main/java/org/lightadmin/test/model/FilterTestEntity.java
1799
package org.lightadmin.test.model; import org.lightadmin.demo.model.AbstractEntity; import javax.persistence.Entity; import java.math.BigDecimal; @Entity public class FilterTestEntity extends AbstractEntity { private String textField; private Integer integerField; private int primitiveIntegerField; private BigDecimal decimalField; private BigDecimal calculatedField; private Boolean booleanField; public FilterTestEntity(final String textField, final int integerField, final BigDecimal decimalField, Boolean booleanField) { this.textField = textField; this.integerField = integerField; this.decimalField = decimalField; this.booleanField = booleanField; } public FilterTestEntity() { } public String getTextField() { return textField; } public void setTextField( final String textField ) { this.textField = textField; } public Integer getIntegerField() { return integerField; } public void setIntegerField( final Integer integerField ) { this.integerField = integerField; } public BigDecimal getDecimalField() { return decimalField; } public void setDecimalField( final BigDecimal decimalField ) { this.decimalField = decimalField; } public int getPrimitiveIntegerField() { return primitiveIntegerField; } public void setPrimitiveIntegerField( int primitiveIntegerField ) { this.primitiveIntegerField = primitiveIntegerField; } public BigDecimal getCalculatedField() { BigDecimal theResult = new BigDecimal( 0 ); return theResult.add( decimalField ).add( new BigDecimal( integerField ) ).add( new BigDecimal( primitiveIntegerField ) ); } public Boolean isBooleanField() { return booleanField; } public void setBooleanField(Boolean booleanField) { this.booleanField = booleanField; } }
apache-2.0
siosio/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyDictLiteralFormToConstructorIntention.java
3943
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.intentions; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.jetbrains.python.PyNames; import com.jetbrains.python.PyPsiBundle; import com.jetbrains.python.psi.*; import org.jetbrains.annotations.NotNull; /** * User: catherine * * Intention to convert dict literal expression to dict constructor if the keys are all string constants on a literal dict. * For instance, * {} -> dict * {'a': 3, 'b': 5} -> dict(a=3, b=5) * {a: 3, b: 5} -> no transformation */ public class PyDictLiteralFormToConstructorIntention extends PyBaseIntentionAction { @Override @NotNull public String getFamilyName() { return PyPsiBundle.message("INTN.convert.dict.literal.to.dict.constructor"); } @Override @NotNull public String getText() { return PyPsiBundle.message("INTN.convert.dict.literal.to.dict.constructor"); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { if (!(file instanceof PyFile)) { return false; } PyDictLiteralExpression dictExpression = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyDictLiteralExpression.class); if (dictExpression != null) { PyKeyValueExpression[] elements = dictExpression.getElements(); if (elements.length != 0) { for (PyKeyValueExpression element : elements) { PyExpression key = element.getKey(); if (! (key instanceof PyStringLiteralExpression)) return false; String str = ((PyStringLiteralExpression)key).getStringValue(); if (PyNames.isReserved(str)) return false; if(str.length() == 0 || Character.isDigit(str.charAt(0))) return false; if (!StringUtil.isJavaIdentifier(str)) return false; } } return true; } return false; } @Override public void doInvoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { PyDictLiteralExpression dictExpression = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyDictLiteralExpression.class); PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); if (dictExpression != null) { replaceDictLiteral(dictExpression, elementGenerator); } } private static void replaceDictLiteral(PyDictLiteralExpression dictExpression, PyElementGenerator elementGenerator) { PyExpression[] argumentList = dictExpression.getElements(); StringBuilder stringBuilder = new StringBuilder("dict("); int size = argumentList.length; for (int i = 0; i != size; ++i) { PyExpression argument = argumentList[i]; if (argument instanceof PyKeyValueExpression) { PyExpression key = ((PyKeyValueExpression)argument).getKey(); PyExpression value = ((PyKeyValueExpression)argument).getValue(); if (key instanceof PyStringLiteralExpression && value != null) { stringBuilder.append(((PyStringLiteralExpression)key).getStringValue()); stringBuilder.append("="); stringBuilder.append(value.getText()); if (i != size-1) stringBuilder.append(", "); } } } stringBuilder.append(")"); PyCallExpression callExpression = (PyCallExpression)elementGenerator.createFromText(LanguageLevel.forElement(dictExpression), PyExpressionStatement.class, stringBuilder.toString()).getExpression(); dictExpression.replace(callExpression); } }
apache-2.0
siosio/intellij-community
plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/FieldMayBeFinalInspectionTest.java
785
package com.siyeh.ig.style; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.testFramework.LightProjectDescriptor; import com.siyeh.ig.LightJavaInspectionTestCase; import org.jetbrains.annotations.NotNull; public class FieldMayBeFinalInspectionTest extends LightJavaInspectionTestCase { @Override protected @NotNull LightProjectDescriptor getProjectDescriptor() { return JAVA_11; } public void testFieldMayBeFinal() { doTest(); } public void testAnonymousObject() { doTest(); } @Override protected InspectionProfileEntry getInspection() { return new FieldMayBeFinalInspection(); } @Override protected String getBasePath() { return "/plugins/InspectionGadgets/test/com/siyeh/igtest/style/field_final"; } }
apache-2.0
DevFactory/java-design-patterns
producer-consumer/src/test/java/com/iluwatar/producer/consumer/StdOutTest.java
2373
/** * The MIT License * Copyright (c) 2014 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.producer.consumer; import org.junit.After; import org.junit.Before; import java.io.PrintStream; import static org.mockito.Mockito.mock; /** * Date: 12/10/15 - 8:37 PM * * @author Jeroen Meulemeester */ public abstract class StdOutTest { /** * The mocked standard out {@link PrintStream}, required since some actions don't have any * influence on accessible objects, except for writing to std-out using {@link System#out} */ private final PrintStream stdOutMock = mock(PrintStream.class); /** * Keep the original std-out so it can be restored after the test */ private final PrintStream stdOutOrig = System.out; /** * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test */ @Before public void setUp() { System.setOut(this.stdOutMock); } /** * Removed the mocked std-out {@link PrintStream} again from the {@link System} class */ @After public void tearDown() { System.setOut(this.stdOutOrig); } /** * Get the mocked stdOut {@link PrintStream} * * @return The stdOut print stream mock, renewed before each test */ final PrintStream getStdOutMock() { return this.stdOutMock; } }
mit
simleo/openmicroscopy
components/server/src/ome/services/JobBean.java
11474
/* * Copyright 2007 Glencoe Software, Inc. All rights reserved. * Use is subject to license terms supplied in LICENSE.txt */ package ome.services; import java.sql.Timestamp; import ome.annotations.RolesAllowed; import ome.api.ITypes; import ome.api.JobHandle; import ome.api.ServiceInterface; import ome.conditions.ApiUsageException; import ome.conditions.ValidationException; import ome.model.IObject; import ome.model.internal.Details; import ome.model.jobs.Job; import ome.model.jobs.JobStatus; import ome.parameters.Parameters; import ome.security.SecureAction; import ome.services.procs.IProcessManager; import ome.services.procs.Process; import ome.services.procs.ProcessCallback; import ome.system.EventContext; import ome.util.ShallowCopy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.annotation.Transactional; /** * Provides methods for submitting asynchronous tasks. * * @author Josh Moore, josh at glencoesoftware.com * @since 3.0-Beta2 * */ @Transactional(readOnly = true) public class JobBean extends AbstractStatefulBean implements JobHandle, ProcessCallback { /** * */ private static final long serialVersionUID = 49809384038000069L; /** The logger for this class. */ private transient static Logger log = LoggerFactory.getLogger(JobBean.class); private Long jobId, resetId; private transient ITypes iTypes; private transient IProcessManager pm; /** default constructor */ public JobBean() { } public Class<? extends ServiceInterface> getServiceInterface() { return JobHandle.class; } // Lifecycle methods // =================================================== /** * Does nothing. The only non-shared state that this instance * holds on to is the jobId and resetId -- two longs -- making * passivation for the moment unimportant. This method should do * what errorIfInvalidState does and reattach the process if we've * been passivated. That will wait for larger changes later. At * which time, proper locking will be necessary! */ @RolesAllowed("user") @Transactional public void passivate() { // Nothing necessary } /** * Does almost nothing. Since nothing is passivated, nothing needs * to be activated. However, since we are still using * errorIfInvalidState, if the {@link #jobId} is non-null, then * this instance will need to handle re-loading on first * access. (Previously it could not be done here, because the * security system was not configured for transactions during * JavaEE callbacks. This is no longer true.) */ @RolesAllowed("user") @Transactional public void activate() { if (jobId != null) { resetId = jobId; jobId = null; } } /* * (non-Javadoc) * * @see ome.api.StatefulServiceInterface#close() */ @RolesAllowed("user") @Transactional(readOnly = true) public void close() { // id is the only thing passivated. // FIXME do we need to check on the process here? // or callbacks? probably. } /* * (non-Javadoc) * * @see ome.api.JobHandle#submit(Job) */ @Transactional(readOnly = false) @RolesAllowed("user") public long submit(Job newJob) { reset(); // TODO or do we want to just checkState // and throw an exception if this is a stale handle. EventContext ec = getCurrentEventContext(); long ms = System.currentTimeMillis(); Timestamp now = new Timestamp(ms); // Values that can't be set by the user newJob.setUsername(ec.getCurrentUserName()); newJob.setGroupname(ec.getCurrentGroupName()); newJob.setType(ec.getCurrentEventType()); newJob.setStarted(null); newJob.setFinished(null); newJob.setSubmitted(now); // Values that the user can optionally set Timestamp t = newJob.getScheduledFor(); if (t == null || t.getTime() < now.getTime()) { newJob.setScheduledFor(now); } JobStatus s = newJob.getStatus(); if (s == null) { newJob.setStatus(new JobStatus(JobHandle.SUBMITTED)); } else { // Verifying the status if (s.getId() != null) { try { s = iQuery.get(JobStatus.class, s.getId()); } catch (Exception e) { throw new ApiUsageException("Unknown job status: " + s); } } if (s.getValue() == null) { throw new ApiUsageException( "JobStatus must have id or value set."); } else { if (!(s.getValue().equals(SUBMITTED) || s.getValue().equals( WAITING))) { throw new ApiUsageException( "Currently only SUBMITTED and WAITING are accepted as JobStatus"); } } } String m = newJob.getMessage(); if (m == null) { newJob.setMessage(""); } // Here it is necessary to perform a {@link SecureAction} since // SecuritySystem#isSystemType() returns true for all Jobs newJob.getDetails().copy(sec.newTransientDetails(newJob)); newJob = secureSave(newJob); jobId = newJob.getId(); return jobId; } /* * (non-Javadoc) * * @see ome.api.JobHandle#attach(long) */ @RolesAllowed("user") public JobStatus attach(long id) { if (jobId == null || jobId.longValue() != id) { reset(); jobId = Long.valueOf(id); } checkAndRegister(); return getJob().getStatus(); } private void reset() { resetId = null; jobId = null; } /** * Types service Bean injector. * * @param typesService * an <code>ITypes</code>. */ public void setTypesService(ITypes typesService) { getBeanHelper().throwIfAlreadySet(this.iTypes, typesService); this.iTypes = typesService; } /** * Process Manager Bean injector. * * @param procMgr * a <code>ProcessManager</code>. */ public void setProcessManager(IProcessManager procMgr) { getBeanHelper().throwIfAlreadySet(this.pm, procMgr); this.pm = procMgr; } // Usage methods // =================================================== protected void errorIfInvalidState() { if (resetId != null) { long reset = resetId.longValue(); attach(reset); } else if (jobId == null) { throw new ApiUsageException( "JobHandle not ready: Please submit() or attach() to a Job."); } } protected void checkAndRegister() { Process p = pm.runningProcess(jobId); if (p != null && p.isActive()) { p.registerCallback(this); } } @RolesAllowed("user") public Job getJob() { Job job = internalJobOnly(); JobStatus status = job.getStatus(); Details unloadedDetails = status.getDetails().shallowCopy(); status.getDetails().shallowCopy(unloadedDetails); Job copy = new ShallowCopy().copy(job); copy.setStatus(job.getStatus()); return copy; } @RolesAllowed("user") public Timestamp jobFinished() { return getJob().getFinished(); } @RolesAllowed("user") public JobStatus jobStatus() { return getJob().getStatus(); } @RolesAllowed("user") public String jobMessage() { return getJob().getMessage(); } @RolesAllowed("user") public boolean jobRunning() { return JobHandle.RUNNING.equals(getJob().getStatus().getValue()); } @RolesAllowed("user") public boolean jobError() { return JobHandle.ERROR.equals(getJob().getStatus().getValue()); } @Transactional(readOnly = false) @RolesAllowed("user") public void cancelJob() { setStatus(JobHandle.CANCELLED); } @Transactional(readOnly = false) @RolesAllowed("user") public String setStatus(String status) { return setStatusAndMessage(status, null); } @Transactional(readOnly = false) @RolesAllowed("user") public String setMessage(String message) { return setStatusAndMessage(null, message); } @Transactional(readOnly = false) @RolesAllowed("user") public String setStatusAndMessage(String status, String message) { // status can only be null if this is invoked locally, otherwise // the @NotNull will prevent that. therefore the return value // will only be the message when called by setMessage() String rv = null; errorIfInvalidState(); Job job = internalJobOnly(); if (message != null) { rv = job.getMessage(); job.setMessage(message); } if (status != null) { JobStatus s = iTypes.getEnumeration(JobStatus.class, status); rv = job.getStatus().getValue(); job.setStatus(s); Timestamp t = new Timestamp(System.currentTimeMillis()); if (status.equals(RUNNING)) { job.setStarted(t); } else if (status.equals(CANCELLED)) { job.setFinished(t); Process p = pm.runningProcess(jobId); if (p != null) { p.cancel(); } } else if (status.equals(FINISHED) || status.equals(ERROR)) { job.setFinished(t); } else { throw new ValidationException("Currently unsupported: " + status); } } secureSave(job); return rv; } // ProcessCallback ~ // ========================================================================= public void processCancelled(Process proc) { throw new UnsupportedOperationException("NYI"); } public void processFinished(Process proc) { throw new UnsupportedOperationException("NYI"); } // Helpers ~ // ========================================================================= private Job internalJobOnly() { errorIfInvalidState(); checkAndRegister(); Job job = iQuery.findByQuery("select j from Job j " + "left outer join fetch j.status status " + "left outer join fetch j.originalFileLinks links " + "left outer join fetch links.child file " + "left outer join fetch j.details.owner owner " + "left outer join fetch owner.groupExperimenterMap map " + "left outer join fetch map.parent where j.id = :id", new Parameters().addId(jobId)); if (job == null) { throw new ApiUsageException("Unknown job:" + jobId); } return job; } private Job secureSave(Job job) { job = sec.doAction(new SecureAction() { public <T extends IObject> T updateObject(T... objs) { T result = iUpdate.saveAndReturnObject(objs[0]); iUpdate.flush(); // was commit return result; } }, job); return job; } }
gpl-2.0
zhiqinghuang/core
src/com/liferay/util/ColorUtil.java
3077
/** * Copyright (c) 2000-2005 Liferay, LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.liferay.util; /** * <a href="ColorUtil.java.html"><b><i>View Source</i></b></a> * * @author Brian Wing Shun Chan * @version $Revision: 1.7 $ * */ public class ColorUtil { public static String getHex(int[] rgb) { StringBuffer sb = new StringBuffer(); sb.append("#"); sb.append( _KEY.substring( (int)Math.floor(rgb[0] / 16), (int)Math.floor(rgb[0] / 16) + 1)); sb.append(_KEY.substring(rgb[0] % 16, (rgb[0] % 16) + 1)); sb.append( _KEY.substring( (int)Math.floor(rgb[1] / 16), (int)Math.floor(rgb[1] / 16) + 1)); sb.append(_KEY.substring(rgb[1] % 16, (rgb[1] % 16) + 1)); sb.append( _KEY.substring( (int)Math.floor(rgb[2] / 16), (int)Math.floor(rgb[2] / 16) + 1)); sb.append(_KEY.substring(rgb[2] % 16, (rgb[2] % 16) + 1)); return sb.toString(); } public static int[] getRGB(String hex) { if (hex.startsWith("#")) { hex = hex.substring(1, hex.length()).toUpperCase(); } else { hex = hex.toUpperCase(); } int[] hexArray = new int[6]; if (hex.length() == 6) { char[] c = hex.toCharArray(); for (int i = 0; i < hex.length(); i++) { if (c[i] == 'A') { hexArray[i] = 10; } else if (c[i] == 'B') { hexArray[i] = 11; } else if (c[i] == 'C') { hexArray[i] = 12; } else if (c[i] == 'D') { hexArray[i] = 13; } else if (c[i] == 'E') { hexArray[i] = 14; } else if (c[i] == 'F') { hexArray[i] = 15; } else { hexArray[i] = GetterUtil.getInteger(new Character(c[i]).toString()); } } } int[] rgb = new int[3]; rgb[0] = (hexArray[0] * 16) + hexArray[1]; rgb[1] = (hexArray[2] * 16) + hexArray[3]; rgb[2] = (hexArray[4] * 16) + hexArray[5]; return rgb; } private static final String _KEY = "0123456789ABCDEF"; }
gpl-3.0
wisdom-garden/dotcms
src/com/liferay/portal/DuplicateRoleException.java
1710
/** * Copyright (c) 2000-2005 Liferay, LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.liferay.portal; /** * <a href="DuplicateRoleException.java.html"><b><i>View Source</i></b></a> * * @author Brian Wing Shun Chan * @version $Revision: 1.6 $ * */ public class DuplicateRoleException extends PortalException { public DuplicateRoleException() { super(); } public DuplicateRoleException(String msg) { super(msg); } public DuplicateRoleException(String msg, Throwable cause) { super(msg, cause); } public DuplicateRoleException(Throwable cause) { super(cause); } }
gpl-3.0
laurianed/scheduling
common/common-api/src/main/java/org/ow2/proactive/authentication/ConnectionInfo.java
2839
/* * ProActive Parallel Suite(TM): * The Open Source library for parallel and distributed * Workflows & Scheduling, Orchestration, Cloud Automation * and Big Data Analysis on Enterprise Grids & Clouds. * * Copyright (c) 2007 - 2017 ActiveEon * Contact: contact@activeeon.com * * This library 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: version 3 of * the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/>. * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. */ package org.ow2.proactive.authentication; import java.io.File; import java.io.Serializable; import org.objectweb.proactive.annotation.PublicAPI; /** * Composite object storing information to connect to the scheduler/rm * * @author The ProActive Team */ @PublicAPI public class ConnectionInfo implements Serializable { private String url; private String login; private String password; private File credentialFile; private boolean insecure; /** * @param url the REST server URL * @param login the login * @param password the password * @param credentialFile path to a file containing encrypted credentials * @param insecure if true the server certificate will not be verified */ public ConnectionInfo(String url, String login, String password, File credentialFile, boolean insecure) { this.url = url; this.login = login; this.password = password; this.credentialFile = credentialFile; this.insecure = insecure; } public String getUrl() { return url; } public String getLogin() { return login; } public String getPassword() { return password; } public File getCredentialFile() { return credentialFile; } public boolean isInsecure() { return insecure; } public void setUrl(String url) { this.url = url; } public void setLogin(String login) { this.login = login; } public void setPassword(String password) { this.password = password; } public void setCredentialFile(File credentialFile) { this.credentialFile = credentialFile; } public void setInsecure(boolean insecure) { this.insecure = insecure; } }
agpl-3.0
EdwardSkoviak/kite
kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Constraints.java
28300
/* * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data.spi; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.apache.avro.Schema; import org.kitesdk.data.PartitionStrategy; import org.kitesdk.data.impl.Accessor; import org.kitesdk.data.spi.partition.CalendarFieldPartitioner; import org.kitesdk.data.spi.partition.ProvidedFieldPartitioner; import org.kitesdk.data.spi.predicates.Exists; import org.kitesdk.data.spi.predicates.In; import org.kitesdk.data.spi.predicates.Predicates; import org.kitesdk.data.spi.predicates.Range; import org.kitesdk.data.spi.predicates.Ranges; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Predicates.alwaysTrue; /** * A set of simultaneous constraints. * * This class accumulates combine manages a set of logical constraints. */ @Immutable public class Constraints { private static final Logger LOG = LoggerFactory.getLogger(Constraints.class); private final Schema schema; private final PartitionStrategy strategy; private final Map<String, Predicate> constraints; private final Map<String, Object> provided; public Constraints(Schema schema) { this(schema, null); } public Constraints(Schema schema, PartitionStrategy strategy) { this.schema = schema; this.strategy = strategy; this.constraints = ImmutableMap.of(); this.provided = ImmutableMap.of(); } private Constraints(Schema schema, PartitionStrategy strategy, Map<String, Predicate> constraints, Map<String, Object> provided) { this.schema = schema; this.strategy = strategy; this.constraints = constraints; this.provided = provided; } private Constraints(Constraints copy, String name, Predicate predicate) { this.schema = copy.schema; this.strategy = copy.strategy; this.constraints = updateImmutable(copy.constraints, name, predicate); this.provided = copy.provided; } private Constraints(Constraints copy, String name, Predicate predicate, Object value) { this.schema = copy.schema; this.strategy = copy.strategy; this.constraints = updateImmutable(copy.constraints, name, predicate); this.provided = updateImmutable(copy.provided, name, value); } @VisibleForTesting Constraints partitionedBy(PartitionStrategy strategy) { return new Constraints(schema, strategy, constraints, provided); } /** * Get a {@link Predicate} for testing entity objects. * * @param <E> The type of entities to be matched * @return a Predicate to test if entity objects satisfy this constraint set */ public <E> Predicate<E> toEntityPredicate(EntityAccessor<E> accessor) { return entityPredicate(constraints, schema, accessor, strategy); } /** * Get a {@link Predicate} for testing entity objects that match the given * {@link StorageKey}. * * @param <E> The type of entities to be matched * @param key a StorageKey for entities tested with the Predicate * @return a Predicate to test if entity objects satisfy this constraint set */ public <E> Predicate<E> toEntityPredicate(StorageKey key, EntityAccessor<E> accessor) { if (key != null) { Map<String, Predicate> predicates = minimizeFor(key); if (predicates.isEmpty()) { return alwaysTrue(); } return entityPredicate(predicates, schema, accessor, strategy); } return toEntityPredicate(accessor); } @VisibleForTesting @SuppressWarnings("unchecked") Map<String, Predicate> minimizeFor(StorageKey key) { Map<String, Predicate> unsatisfied = Maps.newHashMap(constraints); PartitionStrategy strategy = key.getPartitionStrategy(); Set<String> timeFields = Sets.newHashSet(); int i = 0; for (FieldPartitioner fp : Accessor.getDefault().getFieldPartitioners(strategy)) { String partition = fp.getName(); Predicate partitionPredicate = unsatisfied.get(partition); if (partitionPredicate != null && partitionPredicate.apply(key.get(i))) { unsatisfied.remove(partition); LOG.debug("removing " + partition + " satisfied by " + key.get(i)); } String source = fp.getSourceName(); if (fp instanceof CalendarFieldPartitioner) { // keep track of time fields to consider timeFields.add(source); } // remove the field if it is satisfied by the StorageKey Predicate original = unsatisfied.get(source); if (original != null) { Predicate isSatisfiedBy = fp.projectStrict(original); LOG.debug("original: " + original + ", strict: " + isSatisfiedBy); if ((isSatisfiedBy != null) && isSatisfiedBy.apply(key.get(i))) { LOG.debug("removing " + source + " satisfied by " + key.get(i)); unsatisfied.remove(source); } } i += 1; } // remove fields satisfied by the time predicates for (String timeField : timeFields) { Predicate<Long> original = unsatisfied.get(timeField); if (original != null) { Predicate<Marker> isSatisfiedBy = TimeDomain.get(strategy, timeField) .projectStrict(original); LOG.debug("original: " + original + ", strict: " + isSatisfiedBy); if ((isSatisfiedBy != null) && isSatisfiedBy.apply(key)) { LOG.debug("removing " + timeField + " satisfied by " + key); unsatisfied.remove(timeField); } } } return ImmutableMap.copyOf(unsatisfied); } /** * Filter the entities returned by a given iterator by these constraints. * * @param <E> The type of entities to be matched * @return an iterator filtered by these constraints */ public <E> Iterator<E> filter(Iterator<E> iterator, EntityAccessor<E> accessor) { return Iterators.filter(iterator, toEntityPredicate(accessor)); } /** * Get a {@link Predicate} that tests {@link StorageKey} objects. * * If a {@code StorageKey} matches the predicate, it <em>may</em> represent a * partition that is responsible for entities that match this set of * constraints. If it does not match the predicate, it cannot be responsible * for entities that match this constraint set. * * @return a Predicate for testing StorageKey objects * @throws NullPointerException if no partition strategy is defined */ public KeyPredicate toKeyPredicate() { Preconditions.checkNotNull(strategy, "Cannot produce a key predicate without a partition strategy"); return new KeyPredicate(constraints, strategy); } /** * Get a set of {@link MarkerRange} objects that covers the set of possible * {@link StorageKey} partitions for this constraint set. If a * {@code StorageKey} is not in one of the ranges returned by this method, * then its partition cannot contain entities that satisfy this constraint * set. * * @return an Iterable of MarkerRange * @throws NullPointerException if no partition strategy is defined */ public Iterable<MarkerRange> toKeyRanges() { Preconditions.checkNotNull(strategy, "Cannot produce key ranges without a partition strategy"); return new KeyRangeIterable(strategy, constraints); } /** * If this returns true, the entities selected by this set of constraints * align to partition boundaries. * * For example, for a partition strategy [hash(num), identity(num)], * any constraint on the "num" field will be correctly enforced by the * partition predicate for this constraint set. However, a "color" field * wouldn't be satisfied by considering partition values alone and would * require further checks. * * An alternate explanation: This returns whether the key {@link Predicate} * from {@link #toKeyPredicate()} is equivalent to this set of constraints * under the given {@link PartitionStrategy}. The key predicate must accept a * key if that key's partition might include entities matched by this * constraint set. If this method returns true, then all entities in the * partitions it matches are guaranteed to match this constraint set. So, the * partitions are equivalent to the constraints. * * @return true if this constraint set is satisfied by partitioning * @throws NullPointerException if no partition strategy is defined */ @SuppressWarnings("unchecked") public boolean alignedWithBoundaries() { if (constraints.isEmpty()) { return true; } else if (strategy == null) { // constraints must align with partitions, which requires a strategy return false; } Multimap<String, FieldPartitioner> partitioners = HashMultimap.create(); Set<String> partitionFields = Sets.newHashSet(); for (FieldPartitioner fp : Accessor.getDefault().getFieldPartitioners(strategy)) { partitioners.put(fp.getSourceName(), fp); partitionFields.add(fp.getName()); } // The key predicate is equivalent to a constraint set when the permissive // projection for each predicate can be used in its place. This happens if // fp.project(predicate) == fp.projectStrict(predicate): // // let D = some value domain // let pred : D -> {0, 1} // let D_{pred} = {x \in D | pred(x) == 1} (a subset of D selected by pred) // // let fp : D -> S (also a value domain) // let fp.strict(pred) = pred_{fp.strict} : S -> {0, 1} (project strict) // s.t. pred_{fp.strict}(fp(x)) == 1 => pred(x) == 1 // let fp.project(pred) = pred_{fp.project} : S -> {0, 1} (project) // s.t. pred(x) == 1 => pred_{fp.project}(fp(x)) == 1 // // lemma. {x \in D | pred_{fp.strict}(fp(x))} is a subset of D_{pred} // pred_{fp.strict}(fp(x)) == 1 => pred(x) == 1 => x \in D_{pred} // // theorem. (pred_{fp.project}(s) => pred_{fp.strict}(s)) => // D_{pred} == {x \in D | pred_{fp.strict}(fp(x))} // // => let x \in D_{pred}. then pred_{fp.project}(fp(x)) == 1 by def // then pred_{fp.strict(fp(x)) == 1 by premise // therefore {x \in D | pred_{fp.strict}(fp(x))} \subsetOf D_{pred} // <= by previous lemma // // Note: if projectStrict is too conservative or project is too permissive, // then this logic cannot determine that that the original predicate is // satisfied for (Map.Entry<String, Predicate> entry : constraints.entrySet()) { if (partitionFields.contains(entry.getKey())) { // constraint is against partition values and aligned by definition continue; } Collection<FieldPartitioner> fps = partitioners.get(entry.getKey()); if (fps.isEmpty()) { LOG.debug("No field partitioners for key {}", entry.getKey()); return false; } Predicate predicate = entry.getValue(); if (!(predicate instanceof Exists)) { boolean satisfied = false; for (FieldPartitioner fp : fps) { if (fp instanceof CalendarFieldPartitioner) { TimeDomain domain = TimeDomain.get(strategy, entry.getKey()); Predicate strict = domain.projectStrict(predicate); Predicate permissive = domain.project(predicate); LOG.debug("Time predicate strict: {}", strict); LOG.debug("Time predicate permissive: {}", permissive); satisfied = strict != null && strict.equals(permissive); break; } else { Predicate strict = fp.projectStrict(predicate); Predicate permissive = fp.project(predicate); if (strict != null && strict.equals(permissive)) { satisfied = true; break; } } } // this predicate cannot be satisfied by the partition information if (!satisfied) { LOG.debug("Predicate not satisfied: {}", predicate); return false; } } } return true; } /** * Returns a map of provided or fixed values for this constraint set. These * values were accumulated by calls to with(String, Object). * * @return a Map of provided single values. */ public Map<String, Object> getProvidedValues() { return provided; // Immutable, okay to return without copying } @SuppressWarnings("unchecked") public Constraints with(String name, Object... values) { SchemaUtil.checkTypeConsistency(schema, strategy, name, values); if (values.length > 0) { checkContained(name, values); // this is the most specific constraint and is idempotent under "and" In added = Predicates.in(values); if (values.length == 1) { // if there is only one value, it is a provided value return new Constraints(this, name, added, values[0]); } else { return new Constraints(this, name, added); } } else { if (!constraints.containsKey(name)) { // no other constraint => add the exists return new Constraints(this, name, Predicates.exists()); } else { // satisfied by an existing constraint return this; } } } public Constraints from(String name, Comparable value) { SchemaUtil.checkTypeConsistency(schema, strategy, name, value); checkContained(name, value); Range added = Ranges.atLeast(value); return new Constraints(this, name, combine(constraints.get(name), added)); } public Constraints fromAfter(String name, Comparable value) { SchemaUtil.checkTypeConsistency(schema, strategy, name, value); checkContained(name, value); Range added = Ranges.greaterThan(value); return new Constraints(this, name, combine(constraints.get(name), added)); } public Constraints to(String name, Comparable value) { SchemaUtil.checkTypeConsistency(schema, strategy, name, value); checkContained(name, value); Range added = Ranges.atMost(value); return new Constraints(this, name, combine(constraints.get(name), added)); } public Constraints toBefore(String name, Comparable value) { SchemaUtil.checkTypeConsistency(schema, strategy, name, value); checkContained(name, value); Range added = Ranges.lessThan(value); return new Constraints(this, name, combine(constraints.get(name), added)); } /** * Returns the predicate for a named field. * * For testing. * * @param name a String field name * @return a Predicate for the given field, or null if none is set */ @VisibleForTesting Predicate get(String name) { return constraints.get(name); } @SuppressWarnings("unchecked") private void checkContained(String name, Object... values) { for (Object value : values) { if (constraints.containsKey(name)) { Predicate current = constraints.get(name); Preconditions.checkArgument(current.apply(value), "%s does not match %s", current, value); } } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Constraints that = (Constraints) o; return Objects.equal(this.constraints, that.constraints) && Objects.equal(this.schema, that.schema); } @Override public int hashCode() { return Objects.hashCode(schema, constraints); } @Override public String toString() { return Objects.toStringHelper(this).addValue(constraints).toString(); } public Map<String, String> toQueryMap() { Map<String, String> query = Maps.newLinkedHashMap(); return toQueryMap(query, false); } /** * Get a normalized query map for the constraints. A normalized query map will * be equal in value and iteration order for any logically equivalent set of * constraints. */ public Map<String, String> toNormalizedQueryMap() { Map<String, String> query = Maps.newTreeMap(); return toQueryMap(query, true); } private Map<String, String> toQueryMap(Map<String, String> queryMap, boolean normalized) { for (Map.Entry<String, Predicate> entry : constraints.entrySet()) { String name = entry.getKey(); Schema fieldSchema = SchemaUtil.fieldSchema(schema, strategy, name); if(normalized) { queryMap.put(name, Predicates.toNormalizedString(entry.getValue(), fieldSchema)); } else { queryMap.put(name, Predicates.toString(entry.getValue(), fieldSchema)); } } return queryMap; } public static Constraints fromQueryMap(Schema schema, PartitionStrategy strategy, Map<String, String> query) { Map<String, Predicate> constraints = Maps.newLinkedHashMap(); Map<String, Object> provided = Maps.newHashMap(); for (Map.Entry<String, String> entry : query.entrySet()) { String name = entry.getKey(); if (SchemaUtil.isField(schema, strategy, name)) { Schema fieldSchema = SchemaUtil.fieldSchema(schema, strategy, name); Predicate predicate = Predicates.fromString( entry.getValue(), fieldSchema); constraints.put(name, predicate); if (predicate instanceof In) { Set values = Predicates.asSet((In) predicate); if (values.size() == 1) { provided.put(name, Iterables.getOnlyElement(values)); } } } } return new Constraints(schema, strategy, constraints, provided); } @SuppressWarnings("unchecked") static Predicate combine(Predicate left, Predicate right) { if (left == right) { return left; } else if (left == null) { return right; // must be non-null } else if (right == null || right instanceof Exists) { return left; // must be non-null, which satisfies exists } else if (left instanceof Exists) { return right; // must be non-null, which satisfies exists } else if (left instanceof In) { return ((In) left).filter(right); } else if (right instanceof In) { return ((In) right).filter(left); } else if (left instanceof Range && right instanceof Range) { return ((Range) left).intersection((Range) right); } else { return com.google.common.base.Predicates.and(left, right); } } private static <E> Predicate<E> entityPredicate( Map<String, Predicate> predicates, Schema schema, EntityAccessor<E> accessor, PartitionStrategy strategy) { if (Schema.Type.RECORD != schema.getType()) { return alwaysTrue(); } return new EntityPredicate<E>(predicates, schema, accessor, strategy); } private static <K, V> Map<K, V> updateImmutable(Map<K, V> existing, K key, V value) { ImmutableMap.Builder<K, V> builder = ImmutableMap.builder(); boolean added = false; for (Map.Entry<K, V> entry : existing.entrySet()) { if (key.equals(entry.getKey())) { builder.put(key, value); added = true; } else { builder.put(entry.getKey(), entry.getValue()); } } if (!added) { builder.put(key, value); } return builder.build(); } /** * Returns true if there are no constraints. * * @return {@code true} if there are no constraints, {@code false} otherwise */ public boolean isUnbounded() { return constraints.isEmpty(); } /** * A {@link Predicate} for testing entities against a set of predicates. * * @param <E> The type of entities this predicate tests */ private static class EntityPredicate<E> implements Predicate<E> { private final List<Map.Entry<Schema.Field, Predicate>> predicatesByField; private final EntityAccessor<E> accessor; @SuppressWarnings("unchecked") public EntityPredicate(Map<String, Predicate> predicates, Schema schema, EntityAccessor<E> accessor, PartitionStrategy strategy) { List<Schema.Field> fields = schema.getFields(); this.accessor = accessor; Map<Schema.Field, Predicate> predicateMap = Maps.newHashMap(); // in the case of identical source and partition names, the predicate // will be applied for both source and partition values. for (Schema.Field field : fields) { Predicate sourcePredicate = predicates.get(field.name()); if (sourcePredicate != null) { predicateMap.put(field, sourcePredicate); } } if (strategy != null) { // there could be partition predicates to add for (FieldPartitioner fp : Accessor.getDefault().getFieldPartitioners(strategy)) { if (fp instanceof ProvidedFieldPartitioner) { // no source field for provided partitioners, so no values to test continue; } Predicate partitionPredicate = predicates.get(fp.getName()); if (partitionPredicate != null) { Predicate transformPredicate = new TransformPredicate( fp, partitionPredicate); Schema.Field field = schema.getField(fp.getSourceName()); Predicate sourcePredicate = predicateMap.get(field); if (sourcePredicate != null) { // combine the source and the transform-wrapped predicates predicateMap.put(field, combine(sourcePredicate, transformPredicate)); } else { predicateMap.put(field, transformPredicate); } } } } this.predicatesByField = ImmutableList.copyOf(predicateMap.entrySet()); } @Override @SuppressWarnings("unchecked") public boolean apply(@Nullable E entity) { if (entity == null) { return false; } // check each constraint and fail immediately for (Map.Entry<Schema.Field, Predicate> entry : predicatesByField) { Object eValue = accessor.get(entity, ImmutableList.of(entry.getKey())); if (!entry.getValue().apply(eValue)) { return false; } } // all constraints were satisfied return true; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } EntityPredicate other = (EntityPredicate) obj; return Objects.equal(predicatesByField, other.predicatesByField); } @Override public int hashCode() { return Objects.hashCode(predicatesByField); } @Override public String toString() { return Objects.toStringHelper(this) .add("predicates", predicatesByField) .toString(); } } /** * A {@link Predicate} for testing a {@link StorageKey} against a set of * predicates. */ public static class KeyPredicate implements Predicate<StorageKey> { private final List<Predicate> partitionPredicates; private final List<Predicate<Marker>> timePredicates; @SuppressWarnings("unchecked") private KeyPredicate(Map<String, Predicate> predicates, PartitionStrategy strategy) { Preconditions.checkNotNull(strategy, "Cannot produce KeyPredicate without a PartitionStrategy"); // in the case of identical source and partition names, there is only one // predicate and it is used like normal. the only time this conflicts is // when the source and predicate name for a single field are the same, in // which case the result will be the projected predicate combined with // itself. usually the function is identity when this happens and there is // no problem because of the combine identity check. List<FieldPartitioner> partitioners = Accessor.getDefault().getFieldPartitioners(strategy); Predicate[] preds = new Predicate[partitioners.size()]; Map<String, Predicate> timeFields = Maps.newHashMap(); for (int i = 0; i < preds.length; i += 1) { FieldPartitioner fp = partitioners.get(i); Predicate sourcePredicate = predicates.get(fp.getSourceName()); if (sourcePredicate != null) { Predicate projectedPredicate = fp.project(sourcePredicate); if (projectedPredicate != null) { preds[i] = projectedPredicate; } if (fp instanceof CalendarFieldPartitioner) { timeFields.put(fp.getSourceName(), sourcePredicate); } } Predicate partitionPredicate = predicates.get(fp.getName()); if (preds[i] != null) { if (partitionPredicate != null) { preds[i] = combine(partitionPredicate, preds[i]); } } else { if (partitionPredicate != null) { preds[i] = partitionPredicate; } else { preds[i] = alwaysTrue(); } } } this.partitionPredicates = ImmutableList.copyOf(preds); List<Predicate<Marker>> timePreds = Lists.newArrayList(); for (Map.Entry<String, Predicate> entry : timeFields.entrySet()) { timePreds.add(TimeDomain.get(strategy, entry.getKey()) .project(entry.getValue())); } this.timePredicates = ImmutableList.copyOf(timePreds); } @Override @SuppressWarnings("unchecked") public boolean apply(StorageKey key) { if (key == null) { return false; } // this is fail-fast: if the key fails a constraint, then drop it for (int i = 0; i < partitionPredicates.size(); i += 1) { Object pValue = key.get(i); if (!partitionPredicates.get(i).apply(pValue)) { return false; } } for (Predicate<Marker> timePredicate : timePredicates) { if (!timePredicate.apply(key)) { return false; } } // if we made it this far, everything passed return true; } @Override public String toString() { return Objects.toStringHelper(this) .add("predicates", partitionPredicates) .add("timePredicates", timePredicates) .toString(); } } /** * A Predicate that returns the result of transforming its input and applying * a predicate to the transformed value. * @param <S> The type of input to this predicate * @param <T> The type of input to the wrapped predicate. */ private static class TransformPredicate<S, T> implements Predicate<S> { private final Function<S, T> function; private final Predicate<T> predicate; public TransformPredicate(Function<S, T> function, Predicate<T> predicate) { this.function = function; this.predicate = predicate; } @Override public boolean apply(@Nullable S input) { return predicate.apply(function.apply(input)); } @Override public String toString() { return Objects.toStringHelper(this) .add("function", function) .add("predicate", predicate) .toString(); } } }
apache-2.0
legend-hua/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/diskbalancer/TestDiskBalancerRPC.java
12437
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.hadoop.hdfs.server.diskbalancer; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.codec.digest.DigestUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.server.datanode.DataNode; import org.apache.hadoop.hdfs.server.datanode.DiskBalancerWorkStatus; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi; import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsVolumeImpl; import org.apache.hadoop.hdfs.server.diskbalancer.DiskBalancerException.Result; import org.apache.hadoop.hdfs.server.diskbalancer.connectors.ClusterConnector; import org.apache.hadoop.hdfs.server.diskbalancer.connectors.ConnectorFactory; import org.apache.hadoop.hdfs.server.diskbalancer.datamodel.DiskBalancerCluster; import org.apache.hadoop.hdfs.server.diskbalancer.datamodel.DiskBalancerDataNode; import org.apache.hadoop.hdfs.server.diskbalancer.planner.GreedyPlanner; import org.apache.hadoop.hdfs.server.diskbalancer.planner.NodePlan; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.HashMap; import java.util.Map; import java.util.Random; import static org.apache.hadoop.hdfs.server.datanode.DiskBalancerWorkStatus.Result.NO_PLAN; import static org.apache.hadoop.hdfs.server.datanode.DiskBalancerWorkStatus.Result.PLAN_DONE; import static org.apache.hadoop.hdfs.server.datanode.DiskBalancerWorkStatus.Result.PLAN_UNDER_PROGRESS; import static org.junit.Assert.assertTrue; /** * Test DiskBalancer RPC. */ public class TestDiskBalancerRPC { @Rule public ExpectedException thrown = ExpectedException.none(); private static final String PLAN_FILE = "/system/current.plan.json"; private MiniDFSCluster cluster; private Configuration conf; @Before public void setUp() throws Exception { conf = new HdfsConfiguration(); conf.setBoolean(DFSConfigKeys.DFS_DISK_BALANCER_ENABLED, true); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); cluster.waitActive(); } @After public void tearDown() throws Exception { if (cluster != null) { cluster.shutdown(); } } @Test public void testSubmitPlan() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); String planHash = rpcTestHelper.getPlanHash(); int planVersion = rpcTestHelper.getPlanVersion(); NodePlan plan = rpcTestHelper.getPlan(); dataNode.submitDiskBalancerPlan(planHash, planVersion, PLAN_FILE, plan.toJson(), false); } @Test public void testSubmitPlanWithInvalidHash() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); String planHash = rpcTestHelper.getPlanHash(); char[] hashArray = planHash.toCharArray(); hashArray[0]++; planHash = String.valueOf(hashArray); int planVersion = rpcTestHelper.getPlanVersion(); NodePlan plan = rpcTestHelper.getPlan(); thrown.expect(DiskBalancerException.class); thrown.expect(new DiskBalancerResultVerifier(Result.INVALID_PLAN_HASH)); dataNode.submitDiskBalancerPlan(planHash, planVersion, PLAN_FILE, plan.toJson(), false); } @Test public void testSubmitPlanWithInvalidVersion() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); String planHash = rpcTestHelper.getPlanHash(); int planVersion = rpcTestHelper.getPlanVersion(); planVersion++; NodePlan plan = rpcTestHelper.getPlan(); thrown.expect(DiskBalancerException.class); thrown.expect(new DiskBalancerResultVerifier(Result.INVALID_PLAN_VERSION)); dataNode.submitDiskBalancerPlan(planHash, planVersion, PLAN_FILE, plan.toJson(), false); } @Test public void testSubmitPlanWithInvalidPlan() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); String planHash = rpcTestHelper.getPlanHash(); int planVersion = rpcTestHelper.getPlanVersion(); NodePlan plan = rpcTestHelper.getPlan(); thrown.expect(DiskBalancerException.class); thrown.expect(new DiskBalancerResultVerifier(Result.INVALID_PLAN)); dataNode.submitDiskBalancerPlan(planHash, planVersion, "", "", false); } @Test public void testCancelPlan() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); String planHash = rpcTestHelper.getPlanHash(); int planVersion = rpcTestHelper.getPlanVersion(); NodePlan plan = rpcTestHelper.getPlan(); dataNode.submitDiskBalancerPlan(planHash, planVersion, PLAN_FILE, plan.toJson(), false); dataNode.cancelDiskBalancePlan(planHash); } @Test public void testCancelNonExistentPlan() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); String planHash = rpcTestHelper.getPlanHash(); char[] hashArray= planHash.toCharArray(); hashArray[0]++; planHash = String.valueOf(hashArray); NodePlan plan = rpcTestHelper.getPlan(); thrown.expect(DiskBalancerException.class); thrown.expect(new DiskBalancerResultVerifier(Result.NO_SUCH_PLAN)); dataNode.cancelDiskBalancePlan(planHash); } @Test public void testCancelEmptyPlan() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); String planHash = ""; NodePlan plan = rpcTestHelper.getPlan(); thrown.expect(DiskBalancerException.class); thrown.expect(new DiskBalancerResultVerifier(Result.NO_SUCH_PLAN)); dataNode.cancelDiskBalancePlan(planHash); } @Test public void testGetDiskBalancerVolumeMapping() throws Exception { final int dnIndex = 0; DataNode dataNode = cluster.getDataNodes().get(dnIndex); String volumeNameJson = dataNode.getDiskBalancerSetting( DiskBalancerConstants.DISKBALANCER_VOLUME_NAME); Assert.assertNotNull(volumeNameJson); ObjectMapper mapper = new ObjectMapper(); @SuppressWarnings("unchecked") Map<String, String> volumemap = mapper.readValue(volumeNameJson, HashMap.class); Assert.assertEquals(2, volumemap.size()); } @Test public void testGetDiskBalancerInvalidSetting() throws Exception { final int dnIndex = 0; final String invalidSetting = "invalidSetting"; DataNode dataNode = cluster.getDataNodes().get(dnIndex); thrown.expect(DiskBalancerException.class); thrown.expect(new DiskBalancerResultVerifier(Result.UNKNOWN_KEY)); dataNode.getDiskBalancerSetting(invalidSetting); } @Test public void testgetDiskBalancerBandwidth() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); String planHash = rpcTestHelper.getPlanHash(); int planVersion = rpcTestHelper.getPlanVersion(); NodePlan plan = rpcTestHelper.getPlan(); dataNode.submitDiskBalancerPlan(planHash, planVersion, PLAN_FILE, plan.toJson(), false); String bandwidthString = dataNode.getDiskBalancerSetting( DiskBalancerConstants.DISKBALANCER_BANDWIDTH); long value = Long.decode(bandwidthString); Assert.assertEquals(10L, value); } @Test public void testQueryPlan() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); String planHash = rpcTestHelper.getPlanHash(); int planVersion = rpcTestHelper.getPlanVersion(); NodePlan plan = rpcTestHelper.getPlan(); dataNode.submitDiskBalancerPlan(planHash, planVersion, PLAN_FILE, plan.toJson(), false); DiskBalancerWorkStatus status = dataNode.queryDiskBalancerPlan(); Assert.assertTrue(status.getResult() == PLAN_UNDER_PROGRESS || status.getResult() == PLAN_DONE); } @Test public void testQueryPlanWithoutSubmit() throws Exception { RpcTestHelper rpcTestHelper = new RpcTestHelper().invoke(); DataNode dataNode = rpcTestHelper.getDataNode(); DiskBalancerWorkStatus status = dataNode.queryDiskBalancerPlan(); Assert.assertTrue(status.getResult() == NO_PLAN); } @Test public void testMoveBlockAcrossVolume() throws Exception { Configuration conf = new HdfsConfiguration(); final int defaultBlockSize = 100; conf.setBoolean(DFSConfigKeys.DFS_DISK_BALANCER_ENABLED, true); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, defaultBlockSize); conf.setInt(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, defaultBlockSize); String fileName = "/tmp.txt"; Path filePath = new Path(fileName); final int numDatanodes = 1; final int dnIndex = 0; cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(numDatanodes).build(); FsVolumeImpl source = null; FsVolumeImpl dest = null; try { cluster.waitActive(); Random r = new Random(); FileSystem fs = cluster.getFileSystem(dnIndex); DFSTestUtil.createFile(fs, filePath, 10 * 1024, (short) 1, r.nextLong()); DataNode dnNode = cluster.getDataNodes().get(dnIndex); FsDatasetSpi.FsVolumeReferences refs = dnNode.getFSDataset().getFsVolumeReferences(); try { source = (FsVolumeImpl) refs.get(0); dest = (FsVolumeImpl) refs.get(1); DiskBalancerTestUtil.moveAllDataToDestVolume(dnNode.getFSDataset(), source, dest); assertTrue(DiskBalancerTestUtil.getBlockCount(source) == 0); } finally { refs.close(); } } finally { cluster.shutdown(); } } private class RpcTestHelper { private NodePlan plan; private int planVersion; private DataNode dataNode; private String planHash; public NodePlan getPlan() { return plan; } public int getPlanVersion() { return planVersion; } public DataNode getDataNode() { return dataNode; } public String getPlanHash() { return planHash; } public RpcTestHelper invoke() throws Exception { final int dnIndex = 0; cluster.restartDataNode(dnIndex); cluster.waitActive(); ClusterConnector nameNodeConnector = ConnectorFactory.getCluster(cluster.getFileSystem(0).getUri(), conf); DiskBalancerCluster diskBalancerCluster = new DiskBalancerCluster(nameNodeConnector); diskBalancerCluster.readClusterInfo(); Assert.assertEquals(cluster.getDataNodes().size(), diskBalancerCluster.getNodes().size()); diskBalancerCluster.setNodesToProcess(diskBalancerCluster.getNodes()); dataNode = cluster.getDataNodes().get(dnIndex); DiskBalancerDataNode node = diskBalancerCluster.getNodeByUUID( dataNode.getDatanodeUuid()); GreedyPlanner planner = new GreedyPlanner(10.0f, node); plan = new NodePlan(node.getDataNodeName(), node.getDataNodePort()); planner.balanceVolumeSet(node, node.getVolumeSets().get("DISK"), plan); planVersion = 1; planHash = DigestUtils.shaHex(plan.toJson()); return this; } } }
apache-2.0
nwnpallewela/developer-studio
jaggery/plugins/org.eclipse.php.core/src/org/eclipse/php/internal/core/codeassist/contexts/CatchVariableContext.java
1190
/******************************************************************************* * Copyright (c) 2009 IBM Corporation 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 * * Contributors: * IBM Corporation - initial API and implementation * Zend Technologies *******************************************************************************/ package org.eclipse.php.internal.core.codeassist.contexts; import org.eclipse.dltk.core.CompletionRequestor; import org.eclipse.dltk.core.ISourceModule; /** * This context represents state when staying in catch statement variable part. <br/> * Examples: * * <pre> * 1. catch (Exception |) { } * 2. catch (Exception $a|) { } * </pre> * * @author michael */ public class CatchVariableContext extends CatchContext { public boolean isValid(ISourceModule sourceModule, int offset, CompletionRequestor requestor) { if (!super.isValid(sourceModule, offset, requestor)) { return false; } return false; } }
apache-2.0
ChetnaChaudhari/hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/test/java/org/apache/hadoop/mapred/TestLocalModeWithNewApis.java
5220
/** * 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.mapred; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.MRConfig; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestLocalModeWithNewApis { public static final Logger LOG = LoggerFactory.getLogger(TestLocalModeWithNewApis.class); Configuration conf; @Before public void setUp() throws Exception { conf = new Configuration(); conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.LOCAL_FRAMEWORK_NAME); } @After public void tearDown() throws Exception { } @Test public void testNewApis() throws Exception { Random r = new Random(System.currentTimeMillis()); Path tmpBaseDir = new Path("/tmp/wc-" + r.nextInt()); final Path inDir = new Path(tmpBaseDir, "input"); final Path outDir = new Path(tmpBaseDir, "output"); String input = "The quick brown fox\nhas many silly\nred fox sox\n"; FileSystem inFs = inDir.getFileSystem(conf); FileSystem outFs = outDir.getFileSystem(conf); outFs.delete(outDir, true); if (!inFs.mkdirs(inDir)) { throw new IOException("Mkdirs failed to create " + inDir.toString()); } { DataOutputStream file = inFs.create(new Path(inDir, "part-0")); file.writeBytes(input); file.close(); } Job job = Job.getInstance(conf, "word count"); job.setJarByClass(TestLocalModeWithNewApis.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, inDir); FileOutputFormat.setOutputPath(job, outDir); assertEquals(job.waitForCompletion(true), true); String output = readOutput(outDir, conf); assertEquals("The\t1\nbrown\t1\nfox\t2\nhas\t1\nmany\t1\n" + "quick\t1\nred\t1\nsilly\t1\nsox\t1\n", output); outFs.delete(tmpBaseDir, true); } static String readOutput(Path outDir, Configuration conf) throws IOException { FileSystem fs = outDir.getFileSystem(conf); StringBuffer result = new StringBuffer(); Path[] fileList = FileUtil.stat2Paths(fs.listStatus(outDir, new Utils.OutputFileUtils.OutputFilesFilter())); for (Path outputFile : fileList) { LOG.info("Path" + ": "+ outputFile); BufferedReader file = new BufferedReader(new InputStreamReader(fs.open(outputFile))); String line = file.readLine(); while (line != null) { result.append(line); result.append("\n"); line = file.readLine(); } file.close(); } return result.toString(); } public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>{ private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); } } } public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context ) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } }
apache-2.0
packet-tracker/onos
core/store/dist/src/main/java/org/onosproject/store/consistent/impl/DefaultConsistentMapBuilder.java
4460
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.consistent.impl; import org.onosproject.core.ApplicationId; import org.onosproject.store.service.AsyncConsistentMap; import org.onosproject.store.service.ConsistentMap; import org.onosproject.store.service.ConsistentMapBuilder; import org.onosproject.store.service.Serializer; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; /** * Default Consistent Map builder. * * @param <K> type for map key * @param <V> type for map value */ public class DefaultConsistentMapBuilder<K, V> implements ConsistentMapBuilder<K, V> { private Serializer serializer; private String name; private ApplicationId applicationId; private boolean purgeOnUninstall = false; private boolean partitionsEnabled = true; private boolean readOnly = false; private boolean metering = true; private boolean relaxedReadConsistency = false; private final DatabaseManager manager; public DefaultConsistentMapBuilder(DatabaseManager manager) { this.manager = manager; } @Override public ConsistentMapBuilder<K, V> withName(String name) { checkArgument(name != null && !name.isEmpty()); this.name = name; return this; } @Override public ConsistentMapBuilder<K, V> withApplicationId(ApplicationId id) { checkArgument(id != null); this.applicationId = id; return this; } @Override public ConsistentMapBuilder<K, V> withPurgeOnUninstall() { purgeOnUninstall = true; return this; } @Override public ConsistentMapBuilder<K, V> withMeteringDisabled() { metering = false; return this; } @Override public ConsistentMapBuilder<K, V> withSerializer(Serializer serializer) { checkArgument(serializer != null); this.serializer = serializer; return this; } @Override public ConsistentMapBuilder<K, V> withPartitionsDisabled() { partitionsEnabled = false; return this; } @Override public ConsistentMapBuilder<K, V> withUpdatesDisabled() { readOnly = true; return this; } @Override public ConsistentMapBuilder<K, V> withRelaxedReadConsistency() { relaxedReadConsistency = true; return this; } private void validateInputs() { checkState(name != null, "name must be specified"); checkState(serializer != null, "serializer must be specified"); if (purgeOnUninstall) { checkState(applicationId != null, "ApplicationId must be specified when purgeOnUninstall is enabled"); } } @Override public ConsistentMap<K, V> build() { return new DefaultConsistentMap<>(buildAndRegisterMap()); } @Override public AsyncConsistentMap<K, V> buildAsyncMap() { return buildAndRegisterMap(); } private DefaultAsyncConsistentMap<K, V> buildAndRegisterMap() { validateInputs(); Database database = partitionsEnabled ? manager.partitionedDatabase : manager.inMemoryDatabase; if (relaxedReadConsistency) { return manager.registerMap( new AsyncCachingConsistentMap<>(name, applicationId, database, serializer, readOnly, purgeOnUninstall, metering)); } else { return manager.registerMap( new DefaultAsyncConsistentMap<>(name, applicationId, database, serializer, readOnly, purgeOnUninstall, metering)); } } }
apache-2.0
siyuanh/apex-malhar
library/src/test/java/com/datatorrent/lib/db/cache/CacheStoreTest.java
1705
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.lib.db.cache; import java.io.IOException; import java.util.Map; import org.junit.Assert; import org.junit.Test; import com.google.common.collect.Maps; /** * Test fot {@link CacheStore}. */ public class CacheStoreTest { @Test public void CacheStoreTest() { final Map<Object, Object> backupMap = Maps.newHashMap(); backupMap.put(1, "one"); backupMap.put(2, "two"); backupMap.put(3, "three"); backupMap.put(4, "four"); backupMap.put(5, "five"); backupMap.put(6, "six"); backupMap.put(7, "seven"); backupMap.put(8, "eight"); backupMap.put(9, "nine"); backupMap.put(10, "ten"); CacheStore cs = new CacheStore(); cs.setMaxCacheSize(5); try { cs.connect(); cs.putAll(backupMap); Assert.assertEquals(5, cs.getKeys().size()); } catch (IOException e) { e.printStackTrace(); } } }
apache-2.0
tebeka/arrow
java/gandiva/src/main/java/org/apache/arrow/gandiva/expression/StringNode.java
1664
/* * 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.arrow.gandiva.expression; import java.nio.charset.Charset; import org.apache.arrow.gandiva.exceptions.GandivaException; import org.apache.arrow.gandiva.ipc.GandivaTypes; import com.google.protobuf.ByteString; /** * Used to represent expression tree nodes representing utf8 constants. */ class StringNode implements TreeNode { private static final Charset charset = Charset.forName("UTF-8"); private final String value; public StringNode(String value) { this.value = value; } @Override public GandivaTypes.TreeNode toProtobuf() throws GandivaException { GandivaTypes.StringNode stringNode = GandivaTypes.StringNode.newBuilder() .setValue(ByteString.copyFrom(value.getBytes(charset))) .build(); return GandivaTypes.TreeNode.newBuilder() .setStringNode(stringNode) .build(); } }
apache-2.0
asedunov/intellij-community
platform/diff-impl/src/com/intellij/diff/applications/ApplicationStarterBase.java
4832
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.applications; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationStarterEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"}) public abstract class ApplicationStarterBase extends ApplicationStarterEx { protected static final Logger LOG = Logger.getInstance(ApplicationStarterBase.class); protected abstract boolean checkArguments(@NotNull String[] args); @NotNull protected abstract String getUsageMessage(); protected abstract void processCommand(@NotNull String[] args, @Nullable String currentDirectory) throws Exception; // // Impl // @Override public boolean isHeadless() { return false; } @Override public void processExternalCommandLine(@NotNull String[] args, @Nullable String currentDirectory) { if (!checkArguments(args)) { Messages.showMessageDialog(getUsageMessage(), StringUtil.toTitleCase(getCommandName()), Messages.getInformationIcon()); return; } try { processCommand(args, currentDirectory); } catch (Exception e) { Messages.showMessageDialog(String.format("Error showing %s: %s", getCommandName(), e.getMessage()), StringUtil.toTitleCase(getCommandName()), Messages.getErrorIcon()); } finally { saveAll(); } } private static void saveAll() { FileDocumentManager.getInstance().saveAllDocuments(); ApplicationManager.getApplication().saveSettings(); } @Override public void premain(String[] args) { if (!checkArguments(args)) { System.out.println(getUsageMessage()); System.exit(1); } } @Override public void main(String[] args) { try { processCommand(args, null); } catch (Exception e) { e.printStackTrace(); System.exit(1); } catch (Throwable t) { t.printStackTrace(); System.exit(2); } finally { saveAll(); } System.exit(0); } @NotNull public static List<VirtualFile> findFiles(@NotNull List<String> filePaths, @Nullable String currentDirectory) throws Exception { List<VirtualFile> files = new ArrayList<>(); for (String path : filePaths) { VirtualFile virtualFile = findFile(path, currentDirectory); if (virtualFile == null) throw new Exception("Can't find file " + path); files.add(virtualFile); } VfsUtil.markDirtyAndRefresh(false, false, false, VfsUtilCore.toVirtualFileArray(files)); for (int i = 0; i < filePaths.size(); i++) { if (!files.get(i).isValid()) throw new Exception("Can't find file " + filePaths.get(i)); } return files; } @Nullable public static VirtualFile findFile(@NotNull String path, @Nullable String currentDirectory) throws IOException { File file = getFile(path, currentDirectory); VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); if (virtualFile == null) { LOG.warn(String.format("Can't find file: current directory - %s; path - %s", currentDirectory, path)); } return virtualFile; } @NotNull public static File getFile(@NotNull String path, @Nullable String currentDirectory) { File file = new File(path); if (!file.isAbsolute() && currentDirectory != null) { file = new File(currentDirectory, path); } return file; } @Override public boolean canProcessExternalCommandLine() { return true; } @Nullable protected Project getProject() { return null; // TODO: try to guess project } }
apache-2.0
asedunov/intellij-community
plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/ui/StructureTree.java
2344
/* * Copyright 2002-2007 Sascha Weinreuter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.xsltDebugger.ui; import com.intellij.openapi.actionSystem.*; import com.intellij.pom.Navigatable; import com.intellij.ui.PopupHandler; import com.intellij.ui.treeStructure.Tree; import org.intellij.plugins.xsltDebugger.ui.actions.CopyValueAction; import org.intellij.plugins.xsltDebugger.ui.actions.NavigateAction; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; public class StructureTree extends Tree implements TypeSafeDataProvider { public StructureTree(GeneratedStructureModel model) { super(model); setCellRenderer(new GeneratedStructureRenderer()); setRootVisible(false); setShowsRootHandles(true); final DefaultActionGroup structureContextActions = new DefaultActionGroup("StructureContext", true); structureContextActions.add(NavigateAction.getInstance()); structureContextActions.add(new CopyValueAction(this)); PopupHandler.installFollowingSelectionTreePopup(this, structureContextActions, "XSLT.Debugger.GeneratedStructure", ActionManager.getInstance()); } public void calcData(DataKey key, DataSink sink) { if (key.equals(CommonDataKeys.NAVIGATABLE)) { final TreePath selection = getSelectionPath(); if (selection != null) { final Object o = selection.getLastPathComponent(); if (o instanceof Navigatable) { sink.put(CommonDataKeys.NAVIGATABLE, (Navigatable)o); } } } else if (key.equals(CopyValueAction.SELECTED_NODE)) { final TreePath selection = getSelectionPath(); if (selection != null) { final Object o = selection.getLastPathComponent(); sink.put(CopyValueAction.SELECTED_NODE, (DefaultMutableTreeNode)o); } } } }
apache-2.0
siosio/intellij-community
plugins/InspectionGadgets/testsrc/com/siyeh/ig/migration/EqualsReplaceableByObjectsCallInspectionTest.java
2376
/* * 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.siyeh.ig.migration; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.siyeh.ig.LightJavaInspectionTestCase; import org.jetbrains.annotations.Nullable; /** * @author Bas Leijdekkers */ public class EqualsReplaceableByObjectsCallInspectionTest extends LightJavaInspectionTestCase { private EqualsReplaceableByObjectsCallInspection myInspection = new EqualsReplaceableByObjectsCallInspection(); @Override public void setUp() throws Exception { super.setUp(); final InspectionProfileImpl profile = InspectionProfileManager.getInstance(getProject()).getCurrentProfile(); profile.setErrorLevel(HighlightDisplayKey.find("EqualsReplaceableByObjectsCall"), HighlightDisplayLevel.WARNING, getProject()); } @Override protected void tearDown() throws Exception { myInspection = null; super.tearDown(); } public void testEqualsReplaceableByObjectsCall() { testEqualsReplaceable(false); } public void testEqualsReplaceableByObjectsCallCheckNull() { testEqualsReplaceable(true); } protected void testEqualsReplaceable(boolean checkNotNull) { boolean oldNotNull = myInspection.checkNotNull; try { myInspection.checkNotNull = checkNotNull; myFixture.configureByFile(getTestName(false) + ".java"); myFixture.testHighlighting(true, true, false); } finally { myInspection.checkNotNull = oldNotNull; } } @Nullable @Override protected LocalInspectionTool getInspection() { return myInspection; } }
apache-2.0
donNewtonAlpha/onos
cli/src/main/java/org/onosproject/cli/net/IntentListCompilers.java
1730
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.cli.net; import org.apache.karaf.shell.commands.Command; import org.onosproject.cli.AbstractShellCommand; import org.onosproject.net.intent.IntentExtensionService; import java.util.OptionalInt; /** * Lists the inventory of intents and their states. */ @Command(scope = "onos", name = "intent-compilers", description = "Lists the mapping from intent type to compiler component") public class IntentListCompilers extends AbstractShellCommand { @Override protected void execute() { IntentExtensionService service = get(IntentExtensionService.class); OptionalInt length = service.getCompilers().keySet().stream() .mapToInt(s -> s.getName().length()) .max(); if (length.isPresent()) { service.getCompilers().entrySet().forEach(e -> { print("%-" + length.getAsInt() + "s\t%s", e.getKey().getName(), e.getValue().getClass().getName()); }); } else { print("There are no compilers registered."); } } }
apache-2.0
nikhilvibhav/camel
components/camel-tracing/src/test/java/org/apache/camel/tracing/decorators/JdbcSpanDecoratorTest.java
2047
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.tracing.decorators; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.tracing.MockSpanAdapter; import org.apache.camel.tracing.SpanDecorator; import org.apache.camel.tracing.Tag; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; public class JdbcSpanDecoratorTest { private static final String SQL_STATEMENT = "select * from customer"; @Test public void testPre() { Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpointUri()).thenReturn("test"); Mockito.when(exchange.getIn()).thenReturn(message); Mockito.when(message.getBody()).thenReturn(SQL_STATEMENT); SpanDecorator decorator = new JdbcSpanDecorator(); MockSpanAdapter span = new MockSpanAdapter(); decorator.pre(span, exchange, endpoint); assertEquals("sql", span.tags().get(Tag.DB_TYPE.name())); assertEquals(SQL_STATEMENT, span.tags().get(Tag.DB_STATEMENT.name())); } }
apache-2.0
gingerwizard/elasticsearch
server/src/test/java/org/elasticsearch/index/analysis/NamedAnalyzerTests.java
4351
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.analysis; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.elasticsearch.index.mapper.MapperException; import org.elasticsearch.index.mapper.TextFieldMapper; import org.elasticsearch.test.ESTestCase; public class NamedAnalyzerTests extends ESTestCase { public void testCheckAllowedInMode() { try (NamedAnalyzer testAnalyzer = new NamedAnalyzer("my_analyzer", AnalyzerScope.INDEX, createAnalyzerWithMode("my_analyzer", AnalysisMode.INDEX_TIME), Integer.MIN_VALUE)) { testAnalyzer.checkAllowedInMode(AnalysisMode.INDEX_TIME); MapperException ex = expectThrows(MapperException.class, () -> testAnalyzer.checkAllowedInMode(AnalysisMode.SEARCH_TIME)); assertEquals("analyzer [my_analyzer] contains filters [my_analyzer] that are not allowed to run in search time mode.", ex.getMessage()); ex = expectThrows(MapperException.class, () -> testAnalyzer.checkAllowedInMode(AnalysisMode.ALL)); assertEquals("analyzer [my_analyzer] contains filters [my_analyzer] that are not allowed to run in all mode.", ex.getMessage()); } try (NamedAnalyzer testAnalyzer = new NamedAnalyzer("my_analyzer", AnalyzerScope.INDEX, createAnalyzerWithMode("my_analyzer", AnalysisMode.SEARCH_TIME), Integer.MIN_VALUE)) { testAnalyzer.checkAllowedInMode(AnalysisMode.SEARCH_TIME); MapperException ex = expectThrows(MapperException.class, () -> testAnalyzer.checkAllowedInMode(AnalysisMode.INDEX_TIME)); assertEquals("analyzer [my_analyzer] contains filters [my_analyzer] that are not allowed to run in index time mode.", ex.getMessage()); ex = expectThrows(MapperException.class, () -> testAnalyzer.checkAllowedInMode(AnalysisMode.ALL)); assertEquals("analyzer [my_analyzer] contains filters [my_analyzer] that are not allowed to run in all mode.", ex.getMessage()); } try (NamedAnalyzer testAnalyzer = new NamedAnalyzer("my_analyzer", AnalyzerScope.INDEX, createAnalyzerWithMode("my_analyzer", AnalysisMode.ALL), Integer.MIN_VALUE)) { testAnalyzer.checkAllowedInMode(AnalysisMode.ALL); testAnalyzer.checkAllowedInMode(AnalysisMode.INDEX_TIME); testAnalyzer.checkAllowedInMode(AnalysisMode.SEARCH_TIME); } } private Analyzer createAnalyzerWithMode(String name, AnalysisMode mode) { TokenFilterFactory tokenFilter = new TokenFilterFactory() { @Override public String name() { return name; } @Override public TokenStream create(TokenStream tokenStream) { return null; } @Override public AnalysisMode getAnalysisMode() { return mode; } }; TokenFilterFactory[] tokenfilters = new TokenFilterFactory[] { tokenFilter }; CharFilterFactory[] charFilters = new CharFilterFactory[0]; if (mode == AnalysisMode.SEARCH_TIME && randomBoolean()) { AnalyzerComponents components = new AnalyzerComponents(null, charFilters, tokenfilters); // sometimes also return reloadable custom analyzer return new ReloadableCustomAnalyzer(components , TextFieldMapper.Defaults.POSITION_INCREMENT_GAP, -1); } return new CustomAnalyzer(null, charFilters, tokenfilters); } }
apache-2.0
ThiagoGarciaAlves/intellij-community
platform/lang-api/src/com/intellij/facet/FacetType.java
6049
/* * Copyright 2000-2011 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.facet; import com.intellij.facet.autodetecting.FacetDetectorRegistry; import com.intellij.facet.ui.DefaultFacetSettingsEditor; import com.intellij.facet.ui.FacetEditor; import com.intellij.facet.ui.MultipleFacetSettingsEditor; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * Override this class to provide custom type of facets. The implementation should be registered in your {@code plugin.xml}: * <pre> * &lt;extensions defaultExtensionNs="com.intellij"&gt; * &nbsp;&nbsp;&lt;facetType implementation="qualified-class-name"/&gt; * &lt;/extensions&gt; * </pre> * @author nik */ public abstract class FacetType<F extends Facet, C extends FacetConfiguration> { public static final ExtensionPointName<FacetType> EP_NAME = ExtensionPointName.create("com.intellij.facetType"); private final @NotNull FacetTypeId<F> myId; private final @NotNull String myStringId; private final @NotNull String myPresentableName; private final @Nullable FacetTypeId myUnderlyingFacetType; public static <T extends FacetType> T findInstance(Class<T> aClass) { return EP_NAME.findExtension(aClass); } /** * @param id unique instance of {@link FacetTypeId} * @param stringId unique string id of the facet type * @param presentableName name of this facet type which will be shown in UI * @param underlyingFacetType if this parameter is not {@code null} then you will be able to add facets of this type only as * subfacets to a facet of the specified type. If this parameter is {@code null} it will be possible to add facet of this type * directly to a module */ public FacetType(final @NotNull FacetTypeId<F> id, final @NotNull @NonNls String stringId, final @NotNull String presentableName, final @Nullable FacetTypeId underlyingFacetType) { myId = id; myStringId = stringId; myPresentableName = presentableName; myUnderlyingFacetType = underlyingFacetType; } /** * @param id unique instance of {@link FacetTypeId} * @param stringId unique string id of the facet type * @param presentableName name of this facet type which will be shown in UI */ public FacetType(final @NotNull FacetTypeId<F> id, final @NotNull @NonNls String stringId, final @NotNull String presentableName) { this(id, stringId, presentableName, null); } @NotNull public final FacetTypeId<F> getId() { return myId; } @NotNull public final String getStringId() { return myStringId; } @NotNull public String getPresentableName() { return myPresentableName; } /** * Default name which will be used then user creates a facet of this type * @return */ @NotNull @NonNls public String getDefaultFacetName() { return myPresentableName; } @Nullable public final FacetTypeId<?> getUnderlyingFacetType() { return myUnderlyingFacetType; } /** * @deprecated this method is not called by IDEA core anymore. Use {@link com.intellij.framework.detection.FrameworkDetector} extension * to provide automatic detection for facets */ public void registerDetectors(FacetDetectorRegistry<C> registry) { } /** * Create default configuration of facet. See {@link FacetConfiguration} for details * @return */ public abstract C createDefaultConfiguration(); /** * Create a new facet instance * @param module parent module for facet. Must be passed to {@link Facet} constructor * @param name name of facet. Must be passed to {@link Facet} constructor * @param configuration facet configuration. Must be passed to {@link Facet} constructor * @param underlyingFacet underlying facet. Must be passed to {@link Facet} constructor * @return a created facet */ public abstract F createFacet(@NotNull Module module, final String name, @NotNull C configuration, @Nullable Facet underlyingFacet); /** * @return {@code true} if only one facet of this type is allowed within the containing module (if this type doesn't have the underlying * facet type) or within the underlying facet */ public boolean isOnlyOneFacetAllowed() { return true; } /** * @param moduleType type of module * @return {@code true} if facet of this type are allowed in module of type {@code moduleType} */ public abstract boolean isSuitableModuleType(ModuleType moduleType); @Nullable public Icon getIcon() { return null; } /** * Returns the topic in the help file which is shown when help for this facet type is requested * * @return the help topic, or null if no help is available. */ @Nullable @NonNls public String getHelpTopic() { return null; } @Nullable public DefaultFacetSettingsEditor createDefaultConfigurationEditor(@NotNull Project project, @NotNull C configuration) { return null; } /** * Override to allow editing several facets at once * @param project project * @param editors editors of selected facets * @return editor */ @Nullable public MultipleFacetSettingsEditor createMultipleConfigurationsEditor(@NotNull Project project, @NotNull FacetEditor[] editors) { return null; } }
apache-2.0
DadanielZ/incubator-eagle
eagle-core/eagle-app/eagle-app-base/src/main/java/org/apache/eagle/app/messaging/StreamEventMapper.java
1293
/* * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.eagle.app.messaging; import org.apache.eagle.alert.engine.model.StreamEvent; import backtype.storm.tuple.Tuple; import java.io.Serializable; import java.util.List; @FunctionalInterface public interface StreamEventMapper extends Serializable { /** * Map from storm tuple to Stream Event. * * @param tuple * @return * @throws Exception */ List<StreamEvent> map(Tuple tuple) throws Exception; }
apache-2.0
antalpeti/JUnit
src/org/junit/experimental/theories/Theories.java
12849
package org.junit.experimental.theories; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Assume; import org.junit.experimental.theories.internal.Assignments; import org.junit.experimental.theories.internal.ParameterizedAssertionError; import org.junit.internal.AssumptionViolatedException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; /** * The Theories runner allows to test a certain functionality against a subset of an infinite set of data points. * <p> * A Theory is a piece of functionality (a method) that is executed against several data inputs called data points. * To make a test method a theory you mark it with <b>&#064;Theory</b>. To create a data point you create a public * field in your test class and mark it with <b>&#064;DataPoint</b>. The Theories runner then executes your test * method as many times as the number of data points declared, providing a different data point as * the input argument on each invocation. * </p> * <p> * A Theory differs from standard test method in that it captures some aspect of the intended behavior in possibly * infinite numbers of scenarios which corresponds to the number of data points declared. Using assumptions and * assertions properly together with covering multiple scenarios with different data points can make your tests more * flexible and bring them closer to scientific theories (hence the name). * </p> * <p> * For example: * <pre> * * &#064;RunWith(<b>Theories.class</b>) * public class UserTest { * <b>&#064;DataPoint</b> * public static String GOOD_USERNAME = "optimus"; * <b>&#064;DataPoint</b> * public static String USERNAME_WITH_SLASH = "optimus/prime"; * * <b>&#064;Theory</b> * public void filenameIncludesUsername(String username) { * assumeThat(username, not(containsString("/"))); * assertThat(new User(username).configFileName(), containsString(username)); * } * } * </pre> * This makes it clear that the user's filename should be included in the config file name, * only if it doesn't contain a slash. Another test or theory might define what happens when a username does contain * a slash. <code>UserTest</code> will attempt to run <code>filenameIncludesUsername</code> on every compatible data * point defined in the class. If any of the assumptions fail, the data point is silently ignored. If all of the * assumptions pass, but an assertion fails, the test fails. * <p> * Defining general statements as theories allows data point reuse across a bunch of functionality tests and also * allows automated tools to search for new, unexpected data points that expose bugs. * </p> * <p> * The support for Theories has been absorbed from the Popper project, and more complete documentation can be found * from that projects archived documentation. * </p> * * @see <a href="http://web.archive.org/web/20071012143326/popper.tigris.org/tutorial.html">Archived Popper project documentation</a> * @see <a href="http://web.archive.org/web/20110608210825/http://shareandenjoy.saff.net/tdd-specifications.pdf">Paper on Theories</a> */ public class Theories extends BlockJUnit4ClassRunner { public Theories(Class<?> klass) throws InitializationError { super(klass); } @Override protected void collectInitializationErrors(List<Throwable> errors) { super.collectInitializationErrors(errors); validateDataPointFields(errors); validateDataPointMethods(errors); } private void validateDataPointFields(List<Throwable> errors) { Field[] fields = getTestClass().getJavaClass().getDeclaredFields(); for (Field field : fields) { if (field.getAnnotation(DataPoint.class) == null && field.getAnnotation(DataPoints.class) == null) { continue; } if (!Modifier.isStatic(field.getModifiers())) { errors.add(new Error("DataPoint field " + field.getName() + " must be static")); } if (!Modifier.isPublic(field.getModifiers())) { errors.add(new Error("DataPoint field " + field.getName() + " must be public")); } } } private void validateDataPointMethods(List<Throwable> errors) { Method[] methods = getTestClass().getJavaClass().getDeclaredMethods(); for (Method method : methods) { if (method.getAnnotation(DataPoint.class) == null && method.getAnnotation(DataPoints.class) == null) { continue; } if (!Modifier.isStatic(method.getModifiers())) { errors.add(new Error("DataPoint method " + method.getName() + " must be static")); } if (!Modifier.isPublic(method.getModifiers())) { errors.add(new Error("DataPoint method " + method.getName() + " must be public")); } } } @Override protected void validateConstructor(List<Throwable> errors) { validateOnlyOneConstructor(errors); } @Override protected void validateTestMethods(List<Throwable> errors) { for (FrameworkMethod each : computeTestMethods()) { if (each.getAnnotation(Theory.class) != null) { each.validatePublicVoid(false, errors); each.validateNoTypeParametersOnArgs(errors); } else { each.validatePublicVoidNoArg(false, errors); } for (ParameterSignature signature : ParameterSignature.signatures(each.getMethod())) { ParametersSuppliedBy annotation = signature.findDeepAnnotation(ParametersSuppliedBy.class); if (annotation != null) { validateParameterSupplier(annotation.value(), errors); } } } } private void validateParameterSupplier(Class<? extends ParameterSupplier> supplierClass, List<Throwable> errors) { Constructor<?>[] constructors = supplierClass.getConstructors(); if (constructors.length != 1) { errors.add(new Error("ParameterSupplier " + supplierClass.getName() + " must have only one constructor (either empty or taking only a TestClass)")); } else { Class<?>[] paramTypes = constructors[0].getParameterTypes(); if (!(paramTypes.length == 0) && !paramTypes[0].equals(TestClass.class)) { errors.add(new Error("ParameterSupplier " + supplierClass.getName() + " constructor must take either nothing or a single TestClass instance")); } } } @Override protected List<FrameworkMethod> computeTestMethods() { List<FrameworkMethod> testMethods = new ArrayList<FrameworkMethod>(super.computeTestMethods()); List<FrameworkMethod> theoryMethods = getTestClass().getAnnotatedMethods(Theory.class); testMethods.removeAll(theoryMethods); testMethods.addAll(theoryMethods); return testMethods; } @Override public Statement methodBlock(final FrameworkMethod method) { return new TheoryAnchor(method, getTestClass()); } public static class TheoryAnchor extends Statement { private int successes = 0; private final FrameworkMethod testMethod; private final TestClass testClass; private List<AssumptionViolatedException> fInvalidParameters = new ArrayList<AssumptionViolatedException>(); public TheoryAnchor(FrameworkMethod testMethod, TestClass testClass) { this.testMethod = testMethod; this.testClass = testClass; } private TestClass getTestClass() { return testClass; } @Override public void evaluate() throws Throwable { runWithAssignment(Assignments.allUnassigned( testMethod.getMethod(), getTestClass())); //if this test method is not annotated with Theory, then no successes is a valid case boolean hasTheoryAnnotation = testMethod.getAnnotation(Theory.class) != null; if (successes == 0 && hasTheoryAnnotation) { Assert .fail("Never found parameters that satisfied method assumptions. Violated assumptions: " + fInvalidParameters); } } protected void runWithAssignment(Assignments parameterAssignment) throws Throwable { if (!parameterAssignment.isComplete()) { runWithIncompleteAssignment(parameterAssignment); } else { runWithCompleteAssignment(parameterAssignment); } } protected void runWithIncompleteAssignment(Assignments incomplete) throws Throwable { for (PotentialAssignment source : incomplete .potentialsForNextUnassigned()) { runWithAssignment(incomplete.assignNext(source)); } } protected void runWithCompleteAssignment(final Assignments complete) throws Throwable { new BlockJUnit4ClassRunner(getTestClass().getJavaClass()) { @Override protected void collectInitializationErrors( List<Throwable> errors) { // do nothing } @Override public Statement methodBlock(FrameworkMethod method) { final Statement statement = super.methodBlock(method); return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); handleDataPointSuccess(); } catch (AssumptionViolatedException e) { handleAssumptionViolation(e); } catch (Throwable e) { reportParameterizedError(e, complete .getArgumentStrings(nullsOk())); } } }; } @Override protected Statement methodInvoker(FrameworkMethod method, Object test) { return methodCompletesWithParameters(method, complete, test); } @Override public Object createTest() throws Exception { Object[] params = complete.getConstructorArguments(); if (!nullsOk()) { Assume.assumeNotNull(params); } return getTestClass().getOnlyConstructor().newInstance(params); } }.methodBlock(testMethod).evaluate(); } private Statement methodCompletesWithParameters( final FrameworkMethod method, final Assignments complete, final Object freshInstance) { return new Statement() { @Override public void evaluate() throws Throwable { final Object[] values = complete.getMethodArguments(); if (!nullsOk()) { Assume.assumeNotNull(values); } method.invokeExplosively(freshInstance, values); } }; } protected void handleAssumptionViolation(AssumptionViolatedException e) { fInvalidParameters.add(e); } protected void reportParameterizedError(Throwable e, Object... params) throws Throwable { if (params.length == 0) { throw e; } throw new ParameterizedAssertionError(e, testMethod.getName(), params); } private boolean nullsOk() { Theory annotation = testMethod.getMethod().getAnnotation( Theory.class); if (annotation == null) { return false; } return annotation.nullsAccepted(); } protected void handleDataPointSuccess() { successes++; } } }
epl-1.0
md-5/jdk10
src/java.base/share/classes/sun/security/ssl/SSLKeyAgreement.java
1372
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.ssl; interface SSLKeyAgreement extends SSLPossessionGenerator, SSLKeyAgreementGenerator, SSLHandshakeBinding { // blank }
gpl-2.0
KadimIT/android-wallpaper-slideshow
src/com/birbeck/wallpaperslideshow/BitmapUtil.java
10170
/* * Copyright (C) 2010 Stewart Gateley <birbeck@gmail.com> * * 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 com.birbeck.wallpaperslideshow; import java.io.File; import java.io.FileFilter; import java.util.Collection; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import android.util.Log; /** * Collection of utility functions used in this package. */ public class BitmapUtil { public static final int UNCONSTRAINED = -1; private static final String TAG = "BitmapUtil"; public BitmapUtil() { } // Rotates the bitmap by the specified degree. // If a new bitmap is created, the original bitmap is recycled. public static Bitmap rotate(Bitmap b, int degrees, Matrix m) { if (degrees != 0 && b != null) { if (m == null) { m = new Matrix(); } m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2); try { Bitmap b2 = Bitmap.createBitmap( b, 0, 0, b.getWidth(), b.getHeight(), m, true); if (b != b2) { b.recycle(); b = b2; } } catch (OutOfMemoryError ex) { // We have no memory to rotate. Return the original bitmap. Log.e(TAG, "Got oom exception ", ex); } } return b; } /* * Compute the sample size as a function of minSideLength * and maxNumOfPixels. * minSideLength is used to specify that minimal width or height of a * bitmap. * maxNumOfPixels is used to specify the maximal size in pixels that is * tolerable in terms of memory usage. * * The function returns a sample size based on the constraints. * Both size and minSideLength can be passed in as IImage.UNCONSTRAINED, * which indicates no care of the corresponding constraint. * The functions prefers returning a sample size that * generates a smaller bitmap, unless minSideLength = IImage.UNCONSTRAINED. * * Also, the function rounds up the sample size to a power of 2 or multiple * of 8 because BitmapFactory only honors sample size this way. * For example, BitmapFactory downsamples an image by 2 even though the * request is 3. So we round up the sample size to avoid OOM. */ public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) { roundedSize = 1; while (roundedSize < initialSize) { roundedSize <<= 1; } } else { roundedSize = (initialSize + 7) / 8 * 8; } return roundedSize; } private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength == UNCONSTRAINED) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapping zone. return lowerBound; } if ((maxNumOfPixels == UNCONSTRAINED) && (minSideLength == UNCONSTRAINED)) { return 1; } else if (minSideLength == UNCONSTRAINED) { return lowerBound; } else { return upperBound; } } public static Bitmap transform(Matrix scaler, Bitmap source, int targetWidth, int targetHeight, boolean scaleUp, boolean recycle) { int deltaX = source.getWidth() - targetWidth; int deltaY = source.getHeight() - targetHeight; if (!scaleUp && (deltaX < 0 || deltaY < 0)) { /* * In this case the bitmap is smaller, at least in one dimension, * than the target. Transform it by placing as much of the image * as possible into the target and leaving the top/bottom or * left/right (or both) black. */ Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b2); int deltaXHalf = Math.max(0, deltaX / 2); int deltaYHalf = Math.max(0, deltaY / 2); Rect src = new Rect( deltaXHalf, deltaYHalf, deltaXHalf + Math.min(targetWidth, source.getWidth()), deltaYHalf + Math.min(targetHeight, source.getHeight())); int dstX = (targetWidth - src.width()) / 2; int dstY = (targetHeight - src.height()) / 2; Rect dst = new Rect( dstX, dstY, targetWidth - dstX, targetHeight - dstY); c.drawBitmap(source, src, dst, null); if (recycle) { source.recycle(); } return b2; } float bitmapWidthF = source.getWidth(); float bitmapHeightF = source.getHeight(); float bitmapAspect = bitmapWidthF / bitmapHeightF; float viewAspect = (float) targetWidth / targetHeight; if (bitmapAspect > viewAspect) { float scale = targetHeight / bitmapHeightF; if (scale < .9F || scale > 1F) { scaler.setScale(scale, scale); } else { scaler = null; } } else { float scale = targetWidth / bitmapWidthF; if (scale < .9F || scale > 1F) { scaler.setScale(scale, scale); } else { scaler = null; } } Bitmap b1; if (scaler != null) { // this is used for minithumb and crop, so we want to filter here. b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), scaler, true); } else { b1 = source; } if (recycle && b1 != source) { source.recycle(); } int dx1 = Math.max(0, b1.getWidth() - targetWidth); int dy1 = Math.max(0, b1.getHeight() - targetHeight); Bitmap b2 = Bitmap.createBitmap( b1, dx1 / 2, dy1 / 2, targetWidth, targetHeight); if (b2 != b1) { if (recycle || b1 != source) { b1.recycle(); } } return b2; } /** * Make a bitmap from a given Uri. * * @param uri */ public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels, String pathName, BitmapFactory.Options options) { try { if (options == null) options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(pathName, options); if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) { return null; } options.inSampleSize = computeSampleSize( options, minSideLength, maxNumOfPixels); options.inJustDecodeBounds = false; //options.inDither = false; //options.inPreferredConfig = Bitmap.Config.ARGB_8888; return BitmapFactory.decodeFile(pathName, options); } catch (OutOfMemoryError ex) { Log.e(TAG, "Got oom exception ", ex); return null; } } public static String getExtension(String name) { String ext = null; int i = name.lastIndexOf('.'); if (i > 0 && i < name.length() - 1) { ext = name.substring(i+1).toLowerCase(); } return ext; } public static File[] listFiles(File directory, boolean recurse, FileFilter filter) { if (!recurse) { return directory.listFiles(filter); } else { Collection<File> mFiles = new java.util.LinkedList<File>(); innerListFiles(mFiles, directory, filter); return (File[]) mFiles.toArray(new File[mFiles.size()]); } } public static void innerListFiles(Collection<File> files, File directory, FileFilter filter) { File[] found = directory.listFiles(); if (found != null) { for (int i = 0; i < found.length; i++) { if (found[i].isDirectory()) { innerListFiles(files, found[i], filter); } else { File[] found2 = directory.listFiles((FileFilter) filter); for (int j = 0; j < found2.length; j++) { files.add(found2[j]); } } } } } }
gpl-3.0
Git-tl/appcan-plugin-pdfreader-android
uexPDFReader/src/org/emdev/common/xml/parsers/DuckbillParser.java
9356
package org.emdev.common.xml.parsers; import java.util.Arrays; import org.emdev.common.xml.IContentHandler; import org.emdev.common.xml.IXmlTagFactory; import org.emdev.common.xml.TextProvider; import org.emdev.common.xml.tags.XmlTag; import org.emdev.utils.StringUtils; public class DuckbillParser { public void parse(final TextProvider text, final IXmlTagFactory factory, final IContentHandler handler) throws Exception { final char[] xmlChars = text.chars; final int length = text.size; final XmlReader r = new XmlReader(xmlChars, length); int charsStart = -1; while (r.XmlOffset < length) { // Check if START_TAG, END_TAG or COMMENT tokens if (r.skipChar('<')) { // Process text of parent element in case of START_TAG or current element in case of END_TAG if (charsStart != -1) { if (!handler.skipCharacters()) { handler.characters(text, charsStart, r.XmlOffset - 1 - charsStart); } charsStart = -1; } // Check for COMMENT token r.push(); if (r.skipChar('!') && r.skipChar('-') && r.skipChar('-')) { // Process COMMENT token r.pop(); r.skipComment(); continue; } r.pop(); // Check for END_TAG token if (r.skipChar('/')) { // Process END_TAG token final int tagNameStart = r.XmlOffset; r.skipTagName(); final XmlTag tag = factory.getTagByName(r.XmlDoc, tagNameStart, r.XmlOffset - tagNameStart); handler.endElement(tag); r.skipTo('>'); r.XmlOffset++; continue; } // Process START_TAG token final int tagNameStart = r.XmlOffset; r.skipTagName(); final XmlTag tag = factory.getTagByName(r.XmlDoc, tagNameStart, r.XmlOffset - tagNameStart); // Process tag attributes if (handler.parseAttributes(tag)) { final String[] attributes = r.fillAttributes(tag); handler.startElement(tag, attributes); } else { handler.startElement(tag); } r.skipToEndTag(); // Check for closed tag if (r.skipChar('/') && r.skipChar('>')) { // Process closed tag handler.endElement(tag); continue; } } else { // Process text if (charsStart == -1) { charsStart = r.XmlOffset; } // Check for entity if (r.XmlDoc[r.XmlOffset] == '&') { r.push(); if (r.skipTo(';')) { final int endOfEntity = r.XmlOffset; r.pop(); final int startOfEntity = r.XmlOffset; r.XmlOffset++; char entity = (char) -1; if (r.skipChar('#')) { if (r.skipChar('x') || r.skipChar('X')) { entity = (char) StringUtils.parseInt(r.XmlDoc, r.XmlOffset, endOfEntity - r.XmlOffset, 16); } else { entity = (char) StringUtils.parseInt(r.XmlDoc, r.XmlOffset, endOfEntity - r.XmlOffset, 10); } } else { final int idx = r.XmlOffset; if (r.XmlDoc[idx] == 'q' && r.XmlDoc[idx + 1] == 'o' && r.XmlDoc[idx + 2] == 'u' && r.XmlDoc[idx + 3] == 't' && r.XmlDoc[idx + 4] == ';') { // quot entity = 34; } else if (r.XmlDoc[idx] == 'a' && r.XmlDoc[idx + 1] == 'm' && r.XmlDoc[idx + 2] == 'p' && r.XmlDoc[idx + 3] == ';') { // amp entity = 38; } else if (r.XmlDoc[idx] == 'a' && r.XmlDoc[idx + 1] == 'p' && r.XmlDoc[idx + 2] == 'o' && r.XmlDoc[idx + 3] == 's' && r.XmlDoc[idx + 4] == ';') { // apos entity = 39; } else if (r.XmlDoc[idx] == 'l' && r.XmlDoc[idx + 1] == 't' && r.XmlDoc[idx + 2] == ';') { // lt entity = 60; } else if (r.XmlDoc[idx] == 'g' && r.XmlDoc[idx + 1] == 't' && r.XmlDoc[idx + 2] == ';') { // gt entity = 62; } } if (entity != -1) { r.XmlDoc[startOfEntity] = entity; for (int i = startOfEntity + 1; i <= endOfEntity; i++) { r.XmlDoc[i] = 0; } } else { r.XmlOffset = startOfEntity + 1; } } else { r.pop(); } } } // Next token r.XmlOffset++; } } private class XmlReader { public final char[] XmlDoc; public int XmlOffset = 0; public final int XmlLength; private final int[] stack = new int[1024]; private int stackOffset = 0; public XmlReader(final char[] xmlDoc, final int xmlLength) { XmlDoc = xmlDoc; XmlLength = xmlLength; } public boolean skipChar(final char c) { if (XmlDoc[XmlOffset] == c) { XmlOffset++; return true; } return false; } public void push() { stack[stackOffset++] = XmlOffset; } public void pop() { XmlOffset = stack[--stackOffset]; } public void skipComment() { while (XmlOffset < XmlLength) { push(); if (skipChar('-') && skipChar('-') && skipChar('>')) { break; } pop(); XmlOffset++; } } public void skipTagName() { while (XmlOffset < XmlLength) { if (((XmlDoc[XmlOffset] >= 0x1c && XmlDoc[XmlOffset] <= 0x20) || (XmlDoc[XmlOffset] >= 0x9 && XmlDoc[XmlOffset] <= 0xd)) || (XmlDoc[XmlOffset] == '/' && XmlDoc[XmlOffset + 1] == '>') || XmlDoc[XmlOffset] == '>') { break; } XmlOffset++; } } public boolean skipTo(final char c) { while (XmlOffset < XmlLength) { if (XmlDoc[XmlOffset] == c) { return true; } XmlOffset++; } return false; } public void skipToEndTag() { while (XmlOffset < XmlLength) { if ((XmlDoc[XmlOffset] == '/' && XmlDoc[XmlOffset + 1] == '>') || XmlDoc[XmlOffset] == '>') { break; } XmlOffset++; } } public String[] fillAttributes(final XmlTag tag) { if (tag.attributes.length == 0) { return null; } final String[] res = new String[tag.attributes.length]; push(); final int start = XmlOffset; skipToEndTag(); final int end = XmlOffset; pop(); String attrs = new String(XmlDoc, start, end - start).trim(); for (int index = attrs.indexOf("="); index > 0; index = attrs.indexOf("=")) { final String[] qName = attrs.substring(0, index).trim().split(":"); final String attrName = qName[qName.length - 1]; attrs = attrs.substring(index + 1).trim(); final char quote = attrs.charAt(0); if (quote == '"' || quote == '\'') { final int qIndex = attrs.indexOf(quote, 1); if (qIndex > 0) { final String attrValue = attrs.substring(1, qIndex); final int i = Arrays.binarySearch(tag.attributes, attrName); if (i >= 0) { res[i] = attrValue; } attrs = attrs.substring(qIndex + 1).trim(); } else { break; } } else { break; } } return res; } } }
lgpl-3.0
YrAuYong/incubator-calcite
linq4j/src/main/java/org/apache/calcite/linq4j/tree/Node.java
1001
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.linq4j.tree; /** * <p>Parse tree node.</p> */ public interface Node { Node accept(Visitor visitor); void accept(ExpressionWriter expressionWriter); } // End Node.java
apache-2.0
Ethanlm/hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/crypto/key/KeyShell.java
18687
/** * 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.crypto.key; import java.io.IOException; import java.security.InvalidParameterException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.annotations.VisibleForTesting; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.crypto.key.KeyProvider.Metadata; import org.apache.hadoop.crypto.key.KeyProvider.Options; import org.apache.hadoop.tools.CommandShell; import org.apache.hadoop.util.ToolRunner; /** * This program is the CLI utility for the KeyProvider facilities in Hadoop. */ public class KeyShell extends CommandShell { final static private String USAGE_PREFIX = "Usage: hadoop key " + "[generic options]\n"; final static private String COMMANDS = " [-help]\n" + " [" + CreateCommand.USAGE + "]\n" + " [" + RollCommand.USAGE + "]\n" + " [" + DeleteCommand.USAGE + "]\n" + " [" + ListCommand.USAGE + "]\n" + " [" + InvalidateCacheCommand.USAGE + "]\n"; private static final String LIST_METADATA = "keyShell.list.metadata"; @VisibleForTesting public static final String NO_VALID_PROVIDERS = "There are no valid (non-transient) providers configured.\n" + "No action has been taken. Use the -provider option to specify\n" + "a provider. If you want to use a transient provider then you\n" + "MUST use the -provider argument."; private boolean interactive = true; /** If true, fail if the provider requires a password and none is given. */ private boolean strict = false; private boolean userSuppliedProvider = false; /** * Parse the command line arguments and initialize the data. * <pre> * % hadoop key create keyName [-size size] [-cipher algorithm] * [-provider providerPath] * % hadoop key roll keyName [-provider providerPath] * % hadoop key list [-provider providerPath] * % hadoop key delete keyName [-provider providerPath] [-i] * % hadoop key invalidateCache keyName [-provider providerPath] * </pre> * @param args Command line arguments. * @return 0 on success, 1 on failure. * @throws IOException */ @Override protected int init(String[] args) throws IOException { final Options options = KeyProvider.options(getConf()); final Map<String, String> attributes = new HashMap<String, String>(); for (int i = 0; i < args.length; i++) { // parse command line boolean moreTokens = (i < args.length - 1); if (args[i].equals("create")) { String keyName = "-help"; if (moreTokens) { keyName = args[++i]; } setSubCommand(new CreateCommand(keyName, options)); if ("-help".equals(keyName)) { return 1; } } else if (args[i].equals("delete")) { String keyName = "-help"; if (moreTokens) { keyName = args[++i]; } setSubCommand(new DeleteCommand(keyName)); if ("-help".equals(keyName)) { return 1; } } else if (args[i].equals("roll")) { String keyName = "-help"; if (moreTokens) { keyName = args[++i]; } setSubCommand(new RollCommand(keyName)); if ("-help".equals(keyName)) { return 1; } } else if ("list".equals(args[i])) { setSubCommand(new ListCommand()); } else if ("invalidateCache".equals(args[i])) { String keyName = "-help"; if (moreTokens) { keyName = args[++i]; } setSubCommand(new InvalidateCacheCommand(keyName)); if ("-help".equals(keyName)) { return 1; } } else if ("-size".equals(args[i]) && moreTokens) { options.setBitLength(Integer.parseInt(args[++i])); } else if ("-cipher".equals(args[i]) && moreTokens) { options.setCipher(args[++i]); } else if ("-description".equals(args[i]) && moreTokens) { options.setDescription(args[++i]); } else if ("-attr".equals(args[i]) && moreTokens) { final String attrval[] = args[++i].split("=", 2); final String attr = attrval[0].trim(); final String val = attrval[1].trim(); if (attr.isEmpty() || val.isEmpty()) { getOut().println("\nAttributes must be in attribute=value form, " + "or quoted\nlike \"attribute = value\"\n"); return 1; } if (attributes.containsKey(attr)) { getOut().println("\nEach attribute must correspond to only one " + "value:\natttribute \"" + attr + "\" was repeated\n"); return 1; } attributes.put(attr, val); } else if ("-provider".equals(args[i]) && moreTokens) { userSuppliedProvider = true; getConf().set(KeyProviderFactory.KEY_PROVIDER_PATH, args[++i]); } else if ("-metadata".equals(args[i])) { getConf().setBoolean(LIST_METADATA, true); } else if ("-f".equals(args[i]) || ("-force".equals(args[i]))) { interactive = false; } else if (args[i].equals("-strict")) { strict = true; } else if ("-help".equals(args[i])) { return 1; } else { ToolRunner.printGenericCommandUsage(getErr()); return 1; } } if (!attributes.isEmpty()) { options.setAttributes(attributes); } return 0; } @Override public String getCommandUsage() { StringBuffer sbuf = new StringBuffer(USAGE_PREFIX + COMMANDS); String banner = StringUtils.repeat("=", 66); sbuf.append(banner + "\n"); sbuf.append(CreateCommand.USAGE + ":\n\n" + CreateCommand.DESC + "\n"); sbuf.append(banner + "\n"); sbuf.append(RollCommand.USAGE + ":\n\n" + RollCommand.DESC + "\n"); sbuf.append(banner + "\n"); sbuf.append(DeleteCommand.USAGE + ":\n\n" + DeleteCommand.DESC + "\n"); sbuf.append(banner + "\n"); sbuf.append(ListCommand.USAGE + ":\n\n" + ListCommand.DESC + "\n"); sbuf.append(banner + "\n"); sbuf.append(InvalidateCacheCommand.USAGE + ":\n\n" + InvalidateCacheCommand.DESC + "\n"); return sbuf.toString(); } private abstract class Command extends SubCommand { protected KeyProvider provider = null; protected KeyProvider getKeyProvider() { KeyProvider prov = null; List<KeyProvider> providers; try { providers = KeyProviderFactory.getProviders(getConf()); if (userSuppliedProvider) { prov = providers.get(0); } else { for (KeyProvider p : providers) { if (!p.isTransient()) { prov = p; break; } } } } catch (IOException e) { e.printStackTrace(getErr()); } if (prov == null) { getOut().println(NO_VALID_PROVIDERS); } return prov; } protected void printProviderWritten() { getOut().println(provider + " has been updated."); } protected void warnIfTransientProvider() { if (provider.isTransient()) { getOut().println("WARNING: you are modifying a transient provider."); } } public abstract void execute() throws Exception; public abstract String getUsage(); } private class ListCommand extends Command { public static final String USAGE = "list [-provider <provider>] [-strict] [-metadata] [-help]"; public static final String DESC = "The list subcommand displays the keynames contained within\n" + "a particular provider as configured in core-site.xml or\n" + "specified with the -provider argument. -metadata displays\n" + "the metadata. If -strict is supplied, fail immediately if\n" + "the provider requires a password and none is given."; private boolean metadata = false; public boolean validate() { boolean rc = true; provider = getKeyProvider(); if (provider == null) { rc = false; } metadata = getConf().getBoolean(LIST_METADATA, false); return rc; } public void execute() throws IOException { try { final List<String> keys = provider.getKeys(); getOut().println("Listing keys for KeyProvider: " + provider); if (metadata) { final Metadata[] meta = provider.getKeysMetadata(keys.toArray(new String[keys.size()])); for (int i = 0; i < meta.length; ++i) { getOut().println(keys.get(i) + " : " + meta[i]); } } else { for (String keyName : keys) { getOut().println(keyName); } } } catch (IOException e) { getOut().println("Cannot list keys for KeyProvider: " + provider + ": " + e.toString()); throw e; } } @Override public String getUsage() { return USAGE + ":\n\n" + DESC; } } private class RollCommand extends Command { public static final String USAGE = "roll <keyname> [-provider <provider>] [-strict] [-help]"; public static final String DESC = "The roll subcommand creates a new version for the specified key\n" + "within the provider indicated using the -provider argument.\n" + "If -strict is supplied, fail immediately if the provider requires\n" + "a password and none is given."; private String keyName = null; public RollCommand(String keyName) { this.keyName = keyName; } public boolean validate() { boolean rc = true; provider = getKeyProvider(); if (provider == null) { rc = false; } if (keyName == null) { getOut().println("Please provide a <keyname>.\n" + "See the usage description by using -help."); rc = false; } return rc; } public void execute() throws NoSuchAlgorithmException, IOException { try { warnIfTransientProvider(); getOut().println("Rolling key version from KeyProvider: " + provider + "\n for key name: " + keyName); try { provider.rollNewVersion(keyName); provider.flush(); getOut().println(keyName + " has been successfully rolled."); printProviderWritten(); } catch (NoSuchAlgorithmException e) { getOut().println("Cannot roll key: " + keyName + " within KeyProvider: " + provider + ". " + e.toString()); throw e; } } catch (IOException e1) { getOut().println("Cannot roll key: " + keyName + " within KeyProvider: " + provider + ". " + e1.toString()); throw e1; } } @Override public String getUsage() { return USAGE + ":\n\n" + DESC; } } private class DeleteCommand extends Command { public static final String USAGE = "delete <keyname> [-provider <provider>] [-strict] [-f] [-help]"; public static final String DESC = "The delete subcommand deletes all versions of the key\n" + "specified by the <keyname> argument from within the\n" + "provider specified by -provider. The command asks for\n" + "user confirmation unless -f is specified. If -strict is\n" + "supplied, fail immediately if the provider requires a\n" + "password and none is given."; private String keyName = null; private boolean cont = true; public DeleteCommand(String keyName) { this.keyName = keyName; } @Override public boolean validate() { provider = getKeyProvider(); if (provider == null) { return false; } if (keyName == null) { getOut().println("There is no keyName specified. Please specify a " + "<keyname>. See the usage description with -help."); return false; } if (interactive) { try { cont = ToolRunner .confirmPrompt("You are about to DELETE all versions of " + " key " + keyName + " from KeyProvider " + provider + ". Continue? "); if (!cont) { getOut().println(keyName + " has not been deleted."); } return cont; } catch (IOException e) { getOut().println(keyName + " will not be deleted."); e.printStackTrace(getErr()); } } return true; } public void execute() throws IOException { warnIfTransientProvider(); getOut().println("Deleting key: " + keyName + " from KeyProvider: " + provider); if (cont) { try { provider.deleteKey(keyName); provider.flush(); getOut().println(keyName + " has been successfully deleted."); printProviderWritten(); } catch (IOException e) { getOut().println(keyName + " has not been deleted. " + e.toString()); throw e; } } } @Override public String getUsage() { return USAGE + ":\n\n" + DESC; } } private class CreateCommand extends Command { public static final String USAGE = "create <keyname> [-cipher <cipher>] [-size <size>]\n" + " [-description <description>]\n" + " [-attr <attribute=value>]\n" + " [-provider <provider>] [-strict]\n" + " [-help]"; public static final String DESC = "The create subcommand creates a new key for the name specified\n" + "by the <keyname> argument within the provider specified by the\n" + "-provider argument. You may specify a cipher with the -cipher\n" + "argument. The default cipher is currently \"AES/CTR/NoPadding\".\n" + "The default keysize is 128. You may specify the requested key\n" + "length using the -size argument. Arbitrary attribute=value\n" + "style attributes may be specified using the -attr argument.\n" + "-attr may be specified multiple times, once per attribute.\n"; private final String keyName; private final Options options; public CreateCommand(String keyName, Options options) { this.keyName = keyName; this.options = options; } public boolean validate() { boolean rc = true; try { provider = getKeyProvider(); if (provider == null) { rc = false; } else if (provider.needsPassword()) { if (strict) { getOut().println(provider.noPasswordError()); rc = false; } else { getOut().println(provider.noPasswordWarning()); } } } catch (IOException e) { e.printStackTrace(getErr()); } if (keyName == null) { getOut().println("Please provide a <keyname>. " + " See the usage description with -help."); rc = false; } return rc; } public void execute() throws IOException, NoSuchAlgorithmException { warnIfTransientProvider(); try { provider.createKey(keyName, options); provider.flush(); getOut().println(keyName + " has been successfully created " + "with options " + options.toString() + "."); printProviderWritten(); } catch (InvalidParameterException e) { getOut().println(keyName + " has not been created. " + e.toString()); throw e; } catch (IOException e) { getOut().println(keyName + " has not been created. " + e.toString()); throw e; } catch (NoSuchAlgorithmException e) { getOut().println(keyName + " has not been created. " + e.toString()); throw e; } } @Override public String getUsage() { return USAGE + ":\n\n" + DESC; } } private class InvalidateCacheCommand extends Command { public static final String USAGE = "invalidateCache <keyname> [-provider <provider>] [-help]"; public static final String DESC = "The invalidateCache subcommand invalidates the cached key versions\n" + "of the specified key, on the provider indicated using the" + " -provider argument.\n"; private String keyName = null; InvalidateCacheCommand(String keyName) { this.keyName = keyName; } public boolean validate() { boolean rc = true; provider = getKeyProvider(); if (provider == null) { getOut().println("Invalid provider."); rc = false; } if (keyName == null) { getOut().println("Please provide a <keyname>.\n" + "See the usage description by using -help."); rc = false; } return rc; } public void execute() throws NoSuchAlgorithmException, IOException { try { warnIfTransientProvider(); getOut().println("Invalidating cache on KeyProvider: " + provider + "\n for key name: " + keyName); provider.invalidateCache(keyName); getOut().println("Cached keyversions of " + keyName + " has been successfully invalidated."); printProviderWritten(); } catch (IOException e) { getOut().println("Cannot invalidate cache for key: " + keyName + " within KeyProvider: " + provider + ". " + e.toString()); throw e; } } @Override public String getUsage() { return USAGE + ":\n\n" + DESC; } } /** * main() entry point for the KeyShell. While strictly speaking the * return is void, it will System.exit() with a return code: 0 is for * success and 1 for failure. * * @param args Command line arguments. * @throws Exception */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new KeyShell(), args); System.exit(res); } }
apache-2.0
ilayaperumalg/spring-boot
spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java
3163
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.endpoint.web; import java.util.Collections; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link WebOperationRequestPredicate}. * * @author Andy Wilkinson * @author Phillip Webb */ class WebOperationRequestPredicateTests { @Test void predicatesWithIdenticalPathsAreEqual() { assertThat(predicateWithPath("/path")).isEqualTo(predicateWithPath("/path")); } @Test void predicatesWithDifferentPathsAreNotEqual() { assertThat(predicateWithPath("/one")).isNotEqualTo(predicateWithPath("/two")); } @Test void predicatesWithIdenticalPathsWithVariablesAreEqual() { assertThat(predicateWithPath("/path/{foo}")).isEqualTo(predicateWithPath("/path/{foo}")); } @Test void predicatesWhereOneHasAPathAndTheOtherHasAVariableAreNotEqual() { assertThat(predicateWithPath("/path/{foo}")).isNotEqualTo(predicateWithPath("/path/foo")); } @Test void predicatesWithSinglePathVariablesInTheSamplePlaceAreEqual() { assertThat(predicateWithPath("/path/{foo1}")).isEqualTo(predicateWithPath("/path/{foo2}")); } @Test void predicatesWithSingleWildcardPathVariablesInTheSamplePlaceAreEqual() { assertThat(predicateWithPath("/path/{*foo1}")).isEqualTo(predicateWithPath("/path/{*foo2}")); } @Test void predicatesWithSingleWildcardPathVariableAndRegularVariableInTheSamplePlaceAreNotEqual() { assertThat(predicateWithPath("/path/{*foo1}")).isNotEqualTo(predicateWithPath("/path/{foo2}")); } @Test void predicatesWithMultiplePathVariablesInTheSamplePlaceAreEqual() { assertThat(predicateWithPath("/path/{foo1}/more/{bar1}")) .isEqualTo(predicateWithPath("/path/{foo2}/more/{bar2}")); } @Test void predicateWithWildcardPathVariableReturnsMatchAllRemainingPathSegmentsVariable() { assertThat(predicateWithPath("/path/{*foo1}").getMatchAllRemainingPathSegmentsVariable()).isEqualTo("foo1"); } @Test void predicateWithRegularPathVariableDoesNotReturnMatchAllRemainingPathSegmentsVariable() { assertThat(predicateWithPath("/path/{foo1}").getMatchAllRemainingPathSegmentsVariable()).isNull(); } @Test void predicateWithNoPathVariableDoesNotReturnMatchAllRemainingPathSegmentsVariable() { assertThat(predicateWithPath("/path/foo1").getMatchAllRemainingPathSegmentsVariable()).isNull(); } private WebOperationRequestPredicate predicateWithPath(String path) { return new WebOperationRequestPredicate(path, WebEndpointHttpMethod.GET, Collections.emptyList(), Collections.emptyList()); } }
apache-2.0
Yasumoto/commons
src/java/com/twitter/common/text/combiner/StockTokenCombiner.java
1957
// ================================================================================================= // Copyright 2011 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT 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.twitter.common.text.combiner; import java.util.regex.Pattern; import com.twitter.Regex; import com.twitter.common.text.extractor.RegexExtractor; import com.twitter.common.text.token.TwitterTokenStream; import com.twitter.common.text.token.attribute.TokenType; /** * Combines multiple tokens denoting a stock symbol (e.g., $YHOO) back into a single token. */ public class StockTokenCombiner extends ExtractorBasedTokenCombiner { // Regex.VALID_CASHTAG in twitter-text doesn't capture $ symbol, so we need to modify the regex // to capture $ symbol. public static final Pattern STOCK_SYMBOL_PATTERN = Pattern.compile(Regex.VALID_CASHTAG.toString().replace(")\\$(", ")(\\$)("), Pattern.CASE_INSENSITIVE); public StockTokenCombiner(TwitterTokenStream inputStream) { super(inputStream); setExtractor(new RegexExtractor.Builder() .setRegexPattern(STOCK_SYMBOL_PATTERN, 1, 2) .build()); setType(TokenType.STOCK); } }
apache-2.0
wangcy6/storm_app
frame/storm-master/external/storm-kafka-client/src/main/java/org/apache/storm/kafka/spout/ByTopicRecordTranslator.java
7039
/* * 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.storm.kafka.spout; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.storm.tuple.Fields; /** * Based off of a given Kafka topic a ConsumerRecord came from it will be translated to a Storm tuple * and emitted to a given stream. * @param <K> the key of the incoming Records * @param <V> the value of the incoming Records */ public class ByTopicRecordTranslator<K, V> implements RecordTranslator<K, V> { private static final long serialVersionUID = -121699733778988688L; private final RecordTranslator<K,V> defaultTranslator; private final Map<String, RecordTranslator<K,V>> topicToTranslator = new HashMap<>(); private final Map<String, Fields> streamToFields = new HashMap<>(); /** * Create a simple record translator that will use func to extract the fields of the tuple, * named by fields, and emit them to stream. This will handle all topics not explicitly set * elsewhere. * @param func extracts and turns them into a list of objects to be emitted * @param fields the names of the fields extracted * @param stream the stream to emit these fields on. */ public ByTopicRecordTranslator(Func<ConsumerRecord<K, V>, List<Object>> func, Fields fields, String stream) { this(new SimpleRecordTranslator<>(func, fields, stream)); } /** * Create a simple record translator that will use func to extract the fields of the tuple, * named by fields, and emit them to the default stream. This will handle all topics not explicitly set * elsewhere. * @param func extracts and turns them into a list of objects to be emitted * @param fields the names of the fields extracted */ public ByTopicRecordTranslator(Func<ConsumerRecord<K, V>, List<Object>> func, Fields fields) { this(new SimpleRecordTranslator<>(func, fields)); } /** * Create a record translator with the given default translator. * @param defaultTranslator a translator that will be used for all topics not explicitly set * with one of the variants of {@link #forTopic(java.lang.String, org.apache.storm.kafka.spout.RecordTranslator) }. */ public ByTopicRecordTranslator(RecordTranslator<K,V> defaultTranslator) { this.defaultTranslator = defaultTranslator; //This shouldn't throw on a Check, because nothing is configured yet cacheNCheckFields(defaultTranslator); } /** * Configure a translator for a given topic with tuples to be emitted to the default stream. * @param topic the topic this should be used for * @param func extracts and turns them into a list of objects to be emitted * @param fields the names of the fields extracted * @return this to be able to chain configuration * @throws IllegalStateException if the topic is already registered to another translator * @throws IllegalArgumentException if the Fields for the stream this emits to do not match * any already configured Fields for the same stream */ public ByTopicRecordTranslator<K, V> forTopic(String topic, Func<ConsumerRecord<K, V>, List<Object>> func, Fields fields) { return forTopic(topic, new SimpleRecordTranslator<>(func, fields)); } /** * Configure a translator for a given topic. * @param topic the topic this should be used for * @param func extracts and turns them into a list of objects to be emitted * @param fields the names of the fields extracted * @param stream the stream to emit the tuples to. * @return this to be able to chain configuration * @throws IllegalStateException if the topic is already registered to another translator * @throws IllegalArgumentException if the Fields for the stream this emits to do not match * any already configured Fields for the same stream */ public ByTopicRecordTranslator<K, V> forTopic(String topic, Func<ConsumerRecord<K, V>, List<Object>> func, Fields fields, String stream) { return forTopic(topic, new SimpleRecordTranslator<>(func, fields, stream)); } /** * Configure a translator for a given kafka topic. * @param topic the topic this translator should handle * @param translator the translator itself * @return this to be able to chain configuration * @throws IllegalStateException if the topic is already registered to another translator * @throws IllegalArgumentException if the Fields for the stream this emits to do not match * any already configured Fields for the same stream */ public ByTopicRecordTranslator<K, V> forTopic(String topic, RecordTranslator<K,V> translator) { if (topicToTranslator.containsKey(topic)) { throw new IllegalStateException("Topic " + topic + " is already registered"); } cacheNCheckFields(translator); topicToTranslator.put(topic, translator); return this; } private void cacheNCheckFields(RecordTranslator<K, V> translator) { for (String stream : translator.streams()) { Fields fromTrans = translator.getFieldsFor(stream); Fields cached = streamToFields.get(stream); if (cached != null && !fromTrans.equals(cached)) { throw new IllegalArgumentException("Stream " + stream + " currently has Fields of " + cached + " which is not the same as those being added in " + fromTrans); } if (cached == null) { streamToFields.put(stream, fromTrans); } } } @Override public List<Object> apply(ConsumerRecord<K, V> record) { RecordTranslator<K, V> trans = topicToTranslator.getOrDefault(record.topic(), defaultTranslator); return trans.apply(record); } @Override public Fields getFieldsFor(String stream) { return streamToFields.get(stream); } @Override public List<String> streams() { return new ArrayList<>(streamToFields.keySet()); } }
apache-2.0
vovagrechka/fucking-everything
phizdets/phizdets-idea/eclipse-src/org.eclipse.php.core/src/org/eclipse/php/internal/core/phar/IAchiveOutputEntry.java
974
/******************************************************************************* * Copyright (c) 2009 Zhao 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 * * Contributors: * Zhao - initial API and implementation *******************************************************************************/ package org.eclipse.php.internal.core.phar; public interface IAchiveOutputEntry { public String getName(); public void setTime(long time); public long getTime(); public void setSize(long size); public long getSize(); public long getCompressedSize(); public void setCompressedSize(long csize); public void setCrc(long crc); public long getCrc(); public void setMethod(int method); public int getMethod(); public boolean isDirectory(); }
apache-2.0
mhd911/openfire
src/plugins/jitsivideobridge/src/java/com/google/libwebm/mkvparser/Atom.java
1570
// Author: mszal@google.com (Michael Szal) package com.google.libwebm.mkvparser; import com.google.libwebm.Common; import com.google.libwebm.mkvmuxer.Chapters; public class Atom extends Common { public Display getDisplay(int index) { long pointer = GetDisplay(nativePointer, index); return new Display(pointer); } public int getDisplayCount() { return GetDisplayCount(nativePointer); } public long getStartTime(Chapters chapters) { return GetStartTime(nativePointer, chapters.getNativePointer()); } public long getStartTimecode() { return GetStartTimecode(nativePointer); } public long getStopTime(Chapters chapters) { return GetStopTime(nativePointer, chapters.getNativePointer()); } public long getStopTimecode() { return GetStopTimecode(nativePointer); } public String getStringUid() { return GetStringUID(nativePointer); } public long getUid() { return GetUID(nativePointer); } protected Atom(long nativePointer) { super(nativePointer); } @Override protected void deleteObject() { } private static native long GetDisplay(long jAtom, int index); private static native int GetDisplayCount(long jAtom); private static native long GetStartTime(long jAtom, long jChapters); private static native long GetStartTimecode(long jAtom); private static native long GetStopTime(long jAtom, long jChapters); private static native long GetStopTimecode(long jAtom); private static native String GetStringUID(long jAtom); private static native long GetUID(long jAtom); }
apache-2.0
ajhalani/elasticsearch
src/test/java/org/elasticsearch/indices/memory/breaker/CircuitBreakerServiceTests.java
16444
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.indices.memory.breaker; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.admin.cluster.node.stats.NodeStats; import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.breaker.CircuitBreaker; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.indices.breaker.CircuitBreakerStats; import org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; import org.elasticsearch.test.junit.annotations.TestLogging; import org.junit.Test; import java.util.Arrays; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.cardinality; import static org.elasticsearch.test.ElasticsearchIntegrationTest.Scope.TEST; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFailures; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.Matchers.*; /** * Integration tests for InternalCircuitBreakerService */ @ClusterScope(scope = TEST, randomDynamicTemplates = false) public class CircuitBreakerServiceTests extends ElasticsearchIntegrationTest { private String randomRidiculouslySmallLimit() { // 3 different ways to say 100 bytes return randomFrom(Arrays.asList("100b", "100")); //, (10000. / JvmInfo.jvmInfo().getMem().getHeapMax().bytes()) + "%")); // this is prone to rounding errors and will fail if JVM memory changes! } @Test @TestLogging("org.elasticsearch.indices.memory.breaker:TRACE,org.elasticsearch.index.fielddata:TRACE,org.elasticsearch.common.breaker:TRACE") public void testMemoryBreaker() { assertAcked(prepareCreate("cb-test", 1, settingsBuilder().put(SETTING_NUMBER_OF_REPLICAS, between(0, 1)))); final Client client = client(); try { // index some different terms so we have some field data for loading int docCount = scaledRandomIntBetween(300, 1000); for (long id = 0; id < docCount; id++) { client.prepareIndex("cb-test", "type", Long.toString(id)) .setSource(MapBuilder.<String, Object>newMapBuilder().put("test", "value" + id).map()).execute().actionGet(); } // refresh refresh(); // execute a search that loads field data (sorting on the "test" field) client.prepareSearch("cb-test").setSource("{\"sort\": \"test\",\"query\":{\"match_all\":{}}}") .execute().actionGet(); // clear field data cache (thus setting the loaded field data back to 0) client.admin().indices().prepareClearCache("cb-test").setFieldDataCache(true).execute().actionGet(); // Update circuit breaker settings Settings settings = settingsBuilder() .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING, randomRidiculouslySmallLimit()) .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING, 1.05) .build(); client.admin().cluster().prepareUpdateSettings().setTransientSettings(settings).execute().actionGet(); // execute a search that loads field data (sorting on the "test" field) // again, this time it should trip the breaker assertFailures(client.prepareSearch("cb-test").setSource("{\"sort\": \"test\",\"query\":{\"match_all\":{}}}"), RestStatus.INTERNAL_SERVER_ERROR, containsString("Data too large, data for [test] would be larger than limit of [100/100b]")); NodesStatsResponse stats = client.admin().cluster().prepareNodesStats().setBreaker(true).get(); int breaks = 0; for (NodeStats stat : stats.getNodes()) { CircuitBreakerStats breakerStats = stat.getBreaker().getStats(CircuitBreaker.Name.FIELDDATA); breaks += breakerStats.getTrippedCount(); } assertThat(breaks, greaterThanOrEqualTo(1)); } finally { // Reset settings Settings resetSettings = settingsBuilder() .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING, "-1") .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING, HierarchyCircuitBreakerService.DEFAULT_FIELDDATA_OVERHEAD_CONSTANT) .build(); client.admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings).execute().actionGet(); } } @Test @TestLogging("org.elasticsearch.indices.memory.breaker:TRACE,org.elasticsearch.index.fielddata:TRACE,org.elasticsearch.common.breaker:TRACE") public void testRamAccountingTermsEnum() { final Client client = client(); try { // Create an index where the mappings have a field data filter assertAcked(prepareCreate("ramtest").setSource("{\"mappings\": {\"type\": {\"properties\": {\"test\": " + "{\"type\": \"string\",\"fielddata\": {\"filter\": {\"regex\": {\"pattern\": \"^value.*\"}}}}}}}}")); // Wait 10 seconds for green client.admin().cluster().prepareHealth("ramtest").setWaitForGreenStatus().setTimeout("10s").execute().actionGet(); // index some different terms so we have some field data for loading int docCount = scaledRandomIntBetween(300, 1000); for (long id = 0; id < docCount; id++) { client.prepareIndex("ramtest", "type", Long.toString(id)) .setSource(MapBuilder.<String, Object>newMapBuilder().put("test", "value" + id).map()).execute().actionGet(); } // refresh refresh(); // execute a search that loads field data (sorting on the "test" field) client.prepareSearch("ramtest").setSource("{\"sort\": \"test\",\"query\":{\"match_all\":{}}}") .execute().actionGet(); // clear field data cache (thus setting the loaded field data back to 0) client.admin().indices().prepareClearCache("ramtest").setFieldDataCache(true).execute().actionGet(); // Update circuit breaker settings Settings settings = settingsBuilder() .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING, randomRidiculouslySmallLimit()) .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING, 1.05) .build(); client.admin().cluster().prepareUpdateSettings().setTransientSettings(settings).execute().actionGet(); // execute a search that loads field data (sorting on the "test" field) // again, this time it should trip the breaker assertFailures(client.prepareSearch("ramtest").setSource("{\"sort\": \"test\",\"query\":{\"match_all\":{}}}"), RestStatus.INTERNAL_SERVER_ERROR, containsString("Data too large, data for [test] would be larger than limit of [100/100b]")); NodesStatsResponse stats = client.admin().cluster().prepareNodesStats().setBreaker(true).get(); int breaks = 0; for (NodeStats stat : stats.getNodes()) { CircuitBreakerStats breakerStats = stat.getBreaker().getStats(CircuitBreaker.Name.FIELDDATA); breaks += breakerStats.getTrippedCount(); } assertThat(breaks, greaterThanOrEqualTo(1)); } finally { // Reset settings Settings resetSettings = settingsBuilder() .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING, "-1") .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING, HierarchyCircuitBreakerService.DEFAULT_FIELDDATA_OVERHEAD_CONSTANT) .build(); client.admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings).execute().actionGet(); } } /** * Test that a breaker correctly redistributes to a different breaker, in * this case, the fielddata breaker borrows space from the request breaker */ @Test @TestLogging("org.elasticsearch.indices.memory.breaker:TRACE,org.elasticsearch.index.fielddata:TRACE,org.elasticsearch.common.breaker:TRACE") public void testParentChecking() { assertAcked(prepareCreate("cb-test", 1, settingsBuilder().put(SETTING_NUMBER_OF_REPLICAS, between(0, 1)))); Client client = client(); try { // index some different terms so we have some field data for loading int docCount = scaledRandomIntBetween(300, 1000); for (long id = 0; id < docCount; id++) { client.prepareIndex("cb-test", "type", Long.toString(id)) .setSource(MapBuilder.<String, Object>newMapBuilder().put("test", "value" + id).map()).execute().actionGet(); } refresh(); // We need the request limit beforehand, just from a single node because the limit should always be the same long beforeReqLimit = client.admin().cluster().prepareNodesStats().setBreaker(true).get() .getNodes()[0].getBreaker().getStats(CircuitBreaker.Name.REQUEST).getLimit(); Settings resetSettings = settingsBuilder() .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING, "10b") .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING, 1.0) .build(); client.admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings).execute().actionGet(); // Perform a search to load field data for the "test" field try { client.prepareSearch("cb-test").setQuery(matchAllQuery()).addSort("test", SortOrder.DESC).get(); } catch (Exception e) { String errMsg = "[FIELDDATA] Data too large, data for [test] would be larger than limit of [10/10b]"; assertThat("Exception: " + ExceptionsHelper.unwrapCause(e) + " should contain a CircuitBreakingException", ExceptionsHelper.unwrapCause(e).getMessage().contains(errMsg), equalTo(true)); } assertFailures(client.prepareSearch("cb-test").setSource("{\"sort\": \"test\",\"query\":{\"match_all\":{}}}"), RestStatus.INTERNAL_SERVER_ERROR, containsString("Data too large, data for [test] would be larger than limit of [10/10b]")); // Adjust settings so the parent breaker will fail, but the fielddata breaker doesn't resetSettings = settingsBuilder() .put(HierarchyCircuitBreakerService.TOTAL_CIRCUIT_BREAKER_LIMIT_SETTING, "15b") .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING, "90%") .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING, 1.0) .build(); client.admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings).execute().actionGet(); // Perform a search to load field data for the "test" field try { client.prepareSearch("cb-test").setQuery(matchAllQuery()).addSort("test", SortOrder.DESC).get(); } catch (Exception e) { String errMsg = "[PARENT] Data too large, data for [test] would be larger than limit of [15/15b]"; assertThat("Exception: " + ExceptionsHelper.unwrapCause(e) + " should contain a CircuitBreakingException", ExceptionsHelper.unwrapCause(e).getMessage().contains(errMsg), equalTo(true)); } } finally { Settings resetSettings = settingsBuilder() .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING, "-1") .put(HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_LIMIT_SETTING, HierarchyCircuitBreakerService.DEFAULT_REQUEST_BREAKER_LIMIT) .put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING, HierarchyCircuitBreakerService.DEFAULT_FIELDDATA_OVERHEAD_CONSTANT) .build(); client.admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings).execute().actionGet(); } } @Test @TestLogging("org.elasticsearch.indices.memory.breaker:TRACE,org.elasticsearch.index.fielddata:TRACE,org.elasticsearch.common.breaker:TRACE") public void testRequestBreaker() { assertAcked(prepareCreate("cb-test", 1, settingsBuilder().put(SETTING_NUMBER_OF_REPLICAS, between(0, 1)))); Client client = client(); try { // Make request breaker limited to a small amount Settings resetSettings = settingsBuilder() .put(HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_LIMIT_SETTING, "10b") .build(); client.admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings).execute().actionGet(); // index some different terms so we have some field data for loading int docCount = scaledRandomIntBetween(300, 1000); for (long id = 0; id < docCount; id++) { client.prepareIndex("cb-test", "type", Long.toString(id)) .setSource(MapBuilder.<String, Object>newMapBuilder().put("test", id).map()).execute().actionGet(); } refresh(); // A cardinality aggregation uses BigArrays and thus the REQUEST breaker try { client.prepareSearch("cb-test").setQuery(matchAllQuery()).addAggregation(cardinality("card").field("test")).get(); fail("aggregation should have tripped the breaker"); } catch (Exception e) { String errMsg = "CircuitBreakingException[[REQUEST] Data too large, data for [<reused_arrays>] would be larger than limit of [10/10b]]"; assertThat("Exception: " + ExceptionsHelper.unwrapCause(e) + " should contain a CircuitBreakingException", ExceptionsHelper.unwrapCause(e).getMessage().contains(errMsg), equalTo(true)); } } finally { Settings resetSettings = settingsBuilder() .put(HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_LIMIT_SETTING, HierarchyCircuitBreakerService.DEFAULT_REQUEST_BREAKER_LIMIT) .build(); client.admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings).execute().actionGet(); } } }
apache-2.0
hello2009chen/netty-socketio
src/main/java/com/corundumstudio/socketio/store/HazelcastPubSubStore.java
3050
/** * Copyright 2012 Nikita Koksharov * * 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.corundumstudio.socketio.store; import io.netty.util.internal.PlatformDependent; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import com.corundumstudio.socketio.store.pubsub.PubSubListener; import com.corundumstudio.socketio.store.pubsub.PubSubMessage; import com.corundumstudio.socketio.store.pubsub.PubSubStore; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ITopic; import com.hazelcast.core.Message; import com.hazelcast.core.MessageListener; public class HazelcastPubSubStore implements PubSubStore { private final HazelcastInstance hazelcastPub; private final HazelcastInstance hazelcastSub; private final Long nodeId; private final ConcurrentMap<String, Queue<String>> map = PlatformDependent.newConcurrentHashMap(); public HazelcastPubSubStore(HazelcastInstance hazelcastPub, HazelcastInstance hazelcastSub, Long nodeId) { this.hazelcastPub = hazelcastPub; this.hazelcastSub = hazelcastSub; this.nodeId = nodeId; } @Override public void publish(String name, PubSubMessage msg) { msg.setNodeId(nodeId); hazelcastPub.getTopic(name).publish(msg); } @Override public <T extends PubSubMessage> void subscribe(String name, final PubSubListener<T> listener, Class<T> clazz) { ITopic<T> topic = hazelcastSub.getTopic(name); String regId = topic.addMessageListener(new MessageListener<T>() { @Override public void onMessage(Message<T> message) { PubSubMessage msg = message.getMessageObject(); if (!nodeId.equals(msg.getNodeId())) { listener.onMessage(message.getMessageObject()); } } }); Queue<String> list = map.get(name); if (list == null) { list = new ConcurrentLinkedQueue<String>(); Queue<String> oldList = map.putIfAbsent(name, list); if (oldList != null) { list = oldList; } } list.add(regId); } @Override public void unsubscribe(String name) { Queue<String> regIds = map.remove(name); ITopic<Object> topic = hazelcastSub.getTopic(name); for (String id : regIds) { topic.removeMessageListener(id); } } @Override public void shutdown() { } }
apache-2.0
mplushnikov/lombok-intellij-plugin
testData/configsystem/accessors/chain/before/GetterSetterFieldTest.java
589
import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @Getter @Setter public class GetterSetterFieldTest { @Accessors private int intProperty; @Accessors private double doubleProperty; @Accessors private boolean booleanProperty; @Accessors private String stringProperty; public static void main(String[] args) { final GetterSetterFieldTest test = new GetterSetterFieldTest(); test.setStringProperty("") .setIntProperty(1) .setBooleanProperty(true) .setDoubleProperty(0.0); System.out.println(test); } }
bsd-3-clause
theoweiss/openhab2
bundles/org.openhab.persistence.mapdb/src/main/java/org/openhab/persistence/mapdb/internal/MapDbItem.java
2134
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.persistence.mapdb.internal; import java.text.DateFormat; import java.util.Date; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.core.persistence.HistoricItem; import org.eclipse.smarthome.core.persistence.PersistenceItemInfo; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.UnDefType; /** * This is a Java bean used to persist item states with timestamps in the database. * * @author Jens Viebig - Initial contribution * */ @NonNullByDefault public class MapDbItem implements HistoricItem, PersistenceItemInfo { private String name = ""; private State state = UnDefType.NULL; private Date timestamp = new Date(0); @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public State getState() { return state; } public void setState(State state) { this.state = state; } @Override public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } @Override public String toString() { return DateFormat.getDateTimeInstance().format(timestamp) + ": " + name + " -> " + state.toString(); } @Override public @Nullable Integer getCount() { return null; } @Override public @Nullable Date getEarliest() { return null; } @Override public @Nullable Date getLatest() { return null; } public boolean isValid() { return name != null && state != null && timestamp != null; } }
epl-1.0
NSAmelchev/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/binary/ClientBinaryTypeNamePutRequest.java
2387
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.platform.client.binary; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.binary.BinaryRawReader; import org.apache.ignite.internal.processors.platform.client.ClientBooleanResponse; import org.apache.ignite.internal.processors.platform.client.ClientConnectionContext; import org.apache.ignite.internal.processors.platform.client.ClientRequest; import org.apache.ignite.internal.processors.platform.client.ClientResponse; /** * Gets binary type name by id. */ public class ClientBinaryTypeNamePutRequest extends ClientRequest { /** Platform ID, see org.apache.ignite.internal.MarshallerPlatformIds. */ private final byte platformId; /** Type id. */ private final int typeId; /** Type name. */ private final String typeName; /** * Constructor. * * @param reader Reader. */ public ClientBinaryTypeNamePutRequest(BinaryRawReader reader) { super(reader); platformId = reader.readByte(); typeId = reader.readInt(); typeName = reader.readString(); } /** {@inheritDoc} */ @Override public ClientResponse process(ClientConnectionContext ctx) { try { boolean res = ctx.kernalContext().marshallerContext() .registerClassName(platformId, typeId, typeName, false); return new ClientBooleanResponse(requestId(), res); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } }
apache-2.0
rangadi/beam
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/util/common/worker/StubbedExecutor.java
3175
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.dataflow.worker.util.common.worker; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.when; import com.google.api.client.testing.http.FixedClock; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A utility for testing single scheduled tasks. * * <p>The intended target is a task that is scheduled with {@link ScheduledExecutorService} and * during its execution schedules at most one more task; no other tasks are scheduled. This class * then provides a {@link ScheduledExecutorService} that allows manual control over running the * tasks. The client should instantiate this class with a clock, then use {@link getExecutor()} to * get the executor and use it to schedule the initial task, then use {@link runNextRunnable()} to * run the initial task, then use {@link runNextRunnable()} to run the second task, etc. */ public class StubbedExecutor { private static final Logger LOG = LoggerFactory.getLogger(StubbedExecutor.class); private final FixedClock clock; @Mock private ScheduledExecutorService executor; private Runnable lastRunnable; private long lastDelay; public StubbedExecutor(FixedClock c) { this.clock = c; MockitoAnnotations.initMocks(this); when(executor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))) .thenAnswer( invocation -> { assertNull(lastRunnable); Object[] args = invocation.getArguments(); lastRunnable = (Runnable) args[0]; lastDelay = (long) args[1]; LOG.debug("{}: Saving task for later.", clock.currentTimeMillis()); return null; }); } public void runNextRunnable() { assertNotNull(lastRunnable); LOG.debug("{}: Running task after sleeping {} ms.", clock.currentTimeMillis(), lastDelay); clock.setTime(clock.currentTimeMillis() + lastDelay); Runnable r = lastRunnable; lastRunnable = null; r.run(); } public ScheduledExecutorService getExecutor() { return executor; } }
apache-2.0
izzizz/pinot
pinot-controller/src/test/java/com/linkedin/pinot/controller/helix/ControllerSentinelTestV2.java
4992
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.controller.helix; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.helix.manager.zk.ZkClient; import org.json.JSONException; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.linkedin.pinot.common.segment.SegmentMetadata; import com.linkedin.pinot.common.utils.CommonConstants; import com.linkedin.pinot.common.utils.ControllerTenantNameBuilder; import com.linkedin.pinot.common.utils.ZkStarter; import com.linkedin.pinot.controller.helix.core.PinotHelixResourceManager; import com.linkedin.pinot.core.query.utils.SimpleSegmentMetadata; public class ControllerSentinelTestV2 extends ControllerTest { private static final String HELIX_CLUSTER_NAME = "ControllerSentinelTestV2"; static ZkClient _zkClient = null; private PinotHelixResourceManager _pinotResourceManager; @BeforeClass public void setup() throws Exception { startZk(); _zkClient = new ZkClient(ZkStarter.DEFAULT_ZK_STR); startController(); _pinotResourceManager = _controllerStarter.getHelixResourceManager(); ControllerRequestBuilderUtil.addFakeBrokerInstancesToAutoJoinHelixCluster(HELIX_CLUSTER_NAME, ZkStarter.DEFAULT_ZK_STR, 20, true); ControllerRequestBuilderUtil.addFakeDataInstancesToAutoJoinHelixCluster(HELIX_CLUSTER_NAME, ZkStarter.DEFAULT_ZK_STR, 20, true); } @AfterClass public void tearDown() { stopController(); try { if (_zkClient.exists("/" + HELIX_CLUSTER_NAME)) { _zkClient.deleteRecursive("/" + HELIX_CLUSTER_NAME); } } catch (Exception e) { } _zkClient.close(); stopZk(); } @Test public void testOfflineTableLifeCycle() throws JSONException, UnsupportedEncodingException, IOException { // Create offline table creation request String tableName = "testTable"; JSONObject payload = ControllerRequestBuilderUtil.buildCreateOfflineTableJSON(tableName, null, null, 3); sendPostRequest(ControllerRequestURLBuilder.baseUrl(CONTROLLER_BASE_API_URL).forTableCreate(), payload.toString()); Assert.assertEquals( _helixAdmin.getResourceIdealState(HELIX_CLUSTER_NAME, CommonConstants.Helix.BROKER_RESOURCE_INSTANCE) .getPartitionSet().size(), 1); Assert.assertEquals( _helixAdmin.getResourceIdealState(HELIX_CLUSTER_NAME, CommonConstants.Helix.BROKER_RESOURCE_INSTANCE) .getInstanceSet(tableName + "_OFFLINE").size(), 20); // Adding segments for (int i = 0; i < 10; ++i) { Assert.assertEquals(_helixAdmin.getResourceIdealState(HELIX_CLUSTER_NAME, tableName + "_OFFLINE") .getNumPartitions(), i); addOneOfflineSegment(tableName); Assert.assertEquals(_helixAdmin.getResourceIdealState(HELIX_CLUSTER_NAME, tableName + "_OFFLINE") .getNumPartitions(), i + 1); } // Delete table sendDeleteRequest(ControllerRequestURLBuilder.baseUrl(CONTROLLER_BASE_API_URL).forTableDelete(tableName)); Assert.assertEquals( _helixAdmin.getResourceIdealState(HELIX_CLUSTER_NAME, CommonConstants.Helix.BROKER_RESOURCE_INSTANCE) .getPartitionSet().size(), 0); Assert.assertEquals( _helixAdmin.getInstancesInClusterWithTag(HELIX_CLUSTER_NAME, ControllerTenantNameBuilder.getBrokerTenantNameForTenant(ControllerTenantNameBuilder.DEFAULT_TENANT_NAME)) .size(), 20); Assert.assertEquals( _helixAdmin .getInstancesInClusterWithTag( HELIX_CLUSTER_NAME, ControllerTenantNameBuilder .getRealtimeTenantNameForTenant(ControllerTenantNameBuilder.DEFAULT_TENANT_NAME)).size(), 20); Assert.assertEquals( _helixAdmin.getInstancesInClusterWithTag(HELIX_CLUSTER_NAME, ControllerTenantNameBuilder.getOfflineTenantNameForTenant(ControllerTenantNameBuilder.DEFAULT_TENANT_NAME)) .size(), 20); } private void addOneOfflineSegment(String resourceName) { final SegmentMetadata segmentMetadata = new SimpleSegmentMetadata(resourceName); _pinotResourceManager.addSegment(segmentMetadata, "downloadUrl"); } @Override protected String getHelixClusterName() { return HELIX_CLUSTER_NAME; } }
apache-2.0
jwillia/kc-rice1
rice-middleware/kim/kim-impl/src/main/java/org/kuali/rice/kim/impl/type/KimTypeBo.java
5247
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.kuali.rice.kim.impl.type; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import org.apache.commons.collections.CollectionUtils; import org.eclipse.persistence.annotations.JoinFetch; import org.eclipse.persistence.annotations.JoinFetchType; import org.kuali.rice.kim.api.type.KimType; import org.kuali.rice.kim.api.type.KimTypeAttribute; import org.kuali.rice.kim.api.type.KimTypeContract; import org.kuali.rice.krad.bo.BusinessObject; import org.kuali.rice.krad.bo.DataObjectBase; import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator; import org.kuali.rice.krad.data.jpa.converters.BooleanYNConverter; import org.springframework.util.AutoPopulatingList; @Entity @Table(name = "KRIM_TYP_T") public class KimTypeBo extends DataObjectBase implements KimTypeContract, BusinessObject { private static final long serialVersionUID = 1L; @PortableSequenceGenerator(name = "KRIM_TYP_ID_S") @GeneratedValue(generator = "KRIM_TYP_ID_S") @Id @Column(name = "KIM_TYP_ID") private String id; @Column(name = "SRVC_NM") private String serviceName; @Column(name = "NMSPC_CD") private String namespaceCode; @Column(name = "NM") private String name; @JoinFetch(value= JoinFetchType.OUTER) @OneToMany(targetEntity = KimTypeAttributeBo.class, orphanRemoval = true, cascade = { CascadeType.REFRESH, CascadeType.REMOVE, CascadeType.PERSIST }) @JoinColumn(name = "KIM_TYP_ID", referencedColumnName = "KIM_TYP_ID", insertable = false, updatable = false) private List<KimTypeAttributeBo> attributeDefinitions = new AutoPopulatingList<KimTypeAttributeBo>(KimTypeAttributeBo.class); @Column(name = "ACTV_IND") @Convert(converter = BooleanYNConverter.class) private boolean active; /** * Converts a mutable bo to its immutable counterpart * * @param bo the mutable business object * @return the immutable object */ public static KimType to(KimTypeBo bo) { if (bo == null) { return null; } return KimType.Builder.create(bo).build(); } /** * Converts a immutable object to its mutable counterpart * * @param im immutable object * @return the mutable bo */ public static KimTypeBo from(KimType im) { if (im == null) { return null; } KimTypeBo bo = new KimTypeBo(); bo.setId(im.getId()); bo.setServiceName(im.getServiceName()); bo.setNamespaceCode(im.getNamespaceCode()); bo.setName(im.getName()); List<KimTypeAttributeBo> attributeBos = new ArrayList<KimTypeAttributeBo>(); if (CollectionUtils.isNotEmpty(im.getAttributeDefinitions())) { for (KimTypeAttribute kimTypeAttribute : im.getAttributeDefinitions()) { attributeBos.add(KimTypeAttributeBo.from(kimTypeAttribute)); } bo.setAttributeDefinitions(attributeBos); } bo.setActive(im.isActive()); bo.setVersionNumber(im.getVersionNumber()); bo.setObjectId(im.getObjectId()); return bo; } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } @Override public String getNamespaceCode() { return namespaceCode; } public void setNamespaceCode(String namespaceCode) { this.namespaceCode = namespaceCode; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public List<KimTypeAttributeBo> getAttributeDefinitions() { return attributeDefinitions; } public void setAttributeDefinitions(List<KimTypeAttributeBo> attributeDefinitions) { this.attributeDefinitions = attributeDefinitions; } public boolean getActive() { return active; } @Override public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } @Override public void refresh() { } }
apache-2.0
jdahlstrom/vaadin.react
uitest/src/test/java/com/vaadin/tests/components/treetable/MinimalWidthColumnsTest.java
946
/* * Copyright 2000-2014 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.tests.components.treetable; import org.junit.Test; import com.vaadin.tests.tb3.MultiBrowserTest; public class MinimalWidthColumnsTest extends MultiBrowserTest { @Test public void testFor1pxDifference() throws Exception { openTestURL(); sleep(500); compareScreen("onepixdifference"); } }
apache-2.0
michaelgallacher/intellij-community
python/src/com/jetbrains/python/codeInsight/controlflow/ControlFlowCache.java
2221
/* * 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.jetbrains.python.codeInsight.controlflow; import com.intellij.codeInsight.controlflow.ControlFlow; import com.intellij.openapi.util.Key; import com.intellij.reference.SoftReference; import com.jetbrains.python.codeInsight.dataflow.scope.Scope; import com.jetbrains.python.codeInsight.dataflow.scope.impl.ScopeImpl; import org.jetbrains.annotations.NotNull; /** * @author yole */ public class ControlFlowCache { private static Key<SoftReference<ControlFlow>> CONTROL_FLOW_KEY = Key.create("com.jetbrains.python.codeInsight.controlflow.ControlFlow"); private static Key<SoftReference<Scope>> SCOPE_KEY = Key.create("com.jetbrains.python.codeInsight.controlflow.Scope"); private ControlFlowCache() { } public static void clear(ScopeOwner scopeOwner) { scopeOwner.putUserData(CONTROL_FLOW_KEY, null); scopeOwner.putUserData(SCOPE_KEY, null); } public static ControlFlow getControlFlow(@NotNull ScopeOwner element) { SoftReference<ControlFlow> ref = element.getUserData(CONTROL_FLOW_KEY); ControlFlow flow = SoftReference.dereference(ref); if (flow == null) { flow = new PyControlFlowBuilder().buildControlFlow(element); element.putUserData(CONTROL_FLOW_KEY, new SoftReference<>(flow)); } return flow; } @NotNull public static Scope getScope(@NotNull ScopeOwner element) { SoftReference<Scope> ref = element.getUserData(SCOPE_KEY); Scope scope = SoftReference.dereference(ref); if (scope == null) { scope = new ScopeImpl(element); element.putUserData(SCOPE_KEY, new SoftReference<>(scope)); } return scope; } }
apache-2.0
zstackorg/zstack
header/src/main/java/org/zstack/header/identity/APIUpdateUserGroupEvent.java
991
package org.zstack.header.identity; import org.zstack.header.message.APIEvent; import org.zstack.header.rest.RestResponse; /** * Created by xing5 on 2016/3/25. */ @RestResponse(allTo = "inventory") public class APIUpdateUserGroupEvent extends APIEvent { private UserGroupInventory inventory; public APIUpdateUserGroupEvent() { } public APIUpdateUserGroupEvent(String apiId) { super(apiId); } public UserGroupInventory getInventory() { return inventory; } public void setInventory(UserGroupInventory inventory) { this.inventory = inventory; } public static APIUpdateUserGroupEvent __example__() { APIUpdateUserGroupEvent event = new APIUpdateUserGroupEvent(); UserGroupInventory inventory = new UserGroupInventory(); inventory.setName("newname"); inventory.setUuid(uuid()); inventory.setAccountUuid(uuid()); event.setInventory(inventory); return event; } }
apache-2.0
tony810430/flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/TriggerIdPathParameter.java
1637
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.rest.messages; /** {@link MessagePathParameter} for the trigger id of an asynchronous operation. */ public class TriggerIdPathParameter extends MessagePathParameter<TriggerId> { public static final String KEY = "triggerid"; public TriggerIdPathParameter() { super(KEY); } @Override protected TriggerId convertFromString(String value) throws ConversionException { return TriggerId.fromHexString(value); } @Override protected String convertToString(TriggerId value) { return value.toString(); } @Override public String getDescription() { return "32-character hexadecimal string that identifies an asynchronous operation trigger ID. " + "The ID was returned then the operation was triggered."; } }
apache-2.0
fjy/pinot
pinot-common/src/main/java/com/linkedin/pinot/common/metrics/AggregatedHistogram.java
4893
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.common.metrics; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import com.yammer.metrics.core.Histogram; import com.yammer.metrics.core.Metric; import com.yammer.metrics.core.MetricName; import com.yammer.metrics.core.MetricProcessor; import com.yammer.metrics.core.Sampling; import com.yammer.metrics.core.Summarizable; import com.yammer.metrics.stats.Snapshot; /** * * Aggregated Histogram which aggregates and provides Uniform Sampling Histograms. * We can have multi-level aggregations. * * */ public class AggregatedHistogram<T extends Sampling> implements Sampling, Summarizable, Metric { private final List<T> _histograms = new CopyOnWriteArrayList<T>(); private static final long DEFAULT_REFRESH_MS = 60 * 1000L; // 1 minute // Refresh Delay config private final long _refreshMs; // Last Refreshed timestamp private volatile long _lastRefreshedTime; // Sampling stats private volatile double _max; private volatile double _min; private volatile double _mean; private volatile double _stdDev; private volatile double _sum; //Sanpshot private volatile Snapshot _snapshot; public AggregatedHistogram(long refreshMs) { _refreshMs = refreshMs; } public AggregatedHistogram() { _refreshMs = DEFAULT_REFRESH_MS; } /** * Add Collection of metrics to be aggregated * @return this instance */ public AggregatedHistogram<T> addAll(Collection<T> histograms) { _histograms.addAll(histograms); return this; } /** * Add a metric to be aggregated * @return this instance */ public AggregatedHistogram<T> add(T histogram) { _histograms.add(histogram); return this; } /** * Remove a metric which was already added * @return true if the metric was present in the list */ public boolean remove(T histogram) { return _histograms.remove(histogram); } /** * Check elapsed time since last refresh and only refresh if time difference is * greater than threshold. */ private void refreshIfElapsed() { long currentTime = System.currentTimeMillis(); if (currentTime - _lastRefreshedTime > _refreshMs && !_histograms.isEmpty()) { refresh(); _lastRefreshedTime = currentTime; } } /** * update all stats using underlying histograms */ public void refresh() { List<Double> values = new ArrayList<Double>(); _min = Double.MAX_VALUE; _max = Double.MIN_VALUE; _sum = 0; double meanSum = 0.0; for (T hist : _histograms) { if (hist instanceof Histogram) { Histogram h = (Histogram) hist; _min = Math.min(_min, h.min()); _max = Math.max(_max, h.max()); _sum += h.sum(); meanSum += h.mean(); } else { AggregatedHistogram<Sampling> h = (AggregatedHistogram<Sampling>) hist; _min = Math.min(_min, h.min()); _max = Math.max(_max, h.max()); _sum += h.sum(); meanSum += h.mean(); } double[] val = hist.getSnapshot().getValues(); for (double d : val) { values.add(d); } } if (!_histograms.isEmpty()) { _mean = meanSum / _histograms.size(); } if (!values.isEmpty()) { double[] vals = new double[values.size()]; int i = 0; for (Double d : values) { vals[i++] = d; } _snapshot = new Snapshot(vals); } } @Override public double max() { refreshIfElapsed(); return _max; } @Override public double min() { refreshIfElapsed(); return _min; } @Override public double mean() { refreshIfElapsed(); return _mean; } @Override public double stdDev() { refreshIfElapsed(); return _stdDev; } @Override public double sum() { refreshIfElapsed(); return _sum; } @Override public Snapshot getSnapshot() { refreshIfElapsed(); return _snapshot; } @Override public <T2> void processWith(MetricProcessor<T2> processor, MetricName name, T2 context) throws Exception { for (T h : _histograms) { if (h instanceof Metric) { ((Metric) h).processWith(processor, name, context); } } } }
apache-2.0
chjp2046/fbthrift
thrift/tutorial/java/swift/client/src/main/java/com/facebook/swift/exampleclient/App.java
7175
package com.facebook.swift.exampleclient; import com.facebook.swift.codec.guice.ThriftCodecModule; import com.facebook.swift.fb303.Fb303; import com.facebook.swift.service.ThriftClient; import com.facebook.swift.service.ThriftClientManager; import com.facebook.swift.service.guice.ThriftClientModule; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.google.inject.*; import com.google.inject.name.Names; import com.mycila.inject.jsr250.Jsr250; import com.mycila.inject.jsr250.Jsr250Injector; import io.airlift.bootstrap.LifeCycleManager; import io.airlift.bootstrap.LifeCycleModule; import io.airlift.configuration.ConfigurationFactory; import io.airlift.configuration.ConfigurationModule; import io.airlift.log.Logger; import java.util.*; import java.util.concurrent.ExecutionException; import static com.facebook.swift.service.guice.ThriftClientBinder.thriftClientBinder; public class App { private static final Logger LOGGER = Logger.get(App.class); public static void main(String[] args) throws Exception { new App().run(); } public void run() throws Exception { // Make a client call using various different client setup mechanisms plainClientExample(); thriftClientFactoryExample(); guiceLifecycleExample(); jsr250InjectorExample(); collectCounters(); // Shutdown server shutdownServer(); } /** * An example that manually creates a {@link ThriftClientManager} and from that manager * manually creates and connects the client. * * {@link ClientExampleHelper} is used only to make the actually thrift method calls */ private static void plainClientExample() throws ExecutionException, InterruptedException { try (ThriftClientManager clientManager = new ThriftClientManager(); ExampleService rawClient = clientManager.createClient(ClientExampleHelper.getConnector(), ExampleService.class).get()) { ClientExampleHelper.executeWithClientAndInput(rawClient, "plainClientExample"); } } /** * An example that manually creates a {@link ThriftClientManager} and a {@link ThriftClient} * but lets the {@link ClientExampleHelper} open the connection */ private static void thriftClientFactoryExample() throws ExecutionException, InterruptedException { try (ThriftClientManager clientManager = new ThriftClientManager()) { ThriftClient<ExampleService> thriftClient = new ThriftClient<>(clientManager, ExampleService.class); new ClientExampleHelper(thriftClient, "thriftClientFactoryExample").execute(); } } /** * An example that uses the standard guice injector, and a {@link LifeCycleManager} to manage * lifetimes of injected instances. * * Guice configuration handles creation of the {@link ThriftClient} */ private static void guiceLifecycleExample() throws Exception { ImmutableMap<String, String> configuration = ImmutableMap.of( "ExampleService.thrift.client.read-timeout", "1000ms" ); Injector injector = Guice.createInjector( Stage.PRODUCTION, new LifeCycleModule(), new ConfigurationModule(new ConfigurationFactory(configuration)), new ThriftCodecModule(), new ThriftClientModule(), new Module() { @Override public void configure(Binder binder) { binder.bind(String.class) .annotatedWith(Names.named("stringToProcess")) .toInstance("guiceLifecycleExample"); thriftClientBinder(binder).bindThriftClient(ExampleService.class); } }); LifeCycleManager manager = injector.getInstance(LifeCycleManager.class); manager.start(); try { ThriftClient<ExampleService> clientFactory = injector.getInstance(Key.get(new TypeLiteral<ThriftClient<ExampleService>>() {})); String stringToProcess = injector.getInstance(Key.get(String.class, Names.named("stringToProcess"))); new ClientExampleHelper(clientFactory, stringToProcess).execute(); } finally { manager.stop(); } } /** * An example that uses the Mycila Guice injector (with JSR250 extensions for controlling * lifetimes of injected instances) * * Guice configuration handles creation of the {@link ThriftClient} */ private static void jsr250InjectorExample() throws ExecutionException, InterruptedException { ImmutableMap<String, String> configuration = ImmutableMap.of( "ExampleService.thrift.client.read-timeout", "1000ms" ); // In this case, no child injector is needed because Jsr250 handles post-construct // exceptions gracefully by running the @PreDestroy for any injected instances Jsr250Injector injector = Jsr250.createInjector( Stage.PRODUCTION, new ConfigurationModule(new ConfigurationFactory(configuration)), new ThriftCodecModule(), new ThriftClientModule(), new Module() { @Override public void configure(Binder binder) { binder.bind(String.class) .annotatedWith(Names.named("stringToProcess")) .toInstance("jsr250InjectorExample"); thriftClientBinder(binder).bindThriftClient(ExampleService.class); } }); ThriftClient<ExampleService> clientFactory = injector.getInstance(Key.get(new TypeLiteral<ThriftClient<ExampleService>>() {})); String stringToProcess = injector.getInstance(Key.get(String.class, Names.named("stringToProcess"))); new ClientExampleHelper(clientFactory, stringToProcess).execute(); injector.destroy(); } private static void collectCounters() throws ExecutionException, InterruptedException { try (ThriftClientManager clientManager = new ThriftClientManager(); Fb303 rawClient = clientManager.createClient(ClientExampleHelper.getConnector(), Fb303.class).get()) { LOGGER.info("fb303 counters:\n{}", Joiner.on("\n").join(new TreeMap<>(rawClient.getCounters()).entrySet())); } } private static void shutdownServer() throws ExecutionException, InterruptedException { try (ThriftClientManager clientManager = new ThriftClientManager(); Fb303 rawClient = clientManager.createClient(ClientExampleHelper.getConnector(), Fb303.class).get()) { rawClient.shutdown(); } } }
apache-2.0
JREkiwi/sagetv
java/sage/media/bluray/BluRayStreamer.java
1230
/* * Copyright 2015 The SageTV Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sage.media.bluray; /** * * @author Narflex */ public interface BluRayStreamer { // We do this at initialization. //public void setBufferSize(int x); public long getBytesLeftInClip(); public int getCurrClipIndex(); public long getClipPtsOffset(int index); public int getClipIndexForNextRead(); public sage.media.format.ContainerFormat getFileFormat(); public int getTitle(); public long getChapterStartMsec(int chapter); public int getNumTitles(); public int getNumChapters(); public int getChapter(long pts45); public String getTitleDesc(int titleNum); public int getNumAngles(); }
apache-2.0
charles-cooper/idylfin
src/org/apache/commons/math3/analysis/DifferentiableUnivariateMatrixFunction.java
1461
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.analysis; /** * Extension of {@link UnivariateMatrixFunction} representing a differentiable univariate matrix function. * * @version $Id: DifferentiableUnivariateMatrixFunction.java 1383854 2012-09-12 08:55:32Z luc $ * @since 2.0 * @deprecated as of 3.1 replaced by {@link org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableMatrixFunction} */ public interface DifferentiableUnivariateMatrixFunction extends UnivariateMatrixFunction { /** * Returns the derivative of the function * * @return the derivative function */ UnivariateMatrixFunction derivative(); }
apache-2.0
nishantmonu51/druid
server/src/main/java/org/apache/druid/metadata/MetadataRuleManagerConfig.java
1386
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.metadata; import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.Period; /** */ public class MetadataRuleManagerConfig { @JsonProperty private String defaultRule = "_default"; @JsonProperty private Period pollDuration = new Period("PT1M"); @JsonProperty private Period alertThreshold = new Period("PT10M"); public String getDefaultRule() { return defaultRule; } public Period getPollDuration() { return pollDuration; } public Period getAlertThreshold() { return alertThreshold; } }
apache-2.0
RyanMagnusson/cassandra
src/java/org/apache/cassandra/service/pager/QueryPagers.java
2788
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.service.pager; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.db.*; import org.apache.cassandra.db.filter.*; import org.apache.cassandra.db.partitions.*; import org.apache.cassandra.exceptions.RequestExecutionException; import org.apache.cassandra.exceptions.RequestValidationException; import org.apache.cassandra.service.ClientState; import org.apache.cassandra.transport.Server; /** * Static utility methods for paging. */ public class QueryPagers { private QueryPagers() {}; /** * Convenience method that count (live) cells/rows for a given slice of a row, but page underneath. */ public static int countPaged(CFMetaData metadata, DecoratedKey key, ColumnFilter columnFilter, ClusteringIndexFilter filter, DataLimits limits, ConsistencyLevel consistencyLevel, ClientState state, final int pageSize, int nowInSec, boolean isForThrift) throws RequestValidationException, RequestExecutionException { SinglePartitionReadCommand command = SinglePartitionReadCommand.create(isForThrift, metadata, nowInSec, columnFilter, RowFilter.NONE, limits, key, filter); final SinglePartitionPager pager = new SinglePartitionPager(command, null, Server.CURRENT_VERSION); int count = 0; while (!pager.isExhausted()) { try (PartitionIterator iter = pager.fetchPage(pageSize, consistencyLevel, state)) { DataLimits.Counter counter = limits.newCounter(nowInSec, true); PartitionIterators.consume(counter.applyTo(iter)); count += counter.counted(); } } return count; } }
apache-2.0
indi60/hbase-pmc
target/hbase-0.94.1/hbase-0.94.1/src/main/java/org/apache/hadoop/hbase/client/RowLock.java
1646
/** * Copyright 2010 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client; /** * Holds row name and lock id. */ public class RowLock { private byte [] row = null; private long lockId = -1L; /** * Creates a RowLock from a row and lock id * @param row row to lock on * @param lockId the lock id */ public RowLock(final byte [] row, final long lockId) { this.row = row; this.lockId = lockId; } /** * Creates a RowLock with only a lock id * @param lockId lock id */ public RowLock(final long lockId) { this.lockId = lockId; } /** * Get the row for this RowLock * @return the row */ public byte [] getRow() { return row; } /** * Get the lock id from this RowLock * @return the lock id */ public long getLockId() { return lockId; } }
apache-2.0
jk1/intellij-community
platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UsageViewContext.java
1750
package com.intellij.structuralsearch.plugin.ui; import com.intellij.openapi.util.text.StringUtil; import com.intellij.structuralsearch.SSRBundle; import com.intellij.usages.ConfigurableUsageTarget; import com.intellij.usages.UsageView; import com.intellij.usages.UsageViewPresentation; import org.jetbrains.annotations.NotNull; public class UsageViewContext { protected final SearchContext mySearchContext; protected final Configuration myConfiguration; private final ConfigurableUsageTarget myTarget; protected UsageViewContext(Configuration configuration, SearchContext searchContext, Runnable searchStarter) { myConfiguration = configuration; mySearchContext = searchContext; myTarget = new StructuralSearchUsageTarget(configuration, searchContext, searchStarter); } public void setUsageView(final UsageView usageView) {} public ConfigurableUsageTarget getTarget() { return myTarget; } public void configure(@NotNull UsageViewPresentation presentation) { final String pattern = myConfiguration.getMatchOptions().getSearchPattern(); final String scopeText = myConfiguration.getMatchOptions().getScope().getDisplayName(); presentation.setScopeText(scopeText); final String usagesString = SSRBundle.message("occurrences.of", pattern); presentation.setUsagesString(usagesString); presentation.setTabText(StringUtil.shortenTextWithEllipsis(usagesString, 60, 0, false)); presentation.setUsagesWord(SSRBundle.message("occurrence")); presentation.setCodeUsagesString(SSRBundle.message("found.occurrences", scopeText)); presentation.setTargetsNodeText(SSRBundle.message("targets.node.text")); presentation.setCodeUsages(false); } protected void configureActions() {} }
apache-2.0
sameerak/carbon-registry
components/registry/org.wso2.carbon.registry.ws.client/src/main/ws-test/org/wso2/carbon/registry/ws/client/test/security/CommentTest.java
18706
/* * Copyright 2004,2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.registry.ws.client.test.security; import org.wso2.carbon.registry.app.RemoteRegistry; import org.wso2.carbon.registry.core.Collection; import org.wso2.carbon.registry.core.Comment; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.utils.RegistryUtils; import java.util.ArrayList; import java.util.List; public class CommentTest extends SecurityTestSetup { public CommentTest(String text) { super(text); } public void testAddComment() throws Exception { Resource r1 = registry.newResource(); String path = "/d112/r3"; byte[] r1content = RegistryUtils.encodeString("R1 content"); r1.setContent(r1content); registry.put(path, r1); String comment1 = "this is qa comment 4"; String comment2 = "this is qa comment 5"; Comment c1 = new Comment(); c1.setResourcePath(path); c1.setText("This is default comment"); c1.setUser("admin1"); registry.addComment(path, c1); registry.addComment(path, new Comment(comment1)); registry.addComment(path, new Comment(comment2)); Comment[] comments = registry.getComments(path); boolean commentFound = false; for (Comment comment : comments) { if (comment.getText().equals(comment1)) { commentFound = true; //System.out.println(comment.getPath()); assertEquals(comment1, comment.getText()); assertEquals("admin", comment.getUser()); assertEquals(path, comment.getResourcePath()); //System.out.println(comment.getPath()); //break; } if (comment.getText().equals(comment2)) { commentFound = true; assertEquals(comment2, comment.getText()); assertEquals("admin", comment.getUser()); assertEquals(path, comment.getResourcePath()); //break; } if (comment.getText().equals("This is default comment")) { commentFound = true; assertEquals("This is default comment", comment.getText()); assertEquals("admin", comment.getUser()); //break; } } assertTrue("comment '" + comment1 + " is not associated with the artifact /d1/r3", commentFound); Resource commentsResource = registry.get("/d112/r3;comments"); assertTrue("Comment collection resource should be a directory.", commentsResource instanceof Collection); comments = (Comment[]) commentsResource.getContent(); List commentTexts = new ArrayList(); for (Comment comment : comments) { Resource commentResource = registry.get(comment.getPath()); commentTexts.add(commentResource.getContent()); } assertTrue(comment1 + " is not associated for resource /d112/r3.", commentTexts.contains(comment1)); assertTrue(comment2 + " is not associated for resource /d112/r3.", commentTexts.contains(comment2)); } public void testAddCommentToResource() throws Exception { Resource r1 = registry.newResource(); byte[] r1content = RegistryUtils.encodeString("R1 content"); r1.setContent(r1content); registry.put("/d1/r3", r1); String comment1 = "this is qa comment 4"; String comment2 = "this is qa comment 5"; Comment c1 = new Comment(); c1.setResourcePath("/d1/r3"); c1.setText("This is default comment"); c1.setUser("admin"); registry.addComment("/d1/r3", c1); registry.addComment("/d1/r3", new Comment(comment1)); registry.addComment("/d1/r3", new Comment(comment2)); Comment[] comments = registry.getComments("/d1/r3"); boolean commentFound = false; for (Comment comment : comments) { if (comment.getText().equals(comment1)) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); //break; } if (comment.getText().equals(comment2)) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); //break; } if (comment.getText().equals("This is default comment")) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); //break; } } assertTrue("comment '" + comment1 + " is not associated with the artifact /d1/r3", commentFound); Resource commentsResource = registry.get("/d1/r3;comments"); assertTrue("Comment collection resource should be a directory.", commentsResource instanceof Collection); comments = (Comment[]) commentsResource.getContent(); List commentTexts = new ArrayList(); for (Comment comment : comments) { Resource commentResource = registry.get(comment.getPath()); commentTexts.add(commentResource.getContent()); } assertTrue(comment1 + " is not associated for resource /d1/r3.", commentTexts.contains(comment1)); assertTrue(comment2 + " is not associated for resource /d1/r3.", commentTexts.contains(comment2)); /*try { //registry.delete("/d12"); } catch (RegistryException e) { fail("Failed to delete test resources."); } */ } public void testAddCommentToCollection() throws Exception { Resource r1 = registry.newCollection(); r1.setDescription("this is a collection to add comment"); registry.put("/d11/d12", r1); String comment1 = "this is qa comment 1 for collection d12"; String comment2 = "this is qa comment 2 for collection d12"; Comment c1 = new Comment(); c1.setResourcePath("/d11/d12"); c1.setText("This is default comment for d12"); c1.setUser("admin"); try { registry.addComment("/d11/d12", c1); registry.addComment("/d11/d12", new Comment(comment1)); registry.addComment("/d11/d12", new Comment(comment2)); } catch (RegistryException e) { fail("Valid commenting for resources scenario failed"); } Comment[] comments = null; try { comments = registry.getComments("/d11/d12"); } catch (RegistryException e) { fail("Failed to get comments for the resource /d11/d12"); } boolean commentFound = false; for (Comment comment : comments) { if (comment.getText().equals(comment1)) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); //break; } if (comment.getText().equals(comment2)) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); //break; } if (comment.getText().equals(c1.getText())) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); //break; } } assertTrue("comment '" + comment1 + " is not associated with the artifact /d11/d12", commentFound); try { Resource commentsResource = registry.get("/d11/d12;comments"); assertTrue("Comment collection resource should be a directory.", commentsResource instanceof Collection); comments = (Comment[]) commentsResource.getContent(); List commentTexts = new ArrayList(); for (Comment comment : comments) { Resource commentResource = registry.get(comment.getPath()); commentTexts.add(commentResource.getContent()); } assertTrue(comment1 + " is not associated for resource /d11/d12.", commentTexts.contains(comment1)); assertTrue(comment2 + " is not associated for resource /d11/d12.", commentTexts.contains(comment2)); } catch (RegistryException e) { e.printStackTrace(); fail("Failed to get comments form URL: /d11/d12;comments"); } /*try { //registry.delete("/d12"); } catch (RegistryException e) { fail("Failed to delete test resources."); } */ } public void testAddCommenttoRoot() throws Exception { String comment1 = "this is qa comment 1 for root"; String comment2 = "this is qa comment 2 for root"; Comment c1 = new Comment(); c1.setResourcePath("/"); c1.setText("This is default comment for root"); c1.setUser("admin"); try { registry.addComment("/", c1); registry.addComment("/", new Comment(comment1)); registry.addComment("/", new Comment(comment2)); } catch (RegistryException e) { fail("Valid commenting for resources scenario failed"); } Comment[] comments = null; try { comments = registry.getComments("/"); } catch (RegistryException e) { fail("Failed to get comments for the resource /"); } boolean commentFound = false; for (Comment comment : comments) { if (comment.getText().equals(comment1)) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); // //System.out.println("\n"); //break; } if (comment.getText().equals(comment2)) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); // //System.out.println("\n"); //break; } if (comment.getText().equals(c1.getText())) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); // //System.out.println("\n"); //break; } } assertTrue("comment '" + comment1 + " is not associated with the artifact /", commentFound); try { Resource commentsResource = registry.get("/;comments"); assertTrue("Comment collection resource should be a directory.", commentsResource instanceof Collection); comments = (Comment[]) commentsResource.getContent(); List commentTexts = new ArrayList(); for (Comment comment : comments) { Resource commentResource = registry.get(comment.getPath()); commentTexts.add(commentResource.getContent()); } assertTrue(comment1 + " is not associated for resource /.", commentTexts.contains(comment1)); assertTrue(comment2 + " is not associated for resource /.", commentTexts.contains(comment2)); } catch (RegistryException e) { fail("Failed to get comments form URL: /;comments"); } /*try { //registry.delete("/d12"); } catch (RegistryException e) { fail("Failed to delete test resources."); } */ } public void testEditComment() throws Exception { Resource r1 = registry.newResource(); byte[] r1content = RegistryUtils.encodeString("R1 content"); r1.setContent(r1content); r1.setDescription("this is a resource to edit comment"); registry.put("/c101/c11/r1", r1); Comment c1 = new Comment(); c1.setResourcePath("/c10/c11/r1"); c1.setText("This is default comment "); c1.setUser("admin"); String commentPath = registry.addComment("/c101/c11/r1", c1); Comment[] comments = registry.getComments("/c101/c11/r1"); boolean commentFound = false; for (Comment comment : comments) { if (comment.getText().equals(c1.getText())) { commentFound = true; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); // //System.out.println("\n"); //break; } } assertTrue("comment:" + c1.getText() + " is not associated with the artifact /c101/c11/r1", commentFound); try { Resource commentsResource = registry.get("/c101/c11/r1;comments"); assertTrue("Comment resource should be a directory.", commentsResource instanceof Collection); comments = (Comment[]) commentsResource.getContent(); List commentTexts = new ArrayList(); for (Comment comment : comments) { Resource commentResource = registry.get(comment.getPath()); commentTexts.add(commentResource.getContent()); } assertTrue(c1.getText() + " is not associated for resource /c101/c11/r1.", commentTexts.contains(c1.getText())); registry.editComment(comments[0].getPath(), "This is the edited comment"); comments = registry.getComments("/c101/c11/r1"); // System.out.println(comments); Resource resource = registry.get(comments[0].getPath()); assertEquals("This is the edited comment", resource.getContent()); } catch (RegistryException e) { e.printStackTrace(); fail("Failed to get comments form URL:/c101/c11/r1;comments"); } /*Edit comment goes here*/ String editedCommentString = "This is the edited comment"; registry.editComment(commentPath, editedCommentString); Comment[] comments1 = registry.getComments("/c101/c11/r1"); boolean editedCommentFound = false; boolean defaultCommentFound = true; for (Comment comment : comments1) { if (comment.getText().equals(editedCommentString)) { editedCommentFound = true; } else if (comment.getText().equals(c1.getText())) { defaultCommentFound = false; // //System.out.println(comment.getText()); // //System.out.println(comment.getResourcePath()); // //System.out.println(comment.getUser()); // //System.out.println(comment.getTime()); // //System.out.println("\n"); //break; } } assertTrue("comment:" + editedCommentString + " is not associated with the artifact /c101/c11/r1", editedCommentFound); } public void testCommentDelete() throws Exception { String r1Path = "/c1d1/c1"; Collection r1 = registry.newCollection(); registry.put(r1Path, r1); String c1Path = registry.addComment(r1Path, new Comment("test comment1")); registry.addComment(r1Path, new Comment("test comment2")); Comment[] comments1 = registry.getComments(r1Path); assertEquals("There should be two comments.", comments1.length, 2); String[] cTexts1 = {comments1[0].getText(), comments1[1].getText()}; assertTrue("comment is missing", containsString(cTexts1, "test comment1")); assertTrue("comment is missing", containsString(cTexts1, "test comment2")); registry.delete(c1Path); Comment[] comments2 = registry.getComments(r1Path); assertEquals("There should be one comment.", 1, comments2.length); String[] cTexts2 = {comments2[0].getText()}; assertTrue("comment is missing", containsString(cTexts2, "test comment2")); assertTrue("deleted comment still exists", !containsString(cTexts2, "test comment1")); } private boolean containsString(String[] array, String value) { boolean found = false; for (String anArray : array) { if (anArray.startsWith(value)) { found = true; break; } } return found; } }
apache-2.0
yinhe402/lemon
src/main/java/com/mossle/ext/spring/LogoutHttpSessionListener.java
1142
package com.mossle.ext.spring; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import com.mossle.ext.auth.LogoutEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; public class LogoutHttpSessionListener implements HttpSessionListener { private static Logger logger = LoggerFactory .getLogger(LogoutHttpSessionListener.class); public void sessionCreated(HttpSessionEvent se) { } public void sessionDestroyed(HttpSessionEvent se) { ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(se.getSession().getServletContext()); if (ctx == null) { logger.warn("cannot find applicationContext"); return; } HttpSession session = se.getSession(); LogoutEvent logoutEvent = new LogoutEvent(session, null, session.getId()); ctx.publishEvent(logoutEvent); } }
apache-2.0
fengshao0907/titan
titan-core/src/main/java/com/thinkaurelius/titan/graphdb/idmanagement/IDManager.java
21763
package com.thinkaurelius.titan.graphdb.idmanagement; import com.google.common.base.Preconditions; import com.google.common.primitives.Longs; import com.thinkaurelius.titan.core.InvalidIDException; import com.thinkaurelius.titan.diskstorage.StaticBuffer; import com.thinkaurelius.titan.diskstorage.util.BufferUtil; import com.thinkaurelius.titan.graphdb.database.idhandling.VariableLong; /** * Handles the allocation of ids based on the type of element * Responsible for the bit-wise pattern of Titan's internal id scheme. * * @author Matthias Broecheler (me@matthiasb.com) */ public class IDManager { /** *bit mask- Description (+ indicates defined type, * indicates proper & defined type) * * 0 - + User created Vertex * 000 - * Normal vertices * 010 - * Partitioned vertices * 100 - * Unmodifiable (e.g. TTL'ed) vertices * 110 - + Reserved for additional vertex type * 1 - + Hidden * 11 - * Hidden (user created/triggered) Vertex [for later] * 01 - + Schema related vertices * 101 - + Schema Type vertices * 0101 - + Relation Type vertices * 00101 - + Property Key * 000101 - * User Property Key * 100101 - * System Property Key * 10101 - + Edge Label * 010101 - * User Edge Label * 110101 - * System Edge Label * 1101 - Other Type vertices * 01101 - * Vertex Label * 001 - Non-Type vertices * 1001 - * Generic Schema Vertex * 0001 - Reserved for future * * */ public enum VertexIDType { UserVertex { @Override final long offset() { return 1l; } @Override final long suffix() { return 0l; } // 0b @Override final boolean isProper() { return false; } }, NormalVertex { @Override final long offset() { return 3l; } @Override final long suffix() { return 0l; } // 000b @Override final boolean isProper() { return true; } }, PartitionedVertex { @Override final long offset() { return 3l; } @Override final long suffix() { return 2l; } // 010b @Override final boolean isProper() { return true; } }, UnmodifiableVertex { @Override final long offset() { return 3l; } @Override final long suffix() { return 4l; } // 100b @Override final boolean isProper() { return true; } }, Hidden { @Override final long offset() { return 1l; } @Override final long suffix() { return 1l; } // 1b @Override final boolean isProper() { return false; } }, HiddenVertex { @Override final long offset() { return 2l; } @Override final long suffix() { return 3l; } // 11b @Override final boolean isProper() { return true; } }, Schema { @Override final long offset() { return 2l; } @Override final long suffix() { return 1l; } // 01b @Override final boolean isProper() { return false; } }, SchemaType { @Override final long offset() { return 3l; } @Override final long suffix() { return 5l; } // 101b @Override final boolean isProper() { return false; } }, RelationType { @Override final long offset() { return 4l; } @Override final long suffix() { return 5l; } // 0101b @Override final boolean isProper() { return false; } }, PropertyKey { @Override final long offset() { return 5l; } @Override final long suffix() { return 5l; } // 00101b @Override final boolean isProper() { return false; } }, UserPropertyKey { @Override final long offset() { return 6l; } @Override final long suffix() { return 5l; } // 000101b @Override final boolean isProper() { return true; } }, SystemPropertyKey { @Override final long offset() { return 6l; } @Override final long suffix() { return 37l; } // 100101b @Override final boolean isProper() { return true; } }, EdgeLabel { @Override final long offset() { return 5l; } @Override final long suffix() { return 21l; } // 10101b @Override final boolean isProper() { return false; } }, UserEdgeLabel { @Override final long offset() { return 6l; } @Override final long suffix() { return 21l; } // 010101b @Override final boolean isProper() { return true; } }, SystemEdgeLabel { @Override final long offset() { return 6l; } @Override final long suffix() { return 53l; } // 110101b @Override final boolean isProper() { return true; } }, VertexLabel { @Override final long offset() { return 5l; } @Override final long suffix() { return 13l; } // 01101b @Override final boolean isProper() { return true; } }, GenericSchemaType { @Override final long offset() { return 4l; } @Override final long suffix() { return 9l; } // 1001b @Override final boolean isProper() { return true; } }; abstract long offset(); abstract long suffix(); abstract boolean isProper(); public final long addPadding(long count) { assert offset()>0; Preconditions.checkArgument(count>0 && count<(1l<<(TOTAL_BITS-offset())),"Count out of range for type [%s]: %s",this,count); return (count << offset()) | suffix(); } public final long removePadding(long id) { return id >>> offset(); } public final boolean is(long id) { return (id & ((1l << offset()) - 1)) == suffix(); } public final boolean isSubType(VertexIDType type) { return is(type.suffix()); } } /** * Id of the partition that schema elements are assigned to */ public static final int SCHEMA_PARTITION = 0; public static final int PARTITIONED_VERTEX_PARTITION = 1; /** * Number of bits that need to be reserved from the type ids for storing additional information during serialization */ public static final int TYPE_LEN_RESERVE = 3; /** * Total number of bits available to a Titan assigned id * We use only 63 bits to make sure that all ids are positive * */ private static final long TOTAL_BITS = Long.SIZE-1; /** * Maximum number of bits that can be used for the partition prefix of an id */ private static final long MAX_PARTITION_BITS = 16; /** * Default number of bits used for the partition prefix. 0 means there is no partition prefix */ private static final long DEFAULT_PARTITION_BITS = 0; /** * The padding bit with for user vertices */ public static final long USERVERTEX_PADDING_BITWIDTH = VertexIDType.NormalVertex.offset(); /** * The maximum number of padding bits of any type */ public static final long MAX_PADDING_BITWIDTH = VertexIDType.UserEdgeLabel.offset(); /** * Bound on the maximum count for a schema id */ private static final long SCHEMA_COUNT_BOUND = (1l << (TOTAL_BITS - MAX_PADDING_BITWIDTH - TYPE_LEN_RESERVE)); @SuppressWarnings("unused") private final long partitionBits; private final long partitionOffset; private final long partitionIDBound; private final long relationCountBound; private final long vertexCountBound; public IDManager(long partitionBits) { Preconditions.checkArgument(partitionBits >= 0); Preconditions.checkArgument(partitionBits <= MAX_PARTITION_BITS, "Partition bits can be at most %s bits", MAX_PARTITION_BITS); this.partitionBits = partitionBits; partitionIDBound = (1l << (partitionBits)); relationCountBound = partitionBits==0?Long.MAX_VALUE:(1l << (TOTAL_BITS - partitionBits)); assert VertexIDType.NormalVertex.offset()>0; vertexCountBound = (1l << (TOTAL_BITS - partitionBits - USERVERTEX_PADDING_BITWIDTH)); partitionOffset = Long.SIZE - partitionBits; } public IDManager() { this(DEFAULT_PARTITION_BITS); } public long getPartitionBound() { return partitionIDBound; } /* ######################################################## User Relations and Vertices ######################################################## */ /* --- TitanElement id bit format --- * [ 0 | count | partition | ID padding (if any) ] */ private long constructId(long count, long partition, VertexIDType type) { Preconditions.checkArgument(partition<partitionIDBound && partition>=0,"Invalid partition: %s",partition); Preconditions.checkArgument(count>=0); Preconditions.checkArgument(VariableLong.unsignedBitLength(count)+partitionBits+ (type==null?0:type.offset())<=TOTAL_BITS); Preconditions.checkArgument(type==null || type.isProper()); long id = (count<<partitionBits)+partition; if (type!=null) id = type.addPadding(id); return id; } private static VertexIDType getUserVertexIDType(long vertexid) { VertexIDType type=null; if (VertexIDType.NormalVertex.is(vertexid)) type=VertexIDType.NormalVertex; else if (VertexIDType.PartitionedVertex.is(vertexid)) type=VertexIDType.PartitionedVertex; else if (VertexIDType.UnmodifiableVertex.is(vertexid)) type=VertexIDType.UnmodifiableVertex; if (null == type) { throw new InvalidIDException("Vertex ID " + vertexid + " has unrecognized type"); } return type; } private boolean isUserVertex(long vertexid) { return (VertexIDType.NormalVertex.is(vertexid) || VertexIDType.PartitionedVertex.is(vertexid) || VertexIDType.UnmodifiableVertex.is(vertexid)) && ((vertexid>>>(partitionBits+USERVERTEX_PADDING_BITWIDTH))>0); } public long getPartitionId(long vertexid) { if (VertexIDType.Schema.is(vertexid)) return SCHEMA_PARTITION; assert isUserVertex(vertexid) && getUserVertexIDType(vertexid)!=null; long partition = (vertexid>>>USERVERTEX_PADDING_BITWIDTH) & (partitionIDBound-1); assert partition>=0; return partition; } public StaticBuffer getKey(long vertexid) { if (VertexIDType.Schema.is(vertexid)) { //No partition for schema vertices return BufferUtil.getLongBuffer(vertexid); } else { assert isUserVertex(vertexid); VertexIDType type = getUserVertexIDType(vertexid); assert type.offset()==USERVERTEX_PADDING_BITWIDTH; long partition = getPartitionId(vertexid); long count = vertexid>>>(partitionBits+USERVERTEX_PADDING_BITWIDTH); assert count>0; long keyid = (partition<<partitionOffset) | type.addPadding(count); return BufferUtil.getLongBuffer(keyid); } } public long getKeyID(StaticBuffer b) { long value = b.getLong(0); if (VertexIDType.Schema.is(value)) { return value; } else { VertexIDType type = getUserVertexIDType(value); long partition = partitionOffset<Long.SIZE?value>>>partitionOffset:0; long count = (value>>>USERVERTEX_PADDING_BITWIDTH) & ((1l<<(partitionOffset-USERVERTEX_PADDING_BITWIDTH))-1); return constructId(count,partition,type); } } public long getRelationID(long count, long partition) { Preconditions.checkArgument(count>0 && count< relationCountBound,"Invalid count for bound: %s", relationCountBound); return constructId(count, partition, null); } public long getVertexID(long count, long partition, VertexIDType vertexType) { Preconditions.checkArgument(VertexIDType.UserVertex.is(vertexType.suffix()),"Not a user vertex type: %s",vertexType); Preconditions.checkArgument(count>0 && count<vertexCountBound,"Invalid count for bound: %s", vertexCountBound); if (vertexType==VertexIDType.PartitionedVertex) { Preconditions.checkArgument(partition==PARTITIONED_VERTEX_PARTITION); return getCanonicalVertexIdFromCount(count); } else { return constructId(count, partition, vertexType); } } public long getPartitionHashForId(long id) { Preconditions.checkArgument(id>0); Preconditions.checkState(partitionBits>0, "no partition bits"); long result = 0; int offset = 0; while (offset<Long.SIZE) { result = result ^ ((id>>>offset) & (partitionIDBound-1)); offset+=partitionBits; } assert result>=0 && result<partitionIDBound; return result; } private long getCanonicalVertexIdFromCount(long count) { long partition = getPartitionHashForId(count); return constructId(count,partition,VertexIDType.PartitionedVertex); } public long getCanonicalVertexId(long partitionedVertexId) { Preconditions.checkArgument(VertexIDType.PartitionedVertex.is(partitionedVertexId)); long count = partitionedVertexId>>>(partitionBits+USERVERTEX_PADDING_BITWIDTH); return getCanonicalVertexIdFromCount(count); } public boolean isCanonicalVertexId(long partitionVertexId) { return partitionVertexId==getCanonicalVertexId(partitionVertexId); } public long getPartitionedVertexId(long partitionedVertexId, long otherPartition) { Preconditions.checkArgument(VertexIDType.PartitionedVertex.is(partitionedVertexId)); long count = partitionedVertexId>>>(partitionBits+USERVERTEX_PADDING_BITWIDTH); assert count>0; return constructId(count,otherPartition,VertexIDType.PartitionedVertex); } public long[] getPartitionedVertexRepresentatives(long partitionedVertexId) { Preconditions.checkArgument(isPartitionedVertex(partitionedVertexId)); assert getPartitionBound()<Integer.MAX_VALUE; long[] ids = new long[(int)getPartitionBound()]; for (int i=0;i<getPartitionBound();i++) { ids[i]=getPartitionedVertexId(partitionedVertexId,i); } return ids; } public boolean isPartitionedVertex(long id) { return isUserVertex(id) && VertexIDType.PartitionedVertex.is(id); } public long getRelationCountBound() { return relationCountBound; } public long getVertexCountBound() { return vertexCountBound; } /* Temporary ids are negative and don't have partitions */ public static long getTemporaryRelationID(long count) { return makeTemporary(count); } public static long getTemporaryVertexID(VertexIDType type, long count) { Preconditions.checkArgument(type.isProper(),"Invalid vertex id type: %s",type); return makeTemporary(type.addPadding(count)); } private static long makeTemporary(long id) { Preconditions.checkArgument(id>0); return (1l<<63) | id; //make negative but preserve bit pattern } public static boolean isTemporary(long id) { return id<0; } /* ######################################################## Schema Vertices ######################################################## */ /* --- TitanRelation Type id bit format --- * [ 0 | count | ID padding ] * (there is no partition) */ private static void checkSchemaTypeId(VertexIDType type, long count) { Preconditions.checkArgument(VertexIDType.Schema.is(type.suffix()),"Expected schema vertex but got: %s",type); Preconditions.checkArgument(type.isProper(),"Expected proper type but got: %s",type); Preconditions.checkArgument(count > 0 && count < SCHEMA_COUNT_BOUND, "Invalid id [%s] for type [%s] bound: %s", count, type, SCHEMA_COUNT_BOUND); } public static long getSchemaId(VertexIDType type, long count) { checkSchemaTypeId(type,count); return type.addPadding(count); } private static boolean isProperRelationType(long id) { return VertexIDType.UserEdgeLabel.is(id) || VertexIDType.SystemEdgeLabel.is(id) || VertexIDType.UserPropertyKey.is(id) || VertexIDType.SystemPropertyKey.is(id); } public static long stripEntireRelationTypePadding(long id) { Preconditions.checkArgument(isProperRelationType(id)); return VertexIDType.UserEdgeLabel.removePadding(id); } public static long stripRelationTypePadding(long id) { Preconditions.checkArgument(isProperRelationType(id)); return VertexIDType.RelationType.removePadding(id); } public static long addRelationTypePadding(long id) { long typeid = VertexIDType.RelationType.addPadding(id); Preconditions.checkArgument(isProperRelationType(typeid)); return typeid; } public static boolean isSystemRelationTypeId(long id) { return VertexIDType.SystemEdgeLabel.is(id) || VertexIDType.SystemPropertyKey.is(id); } public static long getSchemaCountBound() { return SCHEMA_COUNT_BOUND; } /* ######################################################## Inspector ######################################################## */ private final IDInspector inspector = new IDInspector() { @Override public final boolean isSchemaVertexId(long id) { return isRelationTypeId(id) || isVertexLabelVertexId(id) || isGenericSchemaVertexId(id); } @Override public final boolean isRelationTypeId(long id) { return VertexIDType.RelationType.is(id); } @Override public final boolean isEdgeLabelId(long id) { return VertexIDType.EdgeLabel.is(id); } @Override public final boolean isPropertyKeyId(long id) { return VertexIDType.PropertyKey.is(id); } @Override public boolean isSystemRelationTypeId(long id) { return IDManager.isSystemRelationTypeId(id); } @Override public boolean isGenericSchemaVertexId(long id) { return VertexIDType.GenericSchemaType.is(id); } @Override public boolean isVertexLabelVertexId(long id) { return VertexIDType.VertexLabel.is(id); } @Override public final boolean isUserVertexId(long id) { return IDManager.this.isUserVertex(id); } @Override public boolean isUnmodifiableVertex(long id) { return isUserVertex(id) && VertexIDType.UnmodifiableVertex.is(id); } @Override public boolean isPartitionedVertex(long id) { return IDManager.this.isPartitionedVertex(id); } @Override public long getCanonicalVertexId(long partitionedVertexId) { return IDManager.this.getCanonicalVertexId(partitionedVertexId); } }; public IDInspector getIdInspector() { return inspector; } }
apache-2.0
netroby/gerrit
gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/AccountGroupInfoScreen.java
8283
// Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.admin; import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.VoidResult; import com.google.gerrit.client.groups.GroupApi; import com.google.gerrit.client.groups.GroupInfo; import com.google.gerrit.client.rpc.GerritCallback; import com.google.gerrit.client.ui.AccountGroupSuggestOracle; import com.google.gerrit.client.ui.OnEditEnabler; import com.google.gerrit.client.ui.RemoteSuggestBox; import com.google.gerrit.client.ui.SmallHeading; import com.google.gerrit.reviewdb.client.AccountGroup; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwtexpui.clippy.client.CopyableLabel; import com.google.gwtexpui.globalkey.client.NpTextArea; import com.google.gwtexpui.globalkey.client.NpTextBox; public class AccountGroupInfoScreen extends AccountGroupScreen { private CopyableLabel groupUUIDLabel; private NpTextBox groupNameTxt; private Button saveName; private RemoteSuggestBox ownerTxt; private Button saveOwner; private NpTextArea descTxt; private Button saveDesc; private CheckBox visibleToAllCheckBox; private Button saveGroupOptions; public AccountGroupInfoScreen(final GroupInfo toShow, final String token) { super(toShow, token); } @Override protected void onInitUI() { super.onInitUI(); initUUID(); initName(); initOwner(); initDescription(); initGroupOptions(); } private void enableForm(final boolean canModify) { groupNameTxt.setEnabled(canModify); ownerTxt.setEnabled(canModify); descTxt.setEnabled(canModify); visibleToAllCheckBox.setEnabled(canModify); } private void initUUID() { final VerticalPanel groupUUIDPanel = new VerticalPanel(); groupUUIDPanel.setStyleName(Gerrit.RESOURCES.css().groupUUIDPanel()); groupUUIDPanel.add(new SmallHeading(Util.C.headingGroupUUID())); groupUUIDLabel = new CopyableLabel(""); groupUUIDPanel.add(groupUUIDLabel); add(groupUUIDPanel); } private void initName() { final VerticalPanel groupNamePanel = new VerticalPanel(); groupNamePanel.setStyleName(Gerrit.RESOURCES.css().groupNamePanel()); groupNameTxt = new NpTextBox(); groupNameTxt.setStyleName(Gerrit.RESOURCES.css().groupNameTextBox()); groupNameTxt.setVisibleLength(60); groupNamePanel.add(groupNameTxt); saveName = new Button(Util.C.buttonRenameGroup()); saveName.setEnabled(false); saveName.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final String newName = groupNameTxt.getText().trim(); GroupApi.renameGroup(getGroupUUID(), newName, new GerritCallback<com.google.gerrit.client.VoidResult>() { @Override public void onSuccess(final com.google.gerrit.client.VoidResult result) { saveName.setEnabled(false); setPageTitle(Util.M.group(newName)); groupNameTxt.setText(newName); if (getGroupUUID().equals(getOwnerGroupUUID())) { ownerTxt.setText(newName); } } }); } }); groupNamePanel.add(saveName); add(groupNamePanel); } private void initOwner() { final VerticalPanel ownerPanel = new VerticalPanel(); ownerPanel.setStyleName(Gerrit.RESOURCES.css().groupOwnerPanel()); ownerPanel.add(new SmallHeading(Util.C.headingOwner())); final AccountGroupSuggestOracle accountGroupOracle = new AccountGroupSuggestOracle(); ownerTxt = new RemoteSuggestBox(accountGroupOracle); ownerTxt.setStyleName(Gerrit.RESOURCES.css().groupOwnerTextBox()); ownerTxt.setVisibleLength(60); ownerPanel.add(ownerTxt); saveOwner = new Button(Util.C.buttonChangeGroupOwner()); saveOwner.setEnabled(false); saveOwner.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final String newOwner = ownerTxt.getText().trim(); if (newOwner.length() > 0) { AccountGroup.UUID ownerUuid = accountGroupOracle.getUUID(newOwner); String ownerId = ownerUuid != null ? ownerUuid.get() : newOwner; GroupApi.setGroupOwner(getGroupUUID(), ownerId, new GerritCallback<GroupInfo>() { @Override public void onSuccess(final GroupInfo result) { updateOwnerGroup(result); saveOwner.setEnabled(false); } }); } } }); ownerPanel.add(saveOwner); add(ownerPanel); } private void initDescription() { final VerticalPanel vp = new VerticalPanel(); vp.setStyleName(Gerrit.RESOURCES.css().groupDescriptionPanel()); vp.add(new SmallHeading(Util.C.headingDescription())); descTxt = new NpTextArea(); descTxt.setVisibleLines(6); descTxt.setCharacterWidth(60); vp.add(descTxt); saveDesc = new Button(Util.C.buttonSaveDescription()); saveDesc.setEnabled(false); saveDesc.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final String txt = descTxt.getText().trim(); GroupApi.setGroupDescription(getGroupUUID(), txt, new GerritCallback<VoidResult>() { @Override public void onSuccess(final VoidResult result) { saveDesc.setEnabled(false); } }); } }); vp.add(saveDesc); add(vp); } private void initGroupOptions() { final VerticalPanel groupOptionsPanel = new VerticalPanel(); final VerticalPanel vp = new VerticalPanel(); vp.setStyleName(Gerrit.RESOURCES.css().groupOptionsPanel()); vp.add(new SmallHeading(Util.C.headingGroupOptions())); visibleToAllCheckBox = new CheckBox(Util.C.isVisibleToAll()); vp.add(visibleToAllCheckBox); groupOptionsPanel.add(vp); saveGroupOptions = new Button(Util.C.buttonSaveGroupOptions()); saveGroupOptions.setEnabled(false); saveGroupOptions.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { GroupApi.setGroupOptions(getGroupUUID(), visibleToAllCheckBox.getValue(), new GerritCallback<VoidResult>() { @Override public void onSuccess(final VoidResult result) { saveGroupOptions.setEnabled(false); } }); } }); groupOptionsPanel.add(saveGroupOptions); add(groupOptionsPanel); final OnEditEnabler enabler = new OnEditEnabler(saveGroupOptions); enabler.listenTo(visibleToAllCheckBox); } @Override protected void display(final GroupInfo group, final boolean canModify) { groupUUIDLabel.setText(group.getGroupUUID().get()); groupNameTxt.setText(group.name()); ownerTxt.setText(group.owner() != null?group.owner():Util.M.deletedReference(group.getOwnerUUID().get())); descTxt.setText(group.description()); visibleToAllCheckBox.setValue(group.options().isVisibleToAll()); setMembersTabVisible(AccountGroup.isInternalGroup(group.getGroupUUID())); enableForm(canModify); saveName.setVisible(canModify); saveOwner.setVisible(canModify); saveDesc.setVisible(canModify); saveGroupOptions.setVisible(canModify); new OnEditEnabler(saveDesc, descTxt); new OnEditEnabler(saveName, groupNameTxt); new OnEditEnabler(saveOwner, ownerTxt.getTextBox()); } }
apache-2.0
gpolitis/jitsi
src/net/java/sip/communicator/impl/protocol/jabber/extensions/coin/SIPDialogIDPacketExtension.java
3972
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty 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 net.java.sip.communicator.impl.protocol.jabber.extensions.coin; import java.util.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.*; import org.jivesoftware.smack.packet.*; /** * SIP Dialog ID packet extension. * * @author Sebastien Vincent */ public class SIPDialogIDPacketExtension extends AbstractPacketExtension { /** * The namespace that SIP Dialog ID belongs to. */ public static final String NAMESPACE = ""; /** * The name of the element that contains the SIP Dialog ID data. */ public static final String ELEMENT_NAME = "sip"; /** * Display text element name. */ public static final String ELEMENT_DISPLAY_TEXT = "display-text"; /** * Call ID element name. */ public static final String ELEMENT_CALLID = "call-id"; /** * From tag element name. */ public static final String ELEMENT_FROMTAG = "from-tag"; /** * From tag element name. */ public static final String ELEMENT_TOTAG = "to-tag"; /** * Display text. */ private String displayText = null; /** * Call ID. */ private String callID = null; /** * From tag. */ private String fromTag = null; /** * To tag. */ private String toTag = null; /** * Constructor */ public SIPDialogIDPacketExtension() { super(NAMESPACE, ELEMENT_NAME); } /** * Returns an XML representation of this extension. * * @return an XML representation of this extension. */ @Override public String toXML() { StringBuilder bldr = new StringBuilder(); bldr.append("<").append(getElementName()).append(" "); if(getNamespace() != null) bldr.append("xmlns='").append(getNamespace()).append("'"); //add the rest of the attributes if any for(Map.Entry<String, Object> entry : attributes.entrySet()) { bldr.append(" ") .append(entry.getKey()) .append("='") .append(entry.getValue()) .append("'"); } bldr.append(">"); if(displayText != null) bldr.append("<").append(ELEMENT_DISPLAY_TEXT).append(">").append( displayText).append("</").append( ELEMENT_DISPLAY_TEXT).append(">"); if(callID != null) bldr.append("<").append(ELEMENT_CALLID).append(">").append( callID).append("</").append( ELEMENT_CALLID).append(">"); if(fromTag != null) bldr.append("<").append(ELEMENT_FROMTAG).append(">").append( fromTag).append("</").append( ELEMENT_FROMTAG).append(">"); if(toTag != null) bldr.append("<").append(ELEMENT_TOTAG).append(">").append( toTag).append("</").append( ELEMENT_TOTAG).append(">"); for(PacketExtension ext : getChildExtensions()) { bldr.append(ext.toXML()); } bldr.append("</").append(getElementName()).append(">"); return bldr.toString(); } }
apache-2.0
wangcy6/storm_app
frame/storm-master/external/storm-cassandra/src/test/java/org/apache/storm/cassandra/trident/MapStateTest.java
8707
/** * 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.storm.cassandra.trident; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.DataType; import com.datastax.driver.core.Session; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.querybuilder.Truncate; import com.datastax.driver.core.schemabuilder.Create; import com.datastax.driver.core.schemabuilder.SchemaBuilder; import org.apache.cassandra.locator.SimpleStrategy; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import org.apache.storm.LocalDRPC; import org.apache.storm.cassandra.client.CassandraConf; import org.apache.storm.cassandra.testtools.EmbeddedCassandraResource; import org.apache.storm.cassandra.trident.state.MapStateFactoryBuilder; import org.apache.storm.trident.TridentState; import org.apache.storm.trident.TridentTopology; import org.apache.storm.trident.operation.builtin.Count; import org.apache.storm.trident.operation.builtin.FilterNull; import org.apache.storm.trident.operation.builtin.MapGet; import org.apache.storm.trident.operation.builtin.Sum; import org.apache.storm.trident.state.StateFactory; import org.apache.storm.trident.testing.FixedBatchSpout; import org.apache.storm.trident.testing.Split; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Values; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.*; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class MapStateTest { @ClassRule public static final EmbeddedCassandraResource cassandra = new EmbeddedCassandraResource(); private static Logger logger = LoggerFactory.getLogger(MapStateTest.class); private static Cluster cluster; private Session session; @Test public void nonTransactionalStateTest() throws Exception { StateFactory factory = MapStateFactoryBuilder.nontransactional(getCassandraConfig()) .withTable("words_ks", "words_table") .withKeys("word") .withJSONBinaryState("state") .build(); wordsTest(factory); } @Test public void transactionalStateTest() throws Exception { Map<String, Object> config = new HashMap(); StateFactory factory = MapStateFactoryBuilder.transactional(getCassandraConfig()) .withTable("words_ks", "words_table") .withKeys("word") .withJSONBinaryState("state") .build(); wordsTest(factory); } @Test public void opaqueStateTest() throws Exception { Map<String, Object> config = new HashMap(); StateFactory factory = MapStateFactoryBuilder.opaque(getCassandraConfig()) .withTable("words_ks", "words_table") .withKeys("word") .withJSONBinaryState("state") .build(); wordsTest(factory); } public void wordsTest(StateFactory factory) throws Exception { FixedBatchSpout spout = new FixedBatchSpout( new Fields("sentence"), 3, new Values("the cow jumped over the moon"), new Values("the man went to the store and bought some candy"), new Values("four score and seven years ago"), new Values("how many apples can you eat")); spout.setCycle(false); TridentTopology topology = new TridentTopology(); TridentState wordCounts = topology.newStream("spout1", spout) .each(new Fields("sentence"), new Split(), new Fields("word")) .groupBy(new Fields("word")) .persistentAggregate(factory, new Count(), new Fields("state")) .parallelismHint(1); LocalDRPC client = new LocalDRPC(); topology.newDRPCStream("words", client) .each(new Fields("args"), new Split(), new Fields("word")) .groupBy(new Fields("word")) .stateQuery(wordCounts, new Fields("word"), new MapGet(), new Fields("state")) .each(new Fields("state"), new FilterNull()) .aggregate(new Fields("state"), new Sum(), new Fields("sum")); LocalCluster cluster = new LocalCluster(); logger.info("Submitting topology."); cluster.submitTopology("test", new HashMap(), topology.build()); logger.info("Waiting for something to happen."); int count; do { Thread.sleep(2000); count = session.execute(QueryBuilder.select().all().from("words_ks", "words_table")) .getAvailableWithoutFetching(); logger.info("Found {} records", count); } while (count < 24); logger.info("Starting queries."); assertEquals("[[5]]", client.execute("words", "cat dog the man")); // 5 assertEquals("[[0]]", client.execute("words", "cat")); // 0 assertEquals("[[0]]", client.execute("words", "dog")); // 0 assertEquals("[[4]]", client.execute("words", "the")); // 4 assertEquals("[[1]]", client.execute("words", "man")); // 1 cluster.shutdown(); } @Before public void setUp() throws Exception { Cluster.Builder clusterBuilder = Cluster.builder(); // Add cassandra cluster contact points clusterBuilder.addContactPoint(cassandra.getHost()); clusterBuilder.withPort(cassandra.getNativeTransportPort()); // Build cluster and connect cluster = clusterBuilder.build(); session = cluster.connect(); createKeyspace("words_ks"); createTable("words_ks", "words_table", column("word", DataType.varchar()), column("state", DataType.blob())); } @After public void tearDown() { truncateTable("words_ks", "words_table"); session.close(); } protected void createKeyspace(String keyspace) throws Exception { // Create keyspace not supported in the current datastax driver String createKeyspace = "CREATE KEYSPACE IF NOT EXISTS " + keyspace + " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };"; logger.info(createKeyspace); if (!session.execute(createKeyspace) .wasApplied()) { throw new Exception("Did not create keyspace " + keyspace); } } protected Config getCassandraConfig() { Config cassandraConf = new Config(); cassandraConf.put(CassandraConf.CASSANDRA_NODES, cassandra.getHost()); cassandraConf.put(CassandraConf.CASSANDRA_PORT, cassandra.getNativeTransportPort()); cassandraConf.put(CassandraConf.CASSANDRA_KEYSPACE, "words_ks"); return cassandraConf; } protected void truncateTable(String keyspace, String table) { Truncate truncate = QueryBuilder.truncate(keyspace, table); session.execute(truncate); } protected void createTable(String keyspace, String table, Column key, Column... fields) { Map<String, Object> replication = new HashMap<>(); replication.put("class", SimpleStrategy.class.getSimpleName()); replication.put("replication_factor", 1); Create createTable = SchemaBuilder.createTable(keyspace, table) .ifNotExists() .addPartitionKey(key.name, key.type); for (Column field : fields) { createTable.addColumn(field.name, field.type); } logger.info(createTable.toString()); session.execute(createTable); } protected static Column column(String name, DataType type) { Column column = new Column(); column.name = name; column.type = type; return column; } protected static class Column { public String name; public DataType type; } }
apache-2.0
skyao/netty
transport/src/main/java/io/netty/channel/MultithreadEventLoopGroup.java
3680
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.channel; import io.netty.util.NettyRuntime; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.EventExecutorChooserFactory; import io.netty.util.concurrent.MultithreadEventExecutorGroup; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; /** * Abstract base class for {@link EventLoopGroup} implementations that handles their tasks with multiple threads at * the same time. */ public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup { private static final InternalLogger logger = InternalLoggerFactory.getInstance(MultithreadEventLoopGroup.class); private static final int DEFAULT_EVENT_LOOP_THREADS; static { DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt( "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2)); if (logger.isDebugEnabled()) { logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS); } } /** * @see MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, Executor, Object...) */ protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) { super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args); } /** * @see MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, ThreadFactory, Object...) */ protected MultithreadEventLoopGroup(int nThreads, ThreadFactory threadFactory, Object... args) { super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, threadFactory, args); } /** * @see MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, Executor, * EventExecutorChooserFactory, Object...) */ protected MultithreadEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory, Object... args) { super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, chooserFactory, args); } @Override protected ThreadFactory newDefaultThreadFactory() { return new DefaultThreadFactory(getClass(), Thread.MAX_PRIORITY); } @Override public EventLoop next() { return (EventLoop) super.next(); } @Override protected abstract EventLoop newChild(Executor executor, Object... args) throws Exception; @Override public ChannelFuture register(Channel channel) { return next().register(channel); } @Override public ChannelFuture register(ChannelPromise promise) { return next().register(promise); } @Deprecated @Override public ChannelFuture register(Channel channel, ChannelPromise promise) { return next().register(channel, promise); } }
apache-2.0
Bizyroth/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocol/BlockStoragePolicy.java
9281
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.protocol; import java.util.Arrays; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import com.google.common.annotations.VisibleForTesting; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.fs.StorageType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A block storage policy describes how to select the storage types * for the replicas of a block. */ @InterfaceAudience.Private public class BlockStoragePolicy { public static final Logger LOG = LoggerFactory.getLogger(BlockStoragePolicy .class); /** A 4-bit policy ID */ private final byte id; /** Policy name */ private final String name; /** The storage types to store the replicas of a new block. */ private final StorageType[] storageTypes; /** The fallback storage type for block creation. */ private final StorageType[] creationFallbacks; /** The fallback storage type for replication. */ private final StorageType[] replicationFallbacks; /** * Whether the policy is inherited during file creation. * If set then the policy cannot be changed after file creation. */ private boolean copyOnCreateFile; @VisibleForTesting public BlockStoragePolicy(byte id, String name, StorageType[] storageTypes, StorageType[] creationFallbacks, StorageType[] replicationFallbacks) { this(id, name, storageTypes, creationFallbacks, replicationFallbacks, false); } @VisibleForTesting public BlockStoragePolicy(byte id, String name, StorageType[] storageTypes, StorageType[] creationFallbacks, StorageType[] replicationFallbacks, boolean copyOnCreateFile) { this.id = id; this.name = name; this.storageTypes = storageTypes; this.creationFallbacks = creationFallbacks; this.replicationFallbacks = replicationFallbacks; this.copyOnCreateFile = copyOnCreateFile; } /** * @return a list of {@link StorageType}s for storing the replicas of a block. */ public List<StorageType> chooseStorageTypes(final short replication) { final List<StorageType> types = new LinkedList<StorageType>(); int i = 0, j = 0; // Do not return transient storage types. We will not have accurate // usage information for transient types. for (;i < replication && j < storageTypes.length; ++j) { if (!storageTypes[j].isTransient()) { types.add(storageTypes[j]); ++i; } } final StorageType last = storageTypes[storageTypes.length - 1]; if (!last.isTransient()) { for (; i < replication; i++) { types.add(last); } } return types; } /** * Choose the storage types for storing the remaining replicas, given the * replication number and the storage types of the chosen replicas. * * @param replication the replication number. * @param chosen the storage types of the chosen replicas. * @return a list of {@link StorageType}s for storing the replicas of a block. */ public List<StorageType> chooseStorageTypes(final short replication, final Iterable<StorageType> chosen) { return chooseStorageTypes(replication, chosen, null); } private List<StorageType> chooseStorageTypes(final short replication, final Iterable<StorageType> chosen, final List<StorageType> excess) { final List<StorageType> types = chooseStorageTypes(replication); diff(types, chosen, excess); return types; } /** * Choose the storage types for storing the remaining replicas, given the * replication number, the storage types of the chosen replicas and * the unavailable storage types. It uses fallback storage in case that * the desired storage type is unavailable. * * @param replication the replication number. * @param chosen the storage types of the chosen replicas. * @param unavailables the unavailable storage types. * @param isNewBlock Is it for new block creation? * @return a list of {@link StorageType}s for storing the replicas of a block. */ public List<StorageType> chooseStorageTypes(final short replication, final Iterable<StorageType> chosen, final EnumSet<StorageType> unavailables, final boolean isNewBlock) { final List<StorageType> excess = new LinkedList<StorageType>(); final List<StorageType> storageTypes = chooseStorageTypes( replication, chosen, excess); final int expectedSize = storageTypes.size() - excess.size(); final List<StorageType> removed = new LinkedList<StorageType>(); for(int i = storageTypes.size() - 1; i >= 0; i--) { // replace/remove unavailable storage types. final StorageType t = storageTypes.get(i); if (unavailables.contains(t)) { final StorageType fallback = isNewBlock? getCreationFallback(unavailables) : getReplicationFallback(unavailables); if (fallback == null) { removed.add(storageTypes.remove(i)); } else { storageTypes.set(i, fallback); } } } // remove excess storage types after fallback replacement. diff(storageTypes, excess, null); if (storageTypes.size() < expectedSize) { LOG.warn("Failed to place enough replicas: expected size is " + expectedSize + " but only " + storageTypes.size() + " storage types can be selected " + "(replication=" + replication + ", selected=" + storageTypes + ", unavailable=" + unavailables + ", removed=" + removed + ", policy=" + this + ")"); } return storageTypes; } /** * Compute the difference between two lists t and c so that after the diff * computation we have: t = t - c; * Further, if e is not null, set e = e + c - t; */ private static void diff(List<StorageType> t, Iterable<StorageType> c, List<StorageType> e) { for(StorageType storagetype : c) { final int i = t.indexOf(storagetype); if (i >= 0) { t.remove(i); } else if (e != null) { e.add(storagetype); } } } /** * Choose excess storage types for deletion, given the * replication number and the storage types of the chosen replicas. * * @param replication the replication number. * @param chosen the storage types of the chosen replicas. * @return a list of {@link StorageType}s for deletion. */ public List<StorageType> chooseExcess(final short replication, final Iterable<StorageType> chosen) { final List<StorageType> types = chooseStorageTypes(replication); final List<StorageType> excess = new LinkedList<StorageType>(); diff(types, chosen, excess); return excess; } /** @return the fallback {@link StorageType} for creation. */ public StorageType getCreationFallback(EnumSet<StorageType> unavailables) { return getFallback(unavailables, creationFallbacks); } /** @return the fallback {@link StorageType} for replication. */ public StorageType getReplicationFallback(EnumSet<StorageType> unavailables) { return getFallback(unavailables, replicationFallbacks); } @Override public int hashCode() { return Byte.valueOf(id).hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj == null || !(obj instanceof BlockStoragePolicy)) { return false; } final BlockStoragePolicy that = (BlockStoragePolicy)obj; return this.id == that.id; } @Override public String toString() { return getClass().getSimpleName() + "{" + name + ":" + id + ", storageTypes=" + Arrays.asList(storageTypes) + ", creationFallbacks=" + Arrays.asList(creationFallbacks) + ", replicationFallbacks=" + Arrays.asList(replicationFallbacks) + "}"; } public byte getId() { return id; } public String getName() { return name; } public StorageType[] getStorageTypes() { return this.storageTypes; } public StorageType[] getCreationFallbacks() { return this.creationFallbacks; } public StorageType[] getReplicationFallbacks() { return this.replicationFallbacks; } private static StorageType getFallback(EnumSet<StorageType> unavailables, StorageType[] fallbacks) { for(StorageType fb : fallbacks) { if (!unavailables.contains(fb)) { return fb; } } return null; } public boolean isCopyOnCreateFile() { return copyOnCreateFile; } }
apache-2.0
WouterBanckenACA/aries
sandbox/samples/goat/goat-web/src/main/java/org/apache/aries/samples/goat/web/ServerSideClass.java
9364
/** * 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.aries.samples.goat.web; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import org.apache.aries.samples.goat.info.ComponentInfoImpl; import org.apache.aries.samples.goat.info.RelationshipInfoImpl; import org.apache.aries.samples.goat.api.ComponentInfo; import org.apache.aries.samples.goat.api.ComponentInfoProvider; import org.apache.aries.samples.goat.api.ModelInfoService; import org.apache.aries.samples.goat.api.RelationshipInfo; import org.apache.aries.samples.goat.api.RelationshipInfoProvider; import org.directwebremoting.Browser; import org.directwebremoting.ScriptBuffer; import org.directwebremoting.ScriptSession; import org.directwebremoting.ServerContextFactory; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; public class ServerSideClass { private String modelInfoServiceHint = ""; private ModelInfoService ModelInfoService = null; private Map<ModelInfoService, ComponentInfoProvider.ComponentInfoListener> clisteners = new HashMap<ModelInfoService, ComponentInfoProvider.ComponentInfoListener>(); private Map<ModelInfoService, RelationshipInfoProvider.RelationshipInfoListener> rlisteners = new HashMap<ModelInfoService, RelationshipInfoProvider.RelationshipInfoListener>(); private class ComponentInfoListenerImpl implements ComponentInfoProvider.ComponentInfoListener { String server; public ComponentInfoListenerImpl(String server) { this.server = server; } public void updateComponent(ComponentInfo b) { if (this.server.equals(modelInfoServiceHint)) { // todo: only issue the add for the new bundle, and affected // other bundles. //getInitialComponents(modelInfoServiceHint); //System.out.println("State is: " + b.getComponentProperties().get("State")); addFunctionCall("addComponent", b); } } public void removeComponent(ComponentInfo b) { // todo } } private class RelationshipInfoListenerImpl implements RelationshipInfoProvider.RelationshipInfoListener { String server; public RelationshipInfoListenerImpl(String server) { this.server = server; } public void updateRelationship(RelationshipInfo r) { if (this.server.equals(modelInfoServiceHint)) { addFunctionCall("addRelationship", r); } } public void removeRelationship(RelationshipInfo r) { // todo } } public ServerSideClass() { System.err.println("SSC Built!"); } @SuppressWarnings("unused") private String bundleStateToString(int bundleState) { switch (bundleState) { case Bundle.UNINSTALLED: return "UNINSTALLED"; case Bundle.INSTALLED: return "INSTALLED"; case Bundle.RESOLVED: return "RESOLVED"; case Bundle.STARTING: return "STARTING"; case Bundle.STOPPING: return "STOPPING"; case Bundle.ACTIVE: return "ACTIVE"; default: return "UNKNOWN[" + bundleState + "]"; } } /** * this is invoked by a page onload.. so until it's invoked.. we dont care * about components */ public void getInitialComponents(String dataProvider) { System.err.println("GET INITIAL BUNDLES ASKED TO USE DATAPROVIDER " + dataProvider); if (dataProvider == null) throw new IllegalArgumentException( "Unable to accept 'null' as a dataProvider"); // do we need to update? if (!this.modelInfoServiceHint.equals(dataProvider)) { this.modelInfoServiceHint = dataProvider; if (!(this.ModelInfoService == null)) { // we already had a provider.. we need to shut down the existing // components & relationships in the browsers.. addFunctionCall("forgetAboutEverything"); } ServletContext context = org.directwebremoting.ServerContextFactory .get().getServletContext(); Object o = context.getAttribute("osgi-bundlecontext"); if (o != null) { if (o instanceof BundleContext) { BundleContext b_ctx = (BundleContext) o; System.err.println("Looking up bcip"); try { ServiceReference sr[] = b_ctx.getServiceReferences( ModelInfoService.class.getName(), "(displayName=" + this.modelInfoServiceHint + ")"); if (sr != null) { System.err.println("Getting bcip"); this.ModelInfoService = (ModelInfoService) b_ctx .getService(sr[0]); System.err.println("Got bcip " + this.ModelInfoService); } else { System.err.println("UNABLE TO FIND BCIP!!"); System.err.println("UNABLE TO FIND BCIP!!"); System.err.println("UNABLE TO FIND BCIP!!"); } } catch (InvalidSyntaxException ise) { } if (this.ModelInfoService != null) { if (!rlisteners.containsKey(this.ModelInfoService)) { RelationshipInfoProvider.RelationshipInfoListener rl = new RelationshipInfoListenerImpl( this.modelInfoServiceHint); rlisteners.put(this.ModelInfoService, rl); this.ModelInfoService.getRelationshipInfoProvider() .registerRelationshipInfoListener(rl); } if (!clisteners.containsKey(this.ModelInfoService)) { ComponentInfoProvider.ComponentInfoListener cl = new ComponentInfoListenerImpl( this.modelInfoServiceHint); clisteners.put(this.ModelInfoService, cl); this.ModelInfoService.getComponentInfoProvider() .registerComponentInfoListener(cl); } } } } } Collection<ComponentInfo> bis = this.ModelInfoService .getComponentInfoProvider().getComponents(); System.err.println("Got " + (bis == null ? "null" : bis.size()) + " components back from the provider "); if (bis != null) { for (ComponentInfo b : bis) { System.err.println("Adding Component .. " + b.getId()); addFunctionCall("addComponent", b); } } Collection<RelationshipInfo> ris = this.ModelInfoService .getRelationshipInfoProvider().getRelationships(); System.err.println("Got " + (ris == null ? "null" : ris.size()) + " relationships back from the provider "); if (ris != null) { for (RelationshipInfo r : ris) { System.err.println("Adding relationship type " + r.getType() + " called " + r.getName() + " from " + r.getProvidedBy().getId()); addFunctionCall("addRelationship", r); } } } private void addFunctionCall(String name, Object... params) { final ScriptBuffer script = new ScriptBuffer(); script.appendScript(name).appendScript("("); for (int i = 0; i < params.length; i++) { if (i != 0) script.appendScript(","); script.appendData(params[i]); } script.appendScript(");"); Browser.withAllSessions(new Runnable() { public void run() { for (ScriptSession s : Browser.getTargetSessions()) { s.addScript(script); } } }); } public String[] getProviders() { System.err.println("Getting providers..."); ArrayList<String> result = new ArrayList<String>(); ServletContext context = ServerContextFactory.get().getServletContext(); Object o = context.getAttribute("osgi-bundlecontext"); if (o != null) { if (o instanceof BundleContext) { BundleContext b_ctx = (BundleContext) o; try { System.err.println("Getting providers [2]..."); ServiceReference[] srs = b_ctx.getServiceReferences( ModelInfoService.class.getName(), null); System.err.println("Got.. " + srs); if (srs == null || srs.length == 0) { System.err.println("NO DATA PROVIDERS"); throw new RuntimeException( "Unable to find any data providers"); } System.err.println("Processing srs as loop."); for (ServiceReference sr : srs) { System.err.println("Processing srs entry..."); String name = (String.valueOf(sr .getProperty("displayName"))); result.add(name); } System.err.println("Processed srs as loop."); } catch (InvalidSyntaxException e) { // wont happen, the exception relates to the filter, (2nd // arg above), which is constant null. } } } System.err.println("Returning " + result.size()); String[] arr = new String[result.size()]; arr = result.toArray(arr); for (String x : arr) { System.err.println(" - " + x); } return arr; } }
apache-2.0
cchang738/parquet-mr
parquet-encoding/src/test/java/org/apache/parquet/column/values/bitpacking/TestByteBasedBitPackingEncoder.java
1393
/* * 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.parquet.column.values.bitpacking; import org.junit.Test; public class TestByteBasedBitPackingEncoder { @Test public void testSlabBoundary() { for (int i = 0; i < 32; i++) { final ByteBasedBitPackingEncoder encoder = new ByteBasedBitPackingEncoder(i, Packer.BIG_ENDIAN); // make sure to write more than a slab for (int j = 0; j < 64 * 1024 * 32 + 10; j++) { try { encoder.writeInt(j); } catch (Exception e) { throw new RuntimeException(i + ": error writing " + j, e); } } } } }
apache-2.0
Psantium/walkaround
src/com/google/walkaround/slob/shared/SlobModel.java
2485
/* * Copyright 2011 Google 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.google.walkaround.slob.shared; import javax.annotation.Nullable; import java.util.List; /** * Represents a domain of shared live objects (slobs). * * @author danilatos@google.com (Daniel Danilatos) */ // TODO(danilatos): Have deserialize/serialize operation methods, // and pass reified ops into the other methods like apply() & transform. public interface SlobModel { /** * Read access to an object in this domain. */ interface ReadableSlob { /** * Returns a serialized form of the object. Can be null if the object has no * history. */ @Nullable String snapshot(); } /** * Read/write access to an object in this domain. */ interface Slob extends ReadableSlob { /** * Applies a delta to the object. * * @throws ChangeRejected if the change is invalid. If * {@link ChangeRejected} is thrown, the object MUST remain in the * previous state, ready for application of a valid operation. */ void apply(ChangeData<String> payload) throws ChangeRejected; } /** * Creates an object belonging to this domain. * * @param snapshot initial snapshot from which to deserialize. null if this is a * completely new object. */ Slob create(@Nullable String snapshot) throws InvalidSnapshot; /** * Transforms operations on objects in this domain. * * @return the transformed client payloads (they will need to be re-wrapped). * * @throws ChangeRejected if the client ops were invalid or not compatible * with eachother. The server ops are guaranteed to have passed * through the apply() method successfully and therefore are known * to be valid. */ List<String> transform(List<ChangeData<String>> clientOps, List<ChangeData<String>> serverOps) throws ChangeRejected; }
apache-2.0
InShadow/jmonkeyengine
jme3-core/src/main/java/com/jme3/scene/shape/Cylinder.java
16564
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // $Id: Cylinder.java 4131 2009-03-19 20:15:28Z blaine.dev $ package com.jme3.scene.shape; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.math.FastMath; import com.jme3.math.Vector3f; import com.jme3.scene.Mesh; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.mesh.IndexBuffer; import com.jme3.util.BufferUtils; import static com.jme3.util.BufferUtils.*; import java.io.IOException; import java.nio.FloatBuffer; /** * A simple cylinder, defined by it's height and radius. * (Ported to jME3) * * @author Mark Powell * @version $Revision: 4131 $, $Date: 2009-03-19 16:15:28 -0400 (Thu, 19 Mar 2009) $ */ public class Cylinder extends Mesh { private int axisSamples; private int radialSamples; private float radius; private float radius2; private float height; private boolean closed; private boolean inverted; /** * Default constructor for serialization only. Do not use. */ public Cylinder() { } /** * Creates a new Cylinder. By default its center is the origin. Usually, a * higher sample number creates a better looking cylinder, but at the cost * of more vertex information. * * @param axisSamples * Number of triangle samples along the axis. * @param radialSamples * Number of triangle samples along the radial. * @param radius * The radius of the cylinder. * @param height * The cylinder's height. */ public Cylinder(int axisSamples, int radialSamples, float radius, float height) { this(axisSamples, radialSamples, radius, height, false); } /** * Creates a new Cylinder. By default its center is the origin. Usually, a * higher sample number creates a better looking cylinder, but at the cost * of more vertex information. <br> * If the cylinder is closed the texture is split into axisSamples parts: * top most and bottom most part is used for top and bottom of the cylinder, * rest of the texture for the cylinder wall. The middle of the top is * mapped to texture coordinates (0.5, 1), bottom to (0.5, 0). Thus you need * a suited distorted texture. * * @param axisSamples * Number of triangle samples along the axis. * @param radialSamples * Number of triangle samples along the radial. * @param radius * The radius of the cylinder. * @param height * The cylinder's height. * @param closed * true to create a cylinder with top and bottom surface */ public Cylinder(int axisSamples, int radialSamples, float radius, float height, boolean closed) { this(axisSamples, radialSamples, radius, height, closed, false); } /** * Creates a new Cylinder. By default its center is the origin. Usually, a * higher sample number creates a better looking cylinder, but at the cost * of more vertex information. <br> * If the cylinder is closed the texture is split into axisSamples parts: * top most and bottom most part is used for top and bottom of the cylinder, * rest of the texture for the cylinder wall. The middle of the top is * mapped to texture coordinates (0.5, 1), bottom to (0.5, 0). Thus you need * a suited distorted texture. * * @param axisSamples * Number of triangle samples along the axis. * @param radialSamples * Number of triangle samples along the radial. * @param radius * The radius of the cylinder. * @param height * The cylinder's height. * @param closed * true to create a cylinder with top and bottom surface * @param inverted * true to create a cylinder that is meant to be viewed from the * interior. */ public Cylinder(int axisSamples, int radialSamples, float radius, float height, boolean closed, boolean inverted) { this(axisSamples, radialSamples, radius, radius, height, closed, inverted); } public Cylinder(int axisSamples, int radialSamples, float radius, float radius2, float height, boolean closed, boolean inverted) { super(); updateGeometry(axisSamples, radialSamples, radius, radius2, height, closed, inverted); } /** * @return the number of samples along the cylinder axis */ public int getAxisSamples() { return axisSamples; } /** * @return Returns the height. */ public float getHeight() { return height; } /** * @return number of samples around cylinder */ public int getRadialSamples() { return radialSamples; } /** * @return Returns the radius. */ public float getRadius() { return radius; } public float getRadius2() { return radius2; } /** * @return true if end caps are used. */ public boolean isClosed() { return closed; } /** * @return true if normals and uvs are created for interior use */ public boolean isInverted() { return inverted; } /** * Rebuilds the cylinder based on a new set of parameters. * * @param axisSamples the number of samples along the axis. * @param radialSamples the number of samples around the radial. * @param radius the radius of the bottom of the cylinder. * @param radius2 the radius of the top of the cylinder. * @param height the cylinder's height. * @param closed should the cylinder have top and bottom surfaces. * @param inverted is the cylinder is meant to be viewed from the inside. */ public void updateGeometry(int axisSamples, int radialSamples, float radius, float radius2, float height, boolean closed, boolean inverted) { this.axisSamples = axisSamples; this.radialSamples = radialSamples; this.radius = radius; this.radius2 = radius2; this.height = height; this.closed = closed; this.inverted = inverted; // VertexBuffer pvb = getBuffer(Type.Position); // VertexBuffer nvb = getBuffer(Type.Normal); // VertexBuffer tvb = getBuffer(Type.TexCoord); axisSamples += (closed ? 2 : 0); // Vertices int vertCount = axisSamples * (radialSamples + 1) + (closed ? 2 : 0); setBuffer(Type.Position, 3, createVector3Buffer(getFloatBuffer(Type.Position), vertCount)); // Normals setBuffer(Type.Normal, 3, createVector3Buffer(getFloatBuffer(Type.Normal), vertCount)); // Texture co-ordinates setBuffer(Type.TexCoord, 2, createVector2Buffer(vertCount)); int triCount = ((closed ? 2 : 0) + 2 * (axisSamples - 1)) * radialSamples; setBuffer(Type.Index, 3, createShortBuffer(getShortBuffer(Type.Index), 3 * triCount)); // generate geometry float inverseRadial = 1.0f / radialSamples; float inverseAxisLess = 1.0f / (closed ? axisSamples - 3 : axisSamples - 1); float inverseAxisLessTexture = 1.0f / (axisSamples - 1); float halfHeight = 0.5f * height; // Generate points on the unit circle to be used in computing the mesh // points on a cylinder slice. float[] sin = new float[radialSamples + 1]; float[] cos = new float[radialSamples + 1]; for (int radialCount = 0; radialCount < radialSamples; radialCount++) { float angle = FastMath.TWO_PI * inverseRadial * radialCount; cos[radialCount] = FastMath.cos(angle); sin[radialCount] = FastMath.sin(angle); } sin[radialSamples] = sin[0]; cos[radialSamples] = cos[0]; // calculate normals Vector3f[] vNormals = null; Vector3f vNormal = Vector3f.UNIT_Z; if ((height != 0.0f) && (radius != radius2)) { vNormals = new Vector3f[radialSamples]; Vector3f vHeight = Vector3f.UNIT_Z.mult(height); Vector3f vRadial = new Vector3f(); for (int radialCount = 0; radialCount < radialSamples; radialCount++) { vRadial.set(cos[radialCount], sin[radialCount], 0.0f); Vector3f vRadius = vRadial.mult(radius); Vector3f vRadius2 = vRadial.mult(radius2); Vector3f vMantle = vHeight.subtract(vRadius2.subtract(vRadius)); Vector3f vTangent = vRadial.cross(Vector3f.UNIT_Z); vNormals[radialCount] = vMantle.cross(vTangent).normalize(); } } FloatBuffer nb = getFloatBuffer(Type.Normal); FloatBuffer pb = getFloatBuffer(Type.Position); FloatBuffer tb = getFloatBuffer(Type.TexCoord); // generate the cylinder itself Vector3f tempNormal = new Vector3f(); for (int axisCount = 0, i = 0; axisCount < axisSamples; axisCount++, i++) { float axisFraction; float axisFractionTexture; int topBottom = 0; if (!closed) { axisFraction = axisCount * inverseAxisLess; // in [0,1] axisFractionTexture = axisFraction; } else { if (axisCount == 0) { topBottom = -1; // bottom axisFraction = 0; axisFractionTexture = inverseAxisLessTexture; } else if (axisCount == axisSamples - 1) { topBottom = 1; // top axisFraction = 1; axisFractionTexture = 1 - inverseAxisLessTexture; } else { axisFraction = (axisCount - 1) * inverseAxisLess; axisFractionTexture = axisCount * inverseAxisLessTexture; } } // compute center of slice float z = -halfHeight + height * axisFraction; Vector3f sliceCenter = new Vector3f(0, 0, z); // compute slice vertices with duplication at end point int save = i; for (int radialCount = 0; radialCount < radialSamples; radialCount++, i++) { float radialFraction = radialCount * inverseRadial; // in [0,1) tempNormal.set(cos[radialCount], sin[radialCount], 0.0f); if (vNormals != null) { vNormal = vNormals[radialCount]; } else if (radius == radius2) { vNormal = tempNormal; } if (topBottom == 0) { if (!inverted) nb.put(vNormal.x).put(vNormal.y).put(vNormal.z); else nb.put(-vNormal.x).put(-vNormal.y).put(-vNormal.z); } else { nb.put(0).put(0).put(topBottom * (inverted ? -1 : 1)); } tempNormal.multLocal((radius - radius2) * axisFraction + radius2) .addLocal(sliceCenter); pb.put(tempNormal.x).put(tempNormal.y).put(tempNormal.z); tb.put((inverted ? 1 - radialFraction : radialFraction)) .put(axisFractionTexture); } BufferUtils.copyInternalVector3(pb, save, i); BufferUtils.copyInternalVector3(nb, save, i); tb.put((inverted ? 0.0f : 1.0f)) .put(axisFractionTexture); } if (closed) { pb.put(0).put(0).put(-halfHeight); // bottom center nb.put(0).put(0).put(-1 * (inverted ? -1 : 1)); tb.put(0.5f).put(0); pb.put(0).put(0).put(halfHeight); // top center nb.put(0).put(0).put(1 * (inverted ? -1 : 1)); tb.put(0.5f).put(1); } IndexBuffer ib = getIndexBuffer(); int index = 0; // Connectivity for (int axisCount = 0, axisStart = 0; axisCount < axisSamples - 1; axisCount++) { int i0 = axisStart; int i1 = i0 + 1; axisStart += radialSamples + 1; int i2 = axisStart; int i3 = i2 + 1; for (int i = 0; i < radialSamples; i++) { if (closed && axisCount == 0) { if (!inverted) { ib.put(index++, i0++); ib.put(index++, vertCount - 2); ib.put(index++, i1++); } else { ib.put(index++, i0++); ib.put(index++, i1++); ib.put(index++, vertCount - 2); } } else if (closed && axisCount == axisSamples - 2) { ib.put(index++, i2++); ib.put(index++, inverted ? vertCount - 1 : i3++); ib.put(index++, inverted ? i3++ : vertCount - 1); } else { ib.put(index++, i0++); ib.put(index++, inverted ? i2 : i1); ib.put(index++, inverted ? i1 : i2); ib.put(index++, i1++); ib.put(index++, inverted ? i2++ : i3++); ib.put(index++, inverted ? i3++ : i2++); } } } updateBound(); setStatic(); } @Override public void read(JmeImporter e) throws IOException { super.read(e); InputCapsule capsule = e.getCapsule(this); axisSamples = capsule.readInt("axisSamples", 0); radialSamples = capsule.readInt("radialSamples", 0); radius = capsule.readFloat("radius", 0); radius2 = capsule.readFloat("radius2", 0); height = capsule.readFloat("height", 0); closed = capsule.readBoolean("closed", false); inverted = capsule.readBoolean("inverted", false); } @Override public void write(JmeExporter e) throws IOException { super.write(e); OutputCapsule capsule = e.getCapsule(this); capsule.write(axisSamples, "axisSamples", 0); capsule.write(radialSamples, "radialSamples", 0); capsule.write(radius, "radius", 0); capsule.write(radius2, "radius2", 0); capsule.write(height, "height", 0); capsule.write(closed, "closed", false); capsule.write(inverted, "inverted", false); } }
bsd-3-clause
tbepler/seq-svm
src/org/apache/commons/math3/linear/BlockRealMatrix.java
67656
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.linear; import java.io.Serializable; import java.util.Arrays; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils; /** * Cache-friendly implementation of RealMatrix using a flat arrays to store * square blocks of the matrix. * <p> * This implementation is specially designed to be cache-friendly. Square blocks are * stored as small arrays and allow efficient traversal of data both in row major direction * and columns major direction, one block at a time. This greatly increases performances * for algorithms that use crossed directions loops like multiplication or transposition. * </p> * <p> * The size of square blocks is a static parameter. It may be tuned according to the cache * size of the target computer processor. As a rule of thumbs, it should be the largest * value that allows three blocks to be simultaneously cached (this is necessary for example * for matrix multiplication). The default value is to use 52x52 blocks which is well suited * for processors with 64k L1 cache (one block holds 2704 values or 21632 bytes). This value * could be lowered to 36x36 for processors with 32k L1 cache. * </p> * <p> * The regular blocks represent {@link #BLOCK_SIZE} x {@link #BLOCK_SIZE} squares. Blocks * at right hand side and bottom side which may be smaller to fit matrix dimensions. The square * blocks are flattened in row major order in single dimension arrays which are therefore * {@link #BLOCK_SIZE}<sup>2</sup> elements long for regular blocks. The blocks are themselves * organized in row major order. * </p> * <p> * As an example, for a block size of 52x52, a 100x60 matrix would be stored in 4 blocks. * Block 0 would be a double[2704] array holding the upper left 52x52 square, block 1 would be * a double[416] array holding the upper right 52x8 rectangle, block 2 would be a double[2496] * array holding the lower left 48x52 rectangle and block 3 would be a double[384] array * holding the lower right 48x8 rectangle. * </p> * <p> * The layout complexity overhead versus simple mapping of matrices to java * arrays is negligible for small matrices (about 1%). The gain from cache efficiency leads * to up to 3-fold improvements for matrices of moderate to large size. * </p> * @version $Id: BlockRealMatrix.java 1416643 2012-12-03 19:37:14Z tn $ * @since 2.0 */ public class BlockRealMatrix extends AbstractRealMatrix implements Serializable { /** Block size. */ public static final int BLOCK_SIZE = 52; /** Serializable version identifier */ private static final long serialVersionUID = 4991895511313664478L; /** Blocks of matrix entries. */ private final double blocks[][]; /** Number of rows of the matrix. */ private final int rows; /** Number of columns of the matrix. */ private final int columns; /** Number of block rows of the matrix. */ private final int blockRows; /** Number of block columns of the matrix. */ private final int blockColumns; /** * Create a new matrix with the supplied row and column dimensions. * * @param rows the number of rows in the new matrix * @param columns the number of columns in the new matrix * @throws NotStrictlyPositiveException if row or column dimension is not * positive. */ public BlockRealMatrix(final int rows, final int columns) throws NotStrictlyPositiveException { super(rows, columns); this.rows = rows; this.columns = columns; // number of blocks blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; // allocate storage blocks, taking care of smaller ones at right and bottom blocks = createBlocksLayout(rows, columns); } /** * Create a new dense matrix copying entries from raw layout data. * <p>The input array <em>must</em> already be in raw layout.</p> * <p>Calling this constructor is equivalent to call: * <pre>matrix = new BlockRealMatrix(rawData.length, rawData[0].length, * toBlocksLayout(rawData), false);</pre> * </p> * * @param rawData data for new matrix, in raw layout * @throws DimensionMismatchException if the shape of {@code blockData} is * inconsistent with block layout. * @throws NotStrictlyPositiveException if row or column dimension is not * positive. * @see #BlockRealMatrix(int, int, double[][], boolean) */ public BlockRealMatrix(final double[][] rawData) throws DimensionMismatchException, NotStrictlyPositiveException { this(rawData.length, rawData[0].length, toBlocksLayout(rawData), false); } /** * Create a new dense matrix copying entries from block layout data. * <p>The input array <em>must</em> already be in blocks layout.</p> * * @param rows Number of rows in the new matrix. * @param columns Number of columns in the new matrix. * @param blockData data for new matrix * @param copyArray Whether the input array will be copied or referenced. * @throws DimensionMismatchException if the shape of {@code blockData} is * inconsistent with block layout. * @throws NotStrictlyPositiveException if row or column dimension is not * positive. * @see #createBlocksLayout(int, int) * @see #toBlocksLayout(double[][]) * @see #BlockRealMatrix(double[][]) */ public BlockRealMatrix(final int rows, final int columns, final double[][] blockData, final boolean copyArray) throws DimensionMismatchException, NotStrictlyPositiveException { super(rows, columns); this.rows = rows; this.columns = columns; // number of blocks blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; if (copyArray) { // allocate storage blocks, taking care of smaller ones at right and bottom blocks = new double[blockRows * blockColumns][]; } else { // reference existing array blocks = blockData; } int index = 0; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int iHeight = blockHeight(iBlock); for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++index) { if (blockData[index].length != iHeight * blockWidth(jBlock)) { throw new DimensionMismatchException(blockData[index].length, iHeight * blockWidth(jBlock)); } if (copyArray) { blocks[index] = blockData[index].clone(); } } } } /** * Convert a data array from raw layout to blocks layout. * <p> * Raw layout is the straightforward layout where element at row i and * column j is in array element <code>rawData[i][j]</code>. Blocks layout * is the layout used in {@link BlockRealMatrix} instances, where the matrix * is split in square blocks (except at right and bottom side where blocks may * be rectangular to fit matrix size) and each block is stored in a flattened * one-dimensional array. * </p> * <p> * This method creates an array in blocks layout from an input array in raw layout. * It can be used to provide the array argument of the {@link * #BlockRealMatrix(int, int, double[][], boolean)} constructor. * </p> * @param rawData Data array in raw layout. * @return a new data array containing the same entries but in blocks layout. * @throws DimensionMismatchException if {@code rawData} is not rectangular. * @see #createBlocksLayout(int, int) * @see #BlockRealMatrix(int, int, double[][], boolean) */ public static double[][] toBlocksLayout(final double[][] rawData) throws DimensionMismatchException { final int rows = rawData.length; final int columns = rawData[0].length; final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; // safety checks for (int i = 0; i < rawData.length; ++i) { final int length = rawData[i].length; if (length != columns) { throw new DimensionMismatchException(columns, length); } } // convert array final double[][] blocks = new double[blockRows * blockColumns][]; int blockIndex = 0; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); final int iHeight = pEnd - pStart; for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); final int jWidth = qEnd - qStart; // allocate new block final double[] block = new double[iHeight * jWidth]; blocks[blockIndex] = block; // copy data int index = 0; for (int p = pStart; p < pEnd; ++p) { System.arraycopy(rawData[p], qStart, block, index, jWidth); index += jWidth; } ++blockIndex; } } return blocks; } /** * Create a data array in blocks layout. * <p> * This method can be used to create the array argument of the {@link * #BlockRealMatrix(int, int, double[][], boolean)} constructor. * </p> * @param rows Number of rows in the new matrix. * @param columns Number of columns in the new matrix. * @return a new data array in blocks layout. * @see #toBlocksLayout(double[][]) * @see #BlockRealMatrix(int, int, double[][], boolean) */ public static double[][] createBlocksLayout(final int rows, final int columns) { final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE; final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE; final double[][] blocks = new double[blockRows * blockColumns][]; int blockIndex = 0; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); final int iHeight = pEnd - pStart; for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); final int jWidth = qEnd - qStart; blocks[blockIndex] = new double[iHeight * jWidth]; ++blockIndex; } } return blocks; } /** {@inheritDoc} */ @Override public BlockRealMatrix createMatrix(final int rowDimension, final int columnDimension) throws NotStrictlyPositiveException { return new BlockRealMatrix(rowDimension, columnDimension); } /** {@inheritDoc} */ @Override public BlockRealMatrix copy() { // create an empty matrix BlockRealMatrix copied = new BlockRealMatrix(rows, columns); // copy the blocks for (int i = 0; i < blocks.length; ++i) { System.arraycopy(blocks[i], 0, copied.blocks[i], 0, blocks[i].length); } return copied; } /** {@inheritDoc} */ @Override public BlockRealMatrix add(final RealMatrix m) throws MatrixDimensionMismatchException { try { return add((BlockRealMatrix) m); } catch (ClassCastException cce) { // safety check MatrixUtils.checkAdditionCompatible(this, m); final BlockRealMatrix out = new BlockRealMatrix(rows, columns); // perform addition block-wise, to ensure good cache behavior int blockIndex = 0; for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { // perform addition on the current block final double[] outBlock = out.blocks[blockIndex]; final double[] tBlock = blocks[blockIndex]; final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); int k = 0; for (int p = pStart; p < pEnd; ++p) { for (int q = qStart; q < qEnd; ++q) { outBlock[k] = tBlock[k] + m.getEntry(p, q); ++k; } } // go to next block ++blockIndex; } } return out; } } /** * Compute the sum of this matrix and {@code m}. * * @param m Matrix to be added. * @return {@code this} + m. * @throws MatrixDimensionMismatchException if {@code m} is not the same * size as this matrix. */ public BlockRealMatrix add(final BlockRealMatrix m) throws MatrixDimensionMismatchException { // safety check MatrixUtils.checkAdditionCompatible(this, m); final BlockRealMatrix out = new BlockRealMatrix(rows, columns); // perform addition block-wise, to ensure good cache behavior for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { final double[] outBlock = out.blocks[blockIndex]; final double[] tBlock = blocks[blockIndex]; final double[] mBlock = m.blocks[blockIndex]; for (int k = 0; k < outBlock.length; ++k) { outBlock[k] = tBlock[k] + mBlock[k]; } } return out; } /** {@inheritDoc} */ @Override public BlockRealMatrix subtract(final RealMatrix m) throws MatrixDimensionMismatchException { try { return subtract((BlockRealMatrix) m); } catch (ClassCastException cce) { // safety check MatrixUtils.checkSubtractionCompatible(this, m); final BlockRealMatrix out = new BlockRealMatrix(rows, columns); // perform subtraction block-wise, to ensure good cache behavior int blockIndex = 0; for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { // perform subtraction on the current block final double[] outBlock = out.blocks[blockIndex]; final double[] tBlock = blocks[blockIndex]; final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); int k = 0; for (int p = pStart; p < pEnd; ++p) { for (int q = qStart; q < qEnd; ++q) { outBlock[k] = tBlock[k] - m.getEntry(p, q); ++k; } } // go to next block ++blockIndex; } } return out; } } /** * Subtract {@code m} from this matrix. * * @param m Matrix to be subtracted. * @return {@code this} - m. * @throws MatrixDimensionMismatchException if {@code m} is not the * same size as this matrix. */ public BlockRealMatrix subtract(final BlockRealMatrix m) throws MatrixDimensionMismatchException { // safety check MatrixUtils.checkSubtractionCompatible(this, m); final BlockRealMatrix out = new BlockRealMatrix(rows, columns); // perform subtraction block-wise, to ensure good cache behavior for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { final double[] outBlock = out.blocks[blockIndex]; final double[] tBlock = blocks[blockIndex]; final double[] mBlock = m.blocks[blockIndex]; for (int k = 0; k < outBlock.length; ++k) { outBlock[k] = tBlock[k] - mBlock[k]; } } return out; } /** {@inheritDoc} */ @Override public BlockRealMatrix scalarAdd(final double d) { final BlockRealMatrix out = new BlockRealMatrix(rows, columns); // perform subtraction block-wise, to ensure good cache behavior for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { final double[] outBlock = out.blocks[blockIndex]; final double[] tBlock = blocks[blockIndex]; for (int k = 0; k < outBlock.length; ++k) { outBlock[k] = tBlock[k] + d; } } return out; } /** {@inheritDoc} */ @Override public RealMatrix scalarMultiply(final double d) { final BlockRealMatrix out = new BlockRealMatrix(rows, columns); // perform subtraction block-wise, to ensure good cache behavior for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) { final double[] outBlock = out.blocks[blockIndex]; final double[] tBlock = blocks[blockIndex]; for (int k = 0; k < outBlock.length; ++k) { outBlock[k] = tBlock[k] * d; } } return out; } /** {@inheritDoc} */ @Override public BlockRealMatrix multiply(final RealMatrix m) throws DimensionMismatchException { try { return multiply((BlockRealMatrix) m); } catch (ClassCastException cce) { // safety check MatrixUtils.checkMultiplicationCompatible(this, m); final BlockRealMatrix out = new BlockRealMatrix(rows, m.getColumnDimension()); // perform multiplication block-wise, to ensure good cache behavior int blockIndex = 0; for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, m.getColumnDimension()); // select current block final double[] outBlock = out.blocks[blockIndex]; // perform multiplication on current block for (int kBlock = 0; kBlock < blockColumns; ++kBlock) { final int kWidth = blockWidth(kBlock); final double[] tBlock = blocks[iBlock * blockColumns + kBlock]; final int rStart = kBlock * BLOCK_SIZE; int k = 0; for (int p = pStart; p < pEnd; ++p) { final int lStart = (p - pStart) * kWidth; final int lEnd = lStart + kWidth; for (int q = qStart; q < qEnd; ++q) { double sum = 0; int r = rStart; for (int l = lStart; l < lEnd; ++l) { sum += tBlock[l] * m.getEntry(r, q); ++r; } outBlock[k] += sum; ++k; } } } // go to next block ++blockIndex; } } return out; } } /** * Returns the result of postmultiplying this by {@code m}. * * @param m Matrix to postmultiply by. * @return {@code this} * m. * @throws DimensionMismatchException if the matrices are not compatible. */ public BlockRealMatrix multiply(BlockRealMatrix m) throws DimensionMismatchException { // safety check MatrixUtils.checkMultiplicationCompatible(this, m); final BlockRealMatrix out = new BlockRealMatrix(rows, m.columns); // perform multiplication block-wise, to ensure good cache behavior int blockIndex = 0; for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { final int jWidth = out.blockWidth(jBlock); final int jWidth2 = jWidth + jWidth; final int jWidth3 = jWidth2 + jWidth; final int jWidth4 = jWidth3 + jWidth; // select current block final double[] outBlock = out.blocks[blockIndex]; // perform multiplication on current block for (int kBlock = 0; kBlock < blockColumns; ++kBlock) { final int kWidth = blockWidth(kBlock); final double[] tBlock = blocks[iBlock * blockColumns + kBlock]; final double[] mBlock = m.blocks[kBlock * m.blockColumns + jBlock]; int k = 0; for (int p = pStart; p < pEnd; ++p) { final int lStart = (p - pStart) * kWidth; final int lEnd = lStart + kWidth; for (int nStart = 0; nStart < jWidth; ++nStart) { double sum = 0; int l = lStart; int n = nStart; while (l < lEnd - 3) { sum += tBlock[l] * mBlock[n] + tBlock[l + 1] * mBlock[n + jWidth] + tBlock[l + 2] * mBlock[n + jWidth2] + tBlock[l + 3] * mBlock[n + jWidth3]; l += 4; n += jWidth4; } while (l < lEnd) { sum += tBlock[l++] * mBlock[n]; n += jWidth; } outBlock[k] += sum; ++k; } } } // go to next block ++blockIndex; } } return out; } /** {@inheritDoc} */ @Override public double[][] getData() { final double[][] data = new double[getRowDimension()][getColumnDimension()]; final int lastColumns = columns - (blockColumns - 1) * BLOCK_SIZE; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); int regularPos = 0; int lastPos = 0; for (int p = pStart; p < pEnd; ++p) { final double[] dataP = data[p]; int blockIndex = iBlock * blockColumns; int dataPos = 0; for (int jBlock = 0; jBlock < blockColumns - 1; ++jBlock) { System.arraycopy(blocks[blockIndex++], regularPos, dataP, dataPos, BLOCK_SIZE); dataPos += BLOCK_SIZE; } System.arraycopy(blocks[blockIndex], lastPos, dataP, dataPos, lastColumns); regularPos += BLOCK_SIZE; lastPos += lastColumns; } } return data; } /** {@inheritDoc} */ @Override public double getNorm() { final double[] colSums = new double[BLOCK_SIZE]; double maxColSum = 0; for (int jBlock = 0; jBlock < blockColumns; jBlock++) { final int jWidth = blockWidth(jBlock); Arrays.fill(colSums, 0, jWidth, 0.0); for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int iHeight = blockHeight(iBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; for (int j = 0; j < jWidth; ++j) { double sum = 0; for (int i = 0; i < iHeight; ++i) { sum += FastMath.abs(block[i * jWidth + j]); } colSums[j] += sum; } } for (int j = 0; j < jWidth; ++j) { maxColSum = FastMath.max(maxColSum, colSums[j]); } } return maxColSum; } /** {@inheritDoc} */ @Override public double getFrobeniusNorm() { double sum2 = 0; for (int blockIndex = 0; blockIndex < blocks.length; ++blockIndex) { for (final double entry : blocks[blockIndex]) { sum2 += entry * entry; } } return FastMath.sqrt(sum2); } /** {@inheritDoc} */ @Override public BlockRealMatrix getSubMatrix(final int startRow, final int endRow, final int startColumn, final int endColumn) throws OutOfRangeException, NumberIsTooSmallException { // safety checks MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); // create the output matrix final BlockRealMatrix out = new BlockRealMatrix(endRow - startRow + 1, endColumn - startColumn + 1); // compute blocks shifts final int blockStartRow = startRow / BLOCK_SIZE; final int rowsShift = startRow % BLOCK_SIZE; final int blockStartColumn = startColumn / BLOCK_SIZE; final int columnsShift = startColumn % BLOCK_SIZE; // perform extraction block-wise, to ensure good cache behavior int pBlock = blockStartRow; for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) { final int iHeight = out.blockHeight(iBlock); int qBlock = blockStartColumn; for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) { final int jWidth = out.blockWidth(jBlock); // handle one block of the output matrix final int outIndex = iBlock * out.blockColumns + jBlock; final double[] outBlock = out.blocks[outIndex]; final int index = pBlock * blockColumns + qBlock; final int width = blockWidth(qBlock); final int heightExcess = iHeight + rowsShift - BLOCK_SIZE; final int widthExcess = jWidth + columnsShift - BLOCK_SIZE; if (heightExcess > 0) { // the submatrix block spans on two blocks rows from the original matrix if (widthExcess > 0) { // the submatrix block spans on two blocks columns from the original matrix final int width2 = blockWidth(qBlock + 1); copyBlockPart(blocks[index], width, rowsShift, BLOCK_SIZE, columnsShift, BLOCK_SIZE, outBlock, jWidth, 0, 0); copyBlockPart(blocks[index + 1], width2, rowsShift, BLOCK_SIZE, 0, widthExcess, outBlock, jWidth, 0, jWidth - widthExcess); copyBlockPart(blocks[index + blockColumns], width, 0, heightExcess, columnsShift, BLOCK_SIZE, outBlock, jWidth, iHeight - heightExcess, 0); copyBlockPart(blocks[index + blockColumns + 1], width2, 0, heightExcess, 0, widthExcess, outBlock, jWidth, iHeight - heightExcess, jWidth - widthExcess); } else { // the submatrix block spans on one block column from the original matrix copyBlockPart(blocks[index], width, rowsShift, BLOCK_SIZE, columnsShift, jWidth + columnsShift, outBlock, jWidth, 0, 0); copyBlockPart(blocks[index + blockColumns], width, 0, heightExcess, columnsShift, jWidth + columnsShift, outBlock, jWidth, iHeight - heightExcess, 0); } } else { // the submatrix block spans on one block row from the original matrix if (widthExcess > 0) { // the submatrix block spans on two blocks columns from the original matrix final int width2 = blockWidth(qBlock + 1); copyBlockPart(blocks[index], width, rowsShift, iHeight + rowsShift, columnsShift, BLOCK_SIZE, outBlock, jWidth, 0, 0); copyBlockPart(blocks[index + 1], width2, rowsShift, iHeight + rowsShift, 0, widthExcess, outBlock, jWidth, 0, jWidth - widthExcess); } else { // the submatrix block spans on one block column from the original matrix copyBlockPart(blocks[index], width, rowsShift, iHeight + rowsShift, columnsShift, jWidth + columnsShift, outBlock, jWidth, 0, 0); } } ++qBlock; } ++pBlock; } return out; } /** * Copy a part of a block into another one * <p>This method can be called only when the specified part fits in both * blocks, no verification is done here.</p> * @param srcBlock source block * @param srcWidth source block width ({@link #BLOCK_SIZE} or smaller) * @param srcStartRow start row in the source block * @param srcEndRow end row (exclusive) in the source block * @param srcStartColumn start column in the source block * @param srcEndColumn end column (exclusive) in the source block * @param dstBlock destination block * @param dstWidth destination block width ({@link #BLOCK_SIZE} or smaller) * @param dstStartRow start row in the destination block * @param dstStartColumn start column in the destination block */ private void copyBlockPart(final double[] srcBlock, final int srcWidth, final int srcStartRow, final int srcEndRow, final int srcStartColumn, final int srcEndColumn, final double[] dstBlock, final int dstWidth, final int dstStartRow, final int dstStartColumn) { final int length = srcEndColumn - srcStartColumn; int srcPos = srcStartRow * srcWidth + srcStartColumn; int dstPos = dstStartRow * dstWidth + dstStartColumn; for (int srcRow = srcStartRow; srcRow < srcEndRow; ++srcRow) { System.arraycopy(srcBlock, srcPos, dstBlock, dstPos, length); srcPos += srcWidth; dstPos += dstWidth; } } /** {@inheritDoc} */ @Override public void setSubMatrix(final double[][] subMatrix, final int row, final int column) throws OutOfRangeException, NoDataException, NullArgumentException, DimensionMismatchException { // safety checks MathUtils.checkNotNull(subMatrix); final int refLength = subMatrix[0].length; if (refLength == 0) { throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN); } final int endRow = row + subMatrix.length - 1; final int endColumn = column + refLength - 1; MatrixUtils.checkSubMatrixIndex(this, row, endRow, column, endColumn); for (final double[] subRow : subMatrix) { if (subRow.length != refLength) { throw new DimensionMismatchException(refLength, subRow.length); } } // compute blocks bounds final int blockStartRow = row / BLOCK_SIZE; final int blockEndRow = (endRow + BLOCK_SIZE) / BLOCK_SIZE; final int blockStartColumn = column / BLOCK_SIZE; final int blockEndColumn = (endColumn + BLOCK_SIZE) / BLOCK_SIZE; // perform copy block-wise, to ensure good cache behavior for (int iBlock = blockStartRow; iBlock < blockEndRow; ++iBlock) { final int iHeight = blockHeight(iBlock); final int firstRow = iBlock * BLOCK_SIZE; final int iStart = FastMath.max(row, firstRow); final int iEnd = FastMath.min(endRow + 1, firstRow + iHeight); for (int jBlock = blockStartColumn; jBlock < blockEndColumn; ++jBlock) { final int jWidth = blockWidth(jBlock); final int firstColumn = jBlock * BLOCK_SIZE; final int jStart = FastMath.max(column, firstColumn); final int jEnd = FastMath.min(endColumn + 1, firstColumn + jWidth); final int jLength = jEnd - jStart; // handle one block, row by row final double[] block = blocks[iBlock * blockColumns + jBlock]; for (int i = iStart; i < iEnd; ++i) { System.arraycopy(subMatrix[i - row], jStart - column, block, (i - firstRow) * jWidth + (jStart - firstColumn), jLength); } } } } /** {@inheritDoc} */ @Override public BlockRealMatrix getRowMatrix(final int row) throws OutOfRangeException { MatrixUtils.checkRowIndex(this, row); final BlockRealMatrix out = new BlockRealMatrix(1, columns); // perform copy block-wise, to ensure good cache behavior final int iBlock = row / BLOCK_SIZE; final int iRow = row - iBlock * BLOCK_SIZE; int outBlockIndex = 0; int outIndex = 0; double[] outBlock = out.blocks[outBlockIndex]; for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int jWidth = blockWidth(jBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; final int available = outBlock.length - outIndex; if (jWidth > available) { System.arraycopy(block, iRow * jWidth, outBlock, outIndex, available); outBlock = out.blocks[++outBlockIndex]; System.arraycopy(block, iRow * jWidth, outBlock, 0, jWidth - available); outIndex = jWidth - available; } else { System.arraycopy(block, iRow * jWidth, outBlock, outIndex, jWidth); outIndex += jWidth; } } return out; } /** {@inheritDoc} */ @Override public void setRowMatrix(final int row, final RealMatrix matrix) throws OutOfRangeException, MatrixDimensionMismatchException { try { setRowMatrix(row, (BlockRealMatrix) matrix); } catch (ClassCastException cce) { super.setRowMatrix(row, matrix); } } /** * Sets the entries in row number <code>row</code> * as a row matrix. Row indices start at 0. * * @param row the row to be set * @param matrix row matrix (must have one row and the same number of columns * as the instance) * @throws OutOfRangeException if the specified row index is invalid. * @throws MatrixDimensionMismatchException if the matrix dimensions do * not match one instance row. */ public void setRowMatrix(final int row, final BlockRealMatrix matrix) throws OutOfRangeException, MatrixDimensionMismatchException { MatrixUtils.checkRowIndex(this, row); final int nCols = getColumnDimension(); if ((matrix.getRowDimension() != 1) || (matrix.getColumnDimension() != nCols)) { throw new MatrixDimensionMismatchException(matrix.getRowDimension(), matrix.getColumnDimension(), 1, nCols); } // perform copy block-wise, to ensure good cache behavior final int iBlock = row / BLOCK_SIZE; final int iRow = row - iBlock * BLOCK_SIZE; int mBlockIndex = 0; int mIndex = 0; double[] mBlock = matrix.blocks[mBlockIndex]; for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int jWidth = blockWidth(jBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; final int available = mBlock.length - mIndex; if (jWidth > available) { System.arraycopy(mBlock, mIndex, block, iRow * jWidth, available); mBlock = matrix.blocks[++mBlockIndex]; System.arraycopy(mBlock, 0, block, iRow * jWidth, jWidth - available); mIndex = jWidth - available; } else { System.arraycopy(mBlock, mIndex, block, iRow * jWidth, jWidth); mIndex += jWidth; } } } /** {@inheritDoc} */ @Override public BlockRealMatrix getColumnMatrix(final int column) throws OutOfRangeException { MatrixUtils.checkColumnIndex(this, column); final BlockRealMatrix out = new BlockRealMatrix(rows, 1); // perform copy block-wise, to ensure good cache behavior final int jBlock = column / BLOCK_SIZE; final int jColumn = column - jBlock * BLOCK_SIZE; final int jWidth = blockWidth(jBlock); int outBlockIndex = 0; int outIndex = 0; double[] outBlock = out.blocks[outBlockIndex]; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int iHeight = blockHeight(iBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; for (int i = 0; i < iHeight; ++i) { if (outIndex >= outBlock.length) { outBlock = out.blocks[++outBlockIndex]; outIndex = 0; } outBlock[outIndex++] = block[i * jWidth + jColumn]; } } return out; } /** {@inheritDoc} */ @Override public void setColumnMatrix(final int column, final RealMatrix matrix) throws OutOfRangeException, MatrixDimensionMismatchException { try { setColumnMatrix(column, (BlockRealMatrix) matrix); } catch (ClassCastException cce) { super.setColumnMatrix(column, matrix); } } /** * Sets the entries in column number <code>column</code> * as a column matrix. Column indices start at 0. * * @param column the column to be set * @param matrix column matrix (must have one column and the same number of rows * as the instance) * @throws OutOfRangeException if the specified column index is invalid. * @throws MatrixDimensionMismatchException if the matrix dimensions do * not match one instance column. */ void setColumnMatrix(final int column, final BlockRealMatrix matrix) throws OutOfRangeException, MatrixDimensionMismatchException { MatrixUtils.checkColumnIndex(this, column); final int nRows = getRowDimension(); if ((matrix.getRowDimension() != nRows) || (matrix.getColumnDimension() != 1)) { throw new MatrixDimensionMismatchException(matrix.getRowDimension(), matrix.getColumnDimension(), nRows, 1); } // perform copy block-wise, to ensure good cache behavior final int jBlock = column / BLOCK_SIZE; final int jColumn = column - jBlock * BLOCK_SIZE; final int jWidth = blockWidth(jBlock); int mBlockIndex = 0; int mIndex = 0; double[] mBlock = matrix.blocks[mBlockIndex]; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int iHeight = blockHeight(iBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; for (int i = 0; i < iHeight; ++i) { if (mIndex >= mBlock.length) { mBlock = matrix.blocks[++mBlockIndex]; mIndex = 0; } block[i * jWidth + jColumn] = mBlock[mIndex++]; } } } /** {@inheritDoc} */ @Override public RealVector getRowVector(final int row) throws OutOfRangeException { MatrixUtils.checkRowIndex(this, row); final double[] outData = new double[columns]; // perform copy block-wise, to ensure good cache behavior final int iBlock = row / BLOCK_SIZE; final int iRow = row - iBlock * BLOCK_SIZE; int outIndex = 0; for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int jWidth = blockWidth(jBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; System.arraycopy(block, iRow * jWidth, outData, outIndex, jWidth); outIndex += jWidth; } return new ArrayRealVector(outData, false); } /** {@inheritDoc} */ @Override public void setRowVector(final int row, final RealVector vector) throws OutOfRangeException, MatrixDimensionMismatchException { try { setRow(row, ((ArrayRealVector) vector).getDataRef()); } catch (ClassCastException cce) { super.setRowVector(row, vector); } } /** {@inheritDoc} */ @Override public RealVector getColumnVector(final int column) throws OutOfRangeException { MatrixUtils.checkColumnIndex(this, column); final double[] outData = new double[rows]; // perform copy block-wise, to ensure good cache behavior final int jBlock = column / BLOCK_SIZE; final int jColumn = column - jBlock * BLOCK_SIZE; final int jWidth = blockWidth(jBlock); int outIndex = 0; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int iHeight = blockHeight(iBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; for (int i = 0; i < iHeight; ++i) { outData[outIndex++] = block[i * jWidth + jColumn]; } } return new ArrayRealVector(outData, false); } /** {@inheritDoc} */ @Override public void setColumnVector(final int column, final RealVector vector) throws OutOfRangeException, MatrixDimensionMismatchException { try { setColumn(column, ((ArrayRealVector) vector).getDataRef()); } catch (ClassCastException cce) { super.setColumnVector(column, vector); } } /** {@inheritDoc} */ @Override public double[] getRow(final int row) throws OutOfRangeException { MatrixUtils.checkRowIndex(this, row); final double[] out = new double[columns]; // perform copy block-wise, to ensure good cache behavior final int iBlock = row / BLOCK_SIZE; final int iRow = row - iBlock * BLOCK_SIZE; int outIndex = 0; for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int jWidth = blockWidth(jBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; System.arraycopy(block, iRow * jWidth, out, outIndex, jWidth); outIndex += jWidth; } return out; } /** {@inheritDoc} */ @Override public void setRow(final int row, final double[] array) throws OutOfRangeException, MatrixDimensionMismatchException { MatrixUtils.checkRowIndex(this, row); final int nCols = getColumnDimension(); if (array.length != nCols) { throw new MatrixDimensionMismatchException(1, array.length, 1, nCols); } // perform copy block-wise, to ensure good cache behavior final int iBlock = row / BLOCK_SIZE; final int iRow = row - iBlock * BLOCK_SIZE; int outIndex = 0; for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int jWidth = blockWidth(jBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; System.arraycopy(array, outIndex, block, iRow * jWidth, jWidth); outIndex += jWidth; } } /** {@inheritDoc} */ @Override public double[] getColumn(final int column) throws OutOfRangeException { MatrixUtils.checkColumnIndex(this, column); final double[] out = new double[rows]; // perform copy block-wise, to ensure good cache behavior final int jBlock = column / BLOCK_SIZE; final int jColumn = column - jBlock * BLOCK_SIZE; final int jWidth = blockWidth(jBlock); int outIndex = 0; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int iHeight = blockHeight(iBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; for (int i = 0; i < iHeight; ++i) { out[outIndex++] = block[i * jWidth + jColumn]; } } return out; } /** {@inheritDoc} */ @Override public void setColumn(final int column, final double[] array) throws OutOfRangeException, MatrixDimensionMismatchException { MatrixUtils.checkColumnIndex(this, column); final int nRows = getRowDimension(); if (array.length != nRows) { throw new MatrixDimensionMismatchException(array.length, 1, nRows, 1); } // perform copy block-wise, to ensure good cache behavior final int jBlock = column / BLOCK_SIZE; final int jColumn = column - jBlock * BLOCK_SIZE; final int jWidth = blockWidth(jBlock); int outIndex = 0; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int iHeight = blockHeight(iBlock); final double[] block = blocks[iBlock * blockColumns + jBlock]; for (int i = 0; i < iHeight; ++i) { block[i * jWidth + jColumn] = array[outIndex++]; } } } /** {@inheritDoc} */ @Override public double getEntry(final int row, final int column) throws OutOfRangeException { MatrixUtils.checkMatrixIndex(this, row, column); final int iBlock = row / BLOCK_SIZE; final int jBlock = column / BLOCK_SIZE; final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + (column - jBlock * BLOCK_SIZE); return blocks[iBlock * blockColumns + jBlock][k]; } /** {@inheritDoc} */ @Override public void setEntry(final int row, final int column, final double value) throws OutOfRangeException { MatrixUtils.checkMatrixIndex(this, row, column); final int iBlock = row / BLOCK_SIZE; final int jBlock = column / BLOCK_SIZE; final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + (column - jBlock * BLOCK_SIZE); blocks[iBlock * blockColumns + jBlock][k] = value; } /** {@inheritDoc} */ @Override public void addToEntry(final int row, final int column, final double increment) throws OutOfRangeException { MatrixUtils.checkMatrixIndex(this, row, column); final int iBlock = row / BLOCK_SIZE; final int jBlock = column / BLOCK_SIZE; final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + (column - jBlock * BLOCK_SIZE); blocks[iBlock * blockColumns + jBlock][k] += increment; } /** {@inheritDoc} */ @Override public void multiplyEntry(final int row, final int column, final double factor) throws OutOfRangeException { MatrixUtils.checkMatrixIndex(this, row, column); final int iBlock = row / BLOCK_SIZE; final int jBlock = column / BLOCK_SIZE; final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) + (column - jBlock * BLOCK_SIZE); blocks[iBlock * blockColumns + jBlock][k] *= factor; } /** {@inheritDoc} */ @Override public BlockRealMatrix transpose() { final int nRows = getRowDimension(); final int nCols = getColumnDimension(); final BlockRealMatrix out = new BlockRealMatrix(nCols, nRows); // perform transpose block-wise, to ensure good cache behavior int blockIndex = 0; for (int iBlock = 0; iBlock < blockColumns; ++iBlock) { for (int jBlock = 0; jBlock < blockRows; ++jBlock) { // transpose current block final double[] outBlock = out.blocks[blockIndex]; final double[] tBlock = blocks[jBlock * blockColumns + iBlock]; final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, columns); final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, rows); int k = 0; for (int p = pStart; p < pEnd; ++p) { final int lInc = pEnd - pStart; int l = p - pStart; for (int q = qStart; q < qEnd; ++q) { outBlock[k] = tBlock[l]; ++k; l+= lInc; } } // go to next block ++blockIndex; } } return out; } /** {@inheritDoc} */ @Override public int getRowDimension() { return rows; } /** {@inheritDoc} */ @Override public int getColumnDimension() { return columns; } /** {@inheritDoc} */ @Override public double[] operate(final double[] v) throws DimensionMismatchException { if (v.length != columns) { throw new DimensionMismatchException(v.length, columns); } final double[] out = new double[rows]; // perform multiplication block-wise, to ensure good cache behavior for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final double[] block = blocks[iBlock * blockColumns + jBlock]; final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); int k = 0; for (int p = pStart; p < pEnd; ++p) { double sum = 0; int q = qStart; while (q < qEnd - 3) { sum += block[k] * v[q] + block[k + 1] * v[q + 1] + block[k + 2] * v[q + 2] + block[k + 3] * v[q + 3]; k += 4; q += 4; } while (q < qEnd) { sum += block[k++] * v[q++]; } out[p] += sum; } } } return out; } /** {@inheritDoc} */ @Override public double[] preMultiply(final double[] v) throws DimensionMismatchException { if (v.length != rows) { throw new DimensionMismatchException(v.length, rows); } final double[] out = new double[columns]; // perform multiplication block-wise, to ensure good cache behavior for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int jWidth = blockWidth(jBlock); final int jWidth2 = jWidth + jWidth; final int jWidth3 = jWidth2 + jWidth; final int jWidth4 = jWidth3 + jWidth; final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final double[] block = blocks[iBlock * blockColumns + jBlock]; final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); for (int q = qStart; q < qEnd; ++q) { int k = q - qStart; double sum = 0; int p = pStart; while (p < pEnd - 3) { sum += block[k] * v[p] + block[k + jWidth] * v[p + 1] + block[k + jWidth2] * v[p + 2] + block[k + jWidth3] * v[p + 3]; k += jWidth4; p += 4; } while (p < pEnd) { sum += block[k] * v[p++]; k += jWidth; } out[q] += sum; } } } return out; } /** {@inheritDoc} */ @Override public double walkInRowOrder(final RealMatrixChangingVisitor visitor) { visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); for (int p = pStart; p < pEnd; ++p) { for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int jWidth = blockWidth(jBlock); final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); final double[] block = blocks[iBlock * blockColumns + jBlock]; int k = (p - pStart) * jWidth; for (int q = qStart; q < qEnd; ++q) { block[k] = visitor.visit(p, q, block[k]); ++k; } } } } return visitor.end(); } /** {@inheritDoc} */ @Override public double walkInRowOrder(final RealMatrixPreservingVisitor visitor) { visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); for (int p = pStart; p < pEnd; ++p) { for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int jWidth = blockWidth(jBlock); final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); final double[] block = blocks[iBlock * blockColumns + jBlock]; int k = (p - pStart) * jWidth; for (int q = qStart; q < qEnd; ++q) { visitor.visit(p, q, block[k]); ++k; } } } } return visitor.end(); } /** {@inheritDoc} */ @Override public double walkInRowOrder(final RealMatrixChangingVisitor visitor, final int startRow, final int endRow, final int startColumn, final int endColumn) throws OutOfRangeException, NumberIsTooSmallException { MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { final int p0 = iBlock * BLOCK_SIZE; final int pStart = FastMath.max(startRow, p0); final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); for (int p = pStart; p < pEnd; ++p) { for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { final int jWidth = blockWidth(jBlock); final int q0 = jBlock * BLOCK_SIZE; final int qStart = FastMath.max(startColumn, q0); final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); final double[] block = blocks[iBlock * blockColumns + jBlock]; int k = (p - p0) * jWidth + qStart - q0; for (int q = qStart; q < qEnd; ++q) { block[k] = visitor.visit(p, q, block[k]); ++k; } } } } return visitor.end(); } /** {@inheritDoc} */ @Override public double walkInRowOrder(final RealMatrixPreservingVisitor visitor, final int startRow, final int endRow, final int startColumn, final int endColumn) throws OutOfRangeException, NumberIsTooSmallException { MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { final int p0 = iBlock * BLOCK_SIZE; final int pStart = FastMath.max(startRow, p0); final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); for (int p = pStart; p < pEnd; ++p) { for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { final int jWidth = blockWidth(jBlock); final int q0 = jBlock * BLOCK_SIZE; final int qStart = FastMath.max(startColumn, q0); final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); final double[] block = blocks[iBlock * blockColumns + jBlock]; int k = (p - p0) * jWidth + qStart - q0; for (int q = qStart; q < qEnd; ++q) { visitor.visit(p, q, block[k]); ++k; } } } } return visitor.end(); } /** {@inheritDoc} */ @Override public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor) { visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); int blockIndex = 0; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); final double[] block = blocks[blockIndex]; int k = 0; for (int p = pStart; p < pEnd; ++p) { for (int q = qStart; q < qEnd; ++q) { block[k] = visitor.visit(p, q, block[k]); ++k; } } ++blockIndex; } } return visitor.end(); } /** {@inheritDoc} */ @Override public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor) { visitor.start(rows, columns, 0, rows - 1, 0, columns - 1); int blockIndex = 0; for (int iBlock = 0; iBlock < blockRows; ++iBlock) { final int pStart = iBlock * BLOCK_SIZE; final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows); for (int jBlock = 0; jBlock < blockColumns; ++jBlock) { final int qStart = jBlock * BLOCK_SIZE; final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns); final double[] block = blocks[blockIndex]; int k = 0; for (int p = pStart; p < pEnd; ++p) { for (int q = qStart; q < qEnd; ++q) { visitor.visit(p, q, block[k]); ++k; } } ++blockIndex; } } return visitor.end(); } /** {@inheritDoc} */ @Override public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor, final int startRow, final int endRow, final int startColumn, final int endColumn) throws OutOfRangeException, NumberIsTooSmallException { MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { final int p0 = iBlock * BLOCK_SIZE; final int pStart = FastMath.max(startRow, p0); final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { final int jWidth = blockWidth(jBlock); final int q0 = jBlock * BLOCK_SIZE; final int qStart = FastMath.max(startColumn, q0); final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); final double[] block = blocks[iBlock * blockColumns + jBlock]; for (int p = pStart; p < pEnd; ++p) { int k = (p - p0) * jWidth + qStart - q0; for (int q = qStart; q < qEnd; ++q) { block[k] = visitor.visit(p, q, block[k]); ++k; } } } } return visitor.end(); } /** {@inheritDoc} */ @Override public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor, final int startRow, final int endRow, final int startColumn, final int endColumn) throws OutOfRangeException, NumberIsTooSmallException { MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn); visitor.start(rows, columns, startRow, endRow, startColumn, endColumn); for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) { final int p0 = iBlock * BLOCK_SIZE; final int pStart = FastMath.max(startRow, p0); final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow); for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) { final int jWidth = blockWidth(jBlock); final int q0 = jBlock * BLOCK_SIZE; final int qStart = FastMath.max(startColumn, q0); final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn); final double[] block = blocks[iBlock * blockColumns + jBlock]; for (int p = pStart; p < pEnd; ++p) { int k = (p - p0) * jWidth + qStart - q0; for (int q = qStart; q < qEnd; ++q) { visitor.visit(p, q, block[k]); ++k; } } } } return visitor.end(); } /** * Get the height of a block. * @param blockRow row index (in block sense) of the block * @return height (number of rows) of the block */ private int blockHeight(final int blockRow) { return (blockRow == blockRows - 1) ? rows - blockRow * BLOCK_SIZE : BLOCK_SIZE; } /** * Get the width of a block. * @param blockColumn column index (in block sense) of the block * @return width (number of columns) of the block */ private int blockWidth(final int blockColumn) { return (blockColumn == blockColumns - 1) ? columns - blockColumn * BLOCK_SIZE : BLOCK_SIZE; } }
mit
cevaris/pants
contrib/findbugs/tests/java/org/pantsbuild/contrib/findbugs/LowWarning.java
332
// Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package org.pantsbuild.contrib.findbugs; public class LowWarning { public static void main(String[] args) { System.out.printf("FindBugs Low Warning VA_FORMAT_STRING_USES_NEWLINE: \n"); } }
apache-2.0
cymcsg/UltimateAndroid
deprecated/UltimateAndroidGradle/ultimateandroiduianimation/src/main/java/com/marshalchen/common/uimodule/androidanimations/fading_entrances/FadeInRightAnimator.java
1698
/* * The MIT License (MIT) * * Copyright (c) 2014 daimajia * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.marshalchen.common.uimodule.androidanimations.fading_entrances; import android.view.View; import com.marshalchen.common.uimodule.androidanimations.BaseViewAnimator; import com.nineoldandroids.animation.ObjectAnimator; public class FadeInRightAnimator extends BaseViewAnimator { @Override public void prepare(View target) { getAnimatorAgent().playTogether( ObjectAnimator.ofFloat(target, "alpha", 0, 1), ObjectAnimator.ofFloat(target, "translationX", target.getWidth()/4, 0) ); } }
apache-2.0
smartan/lucene
src/main/java/org/apache/lucene/util/CommandLineUtil.java
4673
package org.apache.lucene.util; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; /** * Class containing some useful methods used by command line tools * */ public final class CommandLineUtil { private CommandLineUtil() { } /** * Creates a specific FSDirectory instance starting from its class name * @param clazzName The name of the FSDirectory class to load * @param file The file to be used as parameter constructor * @return the new FSDirectory instance */ public static FSDirectory newFSDirectory(String clazzName, File file) { try { final Class<? extends FSDirectory> clazz = loadFSDirectoryClass(clazzName); return newFSDirectory(clazz, file); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(FSDirectory.class.getSimpleName() + " implementation not found: " + clazzName, e); } catch (ClassCastException e) { throw new IllegalArgumentException(clazzName + " is not a " + FSDirectory.class.getSimpleName() + " implementation", e); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(clazzName + " constructor with " + File.class.getSimpleName() + " as parameter not found", e); } catch (Exception e) { throw new IllegalArgumentException("Error creating " + clazzName + " instance", e); } } /** * Loads a specific Directory implementation * @param clazzName The name of the Directory class to load * @return The Directory class loaded * @throws ClassNotFoundException If the specified class cannot be found. */ public static Class<? extends Directory> loadDirectoryClass(String clazzName) throws ClassNotFoundException { return Class.forName(adjustDirectoryClassName(clazzName)).asSubclass(Directory.class); } /** * Loads a specific FSDirectory implementation * @param clazzName The name of the FSDirectory class to load * @return The FSDirectory class loaded * @throws ClassNotFoundException If the specified class cannot be found. */ public static Class<? extends FSDirectory> loadFSDirectoryClass(String clazzName) throws ClassNotFoundException { return Class.forName(adjustDirectoryClassName(clazzName)).asSubclass(FSDirectory.class); } private static String adjustDirectoryClassName(String clazzName) { if (clazzName == null || clazzName.trim().length() == 0) { throw new IllegalArgumentException("The " + FSDirectory.class.getSimpleName() + " implementation cannot be null or empty"); } if (clazzName.indexOf(".") == -1) {// if not fully qualified, assume .store clazzName = Directory.class.getPackage().getName() + "." + clazzName; } return clazzName; } /** * Creates a new specific FSDirectory instance * @param clazz The class of the object to be created * @param file The file to be used as parameter constructor * @return The new FSDirectory instance * @throws NoSuchMethodException If the Directory does not have a constructor that takes <code>File</code>. * @throws InstantiationException If the class is abstract or an interface. * @throws IllegalAccessException If the constructor does not have public visibility. * @throws InvocationTargetException If the constructor throws an exception */ public static FSDirectory newFSDirectory(Class<? extends FSDirectory> clazz, File file) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // Assuming every FSDirectory has a ctor(File): Constructor<? extends FSDirectory> ctor = clazz.getConstructor(File.class); return ctor.newInstance(file); } }
apache-2.0
md-5/jdk10
src/java.base/share/classes/javax/security/auth/Destroyable.java
2507
/* * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.security.auth; /** * Objects such as credentials may optionally implement this interface * to provide the capability to destroy its contents. * * @since 1.4 * @see javax.security.auth.Subject */ public interface Destroyable { /** * Destroy this {@code Object}. * * <p> Sensitive information associated with this {@code Object} * is destroyed or cleared. Subsequent calls to certain methods * on this {@code Object} will result in an * {@code IllegalStateException} being thrown. * * @implSpec * The default implementation throws {@code DestroyFailedException}. * * @exception DestroyFailedException if the destroy operation fails. * * @exception SecurityException if the caller does not have permission * to destroy this {@code Object}. */ public default void destroy() throws DestroyFailedException { throw new DestroyFailedException(); } /** * Determine if this {@code Object} has been destroyed. * * @implSpec * The default implementation returns false. * * @return true if this {@code Object} has been destroyed, * false otherwise. */ public default boolean isDestroyed() { return false; } }
gpl-2.0
kauffmj/razza
tools/javancss-32.53/test/Test127.java
312
/** * Useless class with a single genericized constructor to illustrate MagicDraw 11.5 reverse engineering bug. */ public class ClassWithGenericizedConstructor { //public ClassWithGenericizedConstructor(T genericArg) { public <T> ClassWithGenericizedConstructor(T genericArg) { super(); } }
gpl-2.0
DariusX/camel
components/camel-file/src/main/java/org/apache/camel/component/file/strategy/GenericFileNoOpProcessStrategy.java
951
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file.strategy; public class GenericFileNoOpProcessStrategy<T> extends GenericFileProcessStrategySupport<T> { }
apache-2.0
bitblender/drill
exec/java-exec/src/main/java/org/apache/drill/exec/coord/local/LocalClusterCoordinator.java
5334
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.coord.local; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.apache.drill.exec.coord.ClusterCoordinator; import org.apache.drill.exec.coord.DistributedSemaphore; import org.apache.drill.exec.coord.store.CachingTransientStoreFactory; import org.apache.drill.exec.coord.store.TransientStore; import org.apache.drill.exec.coord.store.TransientStoreConfig; import org.apache.drill.exec.coord.store.TransientStoreFactory; import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint; import com.google.common.collect.Maps; public class LocalClusterCoordinator extends ClusterCoordinator { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LocalClusterCoordinator.class); /* * Since we hand out the endpoints list in {@see #getAvailableEndpoints()}, we use a * {@see java.util.concurrent.ConcurrentHashMap} because those guarantee not to throw * ConcurrentModificationException. */ private final Map<RegistrationHandle, DrillbitEndpoint> endpoints = new ConcurrentHashMap<>(); private final ConcurrentMap<String, DistributedSemaphore> semaphores = Maps.newConcurrentMap(); private final TransientStoreFactory factory = CachingTransientStoreFactory.of(new TransientStoreFactory() { @Override public <V> TransientStore<V> getOrCreateStore(TransientStoreConfig<V> config) { return new MapBackedStore<>(config); } @Override public void close() throws Exception { } }); @Override public void close() throws Exception { factory.close(); endpoints.clear(); } @Override public void start(final long millis) throws Exception { logger.debug("Local Cluster Coordinator started."); } @Override public RegistrationHandle register(final DrillbitEndpoint data) { logger.debug("Endpoint registered {}.", data); final Handle h = new Handle(); endpoints.put(h, data); return h; } @Override public void unregister(final RegistrationHandle handle) { if (handle == null) { return; } endpoints.remove(handle); } @Override public Collection<DrillbitEndpoint> getAvailableEndpoints() { return endpoints.values(); } private class Handle implements RegistrationHandle { private final UUID id = UUID.randomUUID(); @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Handle other = (Handle) obj; if (!getOuterType().equals(other.getOuterType())) { return false; } if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } return true; } private LocalClusterCoordinator getOuterType() { return LocalClusterCoordinator.this; } } @Override public DistributedSemaphore getSemaphore(final String name, final int maximumLeases) { if (!semaphores.containsKey(name)) { semaphores.putIfAbsent(name, new LocalSemaphore(maximumLeases)); } return semaphores.get(name); } @Override public <V> TransientStore<V> getOrCreateTransientStore(final TransientStoreConfig<V> config) { return factory.getOrCreateStore(config); } public class LocalSemaphore implements DistributedSemaphore { private final Semaphore semaphore; private final LocalLease localLease = new LocalLease(); public LocalSemaphore(final int size) { semaphore = new Semaphore(size); } @Override public DistributedLease acquire(final long timeout, final TimeUnit timeUnit) throws Exception { if (!semaphore.tryAcquire(timeout, timeUnit)) { return null; } else { return localLease; } } private class LocalLease implements DistributedLease { @Override public void close() throws Exception { semaphore.release(); } } } }
apache-2.0
GlenRSmith/elasticsearch
server/src/test/java/org/elasticsearch/index/query/QueryShardExceptionTests.java
2160
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.query; import org.elasticsearch.index.Index; import org.elasticsearch.test.ESTestCase; import static org.hamcrest.CoreMatchers.equalTo; public class QueryShardExceptionTests extends ESTestCase { public void testCreateFromSearchExecutionContext() { String indexUuid = randomAlphaOfLengthBetween(5, 10); String clusterAlias = randomAlphaOfLengthBetween(5, 10); SearchExecutionContext searchExecutionContext = SearchExecutionContextTests.createSearchExecutionContext(indexUuid, clusterAlias); { QueryShardException queryShardException = new QueryShardException(searchExecutionContext, "error"); assertThat(queryShardException.getIndex().getName(), equalTo(clusterAlias + ":index")); assertThat(queryShardException.getIndex().getUUID(), equalTo(indexUuid)); } { QueryShardException queryShardException = new QueryShardException( searchExecutionContext, "error", new IllegalArgumentException() ); assertThat(queryShardException.getIndex().getName(), equalTo(clusterAlias + ":index")); assertThat(queryShardException.getIndex().getUUID(), equalTo(indexUuid)); } } public void testCreateFromIndex() { String indexUuid = randomAlphaOfLengthBetween(5, 10); String indexName = randomAlphaOfLengthBetween(5, 10); Index index = new Index(indexName, indexUuid); QueryShardException queryShardException = new QueryShardException(index, "error", new IllegalArgumentException()); assertThat(queryShardException.getIndex().getName(), equalTo(indexName)); assertThat(queryShardException.getIndex().getUUID(), equalTo(indexUuid)); } }
apache-2.0
Kevin2030/shiro
web/src/main/java/org/apache/shiro/web/servlet/ServletContextSupport.java
3227
/* * 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.shiro.web.servlet; import javax.servlet.ServletContext; /** * Base implementation for any components that need to access the web application's {@link ServletContext ServletContext}. * * @since 0.2 */ public class ServletContextSupport { //TODO - complete JavaDoc private ServletContext servletContext = null; public ServletContext getServletContext() { return servletContext; } public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @SuppressWarnings({"UnusedDeclaration"}) protected String getContextInitParam(String paramName) { return getServletContext().getInitParameter(paramName); } private ServletContext getRequiredServletContext() { ServletContext servletContext = getServletContext(); if (servletContext == null) { String msg = "ServletContext property must be set via the setServletContext method."; throw new IllegalStateException(msg); } return servletContext; } @SuppressWarnings({"UnusedDeclaration"}) protected void setContextAttribute(String key, Object value) { if (value == null) { removeContextAttribute(key); } else { getRequiredServletContext().setAttribute(key, value); } } @SuppressWarnings({"UnusedDeclaration"}) protected Object getContextAttribute(String key) { return getRequiredServletContext().getAttribute(key); } protected void removeContextAttribute(String key) { getRequiredServletContext().removeAttribute(key); } /** * It is highly recommended not to override this method directly, and instead override the * {@link #toStringBuilder() toStringBuilder()} method, a better-performing alternative. * * @return the String representation of this instance. */ @Override public String toString() { return toStringBuilder().toString(); } /** * Same concept as {@link #toString() toString()}, but returns a {@link StringBuilder} instance instead. * * @return a StringBuilder instance to use for appending String data that will eventually be returned from a * {@code toString()} invocation. */ protected StringBuilder toStringBuilder() { return new StringBuilder(super.toString()); } }
apache-2.0
blackicebird/android
zxing-1.6/android/src/com/google/zxing/client/android/result/ISBNResultHandler.java
2686
/* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.client.android.result; import com.google.zxing.Result; import com.google.zxing.client.android.R; import com.google.zxing.client.result.ISBNParsedResult; import com.google.zxing.client.result.ParsedResult; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.view.View; /** * Handles books encoded by their ISBN values. * * @author dswitkin@google.com (Daniel Switkin) */ public final class ISBNResultHandler extends ResultHandler { private static final int[] buttons = { R.string.button_product_search, R.string.button_book_search, R.string.button_search_book_contents, R.string.button_custom_product_search }; public ISBNResultHandler(Activity activity, ParsedResult result, Result rawResult) { super(activity, result, rawResult); showGoogleShopperButton(new View.OnClickListener() { public void onClick(View view) { ISBNParsedResult isbnResult = (ISBNParsedResult) getResult(); openGoogleShopper(isbnResult.getISBN()); } }); } @Override public int getButtonCount() { return hasCustomProductSearch() ? buttons.length : buttons.length - 1; } @Override public int getButtonText(int index) { return buttons[index]; } @Override public void handleButtonPress(final int index) { showNotOurResults(index, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { ISBNParsedResult isbnResult = (ISBNParsedResult) getResult(); switch (index) { case 0: openProductSearch(isbnResult.getISBN()); break; case 1: openBookSearch(isbnResult.getISBN()); break; case 2: searchBookContents(isbnResult.getISBN()); break; case 3: openURL(fillInCustomSearchURL(isbnResult.getISBN())); break; } } }); } @Override public int getDisplayTitle() { return R.string.result_isbn; } }
mit
s2oBCN/testng
src/test/java/test/timeout/TestTimeOutSampleTest.java
302
package test.timeout; import org.testng.annotations.Test; public class TestTimeOutSampleTest { @Test public void timeoutTest() { try { Thread.sleep(2_000); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); } } }
apache-2.0
dmagda/incubator-ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImplSelfTest.java
6112
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.datastreamer; import java.io.Serializable; import java.util.Map; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.util.typedef.G; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; /** * Tests for {@code IgniteDataStreamerImpl}. */ public class DataStreamerImplSelfTest extends GridCommonAbstractTest { /** IP finder. */ private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** Number of keys to load via data streamer. */ private static final int KEYS_COUNT = 1000; /** Started grid counter. */ private static int cnt; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); TcpDiscoverySpi discoSpi = new TcpDiscoverySpi(); discoSpi.setIpFinder(IP_FINDER); cfg.setDiscoverySpi(discoSpi); // Forth node goes without cache. if (cnt < 4) cfg.setCacheConfiguration(cacheConfiguration()); cnt++; return cfg; } /** * @throws Exception If failed. */ public void testNullPointerExceptionUponDataStreamerClosing() throws Exception { try { startGrids(5); final CyclicBarrier barrier = new CyclicBarrier(2); multithreadedAsync(new Callable<Object>() { @Override public Object call() throws Exception { U.awaitQuiet(barrier); G.stopAll(true); return null; } }, 1); Ignite g4 = grid(4); IgniteDataStreamer<Object, Object> dataLdr = g4.dataStreamer(null); dataLdr.perNodeBufferSize(32); for (int i = 0; i < 100000; i += 2) { dataLdr.addData(i, i); dataLdr.removeData(i + 1); } U.awaitQuiet(barrier); info("Closing data streamer."); try { dataLdr.close(true); } catch (IllegalStateException ignore) { // This is ok to ignore this exception as test is racy by it's nature - // grid is stopping in different thread. } } finally { G.stopAll(true); } } /** * Data streamer should correctly load entries from HashMap in case of grids with more than one node * and with GridOptimizedMarshaller that requires serializable. * * @throws Exception If failed. */ public void testAddDataFromMap() throws Exception { try { cnt = 0; startGrids(2); Ignite g0 = grid(0); IgniteDataStreamer<Integer, String> dataLdr = g0.dataStreamer(null); Map<Integer, String> map = U.newHashMap(KEYS_COUNT); for (int i = 0; i < KEYS_COUNT; i ++) map.put(i, String.valueOf(i)); dataLdr.addData(map); dataLdr.close(); Random rnd = new Random(); IgniteCache<Integer, String> c = g0.cache(null); for (int i = 0; i < KEYS_COUNT; i ++) { Integer k = rnd.nextInt(KEYS_COUNT); String v = c.get(k); assertEquals(k.toString(), v); } } finally { G.stopAll(true); } } /** * Gets cache configuration. * * @return Cache configuration. */ private CacheConfiguration cacheConfiguration() { CacheConfiguration cacheCfg = defaultCacheConfiguration(); cacheCfg.setCacheMode(PARTITIONED); cacheCfg.setBackups(1); cacheCfg.setWriteSynchronizationMode(FULL_SYNC); return cacheCfg; } /** * */ private static class TestObject implements Serializable { /** */ private int val; /** */ private TestObject() { // No-op. } /** * @param val Value. */ private TestObject(int val) { this.val = val; } public Integer val() { return val; } /** {@inheritDoc} */ @Override public int hashCode() { return val; } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { return obj instanceof TestObject && ((TestObject)obj).val == val; } } }
apache-2.0
siyuanh/apex-malhar
library/src/main/java/org/apache/apex/malhar/lib/window/accumulation/Max.java
2095
/** * 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.apex.malhar.lib.window.accumulation; import java.util.Comparator; import org.apache.apex.malhar.lib.window.Accumulation; /** * Max accumulation. * * @since 3.5.0 */ public class Max<T> implements Accumulation<T, T, T> { Comparator<T> comparator; public void setComparator(Comparator<T> comparator) { this.comparator = comparator; } @Override public T defaultAccumulatedValue() { return null; } @Override public T accumulate(T accumulatedValue, T input) { if (accumulatedValue == null) { return input; } else if (comparator != null) { return (comparator.compare(input, accumulatedValue) > 0) ? input : accumulatedValue; } else if (input instanceof Comparable) { return (((Comparable)input).compareTo(accumulatedValue) > 0) ? input : accumulatedValue; } else { throw new RuntimeException("Tuple cannot be compared"); } } @Override public T merge(T accumulatedValue1, T accumulatedValue2) { return accumulate(accumulatedValue1, accumulatedValue2); } @Override public T getOutput(T accumulatedValue) { return accumulatedValue; } @Override public T getRetraction(T value) { // TODO: Need to add implementation for retraction. return null; } }
apache-2.0
zerg000000/mario-ai
src/main/java/ch/idsia/scenarios/oldscenarios/EvolveIncrementally.java
4157
/* * Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the Mario AI nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ch.idsia.scenarios.oldscenarios; import ch.idsia.agents.Agent; import ch.idsia.agents.AgentsPool; import ch.idsia.agents.learning.SimpleMLPAgent; import ch.idsia.benchmark.mario.engine.GlobalOptions; import ch.idsia.benchmark.tasks.MultiSeedProgressTask; import ch.idsia.evolution.Evolvable; import ch.idsia.evolution.ea.ES; import ch.idsia.tools.MarioAIOptions; import ch.idsia.utils.wox.serial.Easy; /** * Created by IntelliJ IDEA. * User: julian * Date: May 4, 2009 * Time: 4:33:25 PM */ public class EvolveIncrementally { final static int generations = 100; final static int populationSize = 100; public static void main(String[] args) { MarioAIOptions options = new MarioAIOptions(new String[0]); // options.setEvaluationQuota(1); Evolvable initial = new SimpleMLPAgent(); if (args.length > 0) { initial = (Evolvable) AgentsPool.loadAgent(args[0], options.isPunj()); } // AgentsPool.registerAgent ((Agent) initial); // maybe need AgentsPool.addAgent((Agent) initial); for (int difficulty = 0; difficulty < 11; difficulty++) { System.out.println("New EvolveIncrementally phase with difficulty = " + difficulty + " started."); options.setLevelDifficulty(difficulty); options.setFPS(GlobalOptions.MaxFPS); options.setVisualization(false); //Task task = new ProgressTask(options); MultiSeedProgressTask task = new MultiSeedProgressTask(options); task.setNumberOfSeeds(3); task.setStartingSeed(0); ES es = new ES(task, initial, populationSize); System.out.println("Evolving " + initial + " with task " + task); for (int gen = 0; gen < generations; gen++) { es.nextGeneration(); double bestResult = es.getBestFitnesses()[0]; System.out.println("Generation " + gen + " best " + bestResult); options.setVisualization(gen % 5 == 0 || bestResult > 4000); // options.setFPS(true); Agent a = (Agent) es.getBests()[0]; a.setName(((Agent) initial).getName() + gen); // AgentsPool.addAgent(a); // AgentsPool.setCurrentAgent(a); int result = task.evaluate(a); options.setVisualization(false); // options.setFPS(true); Easy.save(es.getBests()[0], "evolved.xml"); if (result > 4000) { initial = es.getBests()[0]; break; // Go to next difficulty. } } } System.exit(0); } }
bsd-3-clause
rokn/Count_Words_2015
testing/openjdk/jdk/test/sun/security/ssl/javax/net/ssl/TLSv11/ExportableBlockCipher.java
9988
/* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 4873188 * @summary Support TLS 1.1 * @run main/othervm -Djavax.net.debug=all ExportableBlockCipher * * @author Xuelei Fan */ import java.io.*; import java.net.*; import javax.net.ssl.*; public class ExportableBlockCipher { /* * ============================================================= * Set the various variables needed for the tests, then * specify what tests to run on each side. */ /* * Should we run the client or server in a separate thread? * Both sides can throw exceptions, but do you have a preference * as to which side should be the main thread. */ static boolean separateServerThread = false; /* * Where do we find the keystores? */ static String pathToStores = "/../../../../etc"; static String keyStoreFile = "keystore"; static String trustStoreFile = "truststore"; static String passwd = "passphrase"; /* * Is the server ready to serve? */ volatile static boolean serverReady = false; /* * Turn on SSL debugging? */ static boolean debug = false; /* * If the client or server is doing some kind of object creation * that the other side depends on, and that thread prematurely * exits, you may experience a hang. The test harness will * terminate all hung threads after its timeout has expired, * currently 3 minutes by default, but you might try to be * smart about it.... */ /* * Define the server side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doServerSide() throws Exception { SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort); serverPort = sslServerSocket.getLocalPort(); /* * Signal Client, we're ready for his connect. */ serverReady = true; SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); boolean interrupted = false; try { sslIS.read(); sslOS.write('A'); sslOS.flush(); } catch (SSLException ssle) { // get the expected exception interrupted = true; } finally { sslSocket.close(); } if (!interrupted) { throw new SSLHandshakeException( "A weak cipher suite is negotiated, " + "TLSv1.1 must not negotiate the exportable cipher suites."); } } /* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort); // enable TLSv1.1 only sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"}); // enable a exportable block cipher sslSocket.setEnabledCipherSuites( new String[] {"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"}); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); boolean interrupted = false; try { sslOS.write('B'); sslOS.flush(); sslIS.read(); } catch (SSLException ssle) { // get the expected exception interrupted = true; } finally { sslSocket.close(); } if (!interrupted) { throw new SSLHandshakeException( "A weak cipher suite is negotiated, " + "TLSv1.1 must not negotiate the exportable cipher suites."); } } /* * ============================================================= * The remainder is just support stuff */ // use any free port by default volatile int serverPort = 0; volatile Exception serverException = null; volatile Exception clientException = null; public static void main(String[] args) throws Exception { String keyFilename = System.getProperty("test.src", ".") + "/" + pathToStores + "/" + keyStoreFile; String trustFilename = System.getProperty("test.src", ".") + "/" + pathToStores + "/" + trustStoreFile; System.setProperty("javax.net.ssl.keyStore", keyFilename); System.setProperty("javax.net.ssl.keyStorePassword", passwd); System.setProperty("javax.net.ssl.trustStore", trustFilename); System.setProperty("javax.net.ssl.trustStorePassword", passwd); if (debug) System.setProperty("javax.net.debug", "all"); /* * Start the tests. */ new ExportableBlockCipher(); } Thread clientThread = null; Thread serverThread = null; /* * Primary constructor, used to drive remainder of the test. * * Fork off the other side, then do your work. */ ExportableBlockCipher() throws Exception { try { if (separateServerThread) { startServer(true); startClient(false); } else { startClient(true); startServer(false); } } catch (Exception e) { // swallow for now. Show later } /* * Wait for other side to close down. */ if (separateServerThread) { serverThread.join(); } else { clientThread.join(); } /* * When we get here, the test is pretty much over. * Which side threw the error? */ Exception local; Exception remote; String whichRemote; if (separateServerThread) { remote = serverException; local = clientException; whichRemote = "server"; } else { remote = clientException; local = serverException; whichRemote = "client"; } /* * If both failed, return the curthread's exception, but also * print the remote side Exception */ if ((local != null) && (remote != null)) { System.out.println(whichRemote + " also threw:"); remote.printStackTrace(); System.out.println(); throw local; } if (remote != null) { throw remote; } if (local != null) { throw local; } } void startServer(boolean newThread) throws Exception { if (newThread) { serverThread = new Thread() { public void run() { try { doServerSide(); } catch (Exception e) { /* * Our server thread just died. * * Release the client, if not active already... */ System.err.println("Server died..."); serverReady = true; serverException = e; } } }; serverThread.start(); } else { try { doServerSide(); } catch (Exception e) { serverException = e; } finally { serverReady = true; } } } void startClient(boolean newThread) throws Exception { if (newThread) { clientThread = new Thread() { public void run() { try { doClientSide(); } catch (Exception e) { /* * Our client thread just died. */ System.err.println("Client died..."); clientException = e; } } }; clientThread.start(); } else { try { doClientSide(); } catch (Exception e) { clientException = e; } } } }
mit
legend-hua/hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestSocketFactory.java
8157
/** * 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.ipc; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Proxy.Type; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.HashMap; import java.util.Map; import javax.net.SocketFactory; import org.junit.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.net.SocksSocketFactory; import org.apache.hadoop.net.StandardSocketFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; /** * test StandardSocketFactory and SocksSocketFactory NetUtils * */ public class TestSocketFactory { private static final int START_STOP_TIMEOUT_SEC = 30; private ServerRunnable serverRunnable; private Thread serverThread; private int port; private void startTestServer() throws Exception { // start simple tcp server. serverRunnable = new ServerRunnable(); serverThread = new Thread(serverRunnable); serverThread.start(); final long timeout = System.currentTimeMillis() + START_STOP_TIMEOUT_SEC * 1000; while (!serverRunnable.isReady()) { assertNull(serverRunnable.getThrowable()); Thread.sleep(10); if (System.currentTimeMillis() > timeout) { fail("Server thread did not start properly in allowed time of " + START_STOP_TIMEOUT_SEC + " sec."); } } port = serverRunnable.getPort(); } @After public void stopTestServer() throws InterruptedException { final Thread t = serverThread; if (t != null) { serverThread = null; port = -1; // stop server serverRunnable.stop(); t.join(START_STOP_TIMEOUT_SEC * 1000); assertFalse(t.isAlive()); assertNull(serverRunnable.getThrowable()); } } @Test public void testSocketFactoryAsKeyInMap() { Map<SocketFactory, Integer> dummyCache = new HashMap<SocketFactory, Integer>(); int toBeCached1 = 1; int toBeCached2 = 2; Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.HADOOP_RPC_SOCKET_FACTORY_CLASS_DEFAULT_KEY, "org.apache.hadoop.ipc.TestSocketFactory$DummySocketFactory"); final SocketFactory dummySocketFactory = NetUtils .getDefaultSocketFactory(conf); dummyCache.put(dummySocketFactory, toBeCached1); conf.set(CommonConfigurationKeys.HADOOP_RPC_SOCKET_FACTORY_CLASS_DEFAULT_KEY, "org.apache.hadoop.net.StandardSocketFactory"); final SocketFactory defaultSocketFactory = NetUtils .getDefaultSocketFactory(conf); dummyCache.put(defaultSocketFactory, toBeCached2); Assert .assertEquals("The cache contains two elements", 2, dummyCache.size()); Assert.assertEquals("Equals of both socket factory shouldn't be same", defaultSocketFactory.equals(dummySocketFactory), false); assertSame(toBeCached2, dummyCache.remove(defaultSocketFactory)); dummyCache.put(defaultSocketFactory, toBeCached2); assertSame(toBeCached1, dummyCache.remove(dummySocketFactory)); } /** * A dummy socket factory class that extends the StandardSocketFactory. */ static class DummySocketFactory extends StandardSocketFactory { } /** * Test SocksSocketFactory. */ @Test (timeout=5000) public void testSocksSocketFactory() throws Exception { startTestServer(); testSocketFactory(new SocksSocketFactory()); } /** * Test StandardSocketFactory. */ @Test (timeout=5000) public void testStandardSocketFactory() throws Exception { startTestServer(); testSocketFactory(new StandardSocketFactory()); } /* * Common test implementation. */ private void testSocketFactory(SocketFactory socketFactory) throws Exception { assertNull(serverRunnable.getThrowable()); InetAddress address = InetAddress.getLocalHost(); Socket socket = socketFactory.createSocket(address, port); checkSocket(socket); socket.close(); socket = socketFactory.createSocket(address, port, InetAddress.getLocalHost(), 0); checkSocket(socket); socket.close(); socket = socketFactory.createSocket("localhost", port); checkSocket(socket); socket.close(); socket = socketFactory.createSocket("localhost", port, InetAddress.getLocalHost(), 0); checkSocket(socket); socket.close(); } /** * test proxy methods */ @Test (timeout=5000) public void testProxy() throws Exception { SocksSocketFactory templateWithoutProxy = new SocksSocketFactory(); Proxy proxy = new Proxy(Type.SOCKS, InetSocketAddress.createUnresolved( "localhost", 0)); SocksSocketFactory templateWithProxy = new SocksSocketFactory(proxy); assertFalse(templateWithoutProxy.equals(templateWithProxy)); Configuration configuration = new Configuration(); configuration.set("hadoop.socks.server", "localhost:0"); templateWithoutProxy.setConf(configuration); assertTrue(templateWithoutProxy.equals(templateWithProxy)); } private void checkSocket(Socket socket) throws Exception { BufferedReader input = new BufferedReader(new InputStreamReader( socket.getInputStream())); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeBytes("test\n"); String answer = input.readLine(); assertEquals("TEST", answer); } /** * Simple tcp server. Server gets a string, transforms it to upper case and returns it. */ private static class ServerRunnable implements Runnable { private volatile boolean works = true; private ServerSocket testSocket; private volatile boolean ready = false; private volatile Throwable throwable; private int port0; @Override public void run() { try { testSocket = new ServerSocket(0); port0 = testSocket.getLocalPort(); ready = true; while (works) { try { Socket connectionSocket = testSocket.accept(); BufferedReader input = new BufferedReader(new InputStreamReader( connectionSocket.getInputStream())); DataOutputStream out = new DataOutputStream( connectionSocket.getOutputStream()); String inData = input.readLine(); String outData = inData.toUpperCase() + "\n"; out.writeBytes(outData); } catch (SocketException ignored) { } } } catch (IOException ioe) { ioe.printStackTrace(); throwable = ioe; } } public void stop() { works = false; try { testSocket.close(); } catch (IOException e) { e.printStackTrace(); } } public boolean isReady() { return ready; } public int getPort() { return port0; } public Throwable getThrowable() { return throwable; } } }
apache-2.0
cogitoboy/BroadleafCommerce
common/src/test/java/org/broadleafcommerce/common/extensibility/context/merge/handlers/SchemaLocationMergeTest.java
4366
/* * #%L * BroadleafCommerce Common Libraries * %% * Copyright (C) 2009 - 2014 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.common.extensibility.context.merge.handlers; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import org.apache.xerces.impl.xs.opti.DefaultNode; import org.junit.BeforeClass; import org.junit.Test; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import java.util.Set; /** * Tests for {@link SchemaLocationNodeValueMerge} * * @author Phillip Verheyden (phillipuniverse) */ public class SchemaLocationMergeTest { protected static SchemaLocationNodeValueMerge merge; @BeforeClass public static void setup() { merge = new SchemaLocationNodeValueMerge(); } @Test public void testReplacementRegex() { String val = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"; String replacedVal = merge.getSanitizedValue(val); assertEquals(replacedVal, "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"); } @Test public void testNodeAttributes() { Node node1 = new DummyNode(); node1.setNodeValue("http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" + "\nhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-8.4.xsd" + "\nhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-9.4.xsd" + "\nhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"); Node node2 = new DummyNode(); node2.setNodeValue("http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"); Set<String> mergedVals = merge.getMergedNodeValues(node1, node2); assertArrayEquals(new String[] {"http://www.springframework.org/schema/beans", "http://www.springframework.org/schema/beans/spring-beans.xsd", "http://www.springframework.org/schema/tx", "http://www.springframework.org/schema/tx/spring-tx.xsd"}, mergedVals.toArray()); } @Test public void testAddedAttributes() { Node node1 = new DummyNode(); node1.setNodeValue("http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"); Node node2 = new DummyNode(); node2.setNodeValue("http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"); Set<String> mergedVals = merge.getMergedNodeValues(node1, node2); assertArrayEquals(new String[] {"http://www.springframework.org/schema/beans", "http://www.springframework.org/schema/beans/spring-beans.xsd", "http://www.springframework.org/schema/tx", "http://www.springframework.org/schema/tx/spring-tx.xsd"}, mergedVals.toArray()); } public class DummyNode extends DefaultNode { protected String nodeValue; @Override public String getNodeValue() throws DOMException { return nodeValue; } @Override public void setNodeValue(String nodeValue) throws DOMException { this.nodeValue = nodeValue; } } }
apache-2.0
wskplho/jadx
jadx-samples/src/main/java/jadx/samples/TestConditions.java
1957
package jadx.samples; public class TestConditions extends AbstractTest { public int test1(int num) { boolean inRange = (num >= 59 && num <= 66); if (inRange) { num++; } return num; } public int test1a(int num) { boolean notInRange = (num < 59 || num > 66); if (notInRange) { num--; } return num; } public int test1b(int num) { boolean inc = (num >= 59 && num <= 66 && num != 62); if (inc) { num++; } return num; } public boolean test1c(int num) { return num == 4 || num == 6; } public boolean test2(int num) { if (num == 4 || num == 6) { return String.valueOf(num).equals("4"); } if (num == 5) { return true; } return this.toString().equals("a"); } public void test3(boolean a, boolean b) { if (a || b) { throw new RuntimeException(); } test1(0); } public void test4(int num) { if (num == 4 || num == 6 || num == 8 || num == 10) { accept("a"); } } public boolean test5(int num) { return num > 5 && (num < 10 || num == 7); } private boolean test6(boolean a, boolean b, boolean c) { return (a && b) || c; } public boolean accept(String name) { return name.startsWith("Test") && name.endsWith(".class") && !name.contains("$"); } @Override public boolean testRun() throws Exception { assertEquals(test1(50), 50); assertEquals(test1(60), 61); assertEquals(test1a(50), 49); assertEquals(test1a(60), 60); assertEquals(test1b(60), 61); assertEquals(test1b(62), 62); assertTrue(test1c(4)); assertFalse(test1c(5)); assertTrue(accept("Test.class")); test3(false, false); assertFalse(test5(4)); assertFalse(test5(11)); assertTrue(test5(6)); assertTrue(test5(7)); assertTrue(test5(8)); assertTrue(test6(true, true, false)); assertTrue(test6(false, false, true)); assertFalse(test6(true, false, false)); return true; } public static void main(String[] args) throws Exception { new TestConditions().testRun(); } }
apache-2.0
kaituo/sedge
trunk/contrib/zebra/src/java/org/apache/hadoop/zebra/mapreduce/ZebraSchema.java
1274
/** * 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.zebra.mapreduce; import org.apache.hadoop.zebra.schema.Schema; /** * A wrapper class for Schema. */ public class ZebraSchema { private String schemaStr = null; private ZebraSchema(String str) { String normalizedStr = Schema.normalize(str); schemaStr = normalizedStr; } public static ZebraSchema createZebraSchema(String str) { return new ZebraSchema(str); } public String toString() { return schemaStr; } }
mit
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java
126389
/* * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * <p>These classes are designed to be used while the * corresponding <code>LookAndFeel</code> class has been installed * (<code>UIManager.setLookAndFeel(new <i>XXX</i>LookAndFeel())</code>). * Using them while a different <code>LookAndFeel</code> is installed * may produce unexpected results, including exceptions. * Additionally, changing the <code>LookAndFeel</code> * maintained by the <code>UIManager</code> without updating the * corresponding <code>ComponentUI</code> of any * <code>JComponent</code>s may also produce unexpected results, * such as the wrong colors showing up, and is generally not * encouraged. * */ package com.sun.java.swing.plaf.windows; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.ImageFilter; import java.awt.image.ImageProducer; import java.awt.image.FilteredImageSource; import java.awt.image.RGBImageFilter; import javax.swing.plaf.*; import javax.swing.*; import javax.swing.plaf.basic.*; import javax.swing.border.*; import javax.swing.text.DefaultEditorKit; import java.awt.Font; import java.awt.Color; import java.awt.event.KeyEvent; import java.awt.event.ActionEvent; import java.security.AccessController; import sun.awt.SunToolkit; import sun.awt.OSInfo; import sun.awt.shell.ShellFolder; import sun.font.FontUtilities; import sun.security.action.GetPropertyAction; import sun.swing.DefaultLayoutStyle; import sun.swing.ImageIconUIResource; import sun.swing.SwingLazyValue; import sun.swing.SwingUtilities2; import sun.swing.StringUIClientPropertyKey; import static com.sun.java.swing.plaf.windows.TMSchema.*; import static com.sun.java.swing.plaf.windows.XPStyle.Skin; import com.sun.java.swing.plaf.windows.WindowsIconFactory.VistaMenuItemCheckIconFactory; /** * Implements the Windows95/98/NT/2000 Look and Feel. * UI classes not implemented specifically for Windows will * default to those implemented in Basic. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is appropriate * for short term storage or RMI between applications running the same * version of Swing. A future release of Swing will provide support for * long term persistence. * * @author unattributed */ public class WindowsLookAndFeel extends BasicLookAndFeel { /** * A client property that can be used with any JComponent that will end up * calling the LookAndFeel.getDisabledIcon method. This client property, * when set to Boolean.TRUE, will cause getDisabledIcon to use an * alternate algorithm for creating disabled icons to produce icons * that appear similar to the native Windows file chooser */ static final Object HI_RES_DISABLED_ICON_CLIENT_KEY = new StringUIClientPropertyKey( "WindowsLookAndFeel.generateHiResDisabledIcon"); private boolean updatePending = false; private boolean useSystemFontSettings = true; private boolean useSystemFontSizeSettings; // These properties are not used directly, but are kept as // private members to avoid being GC'd. private DesktopProperty themeActive, dllName, colorName, sizeName; private DesktopProperty aaSettings; private transient LayoutStyle style; /** * Base dialog units along the horizontal axis. */ private int baseUnitX; /** * Base dialog units along the vertical axis. */ private int baseUnitY; public String getName() { return "Windows"; } public String getDescription() { return "The Microsoft Windows Look and Feel"; } public String getID() { return "Windows"; } public boolean isNativeLookAndFeel() { return OSInfo.getOSType() == OSInfo.OSType.WINDOWS; } public boolean isSupportedLookAndFeel() { return isNativeLookAndFeel(); } public void initialize() { super.initialize(); // Set the flag which determines which version of Windows should // be rendered. This flag only need to be set once. // if version <= 4.0 then the classic LAF should be loaded. if (OSInfo.getWindowsVersion().compareTo(OSInfo.WINDOWS_95) <= 0) { isClassicWindows = true; } else { isClassicWindows = false; XPStyle.invalidateStyle(); } // Using the fonts set by the user can potentially cause // performance and compatibility issues, so allow this feature // to be switched off either at runtime or programmatically // String systemFonts = java.security.AccessController.doPrivileged( new GetPropertyAction("swing.useSystemFontSettings")); useSystemFontSettings = (systemFonts == null || Boolean.valueOf(systemFonts).booleanValue()); if (useSystemFontSettings) { Object value = UIManager.get("Application.useSystemFontSettings"); useSystemFontSettings = (value == null || Boolean.TRUE.equals(value)); } KeyboardFocusManager.getCurrentKeyboardFocusManager(). addKeyEventPostProcessor(WindowsRootPaneUI.altProcessor); } /** * Initialize the uiClassID to BasicComponentUI mapping. * The JComponent classes define their own uiClassID constants * (see AbstractComponent.getUIClassID). This table must * map those constants to a BasicComponentUI class of the * appropriate type. * * @see BasicLookAndFeel#getDefaults */ protected void initClassDefaults(UIDefaults table) { super.initClassDefaults(table); final String windowsPackageName = "com.sun.java.swing.plaf.windows."; Object[] uiDefaults = { "ButtonUI", windowsPackageName + "WindowsButtonUI", "CheckBoxUI", windowsPackageName + "WindowsCheckBoxUI", "CheckBoxMenuItemUI", windowsPackageName + "WindowsCheckBoxMenuItemUI", "LabelUI", windowsPackageName + "WindowsLabelUI", "RadioButtonUI", windowsPackageName + "WindowsRadioButtonUI", "RadioButtonMenuItemUI", windowsPackageName + "WindowsRadioButtonMenuItemUI", "ToggleButtonUI", windowsPackageName + "WindowsToggleButtonUI", "ProgressBarUI", windowsPackageName + "WindowsProgressBarUI", "SliderUI", windowsPackageName + "WindowsSliderUI", "SeparatorUI", windowsPackageName + "WindowsSeparatorUI", "SplitPaneUI", windowsPackageName + "WindowsSplitPaneUI", "SpinnerUI", windowsPackageName + "WindowsSpinnerUI", "TabbedPaneUI", windowsPackageName + "WindowsTabbedPaneUI", "TextAreaUI", windowsPackageName + "WindowsTextAreaUI", "TextFieldUI", windowsPackageName + "WindowsTextFieldUI", "PasswordFieldUI", windowsPackageName + "WindowsPasswordFieldUI", "TextPaneUI", windowsPackageName + "WindowsTextPaneUI", "EditorPaneUI", windowsPackageName + "WindowsEditorPaneUI", "TreeUI", windowsPackageName + "WindowsTreeUI", "ToolBarUI", windowsPackageName + "WindowsToolBarUI", "ToolBarSeparatorUI", windowsPackageName + "WindowsToolBarSeparatorUI", "ComboBoxUI", windowsPackageName + "WindowsComboBoxUI", "TableHeaderUI", windowsPackageName + "WindowsTableHeaderUI", "InternalFrameUI", windowsPackageName + "WindowsInternalFrameUI", "DesktopPaneUI", windowsPackageName + "WindowsDesktopPaneUI", "DesktopIconUI", windowsPackageName + "WindowsDesktopIconUI", "FileChooserUI", windowsPackageName + "WindowsFileChooserUI", "MenuUI", windowsPackageName + "WindowsMenuUI", "MenuItemUI", windowsPackageName + "WindowsMenuItemUI", "MenuBarUI", windowsPackageName + "WindowsMenuBarUI", "PopupMenuUI", windowsPackageName + "WindowsPopupMenuUI", "PopupMenuSeparatorUI", windowsPackageName + "WindowsPopupMenuSeparatorUI", "ScrollBarUI", windowsPackageName + "WindowsScrollBarUI", "RootPaneUI", windowsPackageName + "WindowsRootPaneUI" }; table.putDefaults(uiDefaults); } /** * Load the SystemColors into the defaults table. The keys * for SystemColor defaults are the same as the names of * the public fields in SystemColor. If the table is being * created on a native Windows platform we use the SystemColor * values, otherwise we create color objects whose values match * the defaults Windows95 colors. */ protected void initSystemColorDefaults(UIDefaults table) { String[] defaultSystemColors = { "desktop", "#005C5C", /* Color of the desktop background */ "activeCaption", "#000080", /* Color for captions (title bars) when they are active. */ "activeCaptionText", "#FFFFFF", /* Text color for text in captions (title bars). */ "activeCaptionBorder", "#C0C0C0", /* Border color for caption (title bar) window borders. */ "inactiveCaption", "#808080", /* Color for captions (title bars) when not active. */ "inactiveCaptionText", "#C0C0C0", /* Text color for text in inactive captions (title bars). */ "inactiveCaptionBorder", "#C0C0C0", /* Border color for inactive caption (title bar) window borders. */ "window", "#FFFFFF", /* Default color for the interior of windows */ "windowBorder", "#000000", /* ??? */ "windowText", "#000000", /* ??? */ "menu", "#C0C0C0", /* Background color for menus */ "menuPressedItemB", "#000080", /* LightShadow of menubutton highlight */ "menuPressedItemF", "#FFFFFF", /* Default color for foreground "text" in menu item */ "menuText", "#000000", /* Text color for menus */ "text", "#C0C0C0", /* Text background color */ "textText", "#000000", /* Text foreground color */ "textHighlight", "#000080", /* Text background color when selected */ "textHighlightText", "#FFFFFF", /* Text color when selected */ "textInactiveText", "#808080", /* Text color when disabled */ "control", "#C0C0C0", /* Default color for controls (buttons, sliders, etc) */ "controlText", "#000000", /* Default color for text in controls */ "controlHighlight", "#C0C0C0", /*"controlHighlight", "#E0E0E0",*/ /* Specular highlight (opposite of the shadow) */ "controlLtHighlight", "#FFFFFF", /* Highlight color for controls */ "controlShadow", "#808080", /* Shadow color for controls */ "controlDkShadow", "#000000", /* Dark shadow color for controls */ "scrollbar", "#E0E0E0", /* Scrollbar background (usually the "track") */ "info", "#FFFFE1", /* ??? */ "infoText", "#000000" /* ??? */ }; loadSystemColors(table, defaultSystemColors, isNativeLookAndFeel()); } /** * Initialize the defaults table with the name of the ResourceBundle * used for getting localized defaults. */ private void initResourceBundle(UIDefaults table) { table.addResourceBundle( "com.sun.java.swing.plaf.windows.resources.windows" ); } // XXX - there are probably a lot of redundant values that could be removed. // ie. Take a look at RadioButtonBorder, etc... protected void initComponentDefaults(UIDefaults table) { super.initComponentDefaults( table ); initResourceBundle(table); // *** Shared Fonts Integer twelve = Integer.valueOf(12); Integer fontPlain = Integer.valueOf(Font.PLAIN); Integer fontBold = Integer.valueOf(Font.BOLD); Object dialogPlain12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", null, new Object[] {Font.DIALOG, fontPlain, twelve}); Object sansSerifPlain12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", null, new Object[] {Font.SANS_SERIF, fontPlain, twelve}); Object monospacedPlain12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", null, new Object[] {Font.MONOSPACED, fontPlain, twelve}); Object dialogBold12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", null, new Object[] {Font.DIALOG, fontBold, twelve}); // *** Colors // XXX - some of these doens't seem to be used ColorUIResource red = new ColorUIResource(Color.red); ColorUIResource black = new ColorUIResource(Color.black); ColorUIResource white = new ColorUIResource(Color.white); ColorUIResource gray = new ColorUIResource(Color.gray); ColorUIResource darkGray = new ColorUIResource(Color.darkGray); ColorUIResource scrollBarTrackHighlight = darkGray; // Set the flag which determines which version of Windows should // be rendered. This flag only need to be set once. // if version <= 4.0 then the classic LAF should be loaded. isClassicWindows = OSInfo.getWindowsVersion().compareTo(OSInfo.WINDOWS_95) <= 0; // *** Tree Object treeExpandedIcon = WindowsTreeUI.ExpandedIcon.createExpandedIcon(); Object treeCollapsedIcon = WindowsTreeUI.CollapsedIcon.createCollapsedIcon(); // *** Text Object fieldInputMap = new UIDefaults.LazyInputMap(new Object[] { "control C", DefaultEditorKit.copyAction, "control V", DefaultEditorKit.pasteAction, "control X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "control A", DefaultEditorKit.selectAllAction, "control BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "control LEFT", DefaultEditorKit.previousWordAction, "control RIGHT", DefaultEditorKit.nextWordAction, "control shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "control shift RIGHT", DefaultEditorKit.selectionNextWordAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/ }); Object passwordInputMap = new UIDefaults.LazyInputMap(new Object[] { "control C", DefaultEditorKit.copyAction, "control V", DefaultEditorKit.pasteAction, "control X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "control A", DefaultEditorKit.selectAllAction, "control BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "control LEFT", DefaultEditorKit.beginLineAction, "control RIGHT", DefaultEditorKit.endLineAction, "control shift LEFT", DefaultEditorKit.selectionBeginLineAction, "control shift RIGHT", DefaultEditorKit.selectionEndLineAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/ }); Object multilineInputMap = new UIDefaults.LazyInputMap(new Object[] { "control C", DefaultEditorKit.copyAction, "control V", DefaultEditorKit.pasteAction, "control X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "control LEFT", DefaultEditorKit.previousWordAction, "control RIGHT", DefaultEditorKit.nextWordAction, "control shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "control shift RIGHT", DefaultEditorKit.selectionNextWordAction, "control A", DefaultEditorKit.selectAllAction, "control BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "control HOME", DefaultEditorKit.beginAction, "control END", DefaultEditorKit.endAction, "control shift HOME", DefaultEditorKit.selectionBeginAction, "control shift END", DefaultEditorKit.selectionEndAction, "UP", DefaultEditorKit.upAction, "DOWN", DefaultEditorKit.downAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "PAGE_UP", DefaultEditorKit.pageUpAction, "PAGE_DOWN", DefaultEditorKit.pageDownAction, "shift PAGE_UP", "selection-page-up", "shift PAGE_DOWN", "selection-page-down", "ctrl shift PAGE_UP", "selection-page-left", "ctrl shift PAGE_DOWN", "selection-page-right", "shift UP", DefaultEditorKit.selectionUpAction, "shift DOWN", DefaultEditorKit.selectionDownAction, "ENTER", DefaultEditorKit.insertBreakAction, "TAB", DefaultEditorKit.insertTabAction, "control T", "next-link-action", "control shift T", "previous-link-action", "control SPACE", "activate-link-action", "control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/ }); Object menuItemAcceleratorDelimiter = "+"; Object ControlBackgroundColor = new DesktopProperty( "win.3d.backgroundColor", table.get("control")); Object ControlLightColor = new DesktopProperty( "win.3d.lightColor", table.get("controlHighlight")); Object ControlHighlightColor = new DesktopProperty( "win.3d.highlightColor", table.get("controlLtHighlight")); Object ControlShadowColor = new DesktopProperty( "win.3d.shadowColor", table.get("controlShadow")); Object ControlDarkShadowColor = new DesktopProperty( "win.3d.darkShadowColor", table.get("controlDkShadow")); Object ControlTextColor = new DesktopProperty( "win.button.textColor", table.get("controlText")); Object MenuBackgroundColor = new DesktopProperty( "win.menu.backgroundColor", table.get("menu")); Object MenuBarBackgroundColor = new DesktopProperty( "win.menubar.backgroundColor", table.get("menu")); Object MenuTextColor = new DesktopProperty( "win.menu.textColor", table.get("menuText")); Object SelectionBackgroundColor = new DesktopProperty( "win.item.highlightColor", table.get("textHighlight")); Object SelectionTextColor = new DesktopProperty( "win.item.highlightTextColor", table.get("textHighlightText")); Object WindowBackgroundColor = new DesktopProperty( "win.frame.backgroundColor", table.get("window")); Object WindowTextColor = new DesktopProperty( "win.frame.textColor", table.get("windowText")); Object WindowBorderWidth = new DesktopProperty( "win.frame.sizingBorderWidth", Integer.valueOf(1)); Object TitlePaneHeight = new DesktopProperty( "win.frame.captionHeight", Integer.valueOf(18)); Object TitleButtonWidth = new DesktopProperty( "win.frame.captionButtonWidth", Integer.valueOf(16)); Object TitleButtonHeight = new DesktopProperty( "win.frame.captionButtonHeight", Integer.valueOf(16)); Object InactiveTextColor = new DesktopProperty( "win.text.grayedTextColor", table.get("textInactiveText")); Object ScrollbarBackgroundColor = new DesktopProperty( "win.scrollbar.backgroundColor", table.get("scrollbar")); Object TextBackground = new XPColorValue(Part.EP_EDIT, null, Prop.FILLCOLOR, WindowBackgroundColor); //The following four lines were commented out as part of bug 4991597 //This code *is* correct, however it differs from WindowsXP and is, apparently //a Windows XP bug. Until Windows fixes this bug, we shall also exhibit the same //behavior //Object ReadOnlyTextBackground = new XPColorValue(Part.EP_EDITTEXT, State.READONLY, Prop.FILLCOLOR, // ControlBackgroundColor); //Object DisabledTextBackground = new XPColorValue(Part.EP_EDITTEXT, State.DISABLED, Prop.FILLCOLOR, // ControlBackgroundColor); Object ReadOnlyTextBackground = ControlBackgroundColor; Object DisabledTextBackground = ControlBackgroundColor; Object MenuFont = dialogPlain12; Object FixedControlFont = monospacedPlain12; Object ControlFont = dialogPlain12; Object MessageFont = dialogPlain12; Object WindowFont = dialogBold12; Object ToolTipFont = sansSerifPlain12; Object IconFont = ControlFont; Object scrollBarWidth = new DesktopProperty("win.scrollbar.width", Integer.valueOf(16)); Object menuBarHeight = new DesktopProperty("win.menu.height", null); Object hotTrackingOn = new DesktopProperty("win.item.hotTrackingOn", true); Object showMnemonics = new DesktopProperty("win.menu.keyboardCuesOn", Boolean.TRUE); if (useSystemFontSettings) { MenuFont = getDesktopFontValue("win.menu.font", MenuFont); FixedControlFont = getDesktopFontValue("win.ansiFixed.font", FixedControlFont); ControlFont = getDesktopFontValue("win.defaultGUI.font", ControlFont); MessageFont = getDesktopFontValue("win.messagebox.font", MessageFont); WindowFont = getDesktopFontValue("win.frame.captionFont", WindowFont); IconFont = getDesktopFontValue("win.icon.font", IconFont); ToolTipFont = getDesktopFontValue("win.tooltip.font", ToolTipFont); /* Put the desktop AA settings in the defaults. * JComponent.setUI() retrieves this and makes it available * as a client property on the JComponent. Use the same key name * for both client property and UIDefaults. * Also need to set up listeners for changes in these settings. */ Object aaTextInfo = SwingUtilities2.AATextInfo.getAATextInfo(true); table.put(SwingUtilities2.AA_TEXT_PROPERTY_KEY, aaTextInfo); this.aaSettings = new FontDesktopProperty(SunToolkit.DESKTOPFONTHINTS); } if (useSystemFontSizeSettings) { MenuFont = new WindowsFontSizeProperty("win.menu.font.height", Font.DIALOG, Font.PLAIN, 12); FixedControlFont = new WindowsFontSizeProperty("win.ansiFixed.font.height", Font.MONOSPACED, Font.PLAIN, 12); ControlFont = new WindowsFontSizeProperty("win.defaultGUI.font.height", Font.DIALOG, Font.PLAIN, 12); MessageFont = new WindowsFontSizeProperty("win.messagebox.font.height", Font.DIALOG, Font.PLAIN, 12); WindowFont = new WindowsFontSizeProperty("win.frame.captionFont.height", Font.DIALOG, Font.BOLD, 12); ToolTipFont = new WindowsFontSizeProperty("win.tooltip.font.height", Font.SANS_SERIF, Font.PLAIN, 12); IconFont = new WindowsFontSizeProperty("win.icon.font.height", Font.DIALOG, Font.PLAIN, 12); } if (!(this instanceof WindowsClassicLookAndFeel) && (OSInfo.getOSType() == OSInfo.OSType.WINDOWS && OSInfo.getWindowsVersion().compareTo(OSInfo.WINDOWS_XP) >= 0) && AccessController.doPrivileged(new GetPropertyAction("swing.noxp")) == null) { // These desktop properties are not used directly, but are needed to // trigger realoading of UI's. this.themeActive = new TriggerDesktopProperty("win.xpstyle.themeActive"); this.dllName = new TriggerDesktopProperty("win.xpstyle.dllName"); this.colorName = new TriggerDesktopProperty("win.xpstyle.colorName"); this.sizeName = new TriggerDesktopProperty("win.xpstyle.sizeName"); } Object[] defaults = { // *** Auditory Feedback // this key defines which of the various cues to render // Overridden from BasicL&F. This L&F should play all sounds // all the time. The infrastructure decides what to play. // This is disabled until sound bugs can be resolved. "AuditoryCues.playList", null, // table.get("AuditoryCues.cueList"), "Application.useSystemFontSettings", Boolean.valueOf(useSystemFontSettings), "TextField.focusInputMap", fieldInputMap, "PasswordField.focusInputMap", passwordInputMap, "TextArea.focusInputMap", multilineInputMap, "TextPane.focusInputMap", multilineInputMap, "EditorPane.focusInputMap", multilineInputMap, // Buttons "Button.font", ControlFont, "Button.background", ControlBackgroundColor, // Button.foreground, Button.shadow, Button.darkShadow, // Button.disabledForground, and Button.disabledShadow are only // used for Windows Classic. Windows XP will use colors // from the current visual style. "Button.foreground", ControlTextColor, "Button.shadow", ControlShadowColor, "Button.darkShadow", ControlDarkShadowColor, "Button.light", ControlLightColor, "Button.highlight", ControlHighlightColor, "Button.disabledForeground", InactiveTextColor, "Button.disabledShadow", ControlHighlightColor, "Button.focus", black, "Button.dashedRectGapX", new XPValue(Integer.valueOf(3), Integer.valueOf(5)), "Button.dashedRectGapY", new XPValue(Integer.valueOf(3), Integer.valueOf(4)), "Button.dashedRectGapWidth", new XPValue(Integer.valueOf(6), Integer.valueOf(10)), "Button.dashedRectGapHeight", new XPValue(Integer.valueOf(6), Integer.valueOf(8)), "Button.textShiftOffset", new XPValue(Integer.valueOf(0), Integer.valueOf(1)), // W2K keyboard navigation hidding. "Button.showMnemonics", showMnemonics, "Button.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), "CheckBox.font", ControlFont, "CheckBox.interiorBackground", WindowBackgroundColor, "CheckBox.background", ControlBackgroundColor, "CheckBox.foreground", WindowTextColor, "CheckBox.shadow", ControlShadowColor, "CheckBox.darkShadow", ControlDarkShadowColor, "CheckBox.light", ControlLightColor, "CheckBox.highlight", ControlHighlightColor, "CheckBox.focus", black, "CheckBox.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), // margin is 2 all the way around, BasicBorders.RadioButtonBorder // (checkbox uses RadioButtonBorder) is 2 all the way around too. "CheckBox.totalInsets", new Insets(4, 4, 4, 4), "CheckBoxMenuItem.font", MenuFont, "CheckBoxMenuItem.background", MenuBackgroundColor, "CheckBoxMenuItem.foreground", MenuTextColor, "CheckBoxMenuItem.selectionForeground", SelectionTextColor, "CheckBoxMenuItem.selectionBackground", SelectionBackgroundColor, "CheckBoxMenuItem.acceleratorForeground", MenuTextColor, "CheckBoxMenuItem.acceleratorSelectionForeground", SelectionTextColor, "CheckBoxMenuItem.commandSound", "win.sound.menuCommand", "ComboBox.font", ControlFont, "ComboBox.background", WindowBackgroundColor, "ComboBox.foreground", WindowTextColor, "ComboBox.buttonBackground", ControlBackgroundColor, "ComboBox.buttonShadow", ControlShadowColor, "ComboBox.buttonDarkShadow", ControlDarkShadowColor, "ComboBox.buttonHighlight", ControlHighlightColor, "ComboBox.selectionBackground", SelectionBackgroundColor, "ComboBox.selectionForeground", SelectionTextColor, "ComboBox.editorBorder", new XPValue(new EmptyBorder(1,2,1,1), new EmptyBorder(1,4,1,4)), "ComboBox.disabledBackground", new XPColorValue(Part.CP_COMBOBOX, State.DISABLED, Prop.FILLCOLOR, DisabledTextBackground), "ComboBox.disabledForeground", new XPColorValue(Part.CP_COMBOBOX, State.DISABLED, Prop.TEXTCOLOR, InactiveTextColor), "ComboBox.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "hidePopup", "PAGE_UP", "pageUpPassThrough", "PAGE_DOWN", "pageDownPassThrough", "HOME", "homePassThrough", "END", "endPassThrough", "DOWN", "selectNext2", "KP_DOWN", "selectNext2", "UP", "selectPrevious2", "KP_UP", "selectPrevious2", "ENTER", "enterPressed", "F4", "togglePopup", "alt DOWN", "togglePopup", "alt KP_DOWN", "togglePopup", "alt UP", "togglePopup", "alt KP_UP", "togglePopup" }), // DeskTop. "Desktop.background", new DesktopProperty( "win.desktop.backgroundColor", table.get("desktop")), "Desktop.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl F5", "restore", "ctrl F4", "close", "ctrl F7", "move", "ctrl F8", "resize", "RIGHT", "right", "KP_RIGHT", "right", "LEFT", "left", "KP_LEFT", "left", "UP", "up", "KP_UP", "up", "DOWN", "down", "KP_DOWN", "down", "ESCAPE", "escape", "ctrl F9", "minimize", "ctrl F10", "maximize", "ctrl F6", "selectNextFrame", "ctrl TAB", "selectNextFrame", "ctrl alt F6", "selectNextFrame", "shift ctrl alt F6", "selectPreviousFrame", "ctrl F12", "navigateNext", "shift ctrl F12", "navigatePrevious" }), // DesktopIcon "DesktopIcon.width", Integer.valueOf(160), "EditorPane.font", ControlFont, "EditorPane.background", WindowBackgroundColor, "EditorPane.foreground", WindowTextColor, "EditorPane.selectionBackground", SelectionBackgroundColor, "EditorPane.selectionForeground", SelectionTextColor, "EditorPane.caretForeground", WindowTextColor, "EditorPane.inactiveForeground", InactiveTextColor, "EditorPane.inactiveBackground", WindowBackgroundColor, "EditorPane.disabledBackground", DisabledTextBackground, "FileChooser.homeFolderIcon", new LazyWindowsIcon(null, "icons/HomeFolder.gif"), "FileChooser.listFont", IconFont, "FileChooser.listViewBackground", new XPColorValue(Part.LVP_LISTVIEW, null, Prop.FILLCOLOR, WindowBackgroundColor), "FileChooser.listViewBorder", new XPBorderValue(Part.LVP_LISTVIEW, new SwingLazyValue( "javax.swing.plaf.BorderUIResource", "getLoweredBevelBorderUIResource")), "FileChooser.listViewIcon", new LazyWindowsIcon("fileChooserIcon ListView", "icons/ListView.gif"), "FileChooser.listViewWindowsStyle", Boolean.TRUE, "FileChooser.detailsViewIcon", new LazyWindowsIcon("fileChooserIcon DetailsView", "icons/DetailsView.gif"), "FileChooser.viewMenuIcon", new LazyWindowsIcon("fileChooserIcon ViewMenu", "icons/ListView.gif"), "FileChooser.upFolderIcon", new LazyWindowsIcon("fileChooserIcon UpFolder", "icons/UpFolder.gif"), "FileChooser.newFolderIcon", new LazyWindowsIcon("fileChooserIcon NewFolder", "icons/NewFolder.gif"), "FileChooser.useSystemExtensionHiding", Boolean.TRUE, "FileChooser.lookInLabelMnemonic", Integer.valueOf(KeyEvent.VK_I), "FileChooser.fileNameLabelMnemonic", Integer.valueOf(KeyEvent.VK_N), "FileChooser.filesOfTypeLabelMnemonic", Integer.valueOf(KeyEvent.VK_T), "FileChooser.usesSingleFilePane", Boolean.TRUE, "FileChooser.noPlacesBar", new DesktopProperty("win.comdlg.noPlacesBar", Boolean.FALSE), "FileChooser.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "cancelSelection", "F2", "editFileName", "F5", "refresh", "BACK_SPACE", "Go Up" }), "FileView.directoryIcon", SwingUtilities2.makeIcon(getClass(), WindowsLookAndFeel.class, "icons/Directory.gif"), "FileView.fileIcon", SwingUtilities2.makeIcon(getClass(), WindowsLookAndFeel.class, "icons/File.gif"), "FileView.computerIcon", SwingUtilities2.makeIcon(getClass(), WindowsLookAndFeel.class, "icons/Computer.gif"), "FileView.hardDriveIcon", SwingUtilities2.makeIcon(getClass(), WindowsLookAndFeel.class, "icons/HardDrive.gif"), "FileView.floppyDriveIcon", SwingUtilities2.makeIcon(getClass(), WindowsLookAndFeel.class, "icons/FloppyDrive.gif"), "FormattedTextField.font", ControlFont, "InternalFrame.titleFont", WindowFont, "InternalFrame.titlePaneHeight", TitlePaneHeight, "InternalFrame.titleButtonWidth", TitleButtonWidth, "InternalFrame.titleButtonHeight", TitleButtonHeight, "InternalFrame.titleButtonToolTipsOn", hotTrackingOn, "InternalFrame.borderColor", ControlBackgroundColor, "InternalFrame.borderShadow", ControlShadowColor, "InternalFrame.borderDarkShadow", ControlDarkShadowColor, "InternalFrame.borderHighlight", ControlHighlightColor, "InternalFrame.borderLight", ControlLightColor, "InternalFrame.borderWidth", WindowBorderWidth, "InternalFrame.minimizeIconBackground", ControlBackgroundColor, "InternalFrame.resizeIconHighlight", ControlLightColor, "InternalFrame.resizeIconShadow", ControlShadowColor, "InternalFrame.activeBorderColor", new DesktopProperty( "win.frame.activeBorderColor", table.get("windowBorder")), "InternalFrame.inactiveBorderColor", new DesktopProperty( "win.frame.inactiveBorderColor", table.get("windowBorder")), "InternalFrame.activeTitleBackground", new DesktopProperty( "win.frame.activeCaptionColor", table.get("activeCaption")), "InternalFrame.activeTitleGradient", new DesktopProperty( "win.frame.activeCaptionGradientColor", table.get("activeCaption")), "InternalFrame.activeTitleForeground", new DesktopProperty( "win.frame.captionTextColor", table.get("activeCaptionText")), "InternalFrame.inactiveTitleBackground", new DesktopProperty( "win.frame.inactiveCaptionColor", table.get("inactiveCaption")), "InternalFrame.inactiveTitleGradient", new DesktopProperty( "win.frame.inactiveCaptionGradientColor", table.get("inactiveCaption")), "InternalFrame.inactiveTitleForeground", new DesktopProperty( "win.frame.inactiveCaptionTextColor", table.get("inactiveCaptionText")), "InternalFrame.maximizeIcon", WindowsIconFactory.createFrameMaximizeIcon(), "InternalFrame.minimizeIcon", WindowsIconFactory.createFrameMinimizeIcon(), "InternalFrame.iconifyIcon", WindowsIconFactory.createFrameIconifyIcon(), "InternalFrame.closeIcon", WindowsIconFactory.createFrameCloseIcon(), "InternalFrame.icon", new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsInternalFrameTitlePane$ScalableIconUIResource", // The constructor takes one arg: an array of UIDefaults.LazyValue // representing the icons new Object[][] { { SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/JavaCup16.png"), SwingUtilities2.makeIcon(getClass(), WindowsLookAndFeel.class, "icons/JavaCup32.png") } }), // Internal Frame Auditory Cue Mappings "InternalFrame.closeSound", "win.sound.close", "InternalFrame.maximizeSound", "win.sound.maximize", "InternalFrame.minimizeSound", "win.sound.minimize", "InternalFrame.restoreDownSound", "win.sound.restoreDown", "InternalFrame.restoreUpSound", "win.sound.restoreUp", "InternalFrame.windowBindings", new Object[] { "shift ESCAPE", "showSystemMenu", "ctrl SPACE", "showSystemMenu", "ESCAPE", "hideSystemMenu"}, // Label "Label.font", ControlFont, "Label.background", ControlBackgroundColor, "Label.foreground", WindowTextColor, "Label.disabledForeground", InactiveTextColor, "Label.disabledShadow", ControlHighlightColor, // List. "List.font", ControlFont, "List.background", WindowBackgroundColor, "List.foreground", WindowTextColor, "List.selectionBackground", SelectionBackgroundColor, "List.selectionForeground", SelectionTextColor, "List.lockToPositionOnScroll", Boolean.TRUE, "List.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "HOME", "selectFirstRow", "shift HOME", "selectFirstRowExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRowChangeLead", "END", "selectLastRow", "shift END", "selectLastRowExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRowChangeLead", "PAGE_UP", "scrollUp", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDown", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), // PopupMenu "PopupMenu.font", MenuFont, "PopupMenu.background", MenuBackgroundColor, "PopupMenu.foreground", MenuTextColor, "PopupMenu.popupSound", "win.sound.menuPopup", "PopupMenu.consumeEventOnClose", Boolean.TRUE, // Menus "Menu.font", MenuFont, "Menu.foreground", MenuTextColor, "Menu.background", MenuBackgroundColor, "Menu.useMenuBarBackgroundForTopLevel", Boolean.TRUE, "Menu.selectionForeground", SelectionTextColor, "Menu.selectionBackground", SelectionBackgroundColor, "Menu.acceleratorForeground", MenuTextColor, "Menu.acceleratorSelectionForeground", SelectionTextColor, "Menu.menuPopupOffsetX", Integer.valueOf(0), "Menu.menuPopupOffsetY", Integer.valueOf(0), "Menu.submenuPopupOffsetX", Integer.valueOf(-4), "Menu.submenuPopupOffsetY", Integer.valueOf(-3), "Menu.crossMenuMnemonic", Boolean.FALSE, "Menu.preserveTopLevelSelection", Boolean.TRUE, // MenuBar. "MenuBar.font", MenuFont, "MenuBar.background", new XPValue(MenuBarBackgroundColor, MenuBackgroundColor), "MenuBar.foreground", MenuTextColor, "MenuBar.shadow", ControlShadowColor, "MenuBar.highlight", ControlHighlightColor, "MenuBar.height", menuBarHeight, "MenuBar.rolloverEnabled", hotTrackingOn, "MenuBar.windowBindings", new Object[] { "F10", "takeFocus" }, "MenuItem.font", MenuFont, "MenuItem.acceleratorFont", MenuFont, "MenuItem.foreground", MenuTextColor, "MenuItem.background", MenuBackgroundColor, "MenuItem.selectionForeground", SelectionTextColor, "MenuItem.selectionBackground", SelectionBackgroundColor, "MenuItem.disabledForeground", InactiveTextColor, "MenuItem.acceleratorForeground", MenuTextColor, "MenuItem.acceleratorSelectionForeground", SelectionTextColor, "MenuItem.acceleratorDelimiter", menuItemAcceleratorDelimiter, // Menu Item Auditory Cue Mapping "MenuItem.commandSound", "win.sound.menuCommand", // indicates that keyboard navigation won't skip disabled menu items "MenuItem.disabledAreNavigable", Boolean.TRUE, "RadioButton.font", ControlFont, "RadioButton.interiorBackground", WindowBackgroundColor, "RadioButton.background", ControlBackgroundColor, "RadioButton.foreground", WindowTextColor, "RadioButton.shadow", ControlShadowColor, "RadioButton.darkShadow", ControlDarkShadowColor, "RadioButton.light", ControlLightColor, "RadioButton.highlight", ControlHighlightColor, "RadioButton.focus", black, "RadioButton.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), // margin is 2 all the way around, BasicBorders.RadioButtonBorder // is 2 all the way around too. "RadioButton.totalInsets", new Insets(4, 4, 4, 4), "RadioButtonMenuItem.font", MenuFont, "RadioButtonMenuItem.foreground", MenuTextColor, "RadioButtonMenuItem.background", MenuBackgroundColor, "RadioButtonMenuItem.selectionForeground", SelectionTextColor, "RadioButtonMenuItem.selectionBackground", SelectionBackgroundColor, "RadioButtonMenuItem.disabledForeground", InactiveTextColor, "RadioButtonMenuItem.acceleratorForeground", MenuTextColor, "RadioButtonMenuItem.acceleratorSelectionForeground", SelectionTextColor, "RadioButtonMenuItem.commandSound", "win.sound.menuCommand", // OptionPane. "OptionPane.font", MessageFont, "OptionPane.messageFont", MessageFont, "OptionPane.buttonFont", MessageFont, "OptionPane.background", ControlBackgroundColor, "OptionPane.foreground", WindowTextColor, "OptionPane.buttonMinimumWidth", new XPDLUValue(50, 50, SwingConstants.EAST), "OptionPane.messageForeground", ControlTextColor, "OptionPane.errorIcon", new LazyWindowsIcon("optionPaneIcon Error", "icons/Error.gif"), "OptionPane.informationIcon", new LazyWindowsIcon("optionPaneIcon Information", "icons/Inform.gif"), "OptionPane.questionIcon", new LazyWindowsIcon("optionPaneIcon Question", "icons/Question.gif"), "OptionPane.warningIcon", new LazyWindowsIcon("optionPaneIcon Warning", "icons/Warn.gif"), "OptionPane.windowBindings", new Object[] { "ESCAPE", "close" }, // Option Pane Auditory Cue Mappings "OptionPane.errorSound", "win.sound.hand", // Error "OptionPane.informationSound", "win.sound.asterisk", // Info Plain "OptionPane.questionSound", "win.sound.question", // Question "OptionPane.warningSound", "win.sound.exclamation", // Warning "FormattedTextField.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.previousWordAction, "ctrl KP_LEFT", DefaultEditorKit.previousWordAction, "ctrl RIGHT", DefaultEditorKit.nextWordAction, "ctrl KP_RIGHT", DefaultEditorKit.nextWordAction, "ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "ctrl BACK_SLASH", "unselect", "control shift O", "toggle-componentOrientation", "ESCAPE", "reset-field-edit", "UP", "increment", "KP_UP", "increment", "DOWN", "decrement", "KP_DOWN", "decrement", }), "FormattedTextField.inactiveBackground", ReadOnlyTextBackground, "FormattedTextField.disabledBackground", DisabledTextBackground, // *** Panel "Panel.font", ControlFont, "Panel.background", ControlBackgroundColor, "Panel.foreground", WindowTextColor, // *** PasswordField "PasswordField.font", ControlFont, "PasswordField.background", TextBackground, "PasswordField.foreground", WindowTextColor, "PasswordField.inactiveForeground", InactiveTextColor, // for disabled "PasswordField.inactiveBackground", ReadOnlyTextBackground, // for readonly "PasswordField.disabledBackground", DisabledTextBackground, // for disabled "PasswordField.selectionBackground", SelectionBackgroundColor, "PasswordField.selectionForeground", SelectionTextColor, "PasswordField.caretForeground",WindowTextColor, "PasswordField.echoChar", new XPValue(new Character((char)0x25CF), new Character('*')), // *** ProgressBar "ProgressBar.font", ControlFont, "ProgressBar.foreground", SelectionBackgroundColor, "ProgressBar.background", ControlBackgroundColor, "ProgressBar.shadow", ControlShadowColor, "ProgressBar.highlight", ControlHighlightColor, "ProgressBar.selectionForeground", ControlBackgroundColor, "ProgressBar.selectionBackground", SelectionBackgroundColor, "ProgressBar.cellLength", Integer.valueOf(7), "ProgressBar.cellSpacing", Integer.valueOf(2), "ProgressBar.indeterminateInsets", new Insets(3, 3, 3, 3), // *** RootPane. // These bindings are only enabled when there is a default // button set on the rootpane. "RootPane.defaultButtonWindowKeyBindings", new Object[] { "ENTER", "press", "released ENTER", "release", "ctrl ENTER", "press", "ctrl released ENTER", "release" }, // *** ScrollBar. "ScrollBar.background", ScrollbarBackgroundColor, "ScrollBar.foreground", ControlBackgroundColor, "ScrollBar.track", white, "ScrollBar.trackForeground", ScrollbarBackgroundColor, "ScrollBar.trackHighlight", black, "ScrollBar.trackHighlightForeground", scrollBarTrackHighlight, "ScrollBar.thumb", ControlBackgroundColor, "ScrollBar.thumbHighlight", ControlHighlightColor, "ScrollBar.thumbDarkShadow", ControlDarkShadowColor, "ScrollBar.thumbShadow", ControlShadowColor, "ScrollBar.width", scrollBarWidth, "ScrollBar.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "positiveUnitIncrement", "KP_RIGHT", "positiveUnitIncrement", "DOWN", "positiveUnitIncrement", "KP_DOWN", "positiveUnitIncrement", "PAGE_DOWN", "positiveBlockIncrement", "ctrl PAGE_DOWN", "positiveBlockIncrement", "LEFT", "negativeUnitIncrement", "KP_LEFT", "negativeUnitIncrement", "UP", "negativeUnitIncrement", "KP_UP", "negativeUnitIncrement", "PAGE_UP", "negativeBlockIncrement", "ctrl PAGE_UP", "negativeBlockIncrement", "HOME", "minScroll", "END", "maxScroll" }), // *** ScrollPane. "ScrollPane.font", ControlFont, "ScrollPane.background", ControlBackgroundColor, "ScrollPane.foreground", ControlTextColor, "ScrollPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "unitScrollRight", "KP_RIGHT", "unitScrollRight", "DOWN", "unitScrollDown", "KP_DOWN", "unitScrollDown", "LEFT", "unitScrollLeft", "KP_LEFT", "unitScrollLeft", "UP", "unitScrollUp", "KP_UP", "unitScrollUp", "PAGE_UP", "scrollUp", "PAGE_DOWN", "scrollDown", "ctrl PAGE_UP", "scrollLeft", "ctrl PAGE_DOWN", "scrollRight", "ctrl HOME", "scrollHome", "ctrl END", "scrollEnd" }), // *** Separator "Separator.background", ControlHighlightColor, "Separator.foreground", ControlShadowColor, // *** Slider. "Slider.font", ControlFont, "Slider.foreground", ControlBackgroundColor, "Slider.background", ControlBackgroundColor, "Slider.highlight", ControlHighlightColor, "Slider.shadow", ControlShadowColor, "Slider.focus", ControlDarkShadowColor, "Slider.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "positiveUnitIncrement", "KP_RIGHT", "positiveUnitIncrement", "DOWN", "negativeUnitIncrement", "KP_DOWN", "negativeUnitIncrement", "PAGE_DOWN", "negativeBlockIncrement", "LEFT", "negativeUnitIncrement", "KP_LEFT", "negativeUnitIncrement", "UP", "positiveUnitIncrement", "KP_UP", "positiveUnitIncrement", "PAGE_UP", "positiveBlockIncrement", "HOME", "minScroll", "END", "maxScroll" }), // Spinner "Spinner.font", ControlFont, "Spinner.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "increment", "KP_UP", "increment", "DOWN", "decrement", "KP_DOWN", "decrement", }), // *** SplitPane "SplitPane.background", ControlBackgroundColor, "SplitPane.highlight", ControlHighlightColor, "SplitPane.shadow", ControlShadowColor, "SplitPane.darkShadow", ControlDarkShadowColor, "SplitPane.dividerSize", Integer.valueOf(5), "SplitPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "negativeIncrement", "DOWN", "positiveIncrement", "LEFT", "negativeIncrement", "RIGHT", "positiveIncrement", "KP_UP", "negativeIncrement", "KP_DOWN", "positiveIncrement", "KP_LEFT", "negativeIncrement", "KP_RIGHT", "positiveIncrement", "HOME", "selectMin", "END", "selectMax", "F8", "startResize", "F6", "toggleFocus", "ctrl TAB", "focusOutForward", "ctrl shift TAB", "focusOutBackward" }), // *** TabbedPane "TabbedPane.tabsOverlapBorder", new XPValue(Boolean.TRUE, Boolean.FALSE), "TabbedPane.tabInsets", new XPValue(new InsetsUIResource(1, 4, 1, 4), new InsetsUIResource(0, 4, 1, 4)), "TabbedPane.tabAreaInsets", new XPValue(new InsetsUIResource(3, 2, 2, 2), new InsetsUIResource(3, 2, 0, 2)), "TabbedPane.font", ControlFont, "TabbedPane.background", ControlBackgroundColor, "TabbedPane.foreground", ControlTextColor, "TabbedPane.highlight", ControlHighlightColor, "TabbedPane.light", ControlLightColor, "TabbedPane.shadow", ControlShadowColor, "TabbedPane.darkShadow", ControlDarkShadowColor, "TabbedPane.focus", ControlTextColor, "TabbedPane.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "navigateRight", "KP_RIGHT", "navigateRight", "LEFT", "navigateLeft", "KP_LEFT", "navigateLeft", "UP", "navigateUp", "KP_UP", "navigateUp", "DOWN", "navigateDown", "KP_DOWN", "navigateDown", "ctrl DOWN", "requestFocusForVisibleComponent", "ctrl KP_DOWN", "requestFocusForVisibleComponent", }), "TabbedPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl TAB", "navigateNext", "ctrl shift TAB", "navigatePrevious", "ctrl PAGE_DOWN", "navigatePageDown", "ctrl PAGE_UP", "navigatePageUp", "ctrl UP", "requestFocus", "ctrl KP_UP", "requestFocus", }), // *** Table "Table.font", ControlFont, "Table.foreground", ControlTextColor, // cell text color "Table.background", WindowBackgroundColor, // cell background color "Table.highlight", ControlHighlightColor, "Table.light", ControlLightColor, "Table.shadow", ControlShadowColor, "Table.darkShadow", ControlDarkShadowColor, "Table.selectionForeground", SelectionTextColor, "Table.selectionBackground", SelectionBackgroundColor, "Table.gridColor", gray, // grid line color "Table.focusCellBackground", WindowBackgroundColor, "Table.focusCellForeground", ControlTextColor, "Table.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "HOME", "selectFirstColumn", "shift HOME", "selectFirstColumnExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRow", "END", "selectLastColumn", "shift END", "selectLastColumnExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRow", "PAGE_UP", "scrollUpChangeSelection", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollLeftExtendSelection", "ctrl PAGE_UP", "scrollLeftChangeSelection", "PAGE_DOWN", "scrollDownChangeSelection", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollRightExtendSelection", "ctrl PAGE_DOWN", "scrollRightChangeSelection", "TAB", "selectNextColumnCell", "shift TAB", "selectPreviousColumnCell", "ENTER", "selectNextRowCell", "shift ENTER", "selectPreviousRowCell", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "ESCAPE", "cancel", "F2", "startEditing", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo", "F8", "focusHeader" }), "Table.sortIconHighlight", ControlShadowColor, "Table.sortIconLight", white, "TableHeader.font", ControlFont, "TableHeader.foreground", ControlTextColor, // header text color "TableHeader.background", ControlBackgroundColor, // header background "TableHeader.focusCellBackground", new XPValue(XPValue.NULL_VALUE, // use default bg from XP styles WindowBackgroundColor), // or white bg otherwise // *** TextArea "TextArea.font", FixedControlFont, "TextArea.background", WindowBackgroundColor, "TextArea.foreground", WindowTextColor, "TextArea.inactiveForeground", InactiveTextColor, "TextArea.inactiveBackground", WindowBackgroundColor, "TextArea.disabledBackground", DisabledTextBackground, "TextArea.selectionBackground", SelectionBackgroundColor, "TextArea.selectionForeground", SelectionTextColor, "TextArea.caretForeground", WindowTextColor, // *** TextField "TextField.font", ControlFont, "TextField.background", TextBackground, "TextField.foreground", WindowTextColor, "TextField.shadow", ControlShadowColor, "TextField.darkShadow", ControlDarkShadowColor, "TextField.light", ControlLightColor, "TextField.highlight", ControlHighlightColor, "TextField.inactiveForeground", InactiveTextColor, // for disabled "TextField.inactiveBackground", ReadOnlyTextBackground, // for readonly "TextField.disabledBackground", DisabledTextBackground, // for disabled "TextField.selectionBackground", SelectionBackgroundColor, "TextField.selectionForeground", SelectionTextColor, "TextField.caretForeground", WindowTextColor, // *** TextPane "TextPane.font", ControlFont, "TextPane.background", WindowBackgroundColor, "TextPane.foreground", WindowTextColor, "TextPane.selectionBackground", SelectionBackgroundColor, "TextPane.selectionForeground", SelectionTextColor, "TextPane.inactiveBackground", WindowBackgroundColor, "TextPane.disabledBackground", DisabledTextBackground, "TextPane.caretForeground", WindowTextColor, // *** TitledBorder "TitledBorder.font", ControlFont, "TitledBorder.titleColor", new XPColorValue(Part.BP_GROUPBOX, null, Prop.TEXTCOLOR, WindowTextColor), // *** ToggleButton "ToggleButton.font", ControlFont, "ToggleButton.background", ControlBackgroundColor, "ToggleButton.foreground", ControlTextColor, "ToggleButton.shadow", ControlShadowColor, "ToggleButton.darkShadow", ControlDarkShadowColor, "ToggleButton.light", ControlLightColor, "ToggleButton.highlight", ControlHighlightColor, "ToggleButton.focus", ControlTextColor, "ToggleButton.textShiftOffset", Integer.valueOf(1), "ToggleButton.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), // *** ToolBar "ToolBar.font", MenuFont, "ToolBar.background", ControlBackgroundColor, "ToolBar.foreground", ControlTextColor, "ToolBar.shadow", ControlShadowColor, "ToolBar.darkShadow", ControlDarkShadowColor, "ToolBar.light", ControlLightColor, "ToolBar.highlight", ControlHighlightColor, "ToolBar.dockingBackground", ControlBackgroundColor, "ToolBar.dockingForeground", red, "ToolBar.floatingBackground", ControlBackgroundColor, "ToolBar.floatingForeground", darkGray, "ToolBar.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "navigateUp", "KP_UP", "navigateUp", "DOWN", "navigateDown", "KP_DOWN", "navigateDown", "LEFT", "navigateLeft", "KP_LEFT", "navigateLeft", "RIGHT", "navigateRight", "KP_RIGHT", "navigateRight" }), "ToolBar.separatorSize", null, // *** ToolTip "ToolTip.font", ToolTipFont, "ToolTip.background", new DesktopProperty("win.tooltip.backgroundColor", table.get("info")), "ToolTip.foreground", new DesktopProperty("win.tooltip.textColor", table.get("infoText")), // *** ToolTipManager "ToolTipManager.enableToolTipMode", "activeApplication", // *** Tree "Tree.selectionBorderColor", black, "Tree.drawDashedFocusIndicator", Boolean.TRUE, "Tree.lineTypeDashed", Boolean.TRUE, "Tree.font", ControlFont, "Tree.background", WindowBackgroundColor, "Tree.foreground", WindowTextColor, "Tree.hash", gray, "Tree.leftChildIndent", Integer.valueOf(8), "Tree.rightChildIndent", Integer.valueOf(11), "Tree.textForeground", WindowTextColor, "Tree.textBackground", WindowBackgroundColor, "Tree.selectionForeground", SelectionTextColor, "Tree.selectionBackground", SelectionBackgroundColor, "Tree.expandedIcon", treeExpandedIcon, "Tree.collapsedIcon", treeCollapsedIcon, "Tree.openIcon", new ActiveWindowsIcon("win.icon.shellIconBPP", "shell32Icon 5", "icons/TreeOpen.gif"), "Tree.closedIcon", new ActiveWindowsIcon("win.icon.shellIconBPP", "shell32Icon 4", "icons/TreeClosed.gif"), "Tree.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ADD", "expand", "SUBTRACT", "collapse", "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPrevious", "KP_UP", "selectPrevious", "shift UP", "selectPreviousExtendSelection", "shift KP_UP", "selectPreviousExtendSelection", "ctrl shift UP", "selectPreviousExtendSelection", "ctrl shift KP_UP", "selectPreviousExtendSelection", "ctrl UP", "selectPreviousChangeLead", "ctrl KP_UP", "selectPreviousChangeLead", "DOWN", "selectNext", "KP_DOWN", "selectNext", "shift DOWN", "selectNextExtendSelection", "shift KP_DOWN", "selectNextExtendSelection", "ctrl shift DOWN", "selectNextExtendSelection", "ctrl shift KP_DOWN", "selectNextExtendSelection", "ctrl DOWN", "selectNextChangeLead", "ctrl KP_DOWN", "selectNextChangeLead", "RIGHT", "selectChild", "KP_RIGHT", "selectChild", "LEFT", "selectParent", "KP_LEFT", "selectParent", "PAGE_UP", "scrollUpChangeSelection", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDownChangeSelection", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "HOME", "selectFirst", "shift HOME", "selectFirstExtendSelection", "ctrl shift HOME", "selectFirstExtendSelection", "ctrl HOME", "selectFirstChangeLead", "END", "selectLast", "shift END", "selectLastExtendSelection", "ctrl shift END", "selectLastExtendSelection", "ctrl END", "selectLastChangeLead", "F2", "startEditing", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "ctrl LEFT", "scrollLeft", "ctrl KP_LEFT", "scrollLeft", "ctrl RIGHT", "scrollRight", "ctrl KP_RIGHT", "scrollRight", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), "Tree.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "cancel" }), // *** Viewport "Viewport.font", ControlFont, "Viewport.background", ControlBackgroundColor, "Viewport.foreground", WindowTextColor, }; table.putDefaults(defaults); table.putDefaults(getLazyValueDefaults()); initVistaComponentDefaults(table); } static boolean isOnVista() { return OSInfo.getOSType() == OSInfo.OSType.WINDOWS && OSInfo.getWindowsVersion().compareTo(OSInfo.WINDOWS_VISTA) >= 0; } private void initVistaComponentDefaults(UIDefaults table) { if (! isOnVista()) { return; } /* START handling menus for Vista */ String[] menuClasses = { "MenuItem", "Menu", "CheckBoxMenuItem", "RadioButtonMenuItem", }; Object menuDefaults[] = new Object[menuClasses.length * 2]; /* all the menus need to be non opaque. */ for (int i = 0, j = 0; i < menuClasses.length; i++) { String key = menuClasses[i] + ".opaque"; Object oldValue = table.get(key); menuDefaults[j++] = key; menuDefaults[j++] = new XPValue(Boolean.FALSE, oldValue); } table.putDefaults(menuDefaults); /* * acceleratorSelectionForeground color is the same as * acceleratorForeground */ for (int i = 0, j = 0; i < menuClasses.length; i++) { String key = menuClasses[i] + ".acceleratorSelectionForeground"; Object oldValue = table.get(key); menuDefaults[j++] = key; menuDefaults[j++] = new XPValue( table.getColor( menuClasses[i] + ".acceleratorForeground"), oldValue); } table.putDefaults(menuDefaults); /* they have the same MenuItemCheckIconFactory */ VistaMenuItemCheckIconFactory menuItemCheckIconFactory = WindowsIconFactory.getMenuItemCheckIconFactory(); for (int i = 0, j = 0; i < menuClasses.length; i++) { String key = menuClasses[i] + ".checkIconFactory"; Object oldValue = table.get(key); menuDefaults[j++] = key; menuDefaults[j++] = new XPValue(menuItemCheckIconFactory, oldValue); } table.putDefaults(menuDefaults); for (int i = 0, j = 0; i < menuClasses.length; i++) { String key = menuClasses[i] + ".checkIcon"; Object oldValue = table.get(key); menuDefaults[j++] = key; menuDefaults[j++] = new XPValue(menuItemCheckIconFactory.getIcon(menuClasses[i]), oldValue); } table.putDefaults(menuDefaults); /* height can be even */ for (int i = 0, j = 0; i < menuClasses.length; i++) { String key = menuClasses[i] + ".evenHeight"; Object oldValue = table.get(key); menuDefaults[j++] = key; menuDefaults[j++] = new XPValue(Boolean.TRUE, oldValue); } table.putDefaults(menuDefaults); /* no margins */ InsetsUIResource insets = new InsetsUIResource(0, 0, 0, 0); for (int i = 0, j = 0; i < menuClasses.length; i++) { String key = menuClasses[i] + ".margin"; Object oldValue = table.get(key); menuDefaults[j++] = key; menuDefaults[j++] = new XPValue(insets, oldValue); } table.putDefaults(menuDefaults); /* set checkIcon offset */ Integer checkIconOffsetInteger = Integer.valueOf(0); for (int i = 0, j = 0; i < menuClasses.length; i++) { String key = menuClasses[i] + ".checkIconOffset"; Object oldValue = table.get(key); menuDefaults[j++] = key; menuDefaults[j++] = new XPValue(checkIconOffsetInteger, oldValue); } table.putDefaults(menuDefaults); /* set width of the gap after check icon */ Integer afterCheckIconGap = WindowsPopupMenuUI.getSpanBeforeGutter() + WindowsPopupMenuUI.getGutterWidth() + WindowsPopupMenuUI.getSpanAfterGutter(); for (int i = 0, j = 0; i < menuClasses.length; i++) { String key = menuClasses[i] + ".afterCheckIconGap"; Object oldValue = table.get(key); menuDefaults[j++] = key; menuDefaults[j++] = new XPValue(afterCheckIconGap, oldValue); } table.putDefaults(menuDefaults); /* text is started after this position */ Object minimumTextOffset = new UIDefaults.ActiveValue() { public Object createValue(UIDefaults table) { return VistaMenuItemCheckIconFactory.getIconWidth() + WindowsPopupMenuUI.getSpanBeforeGutter() + WindowsPopupMenuUI.getGutterWidth() + WindowsPopupMenuUI.getSpanAfterGutter(); } }; for (int i = 0, j = 0; i < menuClasses.length; i++) { String key = menuClasses[i] + ".minimumTextOffset"; Object oldValue = table.get(key); menuDefaults[j++] = key; menuDefaults[j++] = new XPValue(minimumTextOffset, oldValue); } table.putDefaults(menuDefaults); /* * JPopupMenu has a bit of free space around menu items */ String POPUP_MENU_BORDER = "PopupMenu.border"; Object popupMenuBorder = new XPBorderValue(Part.MENU, new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getInternalFrameBorder"), BorderFactory.createEmptyBorder(2, 2, 2, 2)); table.put(POPUP_MENU_BORDER, popupMenuBorder); /* END handling menus for Vista */ /* START table handling for Vista */ table.put("Table.ascendingSortIcon", new XPValue( new SkinIcon(Part.HP_HEADERSORTARROW, State.SORTEDDOWN), new SwingLazyValue( "sun.swing.plaf.windows.ClassicSortArrowIcon", null, new Object[] { Boolean.TRUE }))); table.put("Table.descendingSortIcon", new XPValue( new SkinIcon(Part.HP_HEADERSORTARROW, State.SORTEDUP), new SwingLazyValue( "sun.swing.plaf.windows.ClassicSortArrowIcon", null, new Object[] { Boolean.FALSE }))); /* END table handling for Vista */ } /** * If we support loading of fonts from the desktop this will return * a DesktopProperty representing the font. If the font can't be * represented in the current encoding this will return null and * turn off the use of system fonts. */ private Object getDesktopFontValue(String fontName, Object backup) { if (useSystemFontSettings) { return new WindowsFontProperty(fontName, backup); } return null; } // When a desktop property change is detected, these classes must be // reinitialized in the defaults table to ensure the classes reference // the updated desktop property values (colors mostly) // private Object[] getLazyValueDefaults() { Object buttonBorder = new XPBorderValue(Part.BP_PUSHBUTTON, new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getButtonBorder")); Object textFieldBorder = new XPBorderValue(Part.EP_EDIT, new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getTextFieldBorder")); Object textFieldMargin = new XPValue(new InsetsUIResource(2, 2, 2, 2), new InsetsUIResource(1, 1, 1, 1)); Object spinnerBorder = new XPBorderValue(Part.EP_EDIT, textFieldBorder, new EmptyBorder(2, 2, 2, 2)); Object spinnerArrowInsets = new XPValue(new InsetsUIResource(1, 1, 1, 1), null); Object comboBoxBorder = new XPBorderValue(Part.CP_COMBOBOX, textFieldBorder); // For focus rectangle for cells and trees. Object focusCellHighlightBorder = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsBorders", "getFocusCellHighlightBorder"); Object etchedBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource", "getEtchedBorderUIResource"); Object internalFrameBorder = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsBorders", "getInternalFrameBorder"); Object loweredBevelBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource", "getLoweredBevelBorderUIResource"); Object marginBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders$MarginBorder"); Object menuBarBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getMenuBarBorder"); Object popupMenuBorder = new XPBorderValue(Part.MENU, new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getInternalFrameBorder")); // *** ProgressBar Object progressBarBorder = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsBorders", "getProgressBarBorder"); Object radioButtonBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getRadioButtonBorder"); Object scrollPaneBorder = new XPBorderValue(Part.LBP_LISTBOX, textFieldBorder); Object tableScrollPaneBorder = new XPBorderValue(Part.LBP_LISTBOX, loweredBevelBorder); Object tableHeaderBorder = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsBorders", "getTableHeaderBorder"); // *** ToolBar Object toolBarBorder = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsBorders", "getToolBarBorder"); // *** ToolTips Object toolTipBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource", "getBlackLineBorderUIResource"); Object checkBoxIcon = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsIconFactory", "getCheckBoxIcon"); Object radioButtonIcon = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsIconFactory", "getRadioButtonIcon"); Object radioButtonMenuItemIcon = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsIconFactory", "getRadioButtonMenuItemIcon"); Object menuItemCheckIcon = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsIconFactory", "getMenuItemCheckIcon"); Object menuItemArrowIcon = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsIconFactory", "getMenuItemArrowIcon"); Object menuArrowIcon = new SwingLazyValue( "com.sun.java.swing.plaf.windows.WindowsIconFactory", "getMenuArrowIcon"); Object[] lazyDefaults = { "Button.border", buttonBorder, "CheckBox.border", radioButtonBorder, "ComboBox.border", comboBoxBorder, "DesktopIcon.border", internalFrameBorder, "FormattedTextField.border", textFieldBorder, "FormattedTextField.margin", textFieldMargin, "InternalFrame.border", internalFrameBorder, "List.focusCellHighlightBorder", focusCellHighlightBorder, "Table.focusCellHighlightBorder", focusCellHighlightBorder, "Menu.border", marginBorder, "MenuBar.border", menuBarBorder, "MenuItem.border", marginBorder, "PasswordField.border", textFieldBorder, "PasswordField.margin", textFieldMargin, "PopupMenu.border", popupMenuBorder, "ProgressBar.border", progressBarBorder, "RadioButton.border", radioButtonBorder, "ScrollPane.border", scrollPaneBorder, "Spinner.border", spinnerBorder, "Spinner.arrowButtonInsets", spinnerArrowInsets, "Spinner.arrowButtonSize", new Dimension(17, 9), "Table.scrollPaneBorder", tableScrollPaneBorder, "TableHeader.cellBorder", tableHeaderBorder, "TextArea.margin", textFieldMargin, "TextField.border", textFieldBorder, "TextField.margin", textFieldMargin, "TitledBorder.border", new XPBorderValue(Part.BP_GROUPBOX, etchedBorder), "ToggleButton.border", radioButtonBorder, "ToolBar.border", toolBarBorder, "ToolTip.border", toolTipBorder, "CheckBox.icon", checkBoxIcon, "Menu.arrowIcon", menuArrowIcon, "MenuItem.checkIcon", menuItemCheckIcon, "MenuItem.arrowIcon", menuItemArrowIcon, "RadioButton.icon", radioButtonIcon, "RadioButtonMenuItem.checkIcon", radioButtonMenuItemIcon, "InternalFrame.layoutTitlePaneAtOrigin", new XPValue(Boolean.TRUE, Boolean.FALSE), "Table.ascendingSortIcon", new XPValue( new SwingLazyValue( "sun.swing.icon.SortArrowIcon", null, new Object[] { Boolean.TRUE, "Table.sortIconColor" }), new SwingLazyValue( "sun.swing.plaf.windows.ClassicSortArrowIcon", null, new Object[] { Boolean.TRUE })), "Table.descendingSortIcon", new XPValue( new SwingLazyValue( "sun.swing.icon.SortArrowIcon", null, new Object[] { Boolean.FALSE, "Table.sortIconColor" }), new SwingLazyValue( "sun.swing.plaf.windows.ClassicSortArrowIcon", null, new Object[] { Boolean.FALSE })), }; return lazyDefaults; } public void uninitialize() { super.uninitialize(); if (WindowsPopupMenuUI.mnemonicListener != null) { MenuSelectionManager.defaultManager(). removeChangeListener(WindowsPopupMenuUI.mnemonicListener); } KeyboardFocusManager.getCurrentKeyboardFocusManager(). removeKeyEventPostProcessor(WindowsRootPaneUI.altProcessor); DesktopProperty.flushUnreferencedProperties(); } // Toggle flag for drawing the mnemonic state private static boolean isMnemonicHidden = true; // Flag which indicates that the Win98/Win2k/WinME features // should be disabled. private static boolean isClassicWindows = false; /** * Sets the state of the hide mnemonic flag. This flag is used by the * component UI delegates to determine if the mnemonic should be rendered. * This method is a non operation if the underlying operating system * does not support the mnemonic hiding feature. * * @param hide true if mnemonics should be hidden * @since 1.4 */ public static void setMnemonicHidden(boolean hide) { if (UIManager.getBoolean("Button.showMnemonics") == true) { // Do not hide mnemonics if the UI defaults do not support this isMnemonicHidden = false; } else { isMnemonicHidden = hide; } } /** * Gets the state of the hide mnemonic flag. This only has meaning * if this feature is supported by the underlying OS. * * @return true if mnemonics are hidden, otherwise, false * @see #setMnemonicHidden * @since 1.4 */ public static boolean isMnemonicHidden() { if (UIManager.getBoolean("Button.showMnemonics") == true) { // Do not hide mnemonics if the UI defaults do not support this isMnemonicHidden = false; } return isMnemonicHidden; } /** * Gets the state of the flag which indicates if the old Windows * look and feel should be rendered. This flag is used by the * component UI delegates as a hint to determine which style the component * should be rendered. * * @return true if Windows 95 and Windows NT 4 look and feel should * be rendered * @since 1.4 */ public static boolean isClassicWindows() { return isClassicWindows; } /** * <p> * Invoked when the user attempts an invalid operation, * such as pasting into an uneditable <code>JTextField</code> * that has focus. * </p> * <p> * If the user has enabled visual error indication on * the desktop, this method will flash the caption bar * of the active window. The user can also set the * property awt.visualbell=true to achieve the same * results. * </p> * * @param component Component the error occured in, may be * null indicating the error condition is * not directly associated with a * <code>Component</code>. * * @see javax.swing.LookAndFeel#provideErrorFeedback */ public void provideErrorFeedback(Component component) { super.provideErrorFeedback(component); } /** * {@inheritDoc} */ public LayoutStyle getLayoutStyle() { LayoutStyle style = this.style; if (style == null) { style = new WindowsLayoutStyle(); this.style = style; } return style; } // ********* Auditory Cue support methods and objects ********* /** * Returns an <code>Action</code>. * <P> * This Action contains the information and logic to render an * auditory cue. The <code>Object</code> that is passed to this * method contains the information needed to render the auditory * cue. Normally, this <code>Object</code> is a <code>String</code> * that points to a <code>Toolkit</code> <code>desktopProperty</code>. * This <code>desktopProperty</code> is resolved by AWT and the * Windows OS. * <P> * This <code>Action</code>'s <code>actionPerformed</code> method * is fired by the <code>playSound</code> method. * * @return an Action which knows how to render the auditory * cue for one particular system or user activity * @see #playSound(Action) * @since 1.4 */ protected Action createAudioAction(Object key) { if (key != null) { String audioKey = (String)key; String audioValue = (String)UIManager.get(key); return new AudioAction(audioKey, audioValue); } else { return null; } } static void repaintRootPane(Component c) { JRootPane root = null; for (; c != null; c = c.getParent()) { if (c instanceof JRootPane) { root = (JRootPane)c; } } if (root != null) { root.repaint(); } else { c.repaint(); } } /** * Pass the name String to the super constructor. This is used * later to identify the Action and decide whether to play it or * not. Store the resource String. It is used to get the audio * resource. In this case, the resource is a <code>Runnable</code> * supplied by <code>Toolkit</code>. This <code>Runnable</code> is * effectively a pointer down into the Win32 OS that knows how to * play the right sound. * * @since 1.4 */ private static class AudioAction extends AbstractAction { private Runnable audioRunnable; private String audioResource; /** * We use the String as the name of the Action and as a pointer to * the underlying OSes audio resource. */ public AudioAction(String name, String resource) { super(name); audioResource = resource; } public void actionPerformed(ActionEvent e) { if (audioRunnable == null) { audioRunnable = (Runnable)Toolkit.getDefaultToolkit().getDesktopProperty(audioResource); } if (audioRunnable != null) { // Runnable appears to block until completed playing, hence // start up another thread to handle playing. new Thread(audioRunnable).start(); } } } /** * Gets an <code>Icon</code> from the native libraries if available, * otherwise gets it from an image resource file. */ private static class LazyWindowsIcon implements UIDefaults.LazyValue { private String nativeImage; private String resource; LazyWindowsIcon(String nativeImage, String resource) { this.nativeImage = nativeImage; this.resource = resource; } public Object createValue(UIDefaults table) { if (nativeImage != null) { Image image = (Image)ShellFolder.get(nativeImage); if (image != null) { return new ImageIcon(image); } } return SwingUtilities2.makeIcon(getClass(), WindowsLookAndFeel.class, resource); } } /** * Gets an <code>Icon</code> from the native libraries if available. * A desktop property is used to trigger reloading the icon when needed. */ private class ActiveWindowsIcon implements UIDefaults.ActiveValue { private Icon icon; private String nativeImageName; private String fallbackName; private DesktopProperty desktopProperty; ActiveWindowsIcon(String desktopPropertyName, String nativeImageName, String fallbackName) { this.nativeImageName = nativeImageName; this.fallbackName = fallbackName; if (OSInfo.getOSType() == OSInfo.OSType.WINDOWS && OSInfo.getWindowsVersion().compareTo(OSInfo.WINDOWS_XP) < 0) { // This desktop property is needed to trigger reloading the icon. // It is kept in member variable to avoid GC. this.desktopProperty = new TriggerDesktopProperty(desktopPropertyName) { @Override protected void updateUI() { icon = null; super.updateUI(); } }; } } @Override public Object createValue(UIDefaults table) { if (icon == null) { Image image = (Image)ShellFolder.get(nativeImageName); if (image != null) { icon = new ImageIconUIResource(image); } } if (icon == null && fallbackName != null) { UIDefaults.LazyValue fallback = (UIDefaults.LazyValue) SwingUtilities2.makeIcon(WindowsLookAndFeel.class, BasicLookAndFeel.class, fallbackName); icon = (Icon) fallback.createValue(table); } return icon; } } /** * Icon backed-up by XP Skin. */ private static class SkinIcon implements Icon, UIResource { private final Part part; private final State state; SkinIcon(Part part, State state) { this.part = part; this.state = state; } /** * Draw the icon at the specified location. Icon implementations * may use the Component argument to get properties useful for * painting, e.g. the foreground or background color. */ public void paintIcon(Component c, Graphics g, int x, int y) { XPStyle xp = XPStyle.getXP(); assert xp != null; if (xp != null) { Skin skin = xp.getSkin(null, part); skin.paintSkin(g, x, y, state); } } /** * Returns the icon's width. * * @return an int specifying the fixed width of the icon. */ public int getIconWidth() { int width = 0; XPStyle xp = XPStyle.getXP(); assert xp != null; if (xp != null) { Skin skin = xp.getSkin(null, part); width = skin.getWidth(); } return width; } /** * Returns the icon's height. * * @return an int specifying the fixed height of the icon. */ public int getIconHeight() { int height = 0; XPStyle xp = XPStyle.getXP(); if (xp != null) { Skin skin = xp.getSkin(null, part); height = skin.getHeight(); } return height; } } /** * DesktopProperty for fonts. If a font with the name 'MS Sans Serif' * is returned, it is mapped to 'Microsoft Sans Serif'. */ private static class WindowsFontProperty extends DesktopProperty { WindowsFontProperty(String key, Object backup) { super(key, backup); } public void invalidate(LookAndFeel laf) { if ("win.defaultGUI.font.height".equals(getKey())) { ((WindowsLookAndFeel)laf).style = null; } super.invalidate(laf); } protected Object configureValue(Object value) { if (value instanceof Font) { Font font = (Font)value; if ("MS Sans Serif".equals(font.getName())) { int size = font.getSize(); // 4950968: Workaround to mimic the way Windows maps the default // font size of 6 pts to the smallest available bitmap font size. // This happens mostly on Win 98/Me & NT. int dpi; try { dpi = Toolkit.getDefaultToolkit().getScreenResolution(); } catch (HeadlessException ex) { dpi = 96; } if (Math.round(size * 72F / dpi) < 8) { size = Math.round(8 * dpi / 72F); } Font msFont = new FontUIResource("Microsoft Sans Serif", font.getStyle(), size); if (msFont.getName() != null && msFont.getName().equals(msFont.getFamily())) { font = msFont; } else if (size != font.getSize()) { font = new FontUIResource("MS Sans Serif", font.getStyle(), size); } } if (FontUtilities.fontSupportsDefaultEncoding(font)) { if (!(font instanceof UIResource)) { font = new FontUIResource(font); } } else { font = FontUtilities.getCompositeFontUIResource(font); } return font; } return super.configureValue(value); } } /** * DesktopProperty for fonts that only gets sizes from the desktop, * font name and style are passed into the constructor */ private static class WindowsFontSizeProperty extends DesktopProperty { private String fontName; private int fontSize; private int fontStyle; WindowsFontSizeProperty(String key, String fontName, int fontStyle, int fontSize) { super(key, null); this.fontName = fontName; this.fontSize = fontSize; this.fontStyle = fontStyle; } protected Object configureValue(Object value) { if (value == null) { value = new FontUIResource(fontName, fontStyle, fontSize); } else if (value instanceof Integer) { value = new FontUIResource(fontName, fontStyle, ((Integer)value).intValue()); } return value; } } /** * A value wrapper that actively retrieves values from xp or falls back * to the classic value if not running XP styles. */ private static class XPValue implements UIDefaults.ActiveValue { protected Object classicValue, xpValue; // A constant that lets you specify null when using XP styles. private final static Object NULL_VALUE = new Object(); XPValue(Object xpValue, Object classicValue) { this.xpValue = xpValue; this.classicValue = classicValue; } public Object createValue(UIDefaults table) { Object value = null; if (XPStyle.getXP() != null) { value = getXPValue(table); } if (value == null) { value = getClassicValue(table); } else if (value == NULL_VALUE) { value = null; } return value; } protected Object getXPValue(UIDefaults table) { return recursiveCreateValue(xpValue, table); } protected Object getClassicValue(UIDefaults table) { return recursiveCreateValue(classicValue, table); } private Object recursiveCreateValue(Object value, UIDefaults table) { if (value instanceof UIDefaults.LazyValue) { value = ((UIDefaults.LazyValue)value).createValue(table); } if (value instanceof UIDefaults.ActiveValue) { return ((UIDefaults.ActiveValue)value).createValue(table); } else { return value; } } } private static class XPBorderValue extends XPValue { private final Border extraMargin; XPBorderValue(Part xpValue, Object classicValue) { this(xpValue, classicValue, null); } XPBorderValue(Part xpValue, Object classicValue, Border extraMargin) { super(xpValue, classicValue); this.extraMargin = extraMargin; } public Object getXPValue(UIDefaults table) { Border xpBorder = XPStyle.getXP().getBorder(null, (Part)xpValue); if (extraMargin != null) { return new BorderUIResource. CompoundBorderUIResource(xpBorder, extraMargin); } else { return xpBorder; } } } private static class XPColorValue extends XPValue { XPColorValue(Part part, State state, Prop prop, Object classicValue) { super(new XPColorValueKey(part, state, prop), classicValue); } public Object getXPValue(UIDefaults table) { XPColorValueKey key = (XPColorValueKey)xpValue; return XPStyle.getXP().getColor(key.skin, key.prop, null); } private static class XPColorValueKey { Skin skin; Prop prop; XPColorValueKey(Part part, State state, Prop prop) { this.skin = new Skin(part, state); this.prop = prop; } } } private class XPDLUValue extends XPValue { private int direction; XPDLUValue(int xpdlu, int classicdlu, int direction) { super(Integer.valueOf(xpdlu), Integer.valueOf(classicdlu)); this.direction = direction; } public Object getXPValue(UIDefaults table) { int px = dluToPixels(((Integer)xpValue).intValue(), direction); return Integer.valueOf(px); } public Object getClassicValue(UIDefaults table) { int px = dluToPixels(((Integer)classicValue).intValue(), direction); return Integer.valueOf(px); } } private class TriggerDesktopProperty extends DesktopProperty { TriggerDesktopProperty(String key) { super(key, null); // This call adds a property change listener for the property, // which triggers a call to updateUI(). The value returned // is not interesting here. getValueFromDesktop(); } protected void updateUI() { super.updateUI(); // Make sure property change listener is readded each time getValueFromDesktop(); } } private class FontDesktopProperty extends TriggerDesktopProperty { FontDesktopProperty(String key) { super(key); } protected void updateUI() { Object aaTextInfo = SwingUtilities2.AATextInfo.getAATextInfo(true); UIDefaults defaults = UIManager.getLookAndFeelDefaults(); defaults.put(SwingUtilities2.AA_TEXT_PROPERTY_KEY, aaTextInfo); super.updateUI(); } } // Windows LayoutStyle. From: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch14e.asp private class WindowsLayoutStyle extends DefaultLayoutStyle { @Override public int getPreferredGap(JComponent component1, JComponent component2, ComponentPlacement type, int position, Container parent) { // Checks args super.getPreferredGap(component1, component2, type, position, parent); switch(type) { case INDENT: // Windows doesn't spec this if (position == SwingConstants.EAST || position == SwingConstants.WEST) { int indent = getIndent(component1, position); if (indent > 0) { return indent; } return 10; } // Fall through to related. case RELATED: if (isLabelAndNonlabel(component1, component2, position)) { // Between text labels and their associated controls (for // example, text boxes and list boxes): 3 // NOTE: We're not honoring: // 'Text label beside a button 3 down from the top of // the button,' but I suspect that is an attempt to // enforce a baseline layout which will be handled // separately. In order to enforce this we would need // this API to return a more complicated type (Insets, // or something else). return getButtonGap(component1, component2, position, dluToPixels(3, position)); } // Between related controls: 4 return getButtonGap(component1, component2, position, dluToPixels(4, position)); case UNRELATED: // Between unrelated controls: 7 return getButtonGap(component1, component2, position, dluToPixels(7, position)); } return 0; } @Override public int getContainerGap(JComponent component, int position, Container parent) { // Checks args super.getContainerGap(component, position, parent); return getButtonGap(component, position, dluToPixels(7, position)); } } /** * Converts the dialog unit argument to pixels along the specified * axis. */ private int dluToPixels(int dlu, int direction) { if (baseUnitX == 0) { calculateBaseUnits(); } if (direction == SwingConstants.EAST || direction == SwingConstants.WEST) { return dlu * baseUnitX / 4; } assert (direction == SwingConstants.NORTH || direction == SwingConstants.SOUTH); return dlu * baseUnitY / 8; } /** * Calculates the dialog unit mapping. */ private void calculateBaseUnits() { // This calculation comes from: // http://support.microsoft.com/default.aspx?scid=kb;EN-US;125681 FontMetrics metrics = Toolkit.getDefaultToolkit().getFontMetrics( UIManager.getFont("Button.font")); baseUnitX = metrics.stringWidth( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); baseUnitX = (baseUnitX / 26 + 1) / 2; // The -1 comes from experimentation. baseUnitY = metrics.getAscent() + metrics.getDescent() - 1; } /** * {@inheritDoc} * * @since 1.6 */ public Icon getDisabledIcon(JComponent component, Icon icon) { // if the component has a HI_RES_DISABLED_ICON_CLIENT_KEY // client property set to Boolean.TRUE, then use the new // hi res algorithm for creating the disabled icon (used // in particular by the WindowsFileChooserUI class) if (icon != null && component != null && Boolean.TRUE.equals(component.getClientProperty(HI_RES_DISABLED_ICON_CLIENT_KEY)) && icon.getIconWidth() > 0 && icon.getIconHeight() > 0) { BufferedImage img = new BufferedImage(icon.getIconWidth(), icon.getIconWidth(), BufferedImage.TYPE_INT_ARGB); icon.paintIcon(component, img.getGraphics(), 0, 0); ImageFilter filter = new RGBGrayFilter(); ImageProducer producer = new FilteredImageSource(img.getSource(), filter); Image resultImage = component.createImage(producer); return new ImageIconUIResource(resultImage); } return super.getDisabledIcon(component, icon); } private static class RGBGrayFilter extends RGBImageFilter { public RGBGrayFilter() { canFilterIndexColorModel = true; } public int filterRGB(int x, int y, int rgb) { // find the average of red, green, and blue float avg = (((rgb >> 16) & 0xff) / 255f + ((rgb >> 8) & 0xff) / 255f + (rgb & 0xff) / 255f) / 3; // pull out the alpha channel float alpha = (((rgb>>24)&0xff)/255f); // calc the average avg = Math.min(1.0f, (1f-avg)/(100.0f/35.0f) + avg); // turn back into rgb int rgbval = (int)(alpha * 255f) << 24 | (int)(avg * 255f) << 16 | (int)(avg * 255f) << 8 | (int)(avg * 255f); return rgbval; } } }
mit