repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
bhutchinson/rice
rice-middleware/impl/src/main/java/org/kuali/rice/kim/lookup/GroupLookupableImpl.java
2304
/** * 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.lookup; import org.apache.commons.lang.StringUtils; import org.kuali.rice.kew.api.KewApiConstants; import org.kuali.rice.kim.api.KimConstants; import org.kuali.rice.kim.util.KimCommonUtilsInternal; import org.kuali.rice.kns.lookup.KualiLookupableImpl; import org.kuali.rice.krad.util.KRADConstants; import org.kuali.rice.krad.util.UrlFactory; import java.util.Properties; /** * This is a description of what this class does - shyu don't forget to fill this in. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ public class GroupLookupableImpl extends KualiLookupableImpl { private static final long serialVersionUID = -7862240710174441633L; public String getCreateNewUrl() { String url = ""; if((getLookupableHelperService()).allowsNewOrCopyAction(KimConstants.KimUIConstants.KIM_GROUP_DOCUMENT_TYPE_NAME)){ Properties parameters = new Properties(); parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, KRADConstants.DOC_HANDLER_METHOD); parameters.put(KRADConstants.PARAMETER_COMMAND, KewApiConstants.INITIATE_COMMAND); parameters.put(KRADConstants.DOCUMENT_TYPE_NAME, KimConstants.KimUIConstants.KIM_GROUP_DOCUMENT_TYPE_NAME); if (StringUtils.isNotBlank(getReturnLocation())) { parameters.put(KRADConstants.RETURN_LOCATION_PARAMETER, getReturnLocation()); } url = getCreateNewUrl(UrlFactory.parameterizeUrl( KimCommonUtilsInternal.getKimBasePath()+ KimConstants.KimUIConstants.KIM_GROUP_DOCUMENT_ACTION, parameters)); } return url; } }
apache-2.0
fluxcapacitor/pipeline
predict/dashboard/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/aop/aspectj/WeavingMode.java
752
/** * Copyright 2015 Netflix, Inc. * <p/> * 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 * <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 com.netflix.hystrix.contrib.javanica.aop.aspectj; /** * Created by dmgcodevil */ public enum WeavingMode { COMPILE, RUNTIME }
apache-2.0
adamhongmy/socket.io-android-chat
app/src/main/java/com/github/nkzawa/socketio/androidchat/Constants.java
150
package com.github.nkzawa.socketio.androidchat; public class Constants { public static final String CHAT_SERVER_URL = "http://chat.socket.io"; }
mit
EvilMcJerkface/crate
server/src/main/java/org/elasticsearch/common/lucene/ShardCoreKeyMap.java
6689
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.common.lucene; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.LeafReader; import org.elasticsearch.Assertions; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardUtils; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * A map between segment core cache keys and the shard that these segments * belong to. This allows to get the shard that a segment belongs to or to get * the entire set of live core cache keys for a given index. In order to work * this class needs to be notified about new segments. It modifies the current * mappings as segments that were not known before are added and prevents the * structure from growing indefinitely by registering close listeners on these * segments so that at any time it only tracks live segments. * * NOTE: This is heavy. Avoid using this class unless absolutely required. */ public final class ShardCoreKeyMap { private final Map<IndexReader.CacheKey, ShardId> coreKeyToShard; private final Map<String, Set<IndexReader.CacheKey>> indexToCoreKey; public ShardCoreKeyMap() { coreKeyToShard = new ConcurrentHashMap<>(); indexToCoreKey = new HashMap<>(); } /** * Register a {@link LeafReader}. This is necessary so that the core cache * key of this reader can be found later using {@link #getCoreKeysForIndex(String)}. */ public void add(LeafReader reader) { final ShardId shardId = ShardUtils.extractShardId(reader); if (shardId == null) { throw new IllegalArgumentException("Could not extract shard id from " + reader); } final IndexReader.CacheHelper cacheHelper = reader.getCoreCacheHelper(); if (cacheHelper == null) { throw new IllegalArgumentException("Reader " + reader + " does not support caching"); } final IndexReader.CacheKey coreKey = cacheHelper.getKey(); if (coreKeyToShard.containsKey(coreKey)) { // Do this check before entering the synchronized block in order to // avoid taking the mutex if possible (which should happen most of // the time). return; } final String index = shardId.getIndexName(); synchronized (this) { if (coreKeyToShard.containsKey(coreKey) == false) { Set<IndexReader.CacheKey> objects = indexToCoreKey.get(index); if (objects == null) { objects = new HashSet<>(); indexToCoreKey.put(index, objects); } final boolean added = objects.add(coreKey); assert added; IndexReader.ClosedListener listener = ownerCoreCacheKey -> { assert coreKey == ownerCoreCacheKey; synchronized (ShardCoreKeyMap.this) { coreKeyToShard.remove(ownerCoreCacheKey); final Set<IndexReader.CacheKey> coreKeys = indexToCoreKey.get(index); final boolean removed = coreKeys.remove(coreKey); assert removed; if (coreKeys.isEmpty()) { indexToCoreKey.remove(index); } } }; boolean addedListener = false; try { cacheHelper.addClosedListener(listener); addedListener = true; // Only add the core key to the map as a last operation so that // if another thread sees that the core key is already in the // map (like the check just before this synchronized block), // then it means that the closed listener has already been // registered. ShardId previous = coreKeyToShard.put(coreKey, shardId); assert previous == null; } finally { if (false == addedListener) { try { listener.onClose(coreKey); } catch (IOException e) { throw new RuntimeException("Blow up trying to recover from failure to add listener", e); } } } } } } /** * Return the {@link ShardId} that holds the given segment, or {@code null} * if this segment is not tracked. */ public synchronized ShardId getShardId(Object coreKey) { return coreKeyToShard.get(coreKey); } /** * Get the set of core cache keys associated with the given index. */ public synchronized Set<Object> getCoreKeysForIndex(String index) { final Set<IndexReader.CacheKey> objects = indexToCoreKey.get(index); if (objects == null) { return Collections.emptySet(); } // we have to copy otherwise we risk ConcurrentModificationException return Set.copyOf(objects); } /** * Return the number of tracked segments. */ public synchronized int size() { assert assertSize(); return coreKeyToShard.size(); } private synchronized boolean assertSize() { if (!Assertions.ENABLED) { throw new AssertionError("only run this if assertions are enabled"); } Collection<Set<IndexReader.CacheKey>> values = indexToCoreKey.values(); int size = 0; for (Set<IndexReader.CacheKey> value : values) { size += value.size(); } return size == coreKeyToShard.size(); } }
apache-2.0
gretchiemoran/pentaho-kettle
engine/src/org/pentaho/di/job/entries/dostounix/JobEntryDosToUnix.java
28472
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.job.entries.dostounix; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.vfs2.AllFileSelector; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSelectInfo; import org.apache.commons.vfs2.FileType; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.Job; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.metastore.api.IMetaStore; import org.w3c.dom.Node; /** * This defines a 'Dos to Unix' job entry. * * @author Samatar Hassan * @since 26-03-2008 */ public class JobEntryDosToUnix extends JobEntryBase implements Cloneable, JobEntryInterface { private static final int LF = 0x0a; private static final int CR = 0x0d; private static Class<?> PKG = JobEntryDosToUnix.class; // for i18n purposes, needed by Translator2!! public static final String[] ConversionTypeDesc = new String[] { BaseMessages.getString( PKG, "JobEntryDosToUnix.ConversionType.Guess.Label" ), BaseMessages.getString( PKG, "JobEntryDosToUnix.ConversionType.DosToUnix.Label" ), BaseMessages.getString( PKG, "JobEntryDosToUnix.ConversionType.UnixToDos.Label" ) }; public static final String[] ConversionTypeCode = new String[] { "guess", "dostounix", "unixtodos" }; public static final int CONVERTION_TYPE_GUESS = 0; public static final int CONVERTION_TYPE_DOS_TO_UNIX = 1; public static final int CONVERTION_TYPE_UNIX_TO_DOS = 2; private static final int TYPE_DOS_FILE = 0; private static final int TYPE_UNIX_FILE = 1; private static final int TYPE_BINAY_FILE = 2; public static final String ADD_NOTHING = "nothing"; public static final String SUCCESS_IF_AT_LEAST_X_FILES_PROCESSED = "success_when_at_least"; public static final String SUCCESS_IF_ERROR_FILES_LESS = "success_if_error_files_less"; public static final String SUCCESS_IF_NO_ERRORS = "success_if_no_errors"; public static final String ADD_ALL_FILENAMES = "all_filenames"; public static final String ADD_PROCESSED_FILES_ONLY = "only_processed_filenames"; public static final String ADD_ERROR_FILES_ONLY = "only_error_filenames"; public boolean arg_from_previous; public boolean include_subfolders; public String[] source_filefolder; public String[] wildcard; public int[] conversionTypes; private String nr_errors_less_than; private String success_condition; private String resultfilenames; int nrAllErrors = 0; int nrErrorFiles = 0; int nrProcessedFiles = 0; int limitFiles = 0; int nrErrors = 0; boolean successConditionBroken = false; boolean successConditionBrokenExit = false; private static String tempFolder; public JobEntryDosToUnix( String n ) { super( n, "" ); resultfilenames = ADD_ALL_FILENAMES; arg_from_previous = false; source_filefolder = null; conversionTypes = null; wildcard = null; include_subfolders = false; nr_errors_less_than = "10"; success_condition = SUCCESS_IF_NO_ERRORS; } public JobEntryDosToUnix() { this( "" ); } public Object clone() { JobEntryDosToUnix je = (JobEntryDosToUnix) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer( 300 ); retval.append( super.getXML() ); retval.append( " " ).append( XMLHandler.addTagValue( "arg_from_previous", arg_from_previous ) ); retval.append( " " ).append( XMLHandler.addTagValue( "include_subfolders", include_subfolders ) ); retval.append( " " ).append( XMLHandler.addTagValue( "nr_errors_less_than", nr_errors_less_than ) ); retval.append( " " ).append( XMLHandler.addTagValue( "success_condition", success_condition ) ); retval.append( " " ).append( XMLHandler.addTagValue( "resultfilenames", resultfilenames ) ); retval.append( " <fields>" ).append( Const.CR ); if ( source_filefolder != null ) { for ( int i = 0; i < source_filefolder.length; i++ ) { retval.append( " <field>" ).append( Const.CR ); retval.append( " " ).append( XMLHandler.addTagValue( "source_filefolder", source_filefolder[i] ) ); retval.append( " " ).append( XMLHandler.addTagValue( "wildcard", wildcard[i] ) ); retval.append( " " ).append( XMLHandler.addTagValue( "ConversionType", getConversionTypeCode( conversionTypes[i] ) ) ); retval.append( " </field>" ).append( Const.CR ); } } retval.append( " </fields>" ).append( Const.CR ); return retval.toString(); } private static String getConversionTypeCode( int i ) { if ( i < 0 || i >= ConversionTypeCode.length ) { return ConversionTypeCode[0]; } return ConversionTypeCode[i]; } public static String getConversionTypeDesc( int i ) { if ( i < 0 || i >= ConversionTypeDesc.length ) { return ConversionTypeDesc[0]; } return ConversionTypeDesc[i]; } public static int getConversionTypeByDesc( String tt ) { if ( tt == null ) { return 0; } for ( int i = 0; i < ConversionTypeDesc.length; i++ ) { if ( ConversionTypeDesc[i].equalsIgnoreCase( tt ) ) { return i; } } // If this fails, try to match using the code. return getConversionTypeByCode( tt ); } private static int getConversionTypeByCode( String tt ) { if ( tt == null ) { return 0; } for ( int i = 0; i < ConversionTypeCode.length; i++ ) { if ( ConversionTypeCode[i].equalsIgnoreCase( tt ) ) { return i; } } return 0; } public void loadXML( Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep, IMetaStore metaStore ) throws KettleXMLException { try { super.loadXML( entrynode, databases, slaveServers ); arg_from_previous = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "arg_from_previous" ) ); include_subfolders = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "include_subfolders" ) ); nr_errors_less_than = XMLHandler.getTagValue( entrynode, "nr_errors_less_than" ); success_condition = XMLHandler.getTagValue( entrynode, "success_condition" ); resultfilenames = XMLHandler.getTagValue( entrynode, "resultfilenames" ); Node fields = XMLHandler.getSubNode( entrynode, "fields" ); // How many field arguments? int nrFields = XMLHandler.countNodes( fields, "field" ); source_filefolder = new String[nrFields]; wildcard = new String[nrFields]; conversionTypes = new int[nrFields]; // Read them all... for ( int i = 0; i < nrFields; i++ ) { Node fnode = XMLHandler.getSubNodeByNr( fields, "field", i ); source_filefolder[i] = XMLHandler.getTagValue( fnode, "source_filefolder" ); wildcard[i] = XMLHandler.getTagValue( fnode, "wildcard" ); conversionTypes[i] = getConversionTypeByCode( Const.NVL( XMLHandler.getTagValue( fnode, "ConversionType" ), "" ) ); } } catch ( KettleXMLException xe ) { throw new KettleXMLException( BaseMessages.getString( PKG, "JobDosToUnix.Error.Exception.UnableLoadXML" ), xe ); } } public void loadRep( Repository rep, IMetaStore metaStore, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers ) throws KettleException { try { arg_from_previous = rep.getJobEntryAttributeBoolean( id_jobentry, "arg_from_previous" ); include_subfolders = rep.getJobEntryAttributeBoolean( id_jobentry, "include_subfolders" ); nr_errors_less_than = rep.getJobEntryAttributeString( id_jobentry, "nr_errors_less_than" ); success_condition = rep.getJobEntryAttributeString( id_jobentry, "success_condition" ); resultfilenames = rep.getJobEntryAttributeString( id_jobentry, "resultfilenames" ); // How many arguments? int argnr = rep.countNrJobEntryAttributes( id_jobentry, "source_filefolder" ); source_filefolder = new String[argnr]; wildcard = new String[argnr]; conversionTypes = new int[argnr]; // Read them all... for ( int a = 0; a < argnr; a++ ) { source_filefolder[a] = rep.getJobEntryAttributeString( id_jobentry, a, "source_filefolder" ); wildcard[a] = rep.getJobEntryAttributeString( id_jobentry, a, "wildcard" ); conversionTypes[a] = getConversionTypeByCode( Const.NVL( rep.getJobEntryAttributeString( id_jobentry, "ConversionType" ), "" ) ); } } catch ( KettleException dbe ) { throw new KettleException( BaseMessages.getString( PKG, "JobDosToUnix.Error.Exception.UnableLoadRep" ) + id_jobentry, dbe ); } } public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_job ) throws KettleException { try { rep.saveJobEntryAttribute( id_job, getObjectId(), "arg_from_previous", arg_from_previous ); rep.saveJobEntryAttribute( id_job, getObjectId(), "include_subfolders", include_subfolders ); rep.saveJobEntryAttribute( id_job, getObjectId(), "nr_errors_less_than", nr_errors_less_than ); rep.saveJobEntryAttribute( id_job, getObjectId(), "success_condition", success_condition ); rep.saveJobEntryAttribute( id_job, getObjectId(), "resultfilenames", resultfilenames ); // save the arguments... if ( source_filefolder != null ) { for ( int i = 0; i < source_filefolder.length; i++ ) { rep.saveJobEntryAttribute( id_job, getObjectId(), i, "source_filefolder", source_filefolder[i] ); rep.saveJobEntryAttribute( id_job, getObjectId(), i, "wildcard", wildcard[i] ); rep.saveJobEntryAttribute( id_job, getObjectId(), "ConversionType", getConversionTypeCode( conversionTypes[i] ) ); } } } catch ( KettleDatabaseException dbe ) { throw new KettleException( BaseMessages.getString( PKG, "JobDosToUnix.Error.Exception.UnableSaveRep" ) + id_job, dbe ); } } public Result execute( Result previousResult, int nr ) throws KettleException { Result result = previousResult; result.setNrErrors( 1 ); result.setResult( false ); List<RowMetaAndData> rows = previousResult.getRows(); RowMetaAndData resultRow = null; nrErrors = 0; nrProcessedFiles = 0; nrErrorFiles = 0; limitFiles = Const.toInt( environmentSubstitute( getNrErrorsLessThan() ), 10 ); successConditionBroken = false; successConditionBrokenExit = false; tempFolder = environmentSubstitute( "%%java.io.tmpdir%%" ); // Get source and destination files, also wildcard String[] vsourcefilefolder = source_filefolder; String[] vwildcard = wildcard; if ( arg_from_previous ) { if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.ArgFromPrevious.Found", ( rows != null ? rows .size() : 0 ) + "" ) ); } } if ( arg_from_previous && rows != null ) // Copy the input row to the (command line) arguments { for ( int iteration = 0; iteration < rows.size() && !parentJob.isStopped(); iteration++ ) { if ( successConditionBroken ) { if ( !successConditionBrokenExit ) { logError( BaseMessages.getString( PKG, "JobDosToUnix.Error.SuccessConditionbroken", "" + nrAllErrors ) ); successConditionBrokenExit = true; } result.setEntryNr( nrAllErrors ); result.setNrLinesRejected( nrErrorFiles ); result.setNrLinesWritten( nrProcessedFiles ); return result; } resultRow = rows.get( iteration ); // Get source and destination file names, also wildcard String vsourcefilefolder_previous = resultRow.getString( 0, null ); String vwildcard_previous = resultRow.getString( 1, null ); int convertion_type = JobEntryDosToUnix.getConversionTypeByCode( resultRow.getString( 2, null ) ); if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.ProcessingRow", vsourcefilefolder_previous, vwildcard_previous ) ); } processFileFolder( vsourcefilefolder_previous, vwildcard_previous, convertion_type, parentJob, result ); } } else if ( vsourcefilefolder != null ) { for ( int i = 0; i < vsourcefilefolder.length && !parentJob.isStopped(); i++ ) { if ( successConditionBroken ) { if ( !successConditionBrokenExit ) { logError( BaseMessages.getString( PKG, "JobDosToUnix.Error.SuccessConditionbroken", "" + nrAllErrors ) ); successConditionBrokenExit = true; } result.setEntryNr( nrAllErrors ); result.setNrLinesRejected( nrErrorFiles ); result.setNrLinesWritten( nrProcessedFiles ); return result; } if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.ProcessingRow", vsourcefilefolder[i], vwildcard[i] ) ); } processFileFolder( vsourcefilefolder[i], vwildcard[i], conversionTypes[i], parentJob, result ); } } // Success Condition result.setNrErrors( nrAllErrors ); result.setNrLinesRejected( nrErrorFiles ); result.setNrLinesWritten( nrProcessedFiles ); if ( getSuccessStatus() ) { result.setNrErrors( 0 ); result.setResult( true ); } displayResults(); return result; } private void displayResults() { if ( isDetailed() ) { logDetailed( "=======================================" ); logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.Info.Errors", nrErrors ) ); logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.Info.ErrorFiles", nrErrorFiles ) ); logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.Info.FilesProcessed", nrProcessedFiles ) ); logDetailed( "=======================================" ); } } private boolean checkIfSuccessConditionBroken() { boolean retval = false; if ( ( nrAllErrors > 0 && getSuccessCondition().equals( SUCCESS_IF_NO_ERRORS ) ) || ( nrErrorFiles >= limitFiles && getSuccessCondition().equals( SUCCESS_IF_ERROR_FILES_LESS ) ) ) { retval = true; } return retval; } private boolean getSuccessStatus() { boolean retval = false; if ( ( nrAllErrors == 0 && getSuccessCondition().equals( SUCCESS_IF_NO_ERRORS ) ) || ( nrProcessedFiles >= limitFiles && getSuccessCondition() .equals( SUCCESS_IF_AT_LEAST_X_FILES_PROCESSED ) ) || ( nrErrorFiles < limitFiles && getSuccessCondition().equals( SUCCESS_IF_ERROR_FILES_LESS ) ) ) { retval = true; } return retval; } private void updateErrors() { nrErrors++; updateAllErrors(); if ( checkIfSuccessConditionBroken() ) { // Success condition was broken successConditionBroken = true; } } private void updateAllErrors() { nrAllErrors = nrErrors + nrErrorFiles; } private static int getFileType( FileObject file ) throws Exception { int aCount = 0; // occurences of LF int dCount = 0; // occurences of CR FileInputStream in = null; try { in = new FileInputStream( file.getName().getPathDecoded() ); while ( in.available() > 0 ) { int b = in.read(); if ( b == CR ) { dCount++; if ( in.available() > 0 ) { b = in.read(); if ( b == LF ) { aCount++; } else { return TYPE_BINAY_FILE; } } } else if ( b == LF ) { aCount++; } } } finally { in.close(); } if ( aCount == dCount ) { return TYPE_DOS_FILE; } else { return TYPE_UNIX_FILE; } } private boolean convert( FileObject file, boolean toUnix ) { boolean retval = false; // CR = CR // LF = LF try { String localfilename = KettleVFS.getFilename( file ); File source = new File( localfilename ); if ( isDetailed() ) { if ( toUnix ) { logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.ConvertingFileToUnix", source .getAbsolutePath() ) ); } else { logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.ConvertingFileToDos", source .getAbsolutePath() ) ); } } File tempFile = new File( tempFolder, source.getName() + ".tmp" ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "JobDosToUnix.Log.CreatingTempFile", tempFile.getAbsolutePath() ) ); } FileOutputStream out = new FileOutputStream( tempFile ); FileInputStream in = new FileInputStream( localfilename ); if ( toUnix ) { // Dos to Unix while ( in.available() > 0 ) { int b1 = in.read(); if ( b1 == CR ) { int b2 = in.read(); if ( b2 == LF ) { out.write( LF ); } else { out.write( b1 ); out.write( b2 ); } } else { out.write( b1 ); } } } else { // Unix to Dos while ( in.available() > 0 ) { int b1 = in.read(); if ( b1 == LF ) { out.write( CR ); out.write( LF ); } else { out.write( b1 ); } } } in.close(); out.close(); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "JobDosToUnix.Log.DeletingSourceFile", localfilename ) ); } file.delete(); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "JobDosToUnix.Log.RenamingTempFile", tempFile.getAbsolutePath(), source.getAbsolutePath() ) ); } tempFile.renameTo( source ); retval = true; } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobDosToUnix.Log.ErrorConvertingFile", file.toString(), e .getMessage() ) ); } return retval; } private boolean processFileFolder( String sourcefilefoldername, String wildcard, int convertion, Job parentJob, Result result ) { boolean entrystatus = false; FileObject sourcefilefolder = null; FileObject CurrentFile = null; // Get real source file and wilcard String realSourceFilefoldername = environmentSubstitute( sourcefilefoldername ); if ( Const.isEmpty( realSourceFilefoldername ) ) { logError( BaseMessages.getString( PKG, "JobDosToUnix.log.FileFolderEmpty", sourcefilefoldername ) ); // Update Errors updateErrors(); return entrystatus; } String realWildcard = environmentSubstitute( wildcard ); try { sourcefilefolder = KettleVFS.getFileObject( realSourceFilefoldername ); if ( sourcefilefolder.exists() ) { if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.FileExists", sourcefilefolder.toString() ) ); } if ( sourcefilefolder.getType() == FileType.FILE ) { entrystatus = convertOneFile( sourcefilefolder, convertion, result, parentJob ); } else if ( sourcefilefolder.getType() == FileType.FOLDER ) { FileObject[] fileObjects = sourcefilefolder.findFiles( new AllFileSelector() { public boolean traverseDescendents( FileSelectInfo info ) { return info.getDepth() == 0 || include_subfolders; } public boolean includeFile( FileSelectInfo info ) { FileObject fileObject = info.getFile(); try { if ( fileObject == null ) { return false; } if ( fileObject.getType() != FileType.FILE ) { return false; } } catch ( Exception ex ) { // Upon error don't process the file. return false; } finally { if ( fileObject != null ) { try { fileObject.close(); } catch ( IOException ex ) { /* Ignore */ } } } return true; } } ); if ( fileObjects != null ) { for ( int j = 0; j < fileObjects.length && !parentJob.isStopped(); j++ ) { if ( successConditionBroken ) { if ( !successConditionBrokenExit ) { logError( BaseMessages.getString( PKG, "JobDosToUnix.Error.SuccessConditionbroken", "" + nrAllErrors ) ); successConditionBrokenExit = true; } return false; } // Fetch files in list one after one ... CurrentFile = fileObjects[j]; if ( !CurrentFile.getParent().toString().equals( sourcefilefolder.toString() ) ) { // Not in the Base Folder..Only if include sub folders if ( include_subfolders ) { if ( GetFileWildcard( CurrentFile.toString(), realWildcard ) ) { convertOneFile( CurrentFile, convertion, result, parentJob ); } } } else { // In the base folder if ( GetFileWildcard( CurrentFile.toString(), realWildcard ) ) { convertOneFile( CurrentFile, convertion, result, parentJob ); } } } } } else { logError( BaseMessages.getString( PKG, "JobDosToUnix.Error.UnknowFileFormat", sourcefilefolder .toString() ) ); // Update Errors updateErrors(); } } else { logError( BaseMessages.getString( PKG, "JobDosToUnix.Error.SourceFileNotExists", realSourceFilefoldername ) ); // Update Errors updateErrors(); } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobDosToUnix.Error.Exception.Processing", realSourceFilefoldername .toString(), e.getMessage() ) ); // Update Errors updateErrors(); } finally { if ( sourcefilefolder != null ) { try { sourcefilefolder.close(); } catch ( IOException ex ) { /* Ignore */ } } if ( CurrentFile != null ) { try { CurrentFile.close(); } catch ( IOException ex ) { /* Ignore */ } } } return entrystatus; } private boolean convertOneFile( FileObject file, int convertion, Result result, Job parentJob ) throws KettleException { boolean retval = false; try { // We deal with a file.. boolean convertToUnix = true; if ( convertion == CONVERTION_TYPE_GUESS ) { // Get file Type int fileType = getFileType( file ); if ( fileType == TYPE_DOS_FILE ) { // File type is DOS // We need to convert it to UNIX convertToUnix = true; } else { // File type is not DOS // so let's convert it to DOS convertToUnix = false; } } else if ( convertion == CONVERTION_TYPE_DOS_TO_UNIX ) { convertToUnix = true; } else { convertToUnix = false; } retval = convert( file, convertToUnix ); if ( !retval ) { logError( BaseMessages.getString( PKG, "JobDosToUnix.Error.FileNotConverted", file.toString() ) ); // Update Bad files number updateBadFormed(); if ( resultfilenames.equals( ADD_ALL_FILENAMES ) || resultfilenames.equals( ADD_ERROR_FILES_ONLY ) ) { addFileToResultFilenames( file, result, parentJob ); } } else { if ( isDetailed() ) { logDetailed( "---------------------------" ); logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Error.FileConverted", file, convertToUnix ? "UNIX" : "DOS" ) ); } // Update processed files number updateProcessedFormed(); if ( resultfilenames.equals( ADD_ALL_FILENAMES ) || resultfilenames.equals( ADD_PROCESSED_FILES_ONLY ) ) { addFileToResultFilenames( file, result, parentJob ); } } } catch ( Exception e ) { throw new KettleException( "Unable to convert file '" + file.toString() + "'", e ); } return retval; } private void updateProcessedFormed() { nrProcessedFiles++; } private void updateBadFormed() { nrErrorFiles++; updateAllErrors(); } private void addFileToResultFilenames( FileObject fileaddentry, Result result, Job parentJob ) { try { ResultFile resultFile = new ResultFile( ResultFile.FILE_TYPE_GENERAL, fileaddentry, parentJob.getJobname(), toString() ); result.getResultFiles().put( resultFile.getFile().toString(), resultFile ); if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobDosToUnix.Log.FileAddedToResultFilesName", fileaddentry ) ); } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobDosToUnix.Error.AddingToFilenameResult", fileaddentry.toString(), e.getMessage() ) ); } } /********************************************************** * * @param selectedfile * @param wildcard * @return True if the selectedfile matches the wildcard **********************************************************/ private boolean GetFileWildcard( String selectedfile, String wildcard ) { Pattern pattern = null; boolean getIt = true; if ( !Const.isEmpty( wildcard ) ) { pattern = Pattern.compile( wildcard ); // First see if the file matches the regular expression! if ( pattern != null ) { Matcher matcher = pattern.matcher( selectedfile ); getIt = matcher.matches(); } } return getIt; } public void setIncludeSubfolders( boolean include_subfoldersin ) { this.include_subfolders = include_subfoldersin; } public void setArgFromPrevious( boolean argfrompreviousin ) { this.arg_from_previous = argfrompreviousin; } public void setNrErrorsLessThan( String nr_errors_less_than ) { this.nr_errors_less_than = nr_errors_less_than; } public String getNrErrorsLessThan() { return nr_errors_less_than; } public void setSuccessCondition( String success_condition ) { this.success_condition = success_condition; } public String getSuccessCondition() { return success_condition; } public void setResultFilenames( String resultfilenames ) { this.resultfilenames = resultfilenames; } public String getResultFilenames() { return resultfilenames; } public boolean evaluates() { return true; } }
apache-2.0
md-5/jdk10
test/jdk/sun/security/pkcs12/StoreSecretKeyTest.java
5517
/* * Copyright (c) 2013, 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. * * 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 8005408 8079129 8048830 * @summary KeyStore API enhancements * @run main StoreSecretKeyTest */ import java.io.*; import java.security.*; import java.security.cert.*; import java.security.cert.Certificate; import java.util.*; import javax.crypto.*; import javax.crypto.spec.*; // Store a secret key in a keystore and retrieve it again. public class StoreSecretKeyTest { private final static String DIR = System.getProperty("test.src", "."); private static final char[] PASSWORD = "passphrase".toCharArray(); private static final String KEYSTORE = "keystore.p12"; private static final String CERT = DIR + "/trusted.pem"; private static final String ALIAS = "my trusted cert"; private static final String ALIAS2 = "my secret key"; private enum ALGORITHM { DES(56), DESede(168), AES(128); final int len; ALGORITHM(int l) { len = l; } final int getLength() { return len; } } public static void main(String[] args) throws Exception { boolean isSecretkeyAlgSupported = false; // Skip test if AES is unavailable try { SecretKeyFactory.getInstance("AES"); } catch (NoSuchAlgorithmException nsae) { System.out.println("AES is unavailable. Skipping test..."); return; } for (ALGORITHM alg : ALGORITHM.values()) { isSecretkeyAlgSupported |= testSecretKeyAlgorithm(alg); } if (!isSecretkeyAlgSupported) { throw new Exception("None of the SecretKey algorithms is " + "supported"); } } private static boolean testSecretKeyAlgorithm(ALGORITHM algorithm) throws Exception { System.out.println("Testing algorithm : " + algorithm.name()); new File(KEYSTORE).delete(); try { KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(null, null); // Set trusted certificate entry Certificate cert = loadCertificate(CERT); keystore.setEntry(ALIAS, new KeyStore.TrustedCertificateEntry(cert), null); // Set secret key entry SecretKey secretKey = generateSecretKey(algorithm.name(), algorithm.len); if(secretKey == null) { return false; } keystore.setEntry(ALIAS2, new KeyStore.SecretKeyEntry(secretKey), new KeyStore.PasswordProtection(PASSWORD)); try (FileOutputStream outStream = new FileOutputStream(KEYSTORE)) { System.out.println("Storing keystore to: " + KEYSTORE); keystore.store(outStream, PASSWORD); } try (FileInputStream inStream = new FileInputStream(KEYSTORE)) { System.out.println("Loading keystore from: " + KEYSTORE); keystore.load(inStream, PASSWORD); System.out.println("Loaded keystore with " + keystore.size() + " entries"); } KeyStore.Entry entry = keystore.getEntry(ALIAS2, new KeyStore.PasswordProtection(PASSWORD)); System.out.println("Retrieved entry: " + entry); if (entry instanceof KeyStore.SecretKeyEntry) { System.out.println("Retrieved secret key entry: " + entry); } else { throw new Exception("Not a secret key entry"); } } catch (KeyStoreException | UnrecoverableKeyException ex) { System.out.println("Unable to check SecretKey algorithm due to " + "exception: " + ex.getMessage()); return false; } return true; } private static SecretKey generateSecretKey(String algorithm, int size) throws NoSuchAlgorithmException { KeyGenerator generator = KeyGenerator.getInstance(algorithm); generator.init(size); return generator.generateKey(); } private static Certificate loadCertificate(String certFile) throws Exception { X509Certificate cert = null; try (FileInputStream certStream = new FileInputStream(certFile)) { CertificateFactory factory = CertificateFactory.getInstance("X.509"); return factory.generateCertificate(certStream); } } }
gpl-2.0
sanyaade-g2g-repos/orientdb
core/src/main/java/com/orientechnologies/orient/core/id/ORecordId.java
10643
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.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. * * * * For more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.core.id; import com.orientechnologies.common.util.OPatternConst; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.exception.ODatabaseException; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.serialization.OBinaryProtocol; import com.orientechnologies.orient.core.serialization.OMemoryStream; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; import com.orientechnologies.orient.core.storage.OStorage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; public class ORecordId implements ORID { public static final ORecordId EMPTY_RECORD_ID = new ORecordId(); public static final byte[] EMPTY_RECORD_ID_STREAM = EMPTY_RECORD_ID.toStream(); public static final int PERSISTENT_SIZE = OBinaryProtocol.SIZE_SHORT + OBinaryProtocol.SIZE_LONG; private static final long serialVersionUID = 247070594054408657L; // INT TO AVOID JVM PENALTY, BUT IT'S STORED AS SHORT public int clusterId = CLUSTER_ID_INVALID; public long clusterPosition = CLUSTER_POS_INVALID; public ORecordId() { } public ORecordId(final int iClusterId, final long iPosition) { clusterId = iClusterId; checkClusterLimits(); clusterPosition = iPosition; } public ORecordId(final int iClusterIdId) { clusterId = iClusterIdId; checkClusterLimits(); } public ORecordId(final String iRecordId) { fromString(iRecordId); } /** * Copy constructor. * * @param parentRid * Source object */ public ORecordId(final ORID parentRid) { clusterId = parentRid.getClusterId(); clusterPosition = parentRid.getClusterPosition(); } public static String generateString(final int iClusterId, final long iPosition) { final StringBuilder buffer = new StringBuilder(12); buffer.append(PREFIX); buffer.append(iClusterId); buffer.append(SEPARATOR); buffer.append(iPosition); return buffer.toString(); } public static boolean isValid(final long pos) { return pos != CLUSTER_POS_INVALID; } public static boolean isPersistent(final long pos) { return pos > CLUSTER_POS_INVALID; } public static boolean isNew(final long pos) { return pos < 0; } public static boolean isTemporary(final long clusterPosition) { return clusterPosition < CLUSTER_POS_INVALID; } public static boolean isA(final String iString) { return OPatternConst.PATTERN_RID.matcher(iString).matches(); } public void reset() { clusterId = CLUSTER_ID_INVALID; clusterPosition = CLUSTER_POS_INVALID; } public boolean isValid() { return clusterPosition != CLUSTER_POS_INVALID; } public boolean isPersistent() { return clusterId > -1 && clusterPosition > CLUSTER_POS_INVALID; } public boolean isNew() { return clusterPosition < 0; } public boolean isTemporary() { return clusterId != -1 && clusterPosition < CLUSTER_POS_INVALID; } @Override public String toString() { return generateString(clusterId, clusterPosition); } public StringBuilder toString(StringBuilder iBuffer) { if (iBuffer == null) iBuffer = new StringBuilder(); iBuffer.append(PREFIX); iBuffer.append(clusterId); iBuffer.append(SEPARATOR); iBuffer.append(clusterPosition); return iBuffer; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof OIdentifiable)) return false; final ORecordId other = (ORecordId) ((OIdentifiable) obj).getIdentity(); if (clusterId != other.clusterId) return false; if (clusterPosition != other.clusterPosition) return false; return true; } @Override public int hashCode() { int result = clusterId; result = 31 * result + (int) (clusterPosition ^ (clusterPosition >>> 32)); return result; } public int compareTo(final OIdentifiable iOther) { if (iOther == this) return 0; if (iOther == null) return 1; final int otherClusterId = iOther.getIdentity().getClusterId(); if (clusterId == otherClusterId) { final long otherClusterPos = iOther.getIdentity().getClusterPosition(); return (clusterPosition < otherClusterPos) ? -1 : ((clusterPosition == otherClusterPos) ? 0 : 1); } else if (clusterId > otherClusterId) return 1; return -1; } public int compare(final OIdentifiable iObj1, final OIdentifiable iObj2) { if (iObj1 == iObj2) return 0; if (iObj1 != null) return iObj1.compareTo(iObj2); return -1; } public ORecordId copy() { return new ORecordId(clusterId, clusterPosition); } public ORecordId fromStream(final InputStream iStream) throws IOException { clusterId = OBinaryProtocol.bytes2short(iStream); clusterPosition = OBinaryProtocol.bytes2long(iStream); return this; } public ORecordId fromStream(final OMemoryStream iStream) { clusterId = iStream.getAsShort(); clusterPosition = iStream.getAsLong(); return this; } public ORecordId fromStream(final byte[] iBuffer) { if (iBuffer != null) { clusterId = OBinaryProtocol.bytes2short(iBuffer, 0); clusterPosition = OBinaryProtocol.bytes2long(iBuffer, OBinaryProtocol.SIZE_SHORT); } return this; } public int toStream(final OutputStream iStream) throws IOException { final int beginOffset = OBinaryProtocol.short2bytes((short) clusterId, iStream); OBinaryProtocol.long2bytes(clusterPosition, iStream); return beginOffset; } public int toStream(final OMemoryStream iStream) throws IOException { final int beginOffset = OBinaryProtocol.short2bytes((short) clusterId, iStream); OBinaryProtocol.long2bytes(clusterPosition, iStream); return beginOffset; } public byte[] toStream() { final byte[] buffer = new byte[OBinaryProtocol.SIZE_SHORT + OBinaryProtocol.SIZE_LONG]; OBinaryProtocol.short2bytes((short) clusterId, buffer, 0); OBinaryProtocol.long2bytes(clusterPosition, buffer, OBinaryProtocol.SIZE_SHORT); return buffer; } public int getClusterId() { return clusterId; } public long getClusterPosition() { return clusterPosition; } public void fromString(String iRecordId) { if (iRecordId != null) iRecordId = iRecordId.trim(); if (iRecordId == null || iRecordId.isEmpty()) { clusterId = CLUSTER_ID_INVALID; clusterPosition = CLUSTER_POS_INVALID; return; } if (!OStringSerializerHelper.contains(iRecordId, SEPARATOR)) throw new IllegalArgumentException("Argument '" + iRecordId + "' is not a RecordId in form of string. Format must be: <cluster-id>:<cluster-position>"); final List<String> parts = OStringSerializerHelper.split(iRecordId, SEPARATOR, PREFIX); if (parts.size() != 2) throw new IllegalArgumentException("Argument received '" + iRecordId + "' is not a RecordId in form of string. Format must be: #<cluster-id>:<cluster-position>. Example: #3:12"); clusterId = Integer.parseInt(parts.get(0)); checkClusterLimits(); clusterPosition = Long.parseLong(parts.get(1)); } public void copyFrom(final ORID iSource) { if (iSource == null) throw new IllegalArgumentException("Source is null"); clusterId = iSource.getClusterId(); clusterPosition = iSource.getClusterPosition(); } @Override public void lock(final boolean iExclusive) { ODatabaseRecordThreadLocal.INSTANCE.get().getTransaction() .lockRecord(this, iExclusive ? OStorage.LOCKING_STRATEGY.EXCLUSIVE_LOCK : OStorage.LOCKING_STRATEGY.SHARED_LOCK); } @Override public boolean isLocked() { return ODatabaseRecordThreadLocal.INSTANCE.get().getTransaction().isLockedRecord(this); } @Override public OStorage.LOCKING_STRATEGY lockingStrategy() { return ODatabaseRecordThreadLocal.INSTANCE.get().getTransaction().lockingStrategy(this); } @Override public void unlock() { ODatabaseRecordThreadLocal.INSTANCE.get().getTransaction().unlockRecord(this); } public String next() { return generateString(clusterId, clusterPosition + 1); } @Override public ORID nextRid() { return new ORecordId(clusterId, clusterPosition + 1); } public ORID getIdentity() { return this; } @SuppressWarnings("unchecked") public <T extends ORecord> T getRecord() { if (!isValid()) return null; final ODatabaseDocument db = ODatabaseRecordThreadLocal.INSTANCE.get(); if (db == null) throw new ODatabaseException( "No database found in current thread local space. If you manually control databases over threads assure to set the current database before to use it by calling: ODatabaseRecordThreadLocal.INSTANCE.set(db);"); return (T) db.load(this); } private void checkClusterLimits() { if (clusterId < -2) throw new ODatabaseException("RecordId cannot support negative cluster id. You've used: " + clusterId); if (clusterId > CLUSTER_MAX) throw new ODatabaseException("RecordId cannot support cluster id major than 32767. You've used: " + clusterId); } }
apache-2.0
wu99lin/generator-syp-andy
generators/app/templates/libraries/KJFrame/src/main/java/org/kymjs/kjframe/http/CacheDispatcher.java
4499
/* * Copyright (c) 2014, 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 org.kymjs.kjframe.http; import java.util.concurrent.BlockingQueue; import org.kymjs.kjframe.KJHttp; import org.kymjs.kjframe.utils.KJLoger; import android.os.Process; /** * 缓存调度器<br> * * Note:<br> * 工作描述: 缓存逻辑同样也采用责任链模式,参考注释{@link KJHttp }, * 由缓存任务队列CacheQueue,缓存调度器CacheDispatcher,缓存器Cache组成<br> * * 调度器不停的从CacheQueue中取request,并把这个request尝试从缓存器中获取缓存响应。<br> * 如果缓存器有有效且及时的缓存则直接返回缓存;<br> * 如果缓存器有有效但待刷新的有效缓存,则交给分发器去分发一次中介相应,并再去添加到工作队列中执行网络请求获取最新的数据;<br> * 如果缓存器中没有有效缓存,则把请求添加到mNetworkQueue工作队列中去执行网络请求;<br> * * Note:<br> * 关于中介相应查看{@link Response#intermediate} */ public class CacheDispatcher extends Thread { private final BlockingQueue<Request<?>> mCacheQueue; // 缓存队列 private final BlockingQueue<Request<?>> mNetworkQueue; // 用于执行网络请求的工作队列 private final Cache mCache; // 缓存器 private final Delivery mDelivery; // 分发器 private final HttpConfig mConfig; // 配置器 private volatile boolean mQuit = false; /** * 创建分发器(必须手动调用star()方法启动分发任务) * * @param cacheQueue * 缓存队列 * @param networkQueue * 正在执行的队列 * @param cache * 缓存器对象 * @param delivery * 分发器 */ public CacheDispatcher(BlockingQueue<Request<?>> cacheQueue, BlockingQueue<Request<?>> networkQueue, Cache cache, Delivery delivery, HttpConfig config) { mCacheQueue = cacheQueue; mNetworkQueue = networkQueue; mCache = cache; mDelivery = delivery; mConfig = config; } /** * 强制退出 */ public void quit() { mQuit = true; interrupt(); } /** * 工作在阻塞态 */ @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); mCache.initialize(); while (true) { try { final Request<?> request = mCacheQueue.take(); if (request.isCanceled()) { request.finish("cache-discard-canceled"); continue; } Cache.Entry entry = mCache.get(request.getCacheKey()); if (entry == null) { // 如果没有缓存,去网络请求 mNetworkQueue.put(request); continue; } // 如果缓存过期,去网络请求,图片缓存永久有效 if (entry.isExpired()) { // && !(request instanceof ImageRequest) request.setCacheEntry(entry); mNetworkQueue.put(request); continue; } // 从缓存返回数据 Response<?> response = request .parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders)); KJLoger.debugLog("CacheDispatcher:", "http resopnd from cache"); if (mConfig.useDelayCache) { sleep(mConfig.delayTime); } mDelivery.postResponse(request, response); } catch (InterruptedException e) { if (mQuit) { return; } else { continue; } } } } }
mit
SohamLawar/lire
src/test/java/net/semanticmetadata/lire/benchmarking/SerializationTest.java
5811
/* * This file is part of the LIRE project: http://www.semanticmetadata.net/lire * LIRE is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * LIRE 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 LIRE; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * We kindly ask you to refer the any or one of the following publications in * any publication mentioning or employing Lire: * * Lux Mathias, Savvas A. Chatzichristofis. Lire: Lucene Image Retrieval – * An Extensible Java CBIR Library. In proceedings of the 16th ACM International * Conference on Multimedia, pp. 1085-1088, Vancouver, Canada, 2008 * URL: http://doi.acm.org/10.1145/1459359.1459577 * * Lux Mathias. Content Based Image Retrieval with LIRE. In proceedings of the * 19th ACM International Conference on Multimedia, pp. 735-738, Scottsdale, * Arizona, USA, 2011 * URL: http://dl.acm.org/citation.cfm?id=2072432 * * Mathias Lux, Oge Marques. Visual Information Retrieval using Java and LIRE * Morgan & Claypool, 2013 * URL: http://www.morganclaypool.com/doi/abs/10.2200/S00468ED1V01Y201301ICR025 * * Copyright statement: * -------------------- * (c) 2002-2013 by Mathias Lux (mathias@juggle.at) * http://www.semanticmetadata.net/lire, http://www.lire-project.net */ package net.semanticmetadata.lire.benchmarking; import junit.framework.TestCase; import java.io.*; import java.util.StringTokenizer; /** * Created by IntelliJ IDEA. * User: Mathias Lux, mathias@juggle.at, http://www.semanticmetadata.net * Date: 12.03.2010 * Time: 12:10:38 */ public class SerializationTest extends TestCase { public void testPerformance() throws IOException { double[] array = new double[128]; for (int i = 0; i < array.length; i++) { array[i] = Math.random() * 16; } int timesDone = 100; long ms = System.currentTimeMillis(); for (int i = 0; i < timesDone; i++) { setStringRepresentationStringBuilder(getStringRepresentationStringBuilder(array)); } System.out.println("ms = " + (System.currentTimeMillis() - ms)); ms = System.currentTimeMillis(); for (int i = 0; i < timesDone; i++) { setStringRepresentationDataOut(getStringRepresentationDataOut(array)); } System.out.println("ms = " + (System.currentTimeMillis() - ms)); ms = System.currentTimeMillis(); for (int i = 0; i < timesDone; i++) { setStringRepresentationBB(getStringRepresentationBB(array)); } System.out.println("ms = " + (System.currentTimeMillis() - ms)); double[] doubles = setStringRepresentationBB(getStringRepresentationBB(array)); for (int i = 0; i < array.length; i++) { System.out.println((int) array[i] - doubles[i]); assertTrue((int) array[i] - doubles[i] == 0); } } public String getStringRepresentationStringBuilder(double[] data) { StringBuilder sb = new StringBuilder(data.length * 2 + 25); sb.append("cedd"); sb.append(' '); sb.append(data.length); sb.append(' '); for (double aData : data) { sb.append((int) aData); sb.append(' '); } return sb.toString().trim(); } public double[] setStringRepresentationStringBuilder(String s) { StringTokenizer st = new StringTokenizer(s); if (!st.nextToken().equals("cedd")) throw new UnsupportedOperationException("This is not a CEDD descriptor."); double[] data = new double[Integer.parseInt(st.nextToken())]; for (int i = 0; i < data.length; i++) { if (!st.hasMoreTokens()) throw new IndexOutOfBoundsException("Too few numbers in string representation."); data[i] = Integer.parseInt(st.nextToken()); } return data; } public byte[] getStringRepresentationDataOut(double[] data) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(out); dout.writeInt(data.length); for (double aData : data) { dout.writeInt((int) aData); } dout.flush(); return out.toByteArray(); } public double[] setStringRepresentationDataOut(byte[] in) throws IOException { ByteArrayInputStream bin = new ByteArrayInputStream(in); DataInputStream din = new DataInputStream(bin); double[] data = new double[din.readInt()]; for (int i = 0; i < data.length; i++) { data[i] = din.readInt(); } return data; } public byte[] getStringRepresentationBB(double[] data) throws IOException { byte[] result = new byte[data.length]; for (int i = 0; i < result.length; i++) { result[i] = (byte) data[i]; } return result; } public double[] setStringRepresentationBB(byte[] in) throws IOException { double[] data = new double[in.length]; for (int i = 0; i < data.length; i++) { data[i] = in[i]; } return data; } }
gpl-2.0
gnudeep/wso2-cassandra-2.x.x
src/java/org/apache/cassandra/db/filter/IDiskAtomFilter.java
5782
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db.filter; import java.io.DataInput; import java.io.IOException; import java.util.Comparator; import java.util.Iterator; import org.apache.cassandra.db.*; import org.apache.cassandra.db.columniterator.OnDiskAtomIterator; import org.apache.cassandra.db.composites.CellNameType; import org.apache.cassandra.db.composites.Composite; import org.apache.cassandra.db.composites.CType; import org.apache.cassandra.io.IVersionedSerializer; import org.apache.cassandra.io.sstable.SSTableReader; import org.apache.cassandra.io.util.DataOutputPlus; import org.apache.cassandra.io.util.FileDataInput; /** * Given an implementation-specific description of what columns to look for, provides methods * to extract the desired columns from a Memtable, SSTable, or SuperColumn. Either the get*ColumnIterator * methods will be called, or filterSuperColumn, but not both on the same object. QueryFilter * takes care of putting the two together if subcolumn filtering needs to be done, based on the * querypath that it knows (but that IFilter implementations are oblivious to). */ public interface IDiskAtomFilter { /** * returns an iterator that returns columns from the given columnFamily * matching the Filter criteria in sorted order. */ public Iterator<Cell> getColumnIterator(ColumnFamily cf); public OnDiskAtomIterator getColumnIterator(DecoratedKey key, ColumnFamily cf); /** * Get an iterator that returns columns from the given SSTable using the opened file * matching the Filter criteria in sorted order. * @param sstable * @param file Already opened file data input, saves us opening another one * @param key The key of the row we are about to iterate over */ public OnDiskAtomIterator getSSTableColumnIterator(SSTableReader sstable, FileDataInput file, DecoratedKey key, RowIndexEntry indexEntry); /** * returns an iterator that returns columns from the given SSTable * matching the Filter criteria in sorted order. */ public OnDiskAtomIterator getSSTableColumnIterator(SSTableReader sstable, DecoratedKey key); /** * collects columns from reducedColumns into returnCF. Termination is determined * by the filter code, which should have some limit on the number of columns * to avoid running out of memory on large rows. */ public void collectReducedColumns(ColumnFamily container, Iterator<Cell> reducedColumns, int gcBefore, long now); public Comparator<Cell> getColumnComparator(CellNameType comparator); public boolean isReversed(); public void updateColumnsLimit(int newLimit); public int getLiveCount(ColumnFamily cf, long now); public ColumnCounter columnCounter(CellNameType comparator, long now); public IDiskAtomFilter cloneShallow(); public boolean maySelectPrefix(CType type, Composite prefix); public boolean shouldInclude(SSTableReader sstable); public boolean countCQL3Rows(CellNameType comparator); public boolean isHeadFilter(); /** * Whether the provided cf, that is assumed to contain the head of the * partition, contains enough data to cover this filter. */ public boolean isFullyCoveredBy(ColumnFamily cf, long now); public static class Serializer implements IVersionedSerializer<IDiskAtomFilter> { private final CellNameType type; public Serializer(CellNameType type) { this.type = type; } public void serialize(IDiskAtomFilter filter, DataOutputPlus out, int version) throws IOException { if (filter instanceof SliceQueryFilter) { out.writeByte(0); type.sliceQueryFilterSerializer().serialize((SliceQueryFilter)filter, out, version); } else { out.writeByte(1); type.namesQueryFilterSerializer().serialize((NamesQueryFilter)filter, out, version); } } public IDiskAtomFilter deserialize(DataInput in, int version) throws IOException { int b = in.readByte(); if (b == 0) { return type.sliceQueryFilterSerializer().deserialize(in, version); } else { assert b == 1; return type.namesQueryFilterSerializer().deserialize(in, version); } } public long serializedSize(IDiskAtomFilter filter, int version) { int size = 1; if (filter instanceof SliceQueryFilter) size += type.sliceQueryFilterSerializer().serializedSize((SliceQueryFilter)filter, version); else size += type.namesQueryFilterSerializer().serializedSize((NamesQueryFilter)filter, version); return size; } } public Iterator<RangeTombstone> getRangeTombstoneIterator(ColumnFamily source); }
apache-2.0
cymcsg/UltimateAndroid
deprecated/UltimateAndroidGradle/ultimateandroiduianimation/src/main/java/com/marshalchen/common/uimodule/androidanimations/rotating_exits/RotateOutUpRightAnimator.java
1929
/* * 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.rotating_exits; import android.view.View; import com.marshalchen.common.uimodule.androidanimations.BaseViewAnimator; import com.nineoldandroids.animation.ObjectAnimator; public class RotateOutUpRightAnimator extends BaseViewAnimator { @Override public void prepare(View target) { float x = target.getWidth() - target.getPaddingRight(); float y = target.getHeight() - target.getPaddingBottom(); getAnimatorAgent().playTogether( ObjectAnimator.ofFloat(target, "alpha", 1, 0), ObjectAnimator.ofFloat(target,"rotation",0,90), ObjectAnimator.ofFloat(target,"pivotX",x,x), ObjectAnimator.ofFloat(target,"pivotY",y,y) ); } }
apache-2.0
Ant-Droid/android_frameworks_base_OLD
test-runner/src/android/test/TestSuiteProvider.java
808
/* * 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 android.test; import junit.framework.TestSuite; /** * Implementors will know how to get a test suite. */ public interface TestSuiteProvider { TestSuite getTestSuite(); }
apache-2.0
renatoathaydes/checker-framework
framework/jtreg/BinaryDefaultTestBinary.java
165
public class BinaryDefaultTestBinary { public static BinaryDefaultTestBinary foo(BinaryDefaultTestInterface foo) { return new BinaryDefaultTestBinary(); } }
gpl-2.0
google/error-prone-javac
test/tools/javac/diags/examples/PackageEmptyOrNotFoundError/modulesourcepath/m1x/module-info.java
1089
/* * Copyright (c) 2016, 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. * * 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. */ module m1x { exports p1; }
gpl-2.0
DariusX/camel
components/camel-spring-redis/src/main/java/org/apache/camel/component/redis/RedisConstants.java
2073
/* * 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.redis; public interface RedisConstants { String COMMAND = "CamelRedis.Command"; String KEY = "CamelRedis.Key"; String KEYS = "CamelRedis.Keys"; String FIELD = "CamelRedis.Field"; String FIELDS = "CamelRedis.Fields"; String VALUE = "CamelRedis.Value"; String VALUES = "CamelRedis.Values"; String START = "CamelRedis.Start"; String END = "CamelRedis.End"; String TIMEOUT = "CamelRedis.Timeout"; String OFFSET = "CamelRedis.Offset"; String DESTINATION = "CamelRedis.Destination"; String CHANNEL = "CamelRedis.Channel"; String MESSAGE = "CamelRedis.Message"; String INDEX = "CamelRedis.Index"; String POSITION = "CamelRedis.Position"; String PIVOT = "CamelRedis.Pivot"; String COUNT = "CamelRedis.Count"; String TIMESTAMP = "CamelRedis.Timestamp"; String PATTERN = "CamelRedis.Pattern"; String DB = "CamelRedis.Db"; String SCORE = "CamelRedis.Score"; String MIN = "CamelRedis.Min"; String MAX = "CamelRedis.Max"; String INCREMENT = "CamelRedis.Increment"; String WITHSCORE = "CamelRedis.WithScore"; String LATITUDE = "CamelRedis.Latitude"; String LONGITUDE = "CamelRedis.Longitude"; String RADIUS = "CamelRedis.Radius"; }
apache-2.0
mdanielwork/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/unnecessaryTostring/beforeConflictingFixes.java
282
// "Fix all 'Unnecessary call to 'toString()'' problems in file" "true" public class MyFile { interface UUID {} interface InetAddress {} void test(UUID uuid, InetAddress address) { // IDEA-126310 String nodeString = uuid.toStr<caret>ing() + address.toString(); } }
apache-2.0
GlenRSmith/elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoresRequest.java
4154
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.action.admin.indices.shards; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.master.MasterNodeReadRequest; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; import java.util.EnumSet; /** * Request for {@link IndicesShardStoresAction} */ public class IndicesShardStoresRequest extends MasterNodeReadRequest<IndicesShardStoresRequest> implements IndicesRequest.Replaceable { private String[] indices = Strings.EMPTY_ARRAY; private IndicesOptions indicesOptions = IndicesOptions.strictExpand(); private EnumSet<ClusterHealthStatus> statuses = EnumSet.of(ClusterHealthStatus.YELLOW, ClusterHealthStatus.RED); /** * Create a request for shard stores info for <code>indices</code> */ public IndicesShardStoresRequest(String... indices) { this.indices = indices; } public IndicesShardStoresRequest() {} public IndicesShardStoresRequest(StreamInput in) throws IOException { super(in); indices = in.readStringArray(); int nStatus = in.readVInt(); statuses = EnumSet.noneOf(ClusterHealthStatus.class); for (int i = 0; i < nStatus; i++) { statuses.add(ClusterHealthStatus.readFrom(in)); } indicesOptions = IndicesOptions.readIndicesOptions(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArrayNullable(indices); out.writeVInt(statuses.size()); for (ClusterHealthStatus status : statuses) { out.writeByte(status.value()); } indicesOptions.writeIndicesOptions(out); } /** * Set statuses to filter shards to get stores info on. * see {@link ClusterHealthStatus} for details. * Defaults to "yellow" and "red" status * @param shardStatuses acceptable values are "green", "yellow", "red" and "all" */ public IndicesShardStoresRequest shardStatuses(String... shardStatuses) { statuses = EnumSet.noneOf(ClusterHealthStatus.class); for (String statusString : shardStatuses) { if ("all".equalsIgnoreCase(statusString)) { statuses = EnumSet.allOf(ClusterHealthStatus.class); return this; } statuses.add(ClusterHealthStatus.fromString(statusString)); } return this; } /** * Specifies what type of requested indices to ignore and wildcard indices expressions * By default, expands wildcards to both open and closed indices */ public IndicesShardStoresRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } /** * Sets the indices for the shard stores request */ @Override public IndicesShardStoresRequest indices(String... indices) { this.indices = indices; return this; } @Override public boolean includeDataStreams() { return true; } /** * Returns the shard criteria to get store information on */ public EnumSet<ClusterHealthStatus> shardStatuses() { return statuses; } @Override public String[] indices() { return indices; } @Override public IndicesOptions indicesOptions() { return indicesOptions; } @Override public ActionRequestValidationException validate() { return null; } }
apache-2.0
PaoloRotolo/android-UniversalMusicPlayer
mobile/src/main/java/com/example/android/uamp/ui/ActionBarCastActivity.java
13799
/* * Copyright (C) 2014 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.example.android.uamp.ui; import android.app.ActivityOptions; import android.app.FragmentManager; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.MediaRouteButton; import android.support.v7.media.MediaRouter; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import com.example.android.uamp.R; import com.example.android.uamp.UAMPApplication; import com.example.android.uamp.utils.LogHelper; import com.example.android.uamp.utils.PrefUtils; import com.example.android.uamp.utils.ResourceHelper; import com.github.amlcurran.showcaseview.ShowcaseView; import com.github.amlcurran.showcaseview.targets.ViewTarget; import com.google.sample.castcompanionlibrary.cast.VideoCastManager; import com.google.sample.castcompanionlibrary.cast.callbacks.VideoCastConsumerImpl; /** * Abstract activity with toolbar, navigation drawer and cast support. Needs to be extended by * any activity that wants to be shown as a top level activity. * * The requirements for a subclass is to call {@link #initializeToolbar()} on onCreate, after * setContentView() is called and have three mandatory layout elements: * a {@link android.support.v7.widget.Toolbar} with id 'toolbar', * a {@link android.support.v4.widget.DrawerLayout} with id 'drawerLayout' and * a {@link android.widget.ListView} with id 'drawerList'. */ public abstract class ActionBarCastActivity extends ActionBarActivity { private static final String TAG = LogHelper.makeLogTag(ActionBarCastActivity.class); private static final int DELAY_MILLIS = 1000; private VideoCastManager mCastManager; private MenuItem mMediaRouteMenuItem; private Toolbar mToolbar; private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerList; private DrawerMenuContents mDrawerMenuContents; private boolean mToolbarInitialized; private int mItemToOpenWhenDrawerCloses = -1; private VideoCastConsumerImpl mCastConsumer = new VideoCastConsumerImpl() { @Override public void onFailed(int resourceId, int statusCode) { LogHelper.d(TAG, "onFailed ", resourceId, " status ", statusCode); } @Override public void onConnectionSuspended(int cause) { LogHelper.d(TAG, "onConnectionSuspended() was called with cause: ", cause); } @Override public void onConnectivityRecovered() { } @Override public void onCastDeviceDetected(final MediaRouter.RouteInfo info) { // FTU stands for First Time Use: if (!PrefUtils.isFtuShown(ActionBarCastActivity.this)) { // If user is seeing the cast button for the first time, we will // show an overlay that explains what that button means. PrefUtils.setFtuShown(ActionBarCastActivity.this, true); LogHelper.d(TAG, "Route is visible: ", info); new Handler().postDelayed(new Runnable() { @Override public void run() { if (mMediaRouteMenuItem.isVisible()) { LogHelper.d(TAG, "Cast Icon is visible: ", info.getName()); showFtu(); } } }, DELAY_MILLIS); } } }; private DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.DrawerListener() { @Override public void onDrawerClosed(View drawerView) { if (mDrawerToggle != null) mDrawerToggle.onDrawerClosed(drawerView); int position = mItemToOpenWhenDrawerCloses; if (position >= 0) { Bundle extras = ActivityOptions.makeCustomAnimation( ActionBarCastActivity.this, R.anim.fade_in, R.anim.fade_out).toBundle(); Class activityClass = mDrawerMenuContents.getActivity(position); startActivity(new Intent(ActionBarCastActivity.this, activityClass), extras); } } @Override public void onDrawerStateChanged(int newState) { if (mDrawerToggle != null) mDrawerToggle.onDrawerStateChanged(newState); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { if (mDrawerToggle != null) mDrawerToggle.onDrawerSlide(drawerView, slideOffset); } @Override public void onDrawerOpened(View drawerView) { if (mDrawerToggle != null) mDrawerToggle.onDrawerOpened(drawerView); getSupportActionBar().setTitle(R.string.app_name); } }; private FragmentManager.OnBackStackChangedListener mBackStackChangedListener = new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { updateDrawerToggle(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LogHelper.d(TAG, "Activity onCreate"); // Ensure that Google Play Service is available. VideoCastManager.checkGooglePlayServices(this); mCastManager = ((UAMPApplication) getApplication()).getCastManager(this); mCastManager.reconnectSessionIfPossible(); } @Override protected void onStart() { super.onStart(); if (!mToolbarInitialized) { throw new IllegalStateException("You must run super.initializeToolbar at " + "the end of your onCreate method"); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); if (mDrawerToggle != null) { mDrawerToggle.syncState(); } } @Override public void onResume() { super.onResume(); mCastManager.addVideoCastConsumer(mCastConsumer); mCastManager.incrementUiCounter(); // Whenever the fragment back stack changes, we may need to update the // action bar toggle: only top level screens show the hamburger-like icon, inner // screens - either Activities or fragments - show the "Up" icon instead. getFragmentManager().addOnBackStackChangedListener(mBackStackChangedListener); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (mDrawerToggle != null) { mDrawerToggle.onConfigurationChanged(newConfig); } } @Override public void onPause() { super.onPause(); mCastManager.removeVideoCastConsumer(mCastConsumer); mCastManager.decrementUiCounter(); getFragmentManager().removeOnBackStackChangedListener(mBackStackChangedListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.main, menu); mMediaRouteMenuItem = mCastManager.addMediaRouterButton(menu, R.id.media_route_menu_item); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle != null && mDrawerToggle.onOptionsItemSelected(item)) { return true; } // If not handled by drawerToggle, home needs to be handled by returning to previous if (item != null && item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { // If the drawer is open, back will close it if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(Gravity.START)) { mDrawerLayout.closeDrawers(); return; } // Otherwise, it may return to the previous fragment stack FragmentManager fragmentManager = getFragmentManager(); if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); } else { // Lastly, it will rely on the system behavior for back super.onBackPressed(); } } @Override public void setTitle(CharSequence title) { super.setTitle(title); mToolbar.setTitle(title); } @Override public void setTitle(int titleId) { super.setTitle(titleId); mToolbar.setTitle(titleId); } protected void initializeToolbar() { mToolbar = (Toolbar) findViewById(R.id.toolbar); if (mToolbar == null) { throw new IllegalStateException("Layout is required to include a Toolbar with id " + "'toolbar'"); } mToolbar.inflateMenu(R.menu.main); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); if (mDrawerLayout != null) { mDrawerList = (ListView) findViewById(R.id.drawer_list); if (mDrawerList == null) { throw new IllegalStateException("A layout with a drawerLayout is required to" + "include a ListView with id 'drawerList'"); } // Create an ActionBarDrawerToggle that will handle opening/closing of the drawer: mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open_content_drawer, R.string.close_content_drawer); mDrawerLayout.setDrawerListener(mDrawerListener); mDrawerLayout.setStatusBarBackgroundColor( ResourceHelper.getThemeColor(this, R.attr.colorPrimary, android.R.color.black)); populateDrawerItems(); setSupportActionBar(mToolbar); updateDrawerToggle(); } else { setSupportActionBar(mToolbar); } mToolbarInitialized = true; } private void populateDrawerItems() { mDrawerMenuContents = new DrawerMenuContents(this); final int selectedPosition = mDrawerMenuContents.getPosition(this.getClass()); final int unselectedColor = getResources().getColor(R.color.white); final int selectedColor = getResources().getColor(R.color.drawer_item_selected_background); SimpleAdapter adapter = new SimpleAdapter(this, mDrawerMenuContents.getItems(), R.layout.drawer_list_item, new String[]{DrawerMenuContents.FIELD_TITLE, DrawerMenuContents.FIELD_ICON}, new int[]{R.id.drawer_item_title, R.id.drawer_item_icon}) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); int color = unselectedColor; if (position == selectedPosition) { color = selectedColor; } view.setBackgroundColor(color); return view; } }; mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position != selectedPosition) { view.setBackgroundColor(getResources().getColor( R.color.drawer_item_selected_background)); mItemToOpenWhenDrawerCloses = position; } mDrawerLayout.closeDrawers(); } }); mDrawerList.setAdapter(adapter); } protected void updateDrawerToggle() { if (mDrawerToggle == null) { return; } boolean isRoot = getFragmentManager().getBackStackEntryCount() == 0; mDrawerToggle.setDrawerIndicatorEnabled(isRoot); getSupportActionBar().setDisplayShowHomeEnabled(!isRoot); getSupportActionBar().setDisplayHomeAsUpEnabled(!isRoot); getSupportActionBar().setHomeButtonEnabled(!isRoot); if (isRoot) { mDrawerToggle.syncState(); } } /** * Shows the Cast First Time User experience to the user (an overlay that explains what is * the Cast icon) */ private void showFtu() { Menu menu = mToolbar.getMenu(); View view = menu.findItem(R.id.media_route_menu_item).getActionView(); if (view != null && view instanceof MediaRouteButton) { new ShowcaseView.Builder(this) .setTarget(new ViewTarget(view)) .setContentTitle(R.string.touch_to_cast) .hideOnTouchOutside() .build(); } } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/javax/imageio/stream/FileCacheImageOutputStream.java
8233
/* * Copyright (c) 2000, 2007, 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.imageio.stream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import com.sun.imageio.stream.StreamCloser; /** * An implementation of <code>ImageOutputStream</code> that writes its * output to a regular <code>OutputStream</code>. A file is used to * cache data until it is flushed to the output stream. * */ public class FileCacheImageOutputStream extends ImageOutputStreamImpl { private OutputStream stream; private File cacheFile; private RandomAccessFile cache; // Pos after last (rightmost) byte written private long maxStreamPos = 0L; /** The CloseAction that closes the stream in * the StreamCloser's shutdown hook */ private final StreamCloser.CloseAction closeAction; /** * Constructs a <code>FileCacheImageOutputStream</code> that will write * to a given <code>outputStream</code>. * * <p> A temporary file is used as a cache. If * <code>cacheDir</code>is non-<code>null</code> and is a * directory, the file will be created there. If it is * <code>null</code>, the system-dependent default temporary-file * directory will be used (see the documentation for * <code>File.createTempFile</code> for details). * * @param stream an <code>OutputStream</code> to write to. * @param cacheDir a <code>File</code> indicating where the * cache file should be created, or <code>null</code> to use the * system directory. * * @exception IllegalArgumentException if <code>stream</code> * is <code>null</code>. * @exception IllegalArgumentException if <code>cacheDir</code> is * non-<code>null</code> but is not a directory. * @exception IOException if a cache file cannot be created. */ public FileCacheImageOutputStream(OutputStream stream, File cacheDir) throws IOException { if (stream == null) { throw new IllegalArgumentException("stream == null!"); } if ((cacheDir != null) && !(cacheDir.isDirectory())) { throw new IllegalArgumentException("Not a directory!"); } this.stream = stream; this.cacheFile = File.createTempFile("imageio", ".tmp", cacheDir); this.cache = new RandomAccessFile(cacheFile, "rw"); this.closeAction = StreamCloser.createCloseAction(this); StreamCloser.addToQueue(closeAction); } public int read() throws IOException { checkClosed(); bitOffset = 0; int val = cache.read(); if (val != -1) { ++streamPos; } return val; } public int read(byte[] b, int off, int len) throws IOException { checkClosed(); if (b == null) { throw new NullPointerException("b == null!"); } if (off < 0 || len < 0 || off + len > b.length || off + len < 0) { throw new IndexOutOfBoundsException ("off < 0 || len < 0 || off+len > b.length || off+len < 0!"); } bitOffset = 0; if (len == 0) { return 0; } int nbytes = cache.read(b, off, len); if (nbytes != -1) { streamPos += nbytes; } return nbytes; } public void write(int b) throws IOException { flushBits(); // this will call checkClosed() for us cache.write(b); ++streamPos; maxStreamPos = Math.max(maxStreamPos, streamPos); } public void write(byte[] b, int off, int len) throws IOException { flushBits(); // this will call checkClosed() for us cache.write(b, off, len); streamPos += len; maxStreamPos = Math.max(maxStreamPos, streamPos); } public long length() { try { checkClosed(); return cache.length(); } catch (IOException e) { return -1L; } } /** * Sets the current stream position and resets the bit offset to * 0. It is legal to seek past the end of the file; an * <code>EOFException</code> will be thrown only if a read is * performed. The file length will not be increased until a write * is performed. * * @exception IndexOutOfBoundsException if <code>pos</code> is smaller * than the flushed position. * @exception IOException if any other I/O error occurs. */ public void seek(long pos) throws IOException { checkClosed(); if (pos < flushedPos) { throw new IndexOutOfBoundsException(); } cache.seek(pos); this.streamPos = cache.getFilePointer(); maxStreamPos = Math.max(maxStreamPos, streamPos); this.bitOffset = 0; } /** * Returns <code>true</code> since this * <code>ImageOutputStream</code> caches data in order to allow * seeking backwards. * * @return <code>true</code>. * * @see #isCachedMemory * @see #isCachedFile */ public boolean isCached() { return true; } /** * Returns <code>true</code> since this * <code>ImageOutputStream</code> maintains a file cache. * * @return <code>true</code>. * * @see #isCached * @see #isCachedMemory */ public boolean isCachedFile() { return true; } /** * Returns <code>false</code> since this * <code>ImageOutputStream</code> does not maintain a main memory * cache. * * @return <code>false</code>. * * @see #isCached * @see #isCachedFile */ public boolean isCachedMemory() { return false; } /** * Closes this <code>FileCacheImageOutputStream</code>. All * pending data is flushed to the output, and the cache file * is closed and removed. The destination <code>OutputStream</code> * is not closed. * * @exception IOException if an error occurs. */ public void close() throws IOException { maxStreamPos = cache.length(); seek(maxStreamPos); flushBefore(maxStreamPos); super.close(); cache.close(); cache = null; cacheFile.delete(); cacheFile = null; stream.flush(); stream = null; StreamCloser.removeFromQueue(closeAction); } public void flushBefore(long pos) throws IOException { long oFlushedPos = flushedPos; super.flushBefore(pos); // this will call checkClosed() for us long flushBytes = flushedPos - oFlushedPos; if (flushBytes > 0) { int bufLen = 512; byte[] buf = new byte[bufLen]; cache.seek(oFlushedPos); while (flushBytes > 0) { int len = (int)Math.min(flushBytes, bufLen); cache.readFully(buf, 0, len); stream.write(buf, 0, len); flushBytes -= len; } stream.flush(); } } }
mit
Arvoreen/lombok
test/pretty/resource/before/Lambda.java
216
// version 8: public class Lambda { Runnable r = () -> System.out.println(); java.util.Comparator<Integer> c1 = (a, b) -> a - b; java.util.Comparator<Integer> c2 = (Integer a, Integer b) -> { return a - b; }; }
mit
Samernieve/EnderIO
src/api/java/appeng/api/implementations/tiles/ICrystalGrowthAccelerator.java
1256
/* * The MIT License (MIT) * * Copyright (c) 2013 AlgorithmX2 * * 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 appeng.api.implementations.tiles; public interface ICrystalGrowthAccelerator { boolean isPowered(); }
unlicense
phvu/nd4j
nd4j-jcublas-parent/nd4j-jcublas-common/src/main/java/jcuda/runtime/cudaEvent_t.java
1751
/* * * * Copyright 2015 Skymind,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 jcuda.runtime; import jcuda.NativePointerObject; import jcuda.driver.CUevent; /** * Java port of a cudaEvent_t. * * @see JCuda#cudaEventCreate * @see JCuda#cudaEventDestroy * @see JCuda#cudaEventElapsedTime * @see JCuda#cudaEventQuery * @see JCuda#cudaEventRecord * @see JCuda#cudaEventSynchronize */ public class cudaEvent_t extends NativePointerObject { /** * Creates a new, uninitialized cudaEvent_t */ public cudaEvent_t() { } /** * Creates a cudaEvent_t for the given {@link CUevent}. This * corresponds to casting a CUevent to a cudaEvent_t. * * @param event The other event */ public cudaEvent_t(CUevent event) { super(event); } /** * Returns a String representation of this object. * * @return A String representation of this object. */ @Override public String toString() { return "cudaEvent_t["+ "nativePointer="+getNativePointer()+"]"; } }
apache-2.0
dke-knu/i2am
rdma-based-storm/external/storm-hbase/src/main/java/org/apache/storm/hbase/trident/mapper/SimpleTridentHBaseMapper.java
2992
/** * 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.hbase.trident.mapper; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.hbase.bolt.mapper.HBaseMapper; import org.apache.storm.hbase.common.ColumnList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.storm.trident.tuple.TridentTuple; import static org.apache.storm.hbase.common.Utils.toBytes; import static org.apache.storm.hbase.common.Utils.toLong; /** * */ public class SimpleTridentHBaseMapper implements TridentHBaseMapper { private static final Logger LOG = LoggerFactory.getLogger(SimpleTridentHBaseMapper.class); private String rowKeyField; private byte[] columnFamily; private Fields columnFields; private Fields counterFields; public SimpleTridentHBaseMapper(){ } public SimpleTridentHBaseMapper withRowKeyField(String rowKeyField){ this.rowKeyField = rowKeyField; return this; } public SimpleTridentHBaseMapper withColumnFields(Fields columnFields){ this.columnFields = columnFields; return this; } public SimpleTridentHBaseMapper withCounterFields(Fields counterFields){ this.counterFields = counterFields; return this; } public SimpleTridentHBaseMapper withColumnFamily(String columnFamily){ this.columnFamily = columnFamily.getBytes(); return this; } @Override public byte[] rowKey(TridentTuple tuple) { Object objVal = tuple.getValueByField(this.rowKeyField); return toBytes(objVal); } @Override public ColumnList columns(TridentTuple tuple) { ColumnList cols = new ColumnList(); if(this.columnFields != null){ // TODO timestamps for(String field : this.columnFields){ cols.addColumn(this.columnFamily, field.getBytes(), toBytes(tuple.getValueByField(field))); } } if(this.counterFields != null){ for(String field : this.counterFields){ cols.addCounter(this.columnFamily, field.getBytes(), toLong(tuple.getValueByField(field))); } } return cols; } }
apache-2.0
coding0011/elasticsearch
x-pack/plugin/sql/qa/multi-node/src/test/java/org/elasticsearch/xpack/sql/qa/multi_node/JdbcPreparedStatementIT.java
440
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.sql.qa.multi_node; import org.elasticsearch.xpack.sql.qa.jdbc.PreparedStatementTestCase; public class JdbcPreparedStatementIT extends PreparedStatementTestCase { }
apache-2.0
tubemogul/druid
services/src/main/java/io/druid/cli/convert/ValueConverter.java
1714
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.cli.convert; import com.google.common.collect.ImmutableMap; import java.util.Map; import java.util.Properties; /** * */ public class ValueConverter implements PropertyConverter { private final Map<String, String> valueMap; private final String property; public ValueConverter(String property, Map<String, String> valueMap){ this.property = property; this.valueMap = valueMap; } @Override public boolean canHandle(String property) { return this.property.equals(property); } @Override public Map<String, String> convert(Properties properties) { final String oldValue = properties.getProperty(this.property); if(null == oldValue){ return ImmutableMap.of(); } final String newValue = valueMap.get(oldValue); if(null == newValue){ return ImmutableMap.of(); } return ImmutableMap.of(this.property, newValue); } }
apache-2.0
Elishtar/jcommune
jcommune-service/src/main/java/org/jtalks/jcommune/service/nontransactional/package-info.java
908
/** * Copyright (C) 2011 JTalks.org Team * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * * Package for non-transactional service implementations. * */ package org.jtalks.jcommune.service.nontransactional;
lgpl-2.1
wouterv/orientdb
core/src/main/java/com/orientechnologies/orient/core/sql/functions/text/OSQLMethodReplace.java
1605
/* * Copyright 2013 Orient Technologies. * Copyright 2013 Geomatys. * * 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.orientechnologies.orient.core.sql.functions.text; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.sql.method.misc.OAbstractSQLMethod; /** * Replaces all the occurrences. * * @author Johann Sorel (Geomatys) * @author Luca Garulli */ public class OSQLMethodReplace extends OAbstractSQLMethod { public static final String NAME = "replace"; public OSQLMethodReplace() { super(NAME, 2, 2); } @Override public String getSyntax() { return "replace(<to-find>, <to-replace>)"; } @Override public Object execute(Object iThis, OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iParams) { if (iThis == null || iParams[0] == null || iParams[1] == null) { return iParams[0]; } return iThis.toString().replace(iParams[0].toString(), iParams[1].toString()); } }
apache-2.0
GeeChao/mockito
src/org/mockito/verification/VerificationMode.java
1054
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.verification; import org.mockito.Mockito; import org.mockito.internal.verification.api.VerificationData; /** * Allows verifying that certain behavior happened at least once / exact number * of times / never. E.g: * * <pre class="code"><code class="java"> * verify(mock, times(5)).someMethod(&quot;was called five times&quot;); * * verify(mock, never()).someMethod(&quot;was never called&quot;); * * verify(mock, atLeastOnce()).someMethod(&quot;was called at least once&quot;); * * verify(mock, atLeast(2)).someMethod(&quot;was called at least twice&quot;); * * verify(mock, atMost(3)).someMethod(&quot;was called at most 3 times&quot;); * * </code></pre> * * <b>times(1) is the default</b> and can be omitted * <p> * See examples in javadoc for {@link Mockito#verify(Object, VerificationMode)} */ public interface VerificationMode { void verify(VerificationData data); }
mit
hurricup/intellij-community
java/debugger/impl/src/com/intellij/debugger/codeinsight/RuntimeTypeEvaluator.java
4762
/* * 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.debugger.codeinsight; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.DebuggerInvocationUtil; import com.intellij.debugger.EvaluatingComputable; import com.intellij.debugger.engine.ContextUtil; import com.intellij.debugger.engine.DebuggerUtils; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil; import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; import com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl; import com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator; import com.intellij.debugger.impl.DebuggerContextImpl; import com.intellij.debugger.ui.EditorEvaluationCommand; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.sun.jdi.ClassType; import com.sun.jdi.InterfaceType; import com.sun.jdi.Type; import com.sun.jdi.Value; import org.jetbrains.annotations.Nullable; /** * @author peter */ public abstract class RuntimeTypeEvaluator extends EditorEvaluationCommand<PsiType> { public RuntimeTypeEvaluator(@Nullable Editor editor, PsiElement expression, DebuggerContextImpl context, final ProgressIndicator indicator) { super(editor, expression, context, indicator); } public void threadAction() { PsiType type = null; try { type = evaluate(); } catch (ProcessCanceledException ignored) { } catch (EvaluateException ignored) { } finally { typeCalculationFinished(type); } } protected abstract void typeCalculationFinished(@Nullable PsiType type); @Nullable protected PsiType evaluate(final EvaluationContextImpl evaluationContext) throws EvaluateException { final Project project = evaluationContext.getProject(); ExpressionEvaluator evaluator = DebuggerInvocationUtil.commitAndRunReadAction(project, new EvaluatingComputable<ExpressionEvaluator>() { public ExpressionEvaluator compute() throws EvaluateException { return EvaluatorBuilderImpl.getInstance().build(myElement, ContextUtil.getSourcePosition(evaluationContext)); } }); final Value value = evaluator.evaluate(evaluationContext); if(value != null){ return getCastableRuntimeType(project, value); } throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.surrounded.expression.null")); } @Nullable public static PsiType getCastableRuntimeType(Project project, Value value) { Type type = value.type(); PsiType psiType = findPsiType(project, type); if (psiType != null) { return psiType; } if (type instanceof ClassType) { ClassType superclass = ((ClassType)type).superclass(); if (superclass != null && !CommonClassNames.JAVA_LANG_OBJECT.equals(superclass.name())) { psiType = findPsiType(project, superclass); if (psiType != null) { return psiType; } } for (InterfaceType interfaceType : ((ClassType)type).interfaces()) { psiType = findPsiType(project, interfaceType); if (psiType != null) { return psiType; } } } return null; } private static PsiType findPsiType(Project project, Type type) { AccessToken token = ReadAction.start(); try { return DebuggerUtils.getType(type.name().replace('$', '.'), project); } finally { token.finish(); } } public static boolean isSubtypeable(PsiExpression expr) { final PsiType type = expr.getType(); if (type instanceof PsiPrimitiveType) { return false; } if (type instanceof PsiClassType) { final PsiClass psiClass = ((PsiClassType)type).resolve(); if (psiClass != null && psiClass.hasModifierProperty(PsiModifier.FINAL)) { return false; } } return true; } }
apache-2.0
CandleCandle/camel
camel-core/src/test/java/org/apache/camel/component/properties/PropertiesResolverTest.java
2514
/** * 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.properties; import java.util.Properties; import org.apache.camel.CamelContext; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; /** * @version */ public class PropertiesResolverTest extends ContextTestSupport { public void testPropertiesResolver() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("properties:foo"); } }); } }; } protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); PropertiesComponent pc = new PropertiesComponent(); pc.setLocation("foo"); pc.setPropertiesResolver(new MyCustomResolver()); context.addComponent("properties", pc); return context; } public static class MyCustomResolver implements PropertiesResolver { public Properties resolveProperties(CamelContext context, boolean ignoreMissingLocation, String... uri) throws Exception { Properties answer = new Properties(); answer.put("foo", "mock:result"); return answer; } } }
apache-2.0
hizhangqi/jmeter-1
src/protocol/http/org/apache/jmeter/protocol/http/proxy/SamplerCreator.java
3489
/* * 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.jmeter.protocol.http.proxy; import java.util.List; import java.util.Map; import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.testelement.TestElement; /** * Factory of sampler */ public interface SamplerCreator { /** * @return String[] array of Content types managed by Factory */ String[] getManagedContentTypes(); /** * Create HTTPSamplerBase * @param request {@link HttpRequestHdr} * @param pageEncodings Map of page encodings * @param formEncodings Map of form encodings * @return {@link HTTPSamplerBase} */ HTTPSamplerBase createSampler(HttpRequestHdr request, Map<String, String> pageEncodings, Map<String, String> formEncodings); /** * Populate sampler from request * @param sampler {@link HTTPSamplerBase} * @param request {@link HttpRequestHdr} * @param pageEncodings Map of page encodings * @param formEncodings Map of form encodings * @throws Exception when something fails */ void populateSampler(HTTPSamplerBase sampler, HttpRequestHdr request, Map<String, String> pageEncodings, Map<String, String> formEncodings) throws Exception; /** * Post process sampler * Called after sampling * @param sampler HTTPSamplerBase * @param result SampleResult * @since 2.9 */ void postProcessSampler(HTTPSamplerBase sampler, SampleResult result); /** * Default implementation calls: * <ol> * <li>{@link SamplerCreator}{@link #createSampler(HttpRequestHdr, Map, Map)}</li> * <li>{@link SamplerCreator}{@link #populateSampler(HTTPSamplerBase, HttpRequestHdr, Map, Map)}</li> * </ol> * @param request {@link HttpRequestHdr} * @param pageEncodings Map of page encodings * @param formEncodings Map of form encodings * @return {@link HTTPSamplerBase} * @throws Exception when something fails * @since 2.9 */ HTTPSamplerBase createAndPopulateSampler(HttpRequestHdr request, Map<String, String> pageEncodings, Map<String, String> formEncodings) throws Exception; /** * Create sampler children. * This method can be used to add PostProcessor or ResponseAssertions by * implementations of {@link SamplerCreator}. * Return empty list if nothing to create * @param sampler {@link HTTPSamplerBase} * @param result {@link SampleResult} * @return List */ List<TestElement> createChildren(HTTPSamplerBase sampler, SampleResult result); }
apache-2.0
lennartj/maven-plugins
maven-invoker-plugin/src/it/invocation-reactor-indirect/plugin/src/main/java/org/apache/maven/it/plugins/dummy/MyMojo.java
1968
package org.apache.maven.it.plugins.dummy; /* * Copyright 2001-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. */ import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * @goal touch * @phase process-sources */ public class MyMojo extends AbstractMojo { /** * Location of the file. * @parameter expression="${project.build.directory}" * @required */ private File outputDirectory; public void execute() throws MojoExecutionException { File f = outputDirectory; if ( !f.exists() ) { f.mkdirs(); } File touch = new File( f, "touch.txt" ); FileWriter w = null; try { w = new FileWriter( touch ); w.write( "touch.txt" ); } catch ( IOException e ) { throw new MojoExecutionException( "Error creating file " + touch, e ); } finally { if ( w != null ) { try { w.close(); } catch ( IOException e ) { // ignore } } } } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/langtools/test/tools/javac/diags/CheckResourceKeys.java
14634
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 6964768 6964461 6964469 6964487 6964460 6964481 6980021 * @summary need test program to validate javac resource bundles */ import java.io.*; import java.util.*; import javax.tools.*; import com.sun.tools.classfile.*; /** * Compare string constants in javac classes against keys in javac resource bundles. */ public class CheckResourceKeys { /** * Main program. * Options: * -finddeadkeys * look for keys in resource bundles that are no longer required * -findmissingkeys * look for keys in resource bundles that are missing * * @throws Exception if invoked by jtreg and errors occur */ public static void main(String... args) throws Exception { CheckResourceKeys c = new CheckResourceKeys(); if (c.run(args)) return; if (is_jtreg()) throw new Exception(c.errors + " errors occurred"); else System.exit(1); } static boolean is_jtreg() { return (System.getProperty("test.src") != null); } /** * Main entry point. */ boolean run(String... args) throws Exception { boolean findDeadKeys = false; boolean findMissingKeys = false; if (args.length == 0) { if (is_jtreg()) { findDeadKeys = true; findMissingKeys = true; } else { System.err.println("Usage: java CheckResourceKeys <options>"); System.err.println("where options include"); System.err.println(" -finddeadkeys find keys in resource bundles which are no longer required"); System.err.println(" -findmissingkeys find keys in resource bundles that are required but missing"); return true; } } else { for (String arg: args) { if (arg.equalsIgnoreCase("-finddeadkeys")) findDeadKeys = true; else if (arg.equalsIgnoreCase("-findmissingkeys")) findMissingKeys = true; else error("bad option: " + arg); } } if (errors > 0) return false; Set<String> codeStrings = getCodeStrings(); Set<String> resourceKeys = getResourceKeys(); if (findDeadKeys) findDeadKeys(codeStrings, resourceKeys); if (findMissingKeys) findMissingKeys(codeStrings, resourceKeys); return (errors == 0); } /** * Find keys in resource bundles which are probably no longer required. * A key is probably required if there is a string fragment in the code * that is part of the resource key, or if the key is well-known * according to various pragmatic rules. */ void findDeadKeys(Set<String> codeStrings, Set<String> resourceKeys) { String[] prefixes = { "compiler.err.", "compiler.warn.", "compiler.note.", "compiler.misc.", "javac." }; for (String rk: resourceKeys) { // some keys are used directly, without a prefix. if (codeStrings.contains(rk)) continue; // remove standard prefix String s = null; for (int i = 0; i < prefixes.length && s == null; i++) { if (rk.startsWith(prefixes[i])) { s = rk.substring(prefixes[i].length()); } } if (s == null) { error("Resource key does not start with a standard prefix: " + rk); continue; } if (codeStrings.contains(s)) continue; // keys ending in .1 are often synthesized if (s.endsWith(".1") && codeStrings.contains(s.substring(0, s.length() - 2))) continue; // verbose keys are generated by ClassReader.printVerbose if (s.startsWith("verbose.") && codeStrings.contains(s.substring(8))) continue; // mandatory warning messages are synthesized with no characteristic substring if (isMandatoryWarningString(s)) continue; // check known (valid) exceptions if (knownRequired.contains(rk)) continue; // check known suspects if (needToInvestigate.contains(rk)) continue; error("Resource key not found in code: " + rk); } } /** * The keys for mandatory warning messages are all synthesized and do not * have a significant recognizable substring to look for. */ private boolean isMandatoryWarningString(String s) { String[] bases = { "deprecated", "unchecked", "varargs", "sunapi" }; String[] tails = { ".filename", ".filename.additional", ".plural", ".plural.additional", ".recompile" }; for (String b: bases) { if (s.startsWith(b)) { String tail = s.substring(b.length()); for (String t: tails) { if (tail.equals(t)) return true; } } } return false; } Set<String> knownRequired = new TreeSet<String>(Arrays.asList( // See Resolve.getErrorKey "compiler.err.cant.resolve.args", "compiler.err.cant.resolve.args.params", "compiler.err.cant.resolve.location.args", "compiler.err.cant.resolve.location.args.params", "compiler.misc.cant.resolve.location.args", "compiler.misc.cant.resolve.location.args.params", // JavaCompiler, reports #errors and #warnings "compiler.misc.count.error", "compiler.misc.count.error.plural", "compiler.misc.count.warn", "compiler.misc.count.warn.plural", // Used for LintCategory "compiler.warn.lintOption", // Other "compiler.misc.base.membership" // (sic) )); Set<String> needToInvestigate = new TreeSet<String>(Arrays.asList( "compiler.misc.fatal.err.cant.close.loader", // Supressed by JSR308 "compiler.err.cant.read.file", // UNUSED "compiler.err.illegal.self.ref", // UNUSED "compiler.err.io.exception", // UNUSED "compiler.err.limit.pool.in.class", // UNUSED "compiler.err.name.reserved.for.internal.use", // UNUSED "compiler.err.no.match.entry", // UNUSED "compiler.err.not.within.bounds.explain", // UNUSED "compiler.err.signature.doesnt.match.intf", // UNUSED "compiler.err.signature.doesnt.match.supertype", // UNUSED "compiler.err.type.var.more.than.once", // UNUSED "compiler.err.type.var.more.than.once.in.result", // UNUSED "compiler.misc.ccf.found.later.version", // UNUSED "compiler.misc.non.denotable.type", // UNUSED "compiler.misc.unnamed.package", // should be required, CR 6964147 "compiler.misc.verbose.retro", // UNUSED "compiler.misc.verbose.retro.with", // UNUSED "compiler.misc.verbose.retro.with.list", // UNUSED "compiler.warn.proc.type.already.exists", // TODO in JavacFiler "javac.err.invalid.arg", // UNUSED ?? "javac.opt.arg.class", // UNUSED ?? "javac.opt.arg.pathname", // UNUSED ?? "javac.opt.moreinfo", // option commented out "javac.opt.nogj", // UNUSED "javac.opt.printflat", // option commented out "javac.opt.printsearch", // option commented out "javac.opt.prompt", // option commented out "javac.opt.retrofit", // UNUSED "javac.opt.s", // option commented out "javac.opt.scramble", // option commented out "javac.opt.scrambleall" // option commented out )); /** * For all strings in the code that look like they might be fragments of * a resource key, verify that a key exists. */ void findMissingKeys(Set<String> codeStrings, Set<String> resourceKeys) { for (String cs: codeStrings) { if (cs.matches("[A-Za-z][^.]*\\..*")) { // ignore filenames (i.e. in SourceFile attribute if (cs.matches(".*\\.java")) continue; // ignore package and class names if (cs.matches("(com|java|javax|sun)\\.[A-Za-z.]+")) continue; // explicit known exceptions if (noResourceRequired.contains(cs)) continue; // look for matching resource if (hasMatch(resourceKeys, cs)) continue; error("no match for \"" + cs + "\""); } } } // where private Set<String> noResourceRequired = new HashSet<String>(Arrays.asList( // system properties "application.home", // in Paths.java "env.class.path", "line.separator", "os.name", "user.dir", // file names "ct.sym", "rt.jar", "tools.jar", // -XD option names "process.packages", "ignore.symbol.file", // prefix/embedded strings "compiler.", "compiler.misc.", "count.", "illegal.", "javac.", "verbose." )); /** * Look for a resource that ends in this string fragment. */ boolean hasMatch(Set<String> resourceKeys, String s) { for (String rk: resourceKeys) { if (rk.endsWith(s)) return true; } return false; } /** * Get the set of strings from (most of) the javac classfiles. */ Set<String> getCodeStrings() throws IOException { Set<String> results = new TreeSet<String>(); JavaCompiler c = ToolProvider.getSystemJavaCompiler(); JavaFileManager fm = c.getStandardFileManager(null, null, null); JavaFileManager.Location javacLoc = findJavacLocation(fm); String[] pkgs = { "javax.annotation.processing", "javax.lang.model", "javax.tools", "com.sun.source", "com.sun.tools.javac" }; for (String pkg: pkgs) { for (JavaFileObject fo: fm.list(javacLoc, pkg, EnumSet.of(JavaFileObject.Kind.CLASS), true)) { String name = fo.getName(); // ignore resource files, and files which are not really part of javac if (name.matches(".*resources.[A-Za-z_0-9]+\\.class.*") || name.matches(".*CreateSymbols\\.class.*")) continue; scan(fo, results); } } return results; } // depending on how the test is run, javac may be on bootclasspath or classpath JavaFileManager.Location findJavacLocation(JavaFileManager fm) { JavaFileManager.Location[] locns = { StandardLocation.PLATFORM_CLASS_PATH, StandardLocation.CLASS_PATH }; try { for (JavaFileManager.Location l: locns) { JavaFileObject fo = fm.getJavaFileForInput(l, "com.sun.tools.javac.Main", JavaFileObject.Kind.CLASS); if (fo != null) return l; } } catch (IOException e) { throw new Error(e); } throw new IllegalStateException("Cannot find javac"); } /** * Get the set of strings from a class file. * Only strings that look like they might be a resource key are returned. */ void scan(JavaFileObject fo, Set<String> results) throws IOException { InputStream in = fo.openInputStream(); try { ClassFile cf = ClassFile.read(in); for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) { if (cpinfo.getTag() == ConstantPool.CONSTANT_Utf8) { String v = ((ConstantPool.CONSTANT_Utf8_info) cpinfo).value; if (v.matches("[A-Za-z0-9-_.]+")) results.add(v); } } } catch (ConstantPoolException ignore) { } finally { in.close(); } } /** * Get the set of keys from the javac resource bundles. */ Set<String> getResourceKeys() { Set<String> results = new TreeSet<String>(); for (String name : new String[]{"javac", "compiler"}) { ResourceBundle b = ResourceBundle.getBundle("com.sun.tools.javac.resources." + name); results.addAll(b.keySet()); } return results; } /** * Report an error. */ void error(String msg) { System.err.println("Error: " + msg); errors++; } int errors; }
mit
kabariyamilind/openMRSDEV
api/src/test/java/org/openmrs/module/ModuleInteroperabilityTest.java
2866
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.openmrs.test.BaseContextSensitiveTest; import org.openmrs.test.SkipBaseSetup; import org.openmrs.test.StartModule; import org.openmrs.util.OpenmrsClassLoader; /** * Tests how modules interact and call each other. Both when loaded by Spring during OpenMRS startup * and during normal file usage. */ @SkipBaseSetup @StartModule( { "org/openmrs/module/include/test1-1.0-SNAPSHOT.omod", "org/openmrs/module/include/test2-1.0-SNAPSHOT.omod" }) public class ModuleInteroperabilityTest extends BaseContextSensitiveTest { /** * Test that module A that requires module B can call a service method on module B * * @throws Exception */ @Test public void shouldAllowModuleAToLoadModuleBIfARequiresB() throws Exception { OpenmrsClassLoader loader = OpenmrsClassLoader.getInstance(); Class<?> module1ServiceClass = loader.loadClass("org.openmrs.module.test1.api.Test1Service"); Class<?> module2ServiceClass = loader.loadClass("org.openmrs.module.test2.api.Test2Service"); assertNotNull(module1ServiceClass); assertNotNull(module2ServiceClass); ModuleClassLoader module1ClassLoader = (ModuleClassLoader) module1ServiceClass.getClassLoader(); assertEquals("test1", module1ClassLoader.getModule().getModuleId()); ModuleClassLoader module2ClassLoader = (ModuleClassLoader) module2ServiceClass.getClassLoader(); assertEquals("test2", module2ClassLoader.getModule().getModuleId()); // load a module1 class from the module2 classloader. This simulates a normal class (like a // controller) in one module loading another class that is located in a separate module Class<?> module1TestClass = module2ClassLoader.loadClass("org.openmrs.module.test1.Test1"); ModuleClassLoader module1TestClassLoader = (ModuleClassLoader) module1TestClass.getClassLoader(); assertEquals("test1", module1TestClassLoader.getModule().getModuleId()); // try the same as above except with an already loaded class (the Module1Service class) Class<?> module1ServiceClass2 = module2ClassLoader.loadClass("org.openmrs.module.test1.api.Test1Service"); ModuleClassLoader module1ServiceClassLoader = (ModuleClassLoader) module1ServiceClass2.getClassLoader(); assertEquals("test1", module1ServiceClassLoader.getModule().getModuleId()); } }
mpl-2.0
sheofir/aws-sdk-java
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/ModifyReservedInstancesRequestMarshaller.java
4362
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.ec2.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.internal.ListWithAutoConstructFlag; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Modify Reserved Instances Request Marshaller */ public class ModifyReservedInstancesRequestMarshaller implements Marshaller<Request<ModifyReservedInstancesRequest>, ModifyReservedInstancesRequest> { public Request<ModifyReservedInstancesRequest> marshall(ModifyReservedInstancesRequest modifyReservedInstancesRequest) { if (modifyReservedInstancesRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<ModifyReservedInstancesRequest> request = new DefaultRequest<ModifyReservedInstancesRequest>(modifyReservedInstancesRequest, "AmazonEC2"); request.addParameter("Action", "ModifyReservedInstances"); request.addParameter("Version", "2015-04-15"); if (modifyReservedInstancesRequest.getClientToken() != null) { request.addParameter("ClientToken", StringUtils.fromString(modifyReservedInstancesRequest.getClientToken())); } java.util.List<String> reservedInstancesIdsList = modifyReservedInstancesRequest.getReservedInstancesIds(); int reservedInstancesIdsListIndex = 1; for (String reservedInstancesIdsListValue : reservedInstancesIdsList) { if (reservedInstancesIdsListValue != null) { request.addParameter("ReservedInstancesId." + reservedInstancesIdsListIndex, StringUtils.fromString(reservedInstancesIdsListValue)); } reservedInstancesIdsListIndex++; } java.util.List<ReservedInstancesConfiguration> targetConfigurationsList = modifyReservedInstancesRequest.getTargetConfigurations(); int targetConfigurationsListIndex = 1; for (ReservedInstancesConfiguration targetConfigurationsListValue : targetConfigurationsList) { ReservedInstancesConfiguration reservedInstancesConfigurationMember = targetConfigurationsListValue; if (reservedInstancesConfigurationMember != null) { if (reservedInstancesConfigurationMember.getAvailabilityZone() != null) { request.addParameter("ReservedInstancesConfigurationSetItemType." + targetConfigurationsListIndex + ".AvailabilityZone", StringUtils.fromString(reservedInstancesConfigurationMember.getAvailabilityZone())); } if (reservedInstancesConfigurationMember.getPlatform() != null) { request.addParameter("ReservedInstancesConfigurationSetItemType." + targetConfigurationsListIndex + ".Platform", StringUtils.fromString(reservedInstancesConfigurationMember.getPlatform())); } if (reservedInstancesConfigurationMember.getInstanceCount() != null) { request.addParameter("ReservedInstancesConfigurationSetItemType." + targetConfigurationsListIndex + ".InstanceCount", StringUtils.fromInteger(reservedInstancesConfigurationMember.getInstanceCount())); } if (reservedInstancesConfigurationMember.getInstanceType() != null) { request.addParameter("ReservedInstancesConfigurationSetItemType." + targetConfigurationsListIndex + ".InstanceType", StringUtils.fromString(reservedInstancesConfigurationMember.getInstanceType())); } } targetConfigurationsListIndex++; } return request; } }
apache-2.0
hequn8128/flink
flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/types/valuearray/ByteValueArrayComparator.java
4688
/* * 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.graph.types.valuearray; import org.apache.flink.annotation.Internal; import org.apache.flink.api.common.typeutils.TypeComparator; import org.apache.flink.core.memory.DataInputView; import org.apache.flink.core.memory.DataOutputView; import org.apache.flink.core.memory.MemorySegment; import org.apache.flink.types.NormalizableKey; import java.io.IOException; /** * Specialized comparator for ByteValueArray based on CopyableValueComparator. * * <p>This can be used for grouping keys but not for sorting keys. */ @Internal public class ByteValueArrayComparator extends TypeComparator<ByteValueArray> { private static final long serialVersionUID = 1L; private final boolean ascendingComparison; private final ByteValueArray reference = new ByteValueArray(); private final TypeComparator<?>[] comparators = new TypeComparator[] {this}; public ByteValueArrayComparator(boolean ascending) { this.ascendingComparison = ascending; } @Override public int hash(ByteValueArray record) { return record.hashCode(); } @Override public void setReference(ByteValueArray toCompare) { toCompare.copyTo(reference); } @Override public boolean equalToReference(ByteValueArray candidate) { return candidate.equals(this.reference); } @Override public int compareToReference(TypeComparator<ByteValueArray> referencedComparator) { int comp = ((ByteValueArrayComparator) referencedComparator).reference.compareTo(reference); return ascendingComparison ? comp : -comp; } @Override public int compare(ByteValueArray first, ByteValueArray second) { int comp = first.compareTo(second); return ascendingComparison ? comp : -comp; } @Override public int compareSerialized(DataInputView firstSource, DataInputView secondSource) throws IOException { int firstCount = firstSource.readInt(); int secondCount = secondSource.readInt(); int minCount = Math.min(firstCount, secondCount); while (minCount-- > 0) { byte firstValue = firstSource.readByte(); byte secondValue = secondSource.readByte(); int cmp = Byte.compare(firstValue, secondValue); if (cmp != 0) { return ascendingComparison ? cmp : -cmp; } } int cmp = Integer.compare(firstCount, secondCount); return ascendingComparison ? cmp : -cmp; } @Override public boolean supportsNormalizedKey() { return NormalizableKey.class.isAssignableFrom(ByteValueArray.class); } @Override public int getNormalizeKeyLen() { return reference.getMaxNormalizedKeyLen(); } @Override public boolean isNormalizedKeyPrefixOnly(int keyBytes) { return keyBytes < getNormalizeKeyLen(); } @Override public void putNormalizedKey(ByteValueArray record, MemorySegment target, int offset, int numBytes) { record.copyNormalizedKey(target, offset, numBytes); } @Override public boolean invertNormalizedKey() { return !ascendingComparison; } @Override public TypeComparator<ByteValueArray> duplicate() { return new ByteValueArrayComparator(ascendingComparison); } @Override public int extractKeys(Object record, Object[] target, int index) { target[index] = record; return 1; } @Override public TypeComparator<?>[] getFlatComparators() { return comparators; } // -------------------------------------------------------------------------------------------- // unsupported normalization // -------------------------------------------------------------------------------------------- @Override public boolean supportsSerializationWithKeyNormalization() { return false; } @Override public void writeWithKeyNormalization(ByteValueArray record, DataOutputView target) throws IOException { throw new UnsupportedOperationException(); } @Override public ByteValueArray readWithKeyDenormalization(ByteValueArray reuse, DataInputView source) throws IOException { throw new UnsupportedOperationException(); } }
apache-2.0
siosio/intellij-community
java/java-tests/testData/codeInsight/completion/normal/NoClassesWithDollar.java
49
import imported.*; class C { WithD<caret> }
apache-2.0
Novemser/TomcatTest
webapps/examples/jsp/plugin/applet/Clock2.java
7492
/* * 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.util.*; import java.awt.*; import java.applet.*; import java.text.*; /** * Time! * * @author Rachel Gollub */ public class Clock2 extends Applet implements Runnable { Thread timer; // The thread that displays clock int lastxs, lastys, lastxm, lastym, lastxh, lastyh; // Dimensions used to draw hands SimpleDateFormat formatter; // Formats the date displayed String lastdate; // String to hold date displayed Font clockFaceFont; // Font for number display on clock Date currentDate; // Used to get date to display Color handColor; // Color of main hands and dial Color numberColor; // Color of second hand and numbers public void init() { int x,y; lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0; formatter = new SimpleDateFormat ("EEE MMM dd hh:mm:ss yyyy", Locale.getDefault()); currentDate = new Date(); lastdate = formatter.format(currentDate); clockFaceFont = new Font("Serif", Font.PLAIN, 14); handColor = Color.blue; numberColor = Color.darkGray; try { setBackground(new Color(Integer.parseInt(getParameter("bgcolor"),16))); } catch (Exception E) { } try { handColor = new Color(Integer.parseInt(getParameter("fgcolor1"),16)); } catch (Exception E) { } try { numberColor = new Color(Integer.parseInt(getParameter("fgcolor2"),16)); } catch (Exception E) { } resize(300,300); // Set clock window size } // Plotpoints allows calculation to only cover 45 degrees of the circle, // and then mirror public void plotpoints(int x0, int y0, int x, int y, Graphics g) { g.drawLine(x0+x,y0+y,x0+x,y0+y); g.drawLine(x0+y,y0+x,x0+y,y0+x); g.drawLine(x0+y,y0-x,x0+y,y0-x); g.drawLine(x0+x,y0-y,x0+x,y0-y); g.drawLine(x0-x,y0-y,x0-x,y0-y); g.drawLine(x0-y,y0-x,x0-y,y0-x); g.drawLine(x0-y,y0+x,x0-y,y0+x); g.drawLine(x0-x,y0+y,x0-x,y0+y); } // Circle is just Bresenham's algorithm for a scan converted circle public void circle(int x0, int y0, int r, Graphics g) { int x,y; float d; x=0; y=r; d=5/4-r; plotpoints(x0,y0,x,y,g); while (y>x){ if (d<0) { d=d+2*x+3; x++; } else { d=d+2*(x-y)+5; x++; y--; } plotpoints(x0,y0,x,y,g); } } // Paint is the main part of the program public void paint(Graphics g) { int xh, yh, xm, ym, xs, ys, s = 0, m = 10, h = 10, xcenter, ycenter; String today; currentDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("s",Locale.getDefault()); try { s = Integer.parseInt(formatter.format(currentDate)); } catch (NumberFormatException n) { s = 0; } formatter.applyPattern("m"); try { m = Integer.parseInt(formatter.format(currentDate)); } catch (NumberFormatException n) { m = 10; } formatter.applyPattern("h"); try { h = Integer.parseInt(formatter.format(currentDate)); } catch (NumberFormatException n) { h = 10; } formatter.applyPattern("EEE MMM dd HH:mm:ss yyyy"); today = formatter.format(currentDate); xcenter=80; ycenter=55; // a= s* pi/2 - pi/2 (to switch 0,0 from 3:00 to 12:00) // x = r(cos a) + xcenter, y = r(sin a) + ycenter xs = (int)(Math.cos(s * 3.14f/30 - 3.14f/2) * 45 + xcenter); ys = (int)(Math.sin(s * 3.14f/30 - 3.14f/2) * 45 + ycenter); xm = (int)(Math.cos(m * 3.14f/30 - 3.14f/2) * 40 + xcenter); ym = (int)(Math.sin(m * 3.14f/30 - 3.14f/2) * 40 + ycenter); xh = (int)(Math.cos((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + xcenter); yh = (int)(Math.sin((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + ycenter); // Draw the circle and numbers g.setFont(clockFaceFont); g.setColor(handColor); circle(xcenter,ycenter,50,g); g.setColor(numberColor); g.drawString("9",xcenter-45,ycenter+3); g.drawString("3",xcenter+40,ycenter+3); g.drawString("12",xcenter-5,ycenter-37); g.drawString("6",xcenter-3,ycenter+45); // Erase if necessary, and redraw g.setColor(getBackground()); if (xs != lastxs || ys != lastys) { g.drawLine(xcenter, ycenter, lastxs, lastys); g.drawString(lastdate, 5, 125); } if (xm != lastxm || ym != lastym) { g.drawLine(xcenter, ycenter-1, lastxm, lastym); g.drawLine(xcenter-1, ycenter, lastxm, lastym); } if (xh != lastxh || yh != lastyh) { g.drawLine(xcenter, ycenter-1, lastxh, lastyh); g.drawLine(xcenter-1, ycenter, lastxh, lastyh); } g.setColor(numberColor); g.drawString("", 5, 125); g.drawString(today, 5, 125); g.drawLine(xcenter, ycenter, xs, ys); g.setColor(handColor); g.drawLine(xcenter, ycenter-1, xm, ym); g.drawLine(xcenter-1, ycenter, xm, ym); g.drawLine(xcenter, ycenter-1, xh, yh); g.drawLine(xcenter-1, ycenter, xh, yh); lastxs=xs; lastys=ys; lastxm=xm; lastym=ym; lastxh=xh; lastyh=yh; lastdate = today; currentDate=null; } public void start() { timer = new Thread(this); timer.start(); } public void stop() { timer = null; } public void run() { Thread me = Thread.currentThread(); while (timer == me) { try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { } repaint(); } } public void update(Graphics g) { paint(g); } public String getAppletInfo() { return "Title: A Clock \nAuthor: Rachel Gollub, 1995 \nAn analog clock."; } public String[][] getParameterInfo() { String[][] info = { {"bgcolor", "hexadecimal RGB number", "The background color. Default is the color of your browser."}, {"fgcolor1", "hexadecimal RGB number", "The color of the hands and dial. Default is blue."}, {"fgcolor2", "hexadecimal RGB number", "The color of the seconds hand and numbers. Default is dark gray."} }; return info; } }
apache-2.0
charithag/carbon-device-mgt
components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/JWTConfig.java
4108
package org.wso2.carbon.identity.jwt.client.extension.dto; import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.identity.jwt.client.extension.constant.JWTConstants; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class JWTConfig { private static final String JWT_ISSUER = "iss"; private static final String JWT_EXPIRATION_TIME = "exp"; private static final String JWT_AUDIENCE = "aud"; private static final String VALIDITY_PERIOD = "nbf"; private static final String JWT_TOKEN_ID = "jti"; private static final String JWT_ISSUED_AT = "iat"; private static final String SERVER_TIME_SKEW="skew"; private static final String JKS_PATH ="KeyStore"; private static final String JKS_PRIVATE_KEY_ALIAS ="PrivateKeyAlias"; private static final String JKS_PASSWORD ="KeyStorePassword"; private static final String JKA_PRIVATE_KEY_PASSWORD = "PrivateKeyPassword"; private static final String TOKEN_ENDPOINT = "TokenEndpoint"; private static final String JWT_GRANT_TYPE_NAME = "GrantType"; /** * issuer of the JWT */ private String issuer; /** * skew between IDP and issuer(milliseconds) */ private int skew; /** * Audience of JWT claim */ private List<String> audiences; /** * expiration time of JWT (number of minutes from the current time). */ private int expirationTime; /** * issued Interval from current time of JWT (number of minutes from the current time). */ private int issuedInternal; /** * nbf time of JWT (number of minutes from current time). */ private int validityPeriodInterval; /** * JWT Id. */ private String jti; /** * Token Endpoint; */ private String tokenEndpoint; /** * Configuration for keystore. */ private String keyStorePath; private String keyStorePassword; private String privateKeyAlias; private String privateKeyPassword; /** * Jwt Grant Type Name */ private String jwtGrantType; /** * @param properties load the config from the properties file. */ public JWTConfig(Properties properties) { issuer = properties.getProperty(JWT_ISSUER, null); skew = Integer.parseInt(properties.getProperty(SERVER_TIME_SKEW, "0")); issuedInternal = Integer.parseInt(properties.getProperty(JWT_ISSUED_AT,"0")); expirationTime = Integer.parseInt(properties.getProperty(JWT_EXPIRATION_TIME,"15")); validityPeriodInterval = Integer.parseInt(properties.getProperty(VALIDITY_PERIOD,"0")); jti = properties.getProperty(JWT_TOKEN_ID, null); String audience = properties.getProperty(JWT_AUDIENCE, null); if(audience != null) { audiences = getAudience(audience); } //get Keystore params keyStorePath = properties.getProperty(JKS_PATH); keyStorePassword = properties.getProperty(JKS_PASSWORD); privateKeyAlias = properties.getProperty(JKS_PRIVATE_KEY_ALIAS); privateKeyPassword = properties.getProperty(JKA_PRIVATE_KEY_PASSWORD); tokenEndpoint = properties.getProperty(TOKEN_ENDPOINT, ""); jwtGrantType = properties.getProperty(JWT_GRANT_TYPE_NAME, JWTConstants.JWT_GRANT_TYPE); } private static List<String> getAudience(String audience){ List<String> audiences = new ArrayList<String>(); for(String audi : audience.split(",")){ audiences.add(audi.trim()); } return audiences; } public String getIssuer() { return issuer; } public int getSkew() { return skew; } public List<String> getAudiences() { return audiences; } public int getExpirationTime() { return expirationTime; } public int getIssuedInternal() { return issuedInternal; } public int getValidityPeriodFromCurrentTime() { return validityPeriodInterval; } public String getJti() { return jti; } public String getKeyStorePath() { return keyStorePath; } public String getKeyStorePassword() { return keyStorePassword; } public String getPrivateKeyAlias() { return privateKeyAlias; } public String getPrivateKeyPassword() { return privateKeyPassword; } public String getTokenEndpoint() { return Utils.replaceSystemProperty(tokenEndpoint); } public String getJwtGrantType() { return jwtGrantType; } }
apache-2.0
callmeyan/lemon
src/main/java/com/mossle/party/manager/PartyEntityManager.java
267
package com.mossle.party.manager; import com.mossle.core.hibernate.HibernateEntityDao; import com.mossle.party.domain.PartyEntity; import org.springframework.stereotype.Service; @Service public class PartyEntityManager extends HibernateEntityDao<PartyEntity> { }
apache-2.0
suthat/signal
vendor/mysql-connector-java-5.1.26/src/testsuite/simple/TestBug57662Logger.java
1678
/* Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/J is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FLOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package testsuite.simple; import com.mysql.jdbc.log.StandardLogger; import com.mysql.jdbc.profiler.ProfilerEvent; public class TestBug57662Logger extends StandardLogger { public boolean hasNegativeDurations = false; public TestBug57662Logger(String name) { super(name, false); } @Override protected void logInternal(int level, Object msg, Throwable exception) { if ( !this.hasNegativeDurations && msg instanceof ProfilerEvent) { this.hasNegativeDurations = ((ProfilerEvent) msg).getEventDuration() < 0; } super.logInternal(level, msg, exception); } }
apache-2.0
izeye/spring-boot
spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java
4279
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.diagnostics.analyzer; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.diagnostics.FailureAnalysis; import org.springframework.boot.diagnostics.FailureAnalyzer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** * Tests for {@link BeanCurrentlyInCreationFailureAnalyzer} * * @author Andy Wilkinson */ public class BeanCurrentlyInCreationFailureAnalyzerTests { private final FailureAnalyzer analyzer = new BeanCurrentlyInCreationFailureAnalyzer(); @Test public void cyclicBeanMethods() { FailureAnalysis analysis = performAnalysis(CyclicBeanMethodsConfiguration.class); assertThat(analysis.getDescription()).startsWith( "There is a circular dependency between 3 beans in the application context:"); assertThat(analysis.getDescription()).contains( "one defined in " + CyclicBeanMethodsConfiguration.class.getName()); assertThat(analysis.getDescription()).contains( "two defined in " + CyclicBeanMethodsConfiguration.class.getName()); assertThat(analysis.getDescription()).contains( "three defined in " + CyclicBeanMethodsConfiguration.class.getName()); } @Test public void cycleWithAutowiredFields() { FailureAnalysis analysis = performAnalysis(CycleWithAutowiredFields.class); assertThat(analysis.getDescription()).startsWith( "There is a circular dependency between 3 beans in the application context:"); assertThat(analysis.getDescription()).contains("three defined in " + CycleWithAutowiredFields.BeanThreeConfiguration.class.getName()); assertThat(analysis.getDescription()) .contains("one defined in " + CycleWithAutowiredFields.class.getName()); assertThat(analysis.getDescription()) .contains(CycleWithAutowiredFields.BeanTwoConfiguration.class.getName() + " (field private " + BeanThree.class.getName()); } private FailureAnalysis performAnalysis(Class<?> configuration) { FailureAnalysis analysis = this.analyzer.analyze(createFailure(configuration)); assertThat(analysis).isNotNull(); return analysis; } private Exception createFailure(Class<?> configuration) { ConfigurableApplicationContext context = null; try { context = new AnnotationConfigApplicationContext(configuration); } catch (Exception ex) { ex.printStackTrace(); return ex; } finally { if (context != null) { context.close(); } } fail("Expected failure did not occur"); return null; } @Configuration static class CyclicBeanMethodsConfiguration { @Bean public BeanOne one(BeanTwo two) { return new BeanOne(); } @Bean public BeanTwo two(BeanThree three) { return new BeanTwo(); } @Bean public BeanThree three(BeanOne one) { return new BeanThree(); } } @Configuration public static class CycleWithAutowiredFields { @Bean public BeanOne one(BeanTwo two) { return new BeanOne(); } public static class BeanTwoConfiguration { @SuppressWarnings("unused") @Autowired private BeanThree three; @Bean public BeanTwo two() { return new BeanTwo(); } } public static class BeanThreeConfiguration { @Bean public BeanThree three(BeanOne one) { return new BeanThree(); } } } static class BeanOne { } static class BeanTwo { } static class BeanThree { } }
apache-2.0
mahaliachante/aws-sdk-java
aws-java-sdk-cloudtrail/src/main/java/com/amazonaws/services/cloudtrail/model/transform/StopLoggingRequestMarshaller.java
3042
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.cloudtrail.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.cloudtrail.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; /** * Stop Logging Request Marshaller */ public class StopLoggingRequestMarshaller implements Marshaller<Request<StopLoggingRequest>, StopLoggingRequest> { public Request<StopLoggingRequest> marshall(StopLoggingRequest stopLoggingRequest) { if (stopLoggingRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<StopLoggingRequest> request = new DefaultRequest<StopLoggingRequest>(stopLoggingRequest, "AWSCloudTrail"); String target = "CloudTrail_20131101.StopLogging"; request.addHeader("X-Amz-Target", target); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { StringWriter stringWriter = new StringWriter(); JSONWriter jsonWriter = new JSONWriter(stringWriter); jsonWriter.object(); if (stopLoggingRequest.getName() != null) { jsonWriter.key("Name").value(stopLoggingRequest.getName()); } jsonWriter.endObject(); String snippet = stringWriter.toString(); byte[] content = snippet.getBytes(UTF8); request.setContent(new StringInputStream(snippet)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", "application/x-amz-json-1.1"); } catch(Throwable t) { throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
apache-2.0
NJU-STP/STP
src/main/java/com/mossle/bpm/calendar/AdvancedBusinessCalendarManagerFactoryBean.java
1556
package com.mossle.bpm.calendar; import com.mossle.api.workcal.WorkCalendarConnector; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; public class AdvancedBusinessCalendarManagerFactoryBean implements InitializingBean, FactoryBean<AdvancedBusinessCalendarManager> { private AdvancedBusinessCalendarManager advancedBusinessCalendarManager; private WorkCalendarConnector workCalendarConnector; public AdvancedBusinessCalendarManager getObject() { return advancedBusinessCalendarManager; } public Class<AdvancedBusinessCalendarManager> getObjectType() { return AdvancedBusinessCalendarManager.class; } public boolean isSingleton() { return true; } public void afterPropertiesSet() throws Exception { this.advancedBusinessCalendarManager = new AdvancedBusinessCalendarManager(); this.addBusinessCalendar(new DueDateBusinessCalendar()); this.addBusinessCalendar(new DurationBusinessCalendar()); this.addBusinessCalendar(new CycleBusinessCalendar()); } public void addBusinessCalendar(AdvancedBusinessCalendar businessCalendar) { businessCalendar.setWorkCalendarConnector(workCalendarConnector); this.advancedBusinessCalendarManager .addBusinessCalendar(businessCalendar); } public void setWorkCalendarConnector( WorkCalendarConnector workCalendarConnector) { this.workCalendarConnector = workCalendarConnector; } }
apache-2.0
learning-spring-boot/learning-spring-boot-code-1.2
ch5/teammates-5/src/main/java/learningspringboot/TeammateRepository.java
167
package learningspringboot; import org.springframework.data.repository.CrudRepository; public interface TeammateRepository extends CrudRepository<Teammate, Long> {}
apache-2.0
agoncharuk/ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/datastructures/partitioned/GridCachePartitionedQueueMultiNodeSelfTest.java
1860
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.datastructures.partitioned; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheMemoryMode; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.internal.processors.cache.datastructures.GridCacheQueueMultiNodeAbstractSelfTest; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheMemoryMode.ONHEAP_TIERED; import static org.apache.ignite.cache.CacheMode.PARTITIONED; /** * Queue multi node test. */ public class GridCachePartitionedQueueMultiNodeSelfTest extends GridCacheQueueMultiNodeAbstractSelfTest { /** {@inheritDoc} */ @Override protected CacheMode collectionCacheMode() { return PARTITIONED; } /** {@inheritDoc} */ @Override protected CacheMemoryMode collectionMemoryMode() { return ONHEAP_TIERED; } /** {@inheritDoc} */ @Override protected CacheAtomicityMode collectionCacheAtomicityMode() { return TRANSACTIONAL; } }
apache-2.0
wangshuai112/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/queue/disruptor/JstormProducer.java
2008
/** * 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.alibaba.jstorm.queue.disruptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lmax.disruptor.RingBuffer; public class JstormProducer implements Runnable { Logger logger = LoggerFactory.getLogger(JstormProducer.class); private RingBuffer<JstormEvent> ringBuffer; private int size; public JstormProducer(RingBuffer<JstormEvent> ringBuffer, int size) { this.ringBuffer = ringBuffer; this.size = size; } @Override public void run() { logger.warn("producer start..." + System.currentTimeMillis()); // while (true) { // long seqId = ringBuffer.next(); // // ringBuffer.get(seqId).setMsgId(String.valueOf(seqId)); // ringBuffer.publish(seqId); // // try { // double random = Math.random(); // Thread.sleep((long)(random * 1000)); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } for (int i = 0; i < size; i++) { long seqId = ringBuffer.next(); ringBuffer.get(seqId).setMsgId(String.valueOf(seqId)); ringBuffer.publish(seqId); } } }
apache-2.0
mahaliachante/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Table.java
35519
/* * Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.document; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.http.annotation.ThreadSafe; import com.amazonaws.annotation.Beta; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.document.api.DeleteItemApi; import com.amazonaws.services.dynamodbv2.document.api.GetItemApi; import com.amazonaws.services.dynamodbv2.document.api.PutItemApi; import com.amazonaws.services.dynamodbv2.document.api.QueryApi; import com.amazonaws.services.dynamodbv2.document.api.ScanApi; import com.amazonaws.services.dynamodbv2.document.api.UpdateItemApi; import com.amazonaws.services.dynamodbv2.document.internal.DeleteItemImpl; import com.amazonaws.services.dynamodbv2.document.internal.GetItemImpl; import com.amazonaws.services.dynamodbv2.document.internal.InternalUtils; import com.amazonaws.services.dynamodbv2.document.internal.PutItemImpl; import com.amazonaws.services.dynamodbv2.document.internal.QueryImpl; import com.amazonaws.services.dynamodbv2.document.internal.ScanImpl; import com.amazonaws.services.dynamodbv2.document.internal.UpdateItemImpl; import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec; import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec; import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec; import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec; import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec; import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec; import com.amazonaws.services.dynamodbv2.document.spec.UpdateTableSpec; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.CreateGlobalSecondaryIndexAction; import com.amazonaws.services.dynamodbv2.model.DeleteTableResult; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.DescribeTableResult; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndexDescription; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndexUpdate; import com.amazonaws.services.dynamodbv2.model.IndexStatus; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.amazonaws.services.dynamodbv2.model.TableStatus; import com.amazonaws.services.dynamodbv2.model.UpdateTableRequest; import com.amazonaws.services.dynamodbv2.model.UpdateTableResult; import com.amazonaws.services.dynamodbv2.xspec.DeleteItemExpressionSpec; import com.amazonaws.services.dynamodbv2.xspec.GetItemExpressionSpec; import com.amazonaws.services.dynamodbv2.xspec.QueryExpressionSpec; import com.amazonaws.services.dynamodbv2.xspec.ScanExpressionSpec; import com.amazonaws.services.dynamodbv2.xspec.UpdateItemExpressionSpec; /** * A DynamoDB table. Instance of this class is typically obtained via * {@link DynamoDB#getTable(String)}. */ @ThreadSafe public class Table implements PutItemApi, GetItemApi, QueryApi, ScanApi, UpdateItemApi, DeleteItemApi { private static final long SLEEP_TIME_MILLIS = 5000; private final String tableName; private final AmazonDynamoDB client; private volatile TableDescription tableDescription; private final PutItemImpl putItemDelegate; private final GetItemImpl getItemDelegate; private final UpdateItemImpl updateItemDelegate; private final DeleteItemImpl deleteItemDelegate; private final QueryImpl queryDelegate; private final ScanImpl scanDelegate; public Table(AmazonDynamoDB client, String tableName) { this(client, tableName, null); } public Table(AmazonDynamoDB client, String tableName, TableDescription tableDescription) { if (client == null) throw new IllegalArgumentException("client must be specified"); if (tableName == null || tableName.trim().length() == 0) throw new IllegalArgumentException("table name must not be null or empty"); this.client = client; this.tableName = tableName; this.tableDescription = tableDescription; this.putItemDelegate = new PutItemImpl(client, this); this.getItemDelegate = new GetItemImpl(client, this); this.updateItemDelegate = new UpdateItemImpl(client, this); this.deleteItemDelegate = new DeleteItemImpl(client, this); this.queryDelegate = new QueryImpl(client, this); this.scanDelegate = new ScanImpl(client, this); } public String getTableName() { return tableName; } /** * Returns the table description; or null if the table description has not * yet been described via {@link #describe()}. No network call. */ public TableDescription getDescription() { return tableDescription; } /** * Retrieves the table description from DynamoDB. Involves network calls. * Meant to be called as infrequently as possible to avoid throttling * exception from the server side. * * @return a non-null table description * * @throws ResourceNotFoundException if the table doesn't exist */ public TableDescription describe() { DescribeTableResult result = client.describeTable( InternalUtils.applyUserAgent(new DescribeTableRequest(tableName))); return tableDescription = result.getTable(); } /** * Gets a reference to the specified index. No network call. */ public Index getIndex(String indexName) { return new Index(client, indexName, this); } @Override public PutItemOutcome putItem(Item item) { return putItemDelegate.putItem(item); } @Override public PutItemOutcome putItem(Item item, Expected... expected) { return putItemDelegate.putItem(item, expected); } @Override public PutItemOutcome putItem(Item item, String conditionExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return putItemDelegate.putItem(item, conditionExpression, nameMap, valueMap); } @Override public PutItemOutcome putItem(PutItemSpec spec) { return putItemDelegate.putItem(spec); } @Override public GetItemOutcome getItemOutcome(KeyAttribute... primaryKeyComponents) { return getItemDelegate.getItemOutcome(primaryKeyComponents); } @Override public GetItemOutcome getItemOutcome(PrimaryKey primaryKey) { return getItemDelegate.getItemOutcome(primaryKey); } @Override public GetItemOutcome getItemOutcome(PrimaryKey primaryKey, String projectionExpression, Map<String, String> nameMap) { return getItemDelegate.getItemOutcome(primaryKey, projectionExpression, nameMap); } @Override public GetItemOutcome getItemOutcome(GetItemSpec params) { return getItemDelegate.getItemOutcome(params); } @Override public UpdateItemOutcome updateItem(PrimaryKey primaryKey, AttributeUpdate... attributeUpdates) { return updateItemDelegate.updateItem(primaryKey, attributeUpdates); } @Override public UpdateItemOutcome updateItem(PrimaryKey primaryKey, Collection<Expected> expected, AttributeUpdate... attributeUpdates) { return updateItemDelegate.updateItem(primaryKey, expected, attributeUpdates); } @Override public UpdateItemOutcome updateItem(PrimaryKey primaryKey, String updateExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return updateItemDelegate.updateItem(primaryKey, updateExpression, nameMap, valueMap); } @Override public UpdateItemOutcome updateItem(PrimaryKey primaryKey, String updateExpression, String conditionExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return updateItemDelegate.updateItem(primaryKey, updateExpression, conditionExpression, nameMap, valueMap); } @Override public UpdateItemOutcome updateItem(UpdateItemSpec updateItemSpec) { return updateItemDelegate.updateItem(updateItemSpec); } @Override public ItemCollection<QueryOutcome> query(String hashKeyName, Object hashKeyValue) { return queryDelegate.query(hashKeyName, hashKeyValue); } @Override public ItemCollection<QueryOutcome> query(KeyAttribute hashKey) { return queryDelegate.query(hashKey); } @Override public ItemCollection<QueryOutcome> query(KeyAttribute hashKey, RangeKeyCondition rangeKeyCondition) { return queryDelegate.query(hashKey, rangeKeyCondition); } @Override public ItemCollection<QueryOutcome> query(KeyAttribute hashKey, RangeKeyCondition rangeKeyCondition, String filterExpression, String projectionExpression,Map<String, String> nameMap, Map<String, Object> valueMap) { return queryDelegate.query(hashKey, rangeKeyCondition, filterExpression, projectionExpression, nameMap, valueMap); } @Override public ItemCollection<QueryOutcome> query(KeyAttribute hashKey, RangeKeyCondition rangeKeyCondition, QueryFilter... queryFilters) { return queryDelegate.query(hashKey, rangeKeyCondition, queryFilters); } @Override public ItemCollection<QueryOutcome> query(KeyAttribute hashKey, RangeKeyCondition rangeKeyCondition, String filterExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return queryDelegate.query(hashKey, rangeKeyCondition, filterExpression, nameMap, valueMap); } @Override public ItemCollection<QueryOutcome> query(QuerySpec spec) { return queryDelegate.query(spec); } @Override public ItemCollection<ScanOutcome> scan(ScanFilter... scanFilters) { return scanDelegate.scan(scanFilters); } @Override public ItemCollection<ScanOutcome> scan(String filterExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return scanDelegate.scan(filterExpression, nameMap, valueMap); } @Override public ItemCollection<ScanOutcome> scan(String filterExpression, String projectionExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return scanDelegate.scan(filterExpression, projectionExpression, nameMap, valueMap); } @Override public ItemCollection<ScanOutcome> scan(ScanSpec params) { return scanDelegate.scan(params); } @Beta public ItemCollection<ScanOutcome> scan(ScanExpressionSpec scanExpressions) { return scanDelegate.scan(new ScanSpec() .withProjectionExpression(scanExpressions.getProjectionExpression()) .withFilterExpression(scanExpressions.getFilterExpression()) .withNameMap(scanExpressions.getNameMap()) .withValueMap(scanExpressions.getValueMap())); } @Override public DeleteItemOutcome deleteItem(KeyAttribute... primaryKeyComponents) { return deleteItemDelegate.deleteItem(primaryKeyComponents); } @Override public DeleteItemOutcome deleteItem(PrimaryKey primaryKey) { return deleteItemDelegate.deleteItem(primaryKey); } @Override public DeleteItemOutcome deleteItem(PrimaryKey primaryKey, Expected... expected) { return deleteItemDelegate.deleteItem(primaryKey, expected); } @Override public DeleteItemOutcome deleteItem(PrimaryKey primaryKey, String conditionExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return deleteItemDelegate.deleteItem(primaryKey, conditionExpression, nameMap, valueMap); } @Beta public DeleteItemOutcome deleteItem(PrimaryKey primaryKey, DeleteItemExpressionSpec conditionExpressions) { return deleteItemDelegate.deleteItem(primaryKey, conditionExpressions.getConditionExpression(), conditionExpressions.getNameMap(), conditionExpressions.getValueMap()); } @Override public DeleteItemOutcome deleteItem(DeleteItemSpec spec) { return deleteItemDelegate.deleteItem(spec); } /** * Updates the provisioned throughput for this table. Setting the * throughput for a table helps you manage performance and is part of the * provisioned throughput feature of DynamoDB. * <p> * The provisioned throughput values can be upgraded or downgraded based * on the maximums and minimums listed in the * <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html"> Limits </a> * section in the Amazon DynamoDB Developer Guide. * <p> * This table must be in the <code>ACTIVE</code> state for this operation * to succeed. <i>UpdateTable</i> is an asynchronous operation; while * executing the operation, the table is in the <code>UPDATING</code> * state. While the table is in the <code>UPDATING</code> state, the * table still has the provisioned throughput from before the call. The * new provisioned throughput setting is in effect only when the table * returns to the <code>ACTIVE</code> state after the <i>UpdateTable</i> * operation. * <p> * You can create, update or delete indexes using <i>UpdateTable</i>. * </p> * * @param spec used to specify all the detailed parameters * * @return the updated table description returned from DynamoDB. */ public TableDescription updateTable(UpdateTableSpec spec) { UpdateTableRequest req = spec.getRequest(); req.setTableName(getTableName()); UpdateTableResult result = client.updateTable(req); return this.tableDescription = result.getTableDescription(); } /** * Creates a global secondary index (GSI) with only a hash key on this * table. Involves network calls. This table must be in the * <code>ACTIVE</code> state for this operation to succeed. Creating a * global secondary index is an asynchronous operation; while executing the * operation, the index is in the <code>CREATING</code> state. Once created, * the index will be in <code>ACTIVE</code> state. * * @param create * used to specify the details of the index creation * @param hashKeyDefinition * used to specify the attribute for describing the key schema * for the hash key of the GSI to be created for this table. * * @return the index being created */ public Index createGSI( CreateGlobalSecondaryIndexAction create, AttributeDefinition hashKeyDefinition) { return doCreateGSI(create, hashKeyDefinition); } /** * Creates a global secondary index (GSI) with both a hash key and a range * key on this table. Involves network calls. This table must be in the * <code>ACTIVE</code> state for this operation to succeed. Creating a * global secondary index is an asynchronous operation; while executing the * operation, the index is in the <code>CREATING</code> state. Once created, * the index will be in <code>ACTIVE</code> state. * * @param create * used to specify the details of the index creation * @param hashKeyDefinition * used to specify the attribute for describing the key schema * for the hash key of the GSI to be created for this table. * @param rangeKeyDefinition * used to specify the attribute for describing the key schema * for the range key of the GSI to be created for this table. * * @return the index being created */ public Index createGSI( CreateGlobalSecondaryIndexAction create, AttributeDefinition hashKeyDefinition, AttributeDefinition rangeKeyDefinition) { return doCreateGSI(create, hashKeyDefinition, rangeKeyDefinition); } private Index doCreateGSI( CreateGlobalSecondaryIndexAction create, AttributeDefinition ... keyDefinitions) { UpdateTableSpec spec = new UpdateTableSpec() .withAttributeDefinitions(keyDefinitions) .withGlobalSecondaryIndexUpdates( new GlobalSecondaryIndexUpdate().withCreate(create)) ; updateTable(spec); return this.getIndex(create.getIndexName()); } /** * Updates the provisioned throughput for this table. Setting the * throughput for a table helps you manage performance and is part of the * provisioned throughput feature of DynamoDB. * <p> * The provisioned throughput values can be upgraded or downgraded based * on the maximums and minimums listed in the * <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html"> Limits </a> * section in the Amazon DynamoDB Developer Guide. * <p> * This table must be in the <code>ACTIVE</code> state for this operation * to succeed. <i>UpdateTable</i> is an asynchronous operation; while * executing the operation, the table is in the <code>UPDATING</code> * state. While the table is in the <code>UPDATING</code> state, the * table still has the provisioned throughput from before the call. The * new provisioned throughput setting is in effect only when the table * returns to the <code>ACTIVE</code> state after the <i>UpdateTable</i> * operation. * <p> * You can create, update or delete indexes using <i>UpdateTable</i>. * </p> * * @param provisionedThroughput target provisioned throughput * * @return the updated table description returned from DynamoDB. */ public TableDescription updateTable( ProvisionedThroughput provisionedThroughput) { return updateTable(new UpdateTableSpec() .withProvisionedThroughput(provisionedThroughput)); } /** * A convenient blocking call that can be used, typically during table * creation, to wait for the table to become active by polling the table * every 5 seconds. * * @return the table description when the table has become active * * @throws IllegalArgumentException if the table is being deleted * @throws ResourceNotFoundException if the table doesn't exist */ public TableDescription waitForActive() throws InterruptedException { for (;;) { TableDescription desc = describe(); String status = desc.getTableStatus(); switch (TableStatus.fromValue(status)) { case ACTIVE: return desc; case CREATING: case UPDATING: Thread.sleep(SLEEP_TIME_MILLIS); continue; default: throw new IllegalArgumentException("Table " + tableName + " is not being created (with status=" + status + ")"); } } } /** * A convenient blocking call that can be used, typically during table * deletion, to wait for the table to become deleted by polling the table * every 5 seconds. */ public void waitForDelete() throws InterruptedException { try { for (;;) { TableDescription desc = describe(); String status = desc.getTableStatus(); if (TableStatus.fromValue(status) == TableStatus.DELETING) { Thread.sleep(SLEEP_TIME_MILLIS); } else throw new IllegalArgumentException("Table " + tableName + " is not being deleted (with status=" + status + ")"); } } catch(ResourceNotFoundException deleted) { } return; } /** * A convenient blocking call that can be used to wait on a table until it * has either become active or deleted (ie no longer exists) by polling the * table every 5 seconds. * * @return the table description if the table has become active; or null * if the table has been deleted. */ public TableDescription waitForActiveOrDelete() throws InterruptedException { try { for (;;) { TableDescription desc = describe(); final String status = desc.getTableStatus(); if (TableStatus.fromValue(status) == TableStatus.ACTIVE) return desc; else Thread.sleep(SLEEP_TIME_MILLIS); } } catch(ResourceNotFoundException deleted) { } return null; } /** * A convenient blocking call that can be used to wait on a table and all * it's indexes until both the table and it's indexes have either become * active or deleted (ie no longer exists) by polling the table every 5 * seconds. * * @return the table description if the table and all it's indexes have * become active; or null if the table has been deleted. */ public TableDescription waitForAllActiveOrDelete() throws InterruptedException { try { retry: for (;;) { TableDescription desc = describe(); String status = desc.getTableStatus(); if (TableStatus.fromValue(status) == TableStatus.ACTIVE) { List<GlobalSecondaryIndexDescription> descriptions = desc.getGlobalSecondaryIndexes(); if (descriptions != null) { for (GlobalSecondaryIndexDescription d: descriptions) { status = d.getIndexStatus(); if (IndexStatus.fromValue(status) != IndexStatus.ACTIVE) { // Some index is not active. Keep waiting. Thread.sleep(SLEEP_TIME_MILLIS); continue retry; } } } return desc; } Thread.sleep(SLEEP_TIME_MILLIS); continue; } } catch(ResourceNotFoundException deleted) { } return null; } /** * Deletes the table from DynamoDB. Involves network calls. */ public DeleteTableResult delete() { return client.deleteTable(tableName); } @Override public Item getItem(KeyAttribute... primaryKeyComponents) { return getItemDelegate.getItem(primaryKeyComponents); } @Override public Item getItem(PrimaryKey primaryKey) { return getItemDelegate.getItem(primaryKey); } @Override public Item getItem(PrimaryKey primaryKey, String projectionExpression, Map<String, String> nameMap) { return getItemDelegate.getItem(primaryKey, projectionExpression, nameMap); } @Override public Item getItem(GetItemSpec spec) { return getItemDelegate.getItem(spec); } @Override public GetItemOutcome getItemOutcome(String hashKeyName, Object hashKeyValue) { return getItemDelegate.getItemOutcome(hashKeyName, hashKeyValue); } @Override public GetItemOutcome getItemOutcome(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue) { return getItemDelegate.getItemOutcome(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue); } @Override public Item getItem(String hashKeyName, Object hashKeyValue) { return getItemDelegate.getItem(hashKeyName, hashKeyValue); } @Override public Item getItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue) { return getItemDelegate.getItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue); } @Override public ItemCollection<QueryOutcome> query(String hashKeyName, Object hashKeyValue, RangeKeyCondition rangeKeyCondition) { return queryDelegate.query(hashKeyName, hashKeyValue, rangeKeyCondition); } @Override public ItemCollection<QueryOutcome> query(String hashKeyName, Object hashKeyValue, RangeKeyCondition rangeKeyCondition, QueryFilter... queryFilters) { return queryDelegate.query(hashKeyName, hashKeyValue, rangeKeyCondition, queryFilters); } @Override public ItemCollection<QueryOutcome> query(String hashKeyName, Object hashKeyValue, RangeKeyCondition rangeKeyCondition, String filterExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return queryDelegate.query(hashKeyName, hashKeyValue, rangeKeyCondition, filterExpression, nameMap, valueMap); } @Override public ItemCollection<QueryOutcome> query(String hashKeyName, Object hashKeyValue, RangeKeyCondition rangeKeyCondition, String filterExpression, String projectionExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return queryDelegate.query(hashKeyName, hashKeyValue, rangeKeyCondition, filterExpression, projectionExpression, nameMap, valueMap); } @Beta public ItemCollection<QueryOutcome> query(String hashKeyName, Object hashKeyValue, RangeKeyCondition rangeKeyCondition, QueryExpressionSpec queryExpressions) { return queryDelegate.query(hashKeyName, hashKeyValue, rangeKeyCondition, queryExpressions.getFilterExpression(), queryExpressions.getProjectionExpression(), queryExpressions.getNameMap(), queryExpressions.getValueMap()); } @Override public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, AttributeUpdate... attributeUpdates) { return updateItemDelegate.updateItem(hashKeyName, hashKeyValue, attributeUpdates); } @Override public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, AttributeUpdate... attributeUpdates) { return updateItemDelegate.updateItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, attributeUpdates); } @Override public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, Collection<Expected> expected, AttributeUpdate... attributeUpdates) { return updateItemDelegate.updateItem(hashKeyName, hashKeyValue, expected, attributeUpdates); } @Override public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, Collection<Expected> expected, AttributeUpdate... attributeUpdates) { return updateItemDelegate.updateItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, expected, attributeUpdates); } @Override public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, String updateExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return updateItemDelegate.updateItem(hashKeyName, hashKeyValue, updateExpression, nameMap, valueMap); } @Override public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, String updateExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return updateItemDelegate.updateItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, updateExpression, nameMap, valueMap); } @Override public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, String updateExpression, String conditionExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return updateItemDelegate.updateItem(hashKeyName, hashKeyValue, updateExpression, conditionExpression, nameMap, valueMap); } @Beta public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, UpdateItemExpressionSpec updateExpressions) { return updateItemDelegate.updateItem(hashKeyName, hashKeyValue, updateExpressions.getUpdateExpression(), updateExpressions.getConditionExpression(), updateExpressions.getNameMap(), updateExpressions.getValueMap()); } @Override public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, String updateExpression, String conditionExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return updateItemDelegate.updateItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, updateExpression, conditionExpression, nameMap, valueMap); } @Beta public UpdateItemOutcome updateItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, UpdateItemExpressionSpec updateExpressions) { return updateItemDelegate.updateItem( hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, updateExpressions.getUpdateExpression(), updateExpressions.getConditionExpression(), updateExpressions.getNameMap(), updateExpressions.getValueMap()); } @Override public GetItemOutcome getItemOutcome(String hashKeyName, Object hashKeyValue, String projectionExpression, Map<String, String> nameMap) { return getItemDelegate.getItemOutcome(hashKeyName, hashKeyValue, projectionExpression, nameMap); } @Override public GetItemOutcome getItemOutcome(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, String projectionExpression, Map<String, String> nameMap) { return getItemDelegate.getItemOutcome(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, projectionExpression, nameMap); } @Beta public GetItemOutcome getItemOutcome(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, GetItemExpressionSpec projectionExpressions) { return getItemDelegate.getItemOutcome(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, projectionExpressions.getProjectionExpression(), projectionExpressions.getNameMap()); } @Override public Item getItem(String hashKeyName, Object hashKeyValue, String projectionExpression, Map<String, String> nameMap) { return getItemDelegate.getItem(hashKeyName, hashKeyValue, projectionExpression, nameMap); } @Override public Item getItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, String projectionExpression, Map<String, String> nameMap) { return getItemDelegate.getItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, projectionExpression, nameMap); } @Beta public Item getItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, GetItemExpressionSpec projectionExpressions) { return getItemDelegate.getItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, projectionExpressions.getProjectionExpression(), projectionExpressions.getNameMap()); } @Override public DeleteItemOutcome deleteItem(String hashKeyName, Object hashKeyValue) { return deleteItemDelegate.deleteItem(hashKeyName, hashKeyValue); } @Override public DeleteItemOutcome deleteItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue) { return deleteItemDelegate.deleteItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue); } @Override public DeleteItemOutcome deleteItem(String hashKeyName, Object hashKeyValue, Expected... expected) { return deleteItemDelegate.deleteItem(hashKeyName, hashKeyValue, expected); } @Override public DeleteItemOutcome deleteItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, Expected... expected) { return deleteItemDelegate.deleteItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, expected); } @Override public DeleteItemOutcome deleteItem(String hashKeyName, Object hashKeyValue, String conditionExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return deleteItemDelegate.deleteItem(hashKeyName, hashKeyValue, conditionExpression, nameMap, valueMap); } @Override public DeleteItemOutcome deleteItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, String conditionExpression, Map<String, String> nameMap, Map<String, Object> valueMap) { return deleteItemDelegate.deleteItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, conditionExpression, nameMap, valueMap); } @Beta public DeleteItemOutcome deleteItem(String hashKeyName, Object hashKeyValue, String rangeKeyName, Object rangeKeyValue, DeleteItemExpressionSpec conditionExpressions) { return deleteItemDelegate.deleteItem(hashKeyName, hashKeyValue, rangeKeyName, rangeKeyValue, conditionExpressions.getConditionExpression(), conditionExpressions.getNameMap(), conditionExpressions.getValueMap()); } @Override public String toString() { return "{" + tableName + ": " + tableDescription + "}"; } }
apache-2.0
YolandaMDavis/nifi
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/BannerDTO.java
1790
/* * 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.nifi.web.api.dto; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlType; /** * Banners that should appear on the top and bottom of this NiFi. */ @XmlType(name = "banners") public class BannerDTO { private String headerText; private String footerText; /* getters / setters */ /** * The banner footer text. * * @return The footer text */ @ApiModelProperty( value = "The footer text." ) public String getFooterText() { return footerText; } public void setFooterText(String footerText) { this.footerText = footerText; } /** * The banner header text. * * @return The header text */ @ApiModelProperty( value = "The header text." ) public String getHeaderText() { return headerText; } public void setHeaderText(String headerText) { this.headerText = headerText; } }
apache-2.0
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libjava/classpath/gnu/javax/crypto/sasl/NoSuchUserException.java
2481
/* NoSuchUserException.java -- Copyright (C) 2003, 2006 Free Software Foundation, Inc. This file is a part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Classpath 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 GNU Classpath; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.javax.crypto.sasl; import javax.security.sasl.AuthenticationException; /** * A checked exception thrown to indicate that a designated user is unknown to * the authentication layer. */ public class NoSuchUserException extends AuthenticationException { /** Constructs a <code>NoSuchUserException</code> with no detail message. */ public NoSuchUserException() { super(); } /** * Constructs a <code>NoSuchUserException</code> with the specified detail * message. In the case of this exception, the detail message designates the * offending username. * * @param arg the detail message, which in this case is the username. */ public NoSuchUserException(String arg) { super(arg); } }
bsd-3-clause
jmnarloch/spring-security
samples/gae-xml/src/main/java/samples/gae/web/GaeAppController.java
1280
package samples.gae.web; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.UserServiceFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * * @author Luke Taylor * */ @Controller public class GaeAppController { @RequestMapping(value = "/", method = RequestMethod.GET) public String landing() { return "landing"; } @RequestMapping(value = "/home.htm", method = RequestMethod.GET) public String home() { return "home"; } @RequestMapping(value = "/disabled.htm", method = RequestMethod.GET) public String disabled() { return "disabled"; } @RequestMapping(value = "/logout.htm", method = RequestMethod.GET) public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException { request.getSession().invalidate(); String logoutUrl = UserServiceFactory.getUserService().createLogoutURL( "/loggedout.htm"); response.sendRedirect(logoutUrl); } @RequestMapping(value = "/loggedout.htm", method = RequestMethod.GET) public String loggedOut() { return "loggedout"; } }
apache-2.0
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libjava/classpath/gnu/java/net/protocol/ftp/Handler.java
2281
/* Handler.java -- Copyright (C) 2003, 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.java.net.protocol.ftp; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; /** * An FTP URL stream handler. * * @author Chris Burdess (dog@gnu.org) */ public class Handler extends URLStreamHandler { protected int getDefaultPort() { return FTPConnection.FTP_PORT; } /** * Returns an FTPURLConnection for the given URL. */ public URLConnection openConnection(URL url) throws IOException { return new FTPURLConnection(url); } }
bsd-3-clause
jackalchen/dex2jar
d2j-smali/src/main/java/com/googlecode/d2j/smali/Utils.java
16430
package com.googlecode.d2j.smali; import com.googlecode.d2j.DexConstants; import com.googlecode.d2j.Field; import com.googlecode.d2j.Method; import com.googlecode.d2j.Visibility; import com.googlecode.d2j.reader.Op; import com.googlecode.d2j.visitors.DexAnnotationVisitor; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Utils implements DexConstants { public static void doAccept(DexAnnotationVisitor dexAnnotationVisitor, String k, Object value) { if (value instanceof ArrayList) { DexAnnotationVisitor a = dexAnnotationVisitor.visitArray(k); for (Object o : (ArrayList) value) { doAccept(a, null, o); } a.visitEnd(); } else if (value instanceof Ann) { Ann ann = (Ann) value; DexAnnotationVisitor a = dexAnnotationVisitor.visitAnnotation(k, ann.name); for (Map.Entry<String, Object> e : ann.elements) { doAccept(a, e.getKey(), e.getValue()); } a.visitEnd(); } else if (value instanceof Field) { Field f = (Field) value; dexAnnotationVisitor.visitEnum(k, f.getOwner(), f.getName()); } else { dexAnnotationVisitor.visit(k, value); } } public static int getAcc(String name) { if (name.equals("public")) { return ACC_PUBLIC; } else if (name.equals("private")) { return ACC_PRIVATE; } else if (name.equals("protected")) { return ACC_PROTECTED; } else if (name.equals("static")) { return ACC_STATIC; } else if (name.equals("final")) { return ACC_FINAL; } else if (name.equals("synchronized")) { return ACC_SYNCHRONIZED; } else if (name.equals("volatile")) { return ACC_VOLATILE; } else if (name.equals("bridge")) { return ACC_BRIDGE; } else if (name.equals("varargs")) { return ACC_VARARGS; } else if (name.equals("transient")) { return ACC_TRANSIENT; } else if (name.equals("native")) { return ACC_NATIVE; } else if (name.equals("interface")) { return ACC_INTERFACE; } else if (name.equals("abstract")) { return ACC_ABSTRACT; } else if (name.equals("strict")) { return ACC_STRICT; } else if (name.equals("synthetic")) { return ACC_SYNTHETIC; } else if (name.equals("annotation")) { return ACC_ANNOTATION; } else if (name.equals("enum")) { return ACC_ENUM; } else if (name.equals("constructor")) { return ACC_CONSTRUCTOR; } else if (name.equals("declared-synchronized")) { return ACC_DECLARED_SYNCHRONIZED; } return 0; } public static List<String> listDesc(String desc) { List<String> list = new ArrayList(5); if (desc == null) { return list; } char[] chars = desc.toCharArray(); int i = 0; while (i < chars.length) { switch (chars[i]) { case 'V': case 'Z': case 'C': case 'B': case 'S': case 'I': case 'F': case 'J': case 'D': list.add(Character.toString(chars[i])); i++; break; case '[': { int count = 1; while (chars[i + count] == '[') { count++; } if (chars[i + count] == 'L') { count++; while (chars[i + count] != ';') { count++; } } count++; list.add(new String(chars, i, count)); i += count; break; } case 'L': { int count = 1; while (chars[i + count] != ';') { ++count; } count++; list.add(new String(chars, i, count)); i += count; break; } default: throw new RuntimeException("can't parse type list: " + desc); } } return list; } public static String[] toTypeList(String s) { return listDesc(s).toArray(new String[0]); } static public Byte parseByte(String str) { return Byte.valueOf((byte) parseInt(str.substring(0, str.length() - 1))); } static public Short parseShort(String str) { return Short.valueOf((short) parseInt(str.substring(0, str.length() - 1))); } static public Long parseLong(String str) { int sof = 0; int end = str.length() - 1; int x = 1; if (str.charAt(sof) == '+') { sof++; } else if (str.charAt(sof) == '-') { sof++; x = -1; } BigInteger v; if (str.charAt(sof) == '0') { sof++; if (sof >= end) { return 0L; } char c = str.charAt(sof); if (c == 'x' || c == 'X') {// hex sof++; v = new BigInteger(str.substring(sof, end), 16); } else {// oct v = new BigInteger(str.substring(sof, end), 8); } } else { v = new BigInteger(str.substring(sof, end), 10); } if (x == -1) { return v.negate().longValue(); } else { return v.longValue(); } } static public float parseFloat(String str) { str = str.toLowerCase(); int s = 0; float x = 1f; if (str.charAt(s) == '+') { s++; } else if (str.charAt(s) == '-') { s++; x = -1; } int e = str.length() - 1; if (str.charAt(e) == 'f') { e--; } str = str.substring(s, e + 1); if (str.equals("nan")) { return Float.NaN; } if (str.equals("infinity")) { return x < 0 ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY; } return (float) x * Float.parseFloat(str); } static public double parseDouble(String str) { str = str.toLowerCase(); int s = 0; double x = 1; if (str.charAt(s) == '+') { s++; } else if (str.charAt(s) == '-') { s++; x = -1; } int e = str.length() - 1; if (str.charAt(e) == 'd') { e--; } str = str.substring(s, e + 1); if (str.equals("nan")) { return Double.NaN; } if (str.equals("infinity")) { return x < 0 ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } return x * Double.parseDouble(str); } static public int parseInt(String str, int start, int end) { int sof = start; int x = 1; if (str.charAt(sof) == '+') { sof++; } else if (str.charAt(sof) == '-') { sof++; x = -1; } long v; if (str.charAt(sof) == '0') { sof++; if (sof >= end) { return 0; } char c = str.charAt(sof); if (c == 'x' || c == 'X') {// hex sof++; v = Long.parseLong(str.substring(sof, end), 16); } else {// oct v = Long.parseLong(str.substring(sof, end), 8); } } else { v = Long.parseLong(str.substring(sof, end), 10); } return (int) (v * x); } static public int parseInt(String str) { return parseInt(str, 0, str.length()); } public static String unescapeStr(String str) { return unEscape(str); } public static Character unescapeChar(String str) { return unEscape(str).charAt(0); } public static int[] toIntArray(List<String> ss) { int vs[] = new int[ss.size()]; for (int i = 0; i < ss.size(); i++) { vs[i] = parseInt(ss.get(i)); } return vs; } public static byte[] toByteArray(List<Object> ss) { byte vs[] = new byte[ss.size()]; for (int i = 0; i < ss.size(); i++) { vs[i] = ((Number) (ss.get(i))).byteValue(); } return vs; } static Map<String, Op> ops = new HashMap(); static { for (Op op : Op.values()) { ops.put(op.displayName, op); } } static public Op getOp(String name) { return ops.get(name); } public static String unEscape(String str) { return unEscape0(str, 1, str.length() - 1); } public static String unEscapeId(String str) { return unEscape0(str, 0, str.length()); } public static int findString(String str, int start, int end, char dEnd) { for (int i = start; i < end; ) { char c = str.charAt(i); if (c == '\\') { char d = str.charAt(i + 1); switch (d) { // ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\') case 'b': case 't': case 'n': case 'f': case 'r': case '\"': case '\'': case '\\': i += 2; break; case 'u': String sub = str.substring(i + 2, i + 6); i += 6; break; default: int x = 0; while (x < 3) { char e = str.charAt(i + 1 + x); if (e >= '0' && e <= '7') { x++; } else { break; } } if (x == 0) { throw new RuntimeException("can't pase string"); } i += 1 + x; } } else { if (c == dEnd) { return i; } i++; } } return end; } public static String unEscape0(String str, int start, int end) { StringBuilder sb = new StringBuilder(); for (int i = start; i < end; ) { char c = str.charAt(i); if (c == '\\') { char d = str.charAt(i + 1); switch (d) { // ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\') case 'b': sb.append('\b'); i += 2; break; case 't': sb.append('\t'); i += 2; break; case 'n': sb.append('\n'); i += 2; break; case 'f': sb.append('\f'); i += 2; break; case 'r': sb.append('\r'); i += 2; break; case '\"': sb.append('\"'); i += 2; break; case '\'': sb.append('\''); i += 2; break; case '\\': sb.append('\\'); i += 2; break; case 'u': String sub = str.substring(i + 2, i + 6); sb.append((char) Integer.parseInt(sub, 16)); i += 6; break; default: int x = 0; while (x < 3) { char e = str.charAt(i + 1 + x); if (e >= '0' && e <= '7') { x++; } else { break; } } if (x == 0) { throw new RuntimeException("can't pase string"); } sb.append((char) Integer.parseInt(str.substring(i + 1, i + 1 + x), 8)); i += 1 + x; } } else { sb.append(c); i++; } } return sb.toString(); } public static class Ann { public String name; public List<Map.Entry<String, Object>> elements = new ArrayList(); public void put(String name, Object value) { elements.add(new java.util.AbstractMap.SimpleEntry(name, value)); } } public static Visibility getAnnVisibility(String name) { return Visibility.valueOf(name.toUpperCase()); } public static int methodIns(Method m, boolean isStatic) { int a = isStatic ? 0 : 1; for (String t : m.getParameterTypes()) { switch (t.charAt(0)) { case 'J': case 'D': a += 2; break; default: a += 1; break; } } return a; } public static int reg2ParamIdx(Method m, int reg, int locals, boolean isStatic) { int x = reg - locals; if (x < 0) { return -1; } int a = isStatic ? 0 : 1; String[] parameterTypes = m.getParameterTypes(); for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) { if (x == a) { return i; } String t = parameterTypes[i]; switch (t.charAt(0)) { case 'J': case 'D': a += 2; break; default: a += 1; break; } } return -1; } public static Method parseMethodAndUnescape(String owner, String part) throws RuntimeException { int x = part.indexOf('('); if (x < 0) { throw new RuntimeException(); } int y = part.indexOf(')', x); if (y < 0) { throw new RuntimeException(); } String methodName = unEscapeId(part.substring(0, x)); String[] params = toTypeList(part.substring(x + 1, y)); for (int i = 0; i < params.length; i++) { params[i] = unEscapeId(params[i]); } String ret = unEscapeId(part.substring(y + 1)); return new Method(owner, methodName, params, ret); } public static Method parseMethodAndUnescape(String full) throws RuntimeException { int x = full.indexOf("->"); if (x <= 0) { throw new RuntimeException(); } return parseMethodAndUnescape(unEscapeId(full.substring(0, x)), full.substring(x + 2)); } public static Field parseFieldAndUnescape(String owner, String part) throws RuntimeException { int x = part.indexOf(':'); if (x < 0) { throw new RuntimeException(); } return new Field(owner, unEscapeId(part.substring(0, x)), unEscapeId(part.substring(x + 1))); } public static Field parseFieldAndUnescape(String full) throws RuntimeException { int x = full.indexOf("->"); if (x <= 0) { throw new RuntimeException(); } return parseFieldAndUnescape(unEscapeId(full.substring(0, x)), full.substring(x + 2)); } }
apache-2.0
dyk/liquibase
liquibase-maven-plugin/src/main/java/org/liquibase/maven/plugins/AbstractLiquibaseUpdateMojo.java
1433
package org.liquibase.maven.plugins; import liquibase.exception.LiquibaseException; import liquibase.Liquibase; /** * Liquibase Update Maven plugin. This plugin allows for DatabaseChangeLogs to be * applied to a database as part of a Maven build process. * @author Peter Murray * @description Liquibase Update Maven plugin */ public abstract class AbstractLiquibaseUpdateMojo extends AbstractLiquibaseChangeLogMojo { /** * The number of changes to apply to the database. By default this value is 0, which * will result in all changes (not already applied to the database) being applied. * @parameter expression="${liquibase.changesToApply}" default-value=0 */ protected int changesToApply; /** * Update to the changeSet with the given tag command. * @parameter expression="${liquibase.toTag}" */ protected String toTag; @Override protected void performLiquibaseTask(Liquibase liquibase) throws LiquibaseException { super.performLiquibaseTask(liquibase); doUpdate(liquibase); } /** * Performs the actual "update" work on the database. * @param liquibase The Liquibase object to use to perform the "update". */ protected abstract void doUpdate(Liquibase liquibase) throws LiquibaseException; @Override protected void printSettings(String indent) { super.printSettings(indent); getLog().info(indent + "number of changes to apply: " + changesToApply); } }
apache-2.0
MishaKharaba/xerces-for-android
src/mf/org/w3c/dom/ls/LSParserFilter.java
8908
/* * Copyright (c) 2004 World Wide Web Consortium, * * (Massachusetts Institute of Technology, European Research Consortium for * Informatics and Mathematics, Keio University). All Rights Reserved. This * work is distributed under the W3C(r) Software License [1] 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. * * [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */ package mf.org.w3c.dom.ls; import mf.org.w3c.dom.Element; import mf.org.w3c.dom.Node; /** * <code>LSParserFilter</code>s provide applications the ability to examine * nodes as they are being constructed while parsing. As each node is * examined, it may be modified or removed, or the entire parse may be * terminated early. * <p> At the time any of the filter methods are called by the parser, the * owner Document and DOMImplementation objects exist and are accessible. * The document element is never passed to the <code>LSParserFilter</code> * methods, i.e. it is not possible to filter out the document element. * <code>Document</code>, <code>DocumentType</code>, <code>Notation</code>, * <code>Entity</code>, and <code>Attr</code> nodes are never passed to the * <code>acceptNode</code> method on the filter. The child nodes of an * <code>EntityReference</code> node are passed to the filter if the * parameter "<a href='http://www.w3.org/TR/DOM-Level-3-Core/core.html#parameter-entities'> * entities</a>" is set to <code>false</code>. Note that, as described by the parameter "<a href='http://www.w3.org/TR/DOM-Level-3-Core/core.html#parameter-entities'> * entities</a>", unexpanded entity reference nodes are never discarded and are always * passed to the filter. * <p> All validity checking while parsing a document occurs on the source * document as it appears on the input stream, not on the DOM document as it * is built in memory. With filters, the document in memory may be a subset * of the document on the stream, and its validity may have been affected by * the filtering. * <p> All default attributes must be present on elements when the elements * are passed to the filter methods. All other default content must be * passed to the filter methods. * <p> DOM applications must not raise exceptions in a filter. The effect of * throwing exceptions from a filter is DOM implementation dependent. * <p>See also the <a href='http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407'>Document Object Model (DOM) Level 3 Load and Save Specification</a>. */ public interface LSParserFilter { // Constants returned by startElement and acceptNode /** * Accept the node. */ public static final short FILTER_ACCEPT = 1; /** * Reject the node and its children. */ public static final short FILTER_REJECT = 2; /** * Skip this single node. The children of this node will still be * considered. */ public static final short FILTER_SKIP = 3; /** * Interrupt the normal processing of the document. */ public static final short FILTER_INTERRUPT = 4; /** * The parser will call this method after each <code>Element</code> start * tag has been scanned, but before the remainder of the * <code>Element</code> is processed. The intent is to allow the * element, including any children, to be efficiently skipped. Note that * only element nodes are passed to the <code>startElement</code> * function. * <br>The element node passed to <code>startElement</code> for filtering * will include all of the Element's attributes, but none of the * children nodes. The Element may not yet be in place in the document * being constructed (it may not have a parent node.) * <br>A <code>startElement</code> filter function may access or change * the attributes for the Element. Changing Namespace declarations will * have no effect on namespace resolution by the parser. * <br>For efficiency, the Element node passed to the filter may not be * the same one as is actually placed in the tree if the node is * accepted. And the actual node (node object identity) may be reused * during the process of reading in and filtering a document. * @param elementArg The newly encountered element. At the time this * method is called, the element is incomplete - it will have its * attributes, but no children. * @return * <ul> * <li> <code>FILTER_ACCEPT</code> if the <code>Element</code> should * be included in the DOM document being built. * </li> * <li> * <code>FILTER_REJECT</code> if the <code>Element</code> and all of * its children should be rejected. * </li> * <li> <code>FILTER_SKIP</code> if the * <code>Element</code> should be skipped. All of its children are * inserted in place of the skipped <code>Element</code> node. * </li> * <li> * <code>FILTER_INTERRUPT</code> if the filter wants to stop the * processing of the document. Interrupting the processing of the * document does no longer guarantee that the resulting DOM tree is * XML well-formed. The <code>Element</code> is rejected. * </li> * </ul> Returning * any other values will result in unspecified behavior. */ public short startElement(Element elementArg); /** * This method will be called by the parser at the completion of the * parsing of each node. The node and all of its descendants will exist * and be complete. The parent node will also exist, although it may be * incomplete, i.e. it may have additional children that have not yet * been parsed. Attribute nodes are never passed to this function. * <br>From within this method, the new node may be freely modified - * children may be added or removed, text nodes modified, etc. The state * of the rest of the document outside this node is not defined, and the * affect of any attempt to navigate to, or to modify any other part of * the document is undefined. * <br>For validating parsers, the checks are made on the original * document, before any modification by the filter. No validity checks * are made on any document modifications made by the filter. * <br>If this new node is rejected, the parser might reuse the new node * and any of its descendants. * @param nodeArg The newly constructed element. At the time this method * is called, the element is complete - it has all of its children * (and their children, recursively) and attributes, and is attached * as a child to its parent. * @return * <ul> * <li> <code>FILTER_ACCEPT</code> if this <code>Node</code> should * be included in the DOM document being built. * </li> * <li> * <code>FILTER_REJECT</code> if the <code>Node</code> and all of its * children should be rejected. * </li> * <li> <code>FILTER_SKIP</code> if the * <code>Node</code> should be skipped and the <code>Node</code> * should be replaced by all the children of the <code>Node</code>. * </li> * <li> * <code>FILTER_INTERRUPT</code> if the filter wants to stop the * processing of the document. Interrupting the processing of the * document does no longer guarantee that the resulting DOM tree is * XML well-formed. The <code>Node</code> is accepted and will be the * last completely parsed node. * </li> * </ul> */ public short acceptNode(Node nodeArg); /** * Tells the <code>LSParser</code> what types of nodes to show to the * method <code>LSParserFilter.acceptNode</code>. If a node is not shown * to the filter using this attribute, it is automatically included in * the DOM document being built. See <code>NodeFilter</code> for * definition of the constants. The constants <code>SHOW_ATTRIBUTE</code> * , <code>SHOW_DOCUMENT</code>, <code>SHOW_DOCUMENT_TYPE</code>, * <code>SHOW_NOTATION</code>, <code>SHOW_ENTITY</code>, and * <code>SHOW_DOCUMENT_FRAGMENT</code> are meaningless here. Those nodes * will never be passed to <code>LSParserFilter.acceptNode</code>. * <br> The constants used here are defined in [<a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113'>DOM Level 2 Traversal and Range</a>] * . */ public int getWhatToShow(); }
apache-2.0
akosyakov/intellij-community
python/ipnb/src/org/jetbrains/plugins/ipnb/format/cells/output/IpnbStreamOutputCell.java
475
package org.jetbrains.plugins.ipnb.format.cells.output; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class IpnbStreamOutputCell extends IpnbOutputCell { @NotNull private final String myStream; public IpnbStreamOutputCell(@NotNull final String stream, String[] text, @Nullable final Integer prompt) { super(text, prompt); myStream = stream; } @NotNull public String getStream() { return myStream; } }
apache-2.0
dennishuo/hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/api/records/JobReport.java
2695
/** * 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.mapreduce.v2.api.records; import java.util.List; import org.apache.hadoop.yarn.api.records.Priority; public interface JobReport { public abstract JobId getJobId(); public abstract JobState getJobState(); public abstract float getMapProgress(); public abstract float getReduceProgress(); public abstract float getCleanupProgress(); public abstract float getSetupProgress(); public abstract long getSubmitTime(); public abstract long getStartTime(); public abstract long getFinishTime(); public abstract String getUser(); public abstract String getJobName(); public abstract String getTrackingUrl(); public abstract String getDiagnostics(); public abstract String getJobFile(); public abstract List<AMInfo> getAMInfos(); public abstract boolean isUber(); public abstract Priority getJobPriority(); public abstract String getHistoryFile(); public abstract void setJobId(JobId jobId); public abstract void setJobState(JobState jobState); public abstract void setMapProgress(float progress); public abstract void setReduceProgress(float progress); public abstract void setCleanupProgress(float progress); public abstract void setSetupProgress(float progress); public abstract void setSubmitTime(long submitTime); public abstract void setStartTime(long startTime); public abstract void setFinishTime(long finishTime); public abstract void setUser(String user); public abstract void setJobName(String jobName); public abstract void setTrackingUrl(String trackingUrl); public abstract void setDiagnostics(String diagnostics); public abstract void setJobFile(String jobFile); public abstract void setAMInfos(List<AMInfo> amInfos); public abstract void setIsUber(boolean isUber); public abstract void setJobPriority(Priority priority); public abstract void setHistoryFile(String historyFile); }
apache-2.0
Valodim/k-9
plugins/openpgp-api-library/src/org/openintents/openpgp/util/OpenPgpListPreference.java
9950
/* * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de> * * 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.openintents.openpgp.util; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ResolveInfo; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.net.Uri; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.TextView; import org.openintents.openpgp.R; import java.util.ArrayList; import java.util.List; /** * Does not extend ListPreference, but is very similar to it! * http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/android/preference/ListPreference.java/?v=source */ public class OpenPgpListPreference extends DialogPreference { private static final String OPENKEYCHAIN_PACKAGE = "org.sufficientlysecure.keychain"; private static final String MARKET_INTENT_URI_BASE = "market://details?id=%s"; private static final Intent MARKET_INTENT = new Intent(Intent.ACTION_VIEW, Uri.parse( String.format(MARKET_INTENT_URI_BASE, OPENKEYCHAIN_PACKAGE))); private ArrayList<OpenPgpProviderEntry> mLegacyList = new ArrayList<OpenPgpProviderEntry>(); private ArrayList<OpenPgpProviderEntry> mList = new ArrayList<OpenPgpProviderEntry>(); private String mSelectedPackage; public OpenPgpListPreference(Context context, AttributeSet attrs) { super(context, attrs); } public OpenPgpListPreference(Context context) { this(context, null); } /** * Public method to add new entries for legacy applications * * @param packageName * @param simpleName * @param icon */ public void addLegacyProvider(int position, String packageName, String simpleName, Drawable icon) { mLegacyList.add(position, new OpenPgpProviderEntry(packageName, simpleName, icon)); } @Override protected void onPrepareDialogBuilder(Builder builder) { mList.clear(); // add "none"-entry mList.add(0, new OpenPgpProviderEntry("", getContext().getString(R.string.openpgp_list_preference_none), getContext().getResources().getDrawable(R.drawable.ic_action_cancel_launchersize))); // add all additional (legacy) providers mList.addAll(mLegacyList); // search for OpenPGP providers... ArrayList<OpenPgpProviderEntry> providerList = new ArrayList<OpenPgpProviderEntry>(); Intent intent = new Intent(OpenPgpApi.SERVICE_INTENT); List<ResolveInfo> resInfo = getContext().getPackageManager().queryIntentServices(intent, 0); if (!resInfo.isEmpty()) { for (ResolveInfo resolveInfo : resInfo) { if (resolveInfo.serviceInfo == null) continue; String packageName = resolveInfo.serviceInfo.packageName; String simpleName = String.valueOf(resolveInfo.serviceInfo.loadLabel(getContext() .getPackageManager())); Drawable icon = resolveInfo.serviceInfo.loadIcon(getContext().getPackageManager()); providerList.add(new OpenPgpProviderEntry(packageName, simpleName, icon)); } } if (providerList.isEmpty()) { // add install links if provider list is empty resInfo = getContext().getPackageManager().queryIntentActivities (MARKET_INTENT, 0); for (ResolveInfo resolveInfo : resInfo) { Intent marketIntent = new Intent(MARKET_INTENT); marketIntent.setPackage(resolveInfo.activityInfo.packageName); Drawable icon = resolveInfo.activityInfo.loadIcon(getContext().getPackageManager()); String marketName = String.valueOf(resolveInfo.activityInfo.applicationInfo .loadLabel(getContext().getPackageManager())); String simpleName = String.format(getContext().getString(R.string .openpgp_install_openkeychain_via), marketName); mList.add(new OpenPgpProviderEntry(OPENKEYCHAIN_PACKAGE, simpleName, icon, marketIntent)); } } else { // add provider mList.addAll(providerList); } // Init ArrayAdapter with OpenPGP Providers ListAdapter adapter = new ArrayAdapter<OpenPgpProviderEntry>(getContext(), android.R.layout.select_dialog_singlechoice, android.R.id.text1, mList) { public View getView(int position, View convertView, ViewGroup parent) { // User super class to create the View View v = super.getView(position, convertView, parent); TextView tv = (TextView) v.findViewById(android.R.id.text1); // Put the image on the TextView tv.setCompoundDrawablesWithIntrinsicBounds(mList.get(position).icon, null, null, null); // Add margin between image and text (support various screen densities) int dp10 = (int) (10 * getContext().getResources().getDisplayMetrics().density + 0.5f); tv.setCompoundDrawablePadding(dp10); return v; } }; builder.setSingleChoiceItems(adapter, getIndexOfProviderList(getValue()), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { OpenPgpProviderEntry entry = mList.get(which); if (entry.intent != null) { /* * Intents are called as activity * * Current approach is to assume the user installed the app. * If he does not, the selected package is not valid. * * However applications should always consider this could happen, * as the user might remove the currently used OpenPGP app. */ getContext().startActivity(entry.intent); } mSelectedPackage = entry.packageName; /* * Clicking on an item simulates the positive button click, and dismisses * the dialog. */ OpenPgpListPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE); dialog.dismiss(); } }); /* * The typical interaction for list-based dialogs is to have click-on-an-item dismiss the * dialog instead of the user having to press 'Ok'. */ builder.setPositiveButton(null, null); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult && (mSelectedPackage != null)) { if (callChangeListener(mSelectedPackage)) { setValue(mSelectedPackage); } } } private int getIndexOfProviderList(String packageName) { for (OpenPgpProviderEntry app : mList) { if (app.packageName.equals(packageName)) { return mList.indexOf(app); } } return -1; } public void setValue(String packageName) { mSelectedPackage = packageName; persistString(packageName); } public String getValue() { return mSelectedPackage; } public String getEntry() { return getEntryByValue(mSelectedPackage); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getString(index); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedString(mSelectedPackage) : (String) defaultValue); } public String getEntryByValue(String packageName) { for (OpenPgpProviderEntry app : mList) { if (app.packageName.equals(packageName)) { return app.simpleName; } } return null; } private static class OpenPgpProviderEntry { private String packageName; private String simpleName; private Drawable icon; private Intent intent; public OpenPgpProviderEntry(String packageName, String simpleName, Drawable icon) { this.packageName = packageName; this.simpleName = simpleName; this.icon = icon; } public OpenPgpProviderEntry(String packageName, String simpleName, Drawable icon, Intent intent) { this(packageName, simpleName, icon); this.intent = intent; } @Override public String toString() { return simpleName; } } }
bsd-3-clause
liuxv/Material-Animations
app/src/main/java/com/lgvalle/material_animations/TransitionActivity3.java
1956
package com.lgvalle.material_animations; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.transition.Slide; import android.transition.Transition; import android.transition.TransitionInflater; import android.transition.Visibility; import android.view.Gravity; import android.view.View; import com.lgvalle.material_animations.databinding.ActivityTransition3Binding; public class TransitionActivity3 extends BaseDetailActivity { private int type; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); bindData(); setupWindowAnimations(); setupLayout(); setupToolbar(); } private void bindData() { ActivityTransition3Binding binding = DataBindingUtil.setContentView(this, R.layout.activity_transition3); Sample sample = (Sample) getIntent().getExtras().getSerializable(EXTRA_SAMPLE); type = getIntent().getExtras().getInt(EXTRA_TYPE); binding.setTransition3Sample(sample); } private void setupWindowAnimations() { Transition transition; if (type == TYPE_PROGRAMMATICALLY) { transition = buildEnterTransition(); } else { transition = TransitionInflater.from(this).inflateTransition(R.transition.slide_from_bottom); } getWindow().setEnterTransition(transition); } private void setupLayout() { findViewById(R.id.exit_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finishAfterTransition(); } }); } private Visibility buildEnterTransition() { Slide enterTransition = new Slide(); enterTransition.setDuration(getResources().getInteger(R.integer.anim_duration_long)); enterTransition.setSlideEdge(Gravity.RIGHT); return enterTransition; } }
mit
labertasch/sling
bundles/scripting/javascript/src/main/java/org/apache/sling/scripting/javascript/helper/SlingRhinoDebugger.java
2010
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.scripting.javascript.helper; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.tools.debugger.Dim; import org.mozilla.javascript.tools.debugger.SwingGui; class SlingRhinoDebugger extends Dim { private SlingContextFactory slingContextFactory; private final SwingGui gui; SlingRhinoDebugger(String windowTitle) { gui = new SwingGui(this, windowTitle); gui.pack(); gui.setVisible(true); gui.setExitAction(new Runnable() { public void run() { if (slingContextFactory != null) { slingContextFactory.debuggerStopped(); } } }); } @Override public void attachTo(ContextFactory factory) { super.attachTo(factory); if (factory instanceof SlingContextFactory) { this.slingContextFactory = (SlingContextFactory) factory; } } @Override public void detach() { this.slingContextFactory = null; super.detach(); } @Override public void dispose() { clearAllBreakpoints(); go(); gui.dispose(); super.dispose(); } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/jaxp/src/com/sun/org/apache/bcel/internal/generic/ISUB.java
3590
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ package com.sun.org.apache.bcel.internal.generic; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * ISUB - Substract ints * <PRE>Stack: ..., value1, value2 -&gt; result</PRE> * * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A> */ public class ISUB extends ArithmeticInstruction { /** Substract ints */ public ISUB() { super(com.sun.org.apache.bcel.internal.Constants.ISUB); } /** * Call corresponding visitor method(s). The order is: * Call visitor methods of implemented interfaces first, then * call methods according to the class hierarchy in descending order, * i.e., the most specific visitXXX() call comes last. * * @param v Visitor object */ public void accept(Visitor v) { v.visitTypedInstruction(this); v.visitStackProducer(this); v.visitStackConsumer(this); v.visitArithmeticInstruction(this); v.visitISUB(this); } }
mit
intfloat/CoreNLP
test/src/edu/stanford/nlp/classify/DatasetTest.java
2072
package edu.stanford.nlp.classify; import java.util.Arrays; import edu.stanford.nlp.stats.Counter; import junit.framework.TestCase; import edu.stanford.nlp.ling.BasicDatum; import edu.stanford.nlp.ling.Datum; /** @author Christopher Manning */ public class DatasetTest extends TestCase { public static void testDataset() { Dataset<String, String> data = new Dataset<String, String>(); data.add(new BasicDatum<String, String>(Arrays.asList(new String[]{"fever", "cough", "congestion"}), "cold")); data.add(new BasicDatum<String, String>(Arrays.asList(new String[]{"fever", "cough", "nausea"}), "flu")); data.add(new BasicDatum<String, String>(Arrays.asList(new String[]{"cough", "congestion"}), "cold")); // data.summaryStatistics(); assertEquals(4, data.numFeatures()); assertEquals(4, data.numFeatureTypes()); assertEquals(2, data.numClasses()); assertEquals(8, data.numFeatureTokens()); assertEquals(3, data.size()); data.applyFeatureCountThreshold(2); assertEquals(3, data.numFeatures()); assertEquals(3, data.numFeatureTypes()); assertEquals(2, data.numClasses()); assertEquals(7, data.numFeatureTokens()); assertEquals(3, data.size()); //Dataset data = Dataset.readSVMLightFormat(args[0]); //double[] scores = data.getInformationGains(); //System.out.println(ArrayMath.mean(scores)); //System.out.println(ArrayMath.variance(scores)); LinearClassifierFactory<String, String> factory = new LinearClassifierFactory<String, String>(); LinearClassifier<String, String> classifier = factory.trainClassifier(data); Datum<String, String> d = new BasicDatum<String, String>(Arrays.asList(new String[]{"cough", "fever"})); assertEquals("Classification incorrect", "flu", classifier.classOf(d)); Counter<String> probs = classifier.probabilityOf(d); assertEquals("Returned probability incorrect", 0.4553, probs.getCount("cold"), 0.0001); assertEquals("Returned probability incorrect", 0.5447, probs.getCount("flu"), 0.0001); System.out.println(); } }
gpl-2.0
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/classes/java/text/ParsePosition.java
4834
/* * Copyright (c) 1996, 2013, 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. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.text; /** * <code>ParsePosition</code> is a simple class used by <code>Format</code> * and its subclasses to keep track of the current position during parsing. * The <code>parseObject</code> method in the various <code>Format</code> * classes requires a <code>ParsePosition</code> object as an argument. * * <p> * By design, as you parse through a string with different formats, * you can use the same <code>ParsePosition</code>, since the index parameter * records the current position. * * @author Mark Davis * @see java.text.Format */ public class ParsePosition { /** * Input: the place you start parsing. * <br>Output: position where the parse stopped. * This is designed to be used serially, * with each call setting index up for the next one. */ int index = 0; int errorIndex = -1; /** * Retrieve the current parse position. On input to a parse method, this * is the index of the character at which parsing will begin; on output, it * is the index of the character following the last character parsed. * * @return the current parse position */ public int getIndex() { return index; } /** * Set the current parse position. * * @param index the current parse position */ public void setIndex(int index) { this.index = index; } /** * Create a new ParsePosition with the given initial index. * * @param index initial index */ public ParsePosition(int index) { this.index = index; } /** * Set the index at which a parse error occurred. Formatters * should set this before returning an error code from their * parseObject method. The default value is -1 if this is not set. * * @param ei the index at which an error occurred * @since 1.2 */ public void setErrorIndex(int ei) { errorIndex = ei; } /** * Retrieve the index at which an error occurred, or -1 if the * error index has not been set. * * @return the index at which an error occurred * @since 1.2 */ public int getErrorIndex() { return errorIndex; } /** * Overrides equals */ public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof ParsePosition)) return false; ParsePosition other = (ParsePosition) obj; return (index == other.index && errorIndex == other.errorIndex); } /** * Returns a hash code for this ParsePosition. * @return a hash code value for this object */ public int hashCode() { return (errorIndex << 16) | index; } /** * Return a string representation of this ParsePosition. * @return a string representation of this object */ public String toString() { return getClass().getName() + "[index=" + index + ",errorIndex=" + errorIndex + ']'; } }
mit
kaituo/sedge
trunk/lib-src/bzip2/org/apache/tools/bzip2r/CBZip2OutputStream.java
49261
/* * 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. */ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Ant" and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * <keiron@aftexsw.com> to whom the Ant project is very grateful for his * great code. */ package org.apache.tools.bzip2r; import java.io.OutputStream; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * An output stream that compresses into the BZip2 format (without the file * header chars) into another stream. * * @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a> * * TODO: Update to BZip2 1.0.1 */ public class CBZip2OutputStream extends OutputStream implements BZip2Constants { private final static Log log = LogFactory.getLog(CBZip2OutputStream.class); protected static final int SETMASK = (1 << 21); protected static final int CLEARMASK = (~SETMASK); protected static final int GREATER_ICOST = 15; protected static final int LESSER_ICOST = 0; protected static final int SMALL_THRESH = 20; protected static final int DEPTH_THRESH = 10; /* If you are ever unlucky/improbable enough to get a stack overflow whilst sorting, increase the following constant and try again. In practice I have never seen the stack go above 27 elems, so the following limit seems very generous. */ protected static final int QSORT_STACK_SIZE = 1000; private static void panic() { log.info("panic"); //throw new CError(); } private void makeMaps() { int i; nInUse = 0; for (i = 0; i < 256; i++) { if (inUse[i]) { seqToUnseq[nInUse] = (char) i; unseqToSeq[i] = (char) nInUse; nInUse++; } } } protected static void hbMakeCodeLengths(char[] len, int[] freq, int alphaSize, int maxLen) { /* Nodes and heap entries run from 1. Entry 0 for both the heap and nodes is a sentinel. */ int nNodes, nHeap, n1, n2, i, j, k; boolean tooLong; int[] heap = new int[MAX_ALPHA_SIZE + 2]; int[] weight = new int[MAX_ALPHA_SIZE * 2]; int[] parent = new int[MAX_ALPHA_SIZE * 2]; for (i = 0; i < alphaSize; i++) { weight[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8; } while (true) { nNodes = alphaSize; nHeap = 0; heap[0] = 0; weight[0] = 0; parent[0] = -2; for (i = 1; i <= alphaSize; i++) { parent[i] = -1; nHeap++; heap[nHeap] = i; { int zz, tmp; zz = nHeap; tmp = heap[zz]; while (weight[tmp] < weight[heap[zz >> 1]]) { heap[zz] = heap[zz >> 1]; zz >>= 1; } heap[zz] = tmp; } } if (!(nHeap < (MAX_ALPHA_SIZE + 2))) { panic(); } while (nHeap > 1) { n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; { int zz = 0, yy = 0, tmp = 0; zz = 1; tmp = heap[zz]; while (true) { yy = zz << 1; if (yy > nHeap) { break; } if (yy < nHeap && weight[heap[yy + 1]] < weight[heap[yy]]) { yy++; } if (weight[tmp] < weight[heap[yy]]) { break; } heap[zz] = heap[yy]; zz = yy; } heap[zz] = tmp; } n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; { int zz = 0, yy = 0, tmp = 0; zz = 1; tmp = heap[zz]; while (true) { yy = zz << 1; if (yy > nHeap) { break; } if (yy < nHeap && weight[heap[yy + 1]] < weight[heap[yy]]) { yy++; } if (weight[tmp] < weight[heap[yy]]) { break; } heap[zz] = heap[yy]; zz = yy; } heap[zz] = tmp; } nNodes++; parent[n1] = parent[n2] = nNodes; weight[nNodes] = ((weight[n1] & 0xffffff00) + (weight[n2] & 0xffffff00)) | (1 + (((weight[n1] & 0x000000ff) > (weight[n2] & 0x000000ff)) ? (weight[n1] & 0x000000ff) : (weight[n2] & 0x000000ff))); parent[nNodes] = -1; nHeap++; heap[nHeap] = nNodes; { int zz = 0, tmp = 0; zz = nHeap; tmp = heap[zz]; while (weight[tmp] < weight[heap[zz >> 1]]) { heap[zz] = heap[zz >> 1]; zz >>= 1; } heap[zz] = tmp; } } if (!(nNodes < (MAX_ALPHA_SIZE * 2))) { panic(); } tooLong = false; for (i = 1; i <= alphaSize; i++) { j = 0; k = i; while (parent[k] >= 0) { k = parent[k]; j++; } len[i - 1] = (char) j; if (j > maxLen) { tooLong = true; } } if (!tooLong) { break; } for (i = 1; i < alphaSize; i++) { j = weight[i] >> 8; j = 1 + (j / 2); weight[i] = j << 8; } } } /* index of the last char in the block, so the block size == last + 1. */ int last; /* index in zptr[] of original string after sorting. */ int origPtr; /* always: in the range 0 .. 9. The current block size is 100000 * this number. */ int blockSize100k; boolean blockRandomised; int bytesOut; int bsBuff; int bsLive; CRC mCrc = new CRC(); private boolean[] inUse = new boolean[256]; private int nInUse; private char[] seqToUnseq = new char[256]; private char[] unseqToSeq = new char[256]; private char[] selector = new char[MAX_SELECTORS]; private char[] selectorMtf = new char[MAX_SELECTORS]; private char[] block; private int[] quadrant; private int[] zptr; private short[] szptr; private int[] ftab; private int nMTF; private int[] mtfFreq = new int[MAX_ALPHA_SIZE]; /* * Used when sorting. If too many long comparisons * happen, we stop sorting, randomise the block * slightly, and try again. */ private int workFactor; private int workDone; private int workLimit; private boolean firstAttempt; private int nBlocksRandomised; private int currentChar = -1; private int runLength = 0; private boolean written = false; public CBZip2OutputStream(OutputStream inStream) throws IOException { this(inStream, 9); } public CBZip2OutputStream(OutputStream inStream, int inBlockSize) throws IOException { block = null; quadrant = null; zptr = null; ftab = null; inStream.write("BZ".getBytes()); bsSetStream(inStream); workFactor = 50; if (inBlockSize > 9) { inBlockSize = 9; } if (inBlockSize < 1) { inBlockSize = 1; } blockSize100k = inBlockSize; allocateCompressStructures(); initialize(); initBlock(); } /** * * modified by Oliver Merkel, 010128 * */ public void write(int bv) throws IOException { written = true; int b = (256 + bv) % 256; if (currentChar != -1) { if (currentChar == b) { runLength++; if (runLength > 254) { writeRun(); currentChar = -1; runLength = 0; } } else { writeRun(); runLength = 1; currentChar = b; } } else { currentChar = b; runLength++; } } private void writeRun() throws IOException { if (last < allowableBlockSize) { inUse[currentChar] = true; for (int i = 0; i < runLength; i++) { mCrc.updateCRC((char) currentChar); } switch (runLength) { case 1: last++; block[last + 1] = (char) currentChar; break; case 2: last++; block[last + 1] = (char) currentChar; last++; block[last + 1] = (char) currentChar; break; case 3: last++; block[last + 1] = (char) currentChar; last++; block[last + 1] = (char) currentChar; last++; block[last + 1] = (char) currentChar; break; default: inUse[runLength - 4] = true; last++; block[last + 1] = (char) currentChar; last++; block[last + 1] = (char) currentChar; last++; block[last + 1] = (char) currentChar; last++; block[last + 1] = (char) currentChar; last++; block[last + 1] = (char) (runLength - 4); break; } } else { endBlock(); initBlock(); writeRun(); } } boolean closed = false; protected void finalize() throws Throwable { close(); super.finalize(); } // The bytes to fillin an empty file final private static byte emptyFileArray[] = { 0x39, 0x17, 0x72, 0x45, 0x38, 0x50, (byte) 0x90, 00, 00, 00, 00 }; public void close() throws IOException { if (closed) { return; } if (runLength > 0) { writeRun(); } currentChar = -1; if (written){ endBlock(); endCompression(); } else { bsStream.write(emptyFileArray); } closed = true; super.close(); bsStream.close(); } public void flush() throws IOException { super.flush(); bsStream.flush(); } private int blockCRC, combinedCRC; private void initialize() throws IOException { bytesOut = 0; nBlocksRandomised = 0; /* Write `magic' bytes h indicating file-format == huffmanised, followed by a digit indicating blockSize100k. */ bsPutUChar('h'); bsPutUChar('0' + blockSize100k); combinedCRC = 0; } private int allowableBlockSize; private void initBlock() { // blockNo++; mCrc.initialiseCRC(); last = -1; // ch = 0; for (int i = 0; i < 256; i++) { inUse[i] = false; } /* 20 is just a paranoia constant */ allowableBlockSize = baseBlockSize * blockSize100k - 20; } private void endBlock() throws IOException { blockCRC = mCrc.getFinalCRC(); combinedCRC = (combinedCRC << 1) | (combinedCRC >>> 31); combinedCRC ^= blockCRC; /* sort the block and establish posn of original string */ doReversibleTransformation(); /* A 6-byte block header, the value chosen arbitrarily as 0x314159265359 :-). A 32 bit value does not really give a strong enough guarantee that the value will not appear by chance in the compressed datastream. Worst-case probability of this event, for a 900k block, is about 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits. For a compressed file of size 100Gb -- about 100000 blocks -- only a 48-bit marker will do. NB: normal compression/ decompression do *not* rely on these statistical properties. They are only important when trying to recover blocks from damaged files. */ bsPutUChar(0x31); bsPutUChar(0x41); bsPutUChar(0x59); bsPutUChar(0x26); bsPutUChar(0x53); bsPutUChar(0x59); /* Now the block's CRC, so it is in a known place. */ bsPutint(blockCRC); /* Now a single bit indicating randomisation. */ if (blockRandomised) { bsW(1, 1); nBlocksRandomised++; } else { bsW(1, 0); } /* Finally, block's contents proper. */ moveToFrontCodeAndSend(); } private void endCompression() throws IOException { /* Now another magic 48-bit number, 0x177245385090, to indicate the end of the last block. (sqrt(pi), if you want to know. I did want to use e, but it contains too much repetition -- 27 18 28 18 28 46 -- for me to feel statistically comfortable. Call me paranoid.) */ bsPutUChar(0x17); bsPutUChar(0x72); bsPutUChar(0x45); bsPutUChar(0x38); bsPutUChar(0x50); bsPutUChar(0x90); bsPutint(combinedCRC); bsFinishedWithStream(); } private void hbAssignCodes (int[] code, char[] length, int minLen, int maxLen, int alphaSize) { int n, vec, i; vec = 0; for (n = minLen; n <= maxLen; n++) { for (i = 0; i < alphaSize; i++) { if (length[i] == n) { code[i] = vec; vec++; } }; vec <<= 1; } } private void bsSetStream(OutputStream f) { bsStream = f; bsLive = 0; bsBuff = 0; bytesOut = 0; } private void bsFinishedWithStream() throws IOException { while (bsLive > 0) { int ch = (bsBuff >> 24); try { bsStream.write(ch); // write 8-bit } catch (IOException e) { throw e; } bsBuff <<= 8; bsLive -= 8; bytesOut++; } } private void bsW(int n, int v) throws IOException { while (bsLive >= 8) { int ch = (bsBuff >> 24); try { bsStream.write(ch); // write 8-bit } catch (IOException e) { throw e; } bsBuff <<= 8; bsLive -= 8; bytesOut++; } bsBuff |= (v << (32 - bsLive - n)); bsLive += n; } private void bsPutUChar(int c) throws IOException { bsW(8, c); } private void bsPutint(int u) throws IOException { bsW(8, (u >> 24) & 0xff); bsW(8, (u >> 16) & 0xff); bsW(8, (u >> 8) & 0xff); bsW(8, u & 0xff); } private void bsPutIntVS(int numBits, int c) throws IOException { bsW(numBits, c); } private void sendMTFValues() throws IOException { char len[][] = new char[N_GROUPS][MAX_ALPHA_SIZE]; int v, t, i, j, gs, ge, totc, bt, bc, iter; int nSelectors = 0, alphaSize, minLen, maxLen, selCtr; int nGroups, nBytes; alphaSize = nInUse + 2; for (t = 0; t < N_GROUPS; t++) { for (v = 0; v < alphaSize; v++) { len[t][v] = (char) GREATER_ICOST; } } /* Decide how many coding tables to use */ if (nMTF <= 0) { panic(); } if (nMTF < 200) { nGroups = 2; } else if (nMTF < 600) { nGroups = 3; } else if (nMTF < 1200) { nGroups = 4; } else if (nMTF < 2400) { nGroups = 5; } else { nGroups = 6; } /* Generate an initial set of coding tables */ { int nPart, remF, tFreq, aFreq; nPart = nGroups; remF = nMTF; gs = 0; while (nPart > 0) { tFreq = remF / nPart; ge = gs - 1; aFreq = 0; while (aFreq < tFreq && ge < alphaSize - 1) { ge++; aFreq += mtfFreq[ge]; } if (ge > gs && nPart != nGroups && nPart != 1 && ((nGroups - nPart) % 2 == 1)) { aFreq -= mtfFreq[ge]; ge--; } for (v = 0; v < alphaSize; v++) { if (v >= gs && v <= ge) { len[nPart - 1][v] = (char) LESSER_ICOST; } else { len[nPart - 1][v] = (char) GREATER_ICOST; } } nPart--; gs = ge + 1; remF -= aFreq; } } int[][] rfreq = new int[N_GROUPS][MAX_ALPHA_SIZE]; int[] fave = new int[N_GROUPS]; short[] cost = new short[N_GROUPS]; /* Iterate up to N_ITERS times to improve the tables. */ for (iter = 0; iter < N_ITERS; iter++) { for (t = 0; t < nGroups; t++) { fave[t] = 0; } for (t = 0; t < nGroups; t++) { for (v = 0; v < alphaSize; v++) { rfreq[t][v] = 0; } } nSelectors = 0; totc = 0; gs = 0; while (true) { /* Set group start & end marks. */ if (gs >= nMTF) { break; } ge = gs + G_SIZE - 1; if (ge >= nMTF) { ge = nMTF - 1; } /* Calculate the cost of this group as coded by each of the coding tables. */ for (t = 0; t < nGroups; t++) { cost[t] = 0; } if (nGroups == 6) { short cost0, cost1, cost2, cost3, cost4, cost5; cost0 = cost1 = cost2 = cost3 = cost4 = cost5 = 0; for (i = gs; i <= ge; i++) { short icv = szptr[i]; cost0 += len[0][icv]; cost1 += len[1][icv]; cost2 += len[2][icv]; cost3 += len[3][icv]; cost4 += len[4][icv]; cost5 += len[5][icv]; } cost[0] = cost0; cost[1] = cost1; cost[2] = cost2; cost[3] = cost3; cost[4] = cost4; cost[5] = cost5; } else { for (i = gs; i <= ge; i++) { short icv = szptr[i]; for (t = 0; t < nGroups; t++) { cost[t] += len[t][icv]; } } } /* Find the coding table which is best for this group, and record its identity in the selector table. */ bc = 999999999; bt = -1; for (t = 0; t < nGroups; t++) { if (cost[t] < bc) { bc = cost[t]; bt = t; } }; totc += bc; fave[bt]++; selector[nSelectors] = (char) bt; nSelectors++; /* Increment the symbol frequencies for the selected table. */ for (i = gs; i <= ge; i++) { rfreq[bt][szptr[i]]++; } gs = ge + 1; } /* Recompute the tables based on the accumulated frequencies. */ for (t = 0; t < nGroups; t++) { hbMakeCodeLengths(len[t], rfreq[t], alphaSize, 20); } } rfreq = null; fave = null; cost = null; if (!(nGroups < 8)) { panic(); } if (!(nSelectors < 32768 && nSelectors <= (2 + (900000 / G_SIZE)))) { panic(); } /* Compute MTF values for the selectors. */ { char[] pos = new char[N_GROUPS]; char ll_i, tmp2, tmp; for (i = 0; i < nGroups; i++) { pos[i] = (char) i; } for (i = 0; i < nSelectors; i++) { ll_i = selector[i]; j = 0; tmp = pos[j]; while (ll_i != tmp) { j++; tmp2 = tmp; tmp = pos[j]; pos[j] = tmp2; } pos[0] = tmp; selectorMtf[i] = (char) j; } } int[][] code = new int[N_GROUPS][MAX_ALPHA_SIZE]; /* Assign actual codes for the tables. */ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (len[t][i] > maxLen) { maxLen = len[t][i]; } if (len[t][i] < minLen) { minLen = len[t][i]; } } if (maxLen > 20) { panic(); } if (minLen < 1) { panic(); } hbAssignCodes(code[t], len[t], minLen, maxLen, alphaSize); } /* Transmit the mapping table. */ { boolean[] inUse16 = new boolean[16]; for (i = 0; i < 16; i++) { inUse16[i] = false; for (j = 0; j < 16; j++) { if (inUse[i * 16 + j]) { inUse16[i] = true; } } } nBytes = bytesOut; for (i = 0; i < 16; i++) { if (inUse16[i]) { bsW(1, 1); } else { bsW(1, 0); } } for (i = 0; i < 16; i++) { if (inUse16[i]) { for (j = 0; j < 16; j++) { if (inUse[i * 16 + j]) { bsW(1, 1); } else { bsW(1, 0); } } } } } /* Now the selectors. */ nBytes = bytesOut; bsW (3, nGroups); bsW (15, nSelectors); for (i = 0; i < nSelectors; i++) { for (j = 0; j < selectorMtf[i]; j++) { bsW(1, 1); } bsW(1, 0); } /* Now the coding tables. */ nBytes = bytesOut; for (t = 0; t < nGroups; t++) { int curr = len[t][0]; bsW(5, curr); for (i = 0; i < alphaSize; i++) { while (curr < len[t][i]) { bsW(2, 2); curr++; /* 10 */ } while (curr > len[t][i]) { bsW(2, 3); curr--; /* 11 */ } bsW (1, 0); } } /* And finally, the block data proper */ nBytes = bytesOut; selCtr = 0; gs = 0; while (true) { if (gs >= nMTF) { break; } ge = gs + G_SIZE - 1; if (ge >= nMTF) { ge = nMTF - 1; } for (i = gs; i <= ge; i++) { bsW(len[selector[selCtr]][szptr[i]], code[selector[selCtr]][szptr[i]]); } gs = ge + 1; selCtr++; } if (!(selCtr == nSelectors)) { panic(); } } private void moveToFrontCodeAndSend () throws IOException { bsPutIntVS(24, origPtr); generateMTFValues(); sendMTFValues(); } private OutputStream bsStream; private void simpleSort(int lo, int hi, int d) { int i, j, h, bigN, hp; int v; bigN = hi - lo + 1; if (bigN < 2) { return; } hp = 0; while (incs[hp] < bigN) { hp++; } hp--; for (; hp >= 0; hp--) { h = incs[hp]; i = lo + h; while (true) { /* copy 1 */ if (i > hi) { break; } v = zptr[i]; j = i; while (fullGtU(zptr[j - h] + d, v + d)) { zptr[j] = zptr[j - h]; j = j - h; if (j <= (lo + h - 1)) { break; } } zptr[j] = v; i++; /* copy 2 */ if (i > hi) { break; } v = zptr[i]; j = i; while (fullGtU(zptr[j - h] + d, v + d)) { zptr[j] = zptr[j - h]; j = j - h; if (j <= (lo + h - 1)) { break; } } zptr[j] = v; i++; /* copy 3 */ if (i > hi) { break; } v = zptr[i]; j = i; while (fullGtU(zptr[j - h] + d, v + d)) { zptr[j] = zptr[j - h]; j = j - h; if (j <= (lo + h - 1)) { break; } } zptr[j] = v; i++; if (workDone > workLimit && firstAttempt) { return; } } } } private void vswap(int p1, int p2, int n) { int temp = 0; while (n > 0) { temp = zptr[p1]; zptr[p1] = zptr[p2]; zptr[p2] = temp; p1++; p2++; n--; } } private char med3(char a, char b, char c) { char t; if (a > b) { t = a; a = b; b = t; } if (b > c) { b = c; } if (a > b) { b = a; } return b; } private static class StackElem { int ll; int hh; int dd; } private void qSort3(int loSt, int hiSt, int dSt) { int unLo, unHi, ltLo, gtHi, med, n, m; int sp, lo, hi, d; StackElem[] stack = new StackElem[QSORT_STACK_SIZE]; for (int count = 0; count < QSORT_STACK_SIZE; count++) { stack[count] = new StackElem(); } sp = 0; stack[sp].ll = loSt; stack[sp].hh = hiSt; stack[sp].dd = dSt; sp++; while (sp > 0) { if (sp >= QSORT_STACK_SIZE) { panic(); } sp--; lo = stack[sp].ll; hi = stack[sp].hh; d = stack[sp].dd; if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH) { simpleSort(lo, hi, d); if (workDone > workLimit && firstAttempt) { return; } continue; } med = med3(block[zptr[lo] + d + 1], block[zptr[hi ] + d + 1], block[zptr[(lo + hi) >> 1] + d + 1]); unLo = ltLo = lo; unHi = gtHi = hi; while (true) { while (true) { if (unLo > unHi) { break; } n = ((int) block[zptr[unLo] + d + 1]) - med; if (n == 0) { int temp = 0; temp = zptr[unLo]; zptr[unLo] = zptr[ltLo]; zptr[ltLo] = temp; ltLo++; unLo++; continue; }; if (n > 0) { break; } unLo++; } while (true) { if (unLo > unHi) { break; } n = ((int) block[zptr[unHi] + d + 1]) - med; if (n == 0) { int temp = 0; temp = zptr[unHi]; zptr[unHi] = zptr[gtHi]; zptr[gtHi] = temp; gtHi--; unHi--; continue; }; if (n < 0) { break; } unHi--; } if (unLo > unHi) { break; } int temp = 0; temp = zptr[unLo]; zptr[unLo] = zptr[unHi]; zptr[unHi] = temp; unLo++; unHi--; } if (gtHi < ltLo) { stack[sp].ll = lo; stack[sp].hh = hi; stack[sp].dd = d + 1; sp++; continue; } n = ((ltLo - lo) < (unLo - ltLo)) ? (ltLo - lo) : (unLo - ltLo); vswap(lo, unLo - n, n); m = ((hi - gtHi) < (gtHi - unHi)) ? (hi - gtHi) : (gtHi - unHi); vswap(unLo, hi - m + 1, m); n = lo + unLo - ltLo - 1; m = hi - (gtHi - unHi) + 1; stack[sp].ll = lo; stack[sp].hh = n; stack[sp].dd = d; sp++; stack[sp].ll = n + 1; stack[sp].hh = m - 1; stack[sp].dd = d + 1; sp++; stack[sp].ll = m; stack[sp].hh = hi; stack[sp].dd = d; sp++; } } private void mainSort() { int i, j, ss, sb; int[] runningOrder = new int[256]; int[] copy = new int[256]; boolean[] bigDone = new boolean[256]; int c1, c2; int numQSorted; /* In the various block-sized structures, live data runs from 0 to last+NUM_OVERSHOOT_BYTES inclusive. First, set up the overshoot area for block. */ // if (verbosity >= 4) fprintf ( stderr, " sort initialise ...\n" ); for (i = 0; i < NUM_OVERSHOOT_BYTES; i++) { block[last + i + 2] = block[(i % (last + 1)) + 1]; } for (i = 0; i <= last + NUM_OVERSHOOT_BYTES; i++) { quadrant[i] = 0; } block[0] = block[last + 1]; if (last < 4000) { /* Use simpleSort(), since the full sorting mechanism has quite a large constant overhead. */ for (i = 0; i <= last; i++) { zptr[i] = i; } firstAttempt = false; workDone = workLimit = 0; simpleSort(0, last, 0); } else { numQSorted = 0; for (i = 0; i <= 255; i++) { bigDone[i] = false; } for (i = 0; i <= 65536; i++) { ftab[i] = 0; } c1 = block[0]; for (i = 0; i <= last; i++) { c2 = block[i + 1]; ftab[(c1 << 8) + c2]++; c1 = c2; } for (i = 1; i <= 65536; i++) { ftab[i] += ftab[i - 1]; } c1 = block[1]; for (i = 0; i < last; i++) { c2 = block[i + 2]; j = (c1 << 8) + c2; c1 = c2; ftab[j]--; zptr[ftab[j]] = i; } j = ((block[last + 1]) << 8) + (block[1]); ftab[j]--; zptr[ftab[j]] = last; /* Now ftab contains the first loc of every small bucket. Calculate the running order, from smallest to largest big bucket. */ for (i = 0; i <= 255; i++) { runningOrder[i] = i; } { int vv; int h = 1; do { h = 3 * h + 1; } while (h <= 256); do { h = h / 3; for (i = h; i <= 255; i++) { vv = runningOrder[i]; j = i; while ((ftab[((runningOrder[j - h]) + 1) << 8] - ftab[(runningOrder[j - h]) << 8]) > (ftab[((vv) + 1) << 8] - ftab[(vv) << 8])) { runningOrder[j] = runningOrder[j - h]; j = j - h; if (j <= (h - 1)) { break; } } runningOrder[j] = vv; } } while (h != 1); } /* The main sorting loop. */ for (i = 0; i <= 255; i++) { /* Process big buckets, starting with the least full. */ ss = runningOrder[i]; /* Complete the big bucket [ss] by quicksorting any unsorted small buckets [ss, j]. Hopefully previous pointer-scanning phases have already completed many of the small buckets [ss, j], so we don't have to sort them at all. */ for (j = 0; j <= 255; j++) { sb = (ss << 8) + j; if (!((ftab[sb] & SETMASK) == SETMASK)) { int lo = ftab[sb] & CLEARMASK; int hi = (ftab[sb + 1] & CLEARMASK) - 1; if (hi > lo) { qSort3(lo, hi, 2); numQSorted += (hi - lo + 1); if (workDone > workLimit && firstAttempt) { return; } } ftab[sb] |= SETMASK; } } /* The ss big bucket is now done. Record this fact, and update the quadrant descriptors. Remember to update quadrants in the overshoot area too, if necessary. The "if (i < 255)" test merely skips this updating for the last bucket processed, since updating for the last bucket is pointless. */ bigDone[ss] = true; if (i < 255) { int bbStart = ftab[ss << 8] & CLEARMASK; int bbSize = (ftab[(ss + 1) << 8] & CLEARMASK) - bbStart; int shifts = 0; while ((bbSize >> shifts) > 65534) { shifts++; } for (j = 0; j < bbSize; j++) { int a2update = zptr[bbStart + j]; int qVal = (j >> shifts); quadrant[a2update] = qVal; if (a2update < NUM_OVERSHOOT_BYTES) { quadrant[a2update + last + 1] = qVal; } } if (!(((bbSize - 1) >> shifts) <= 65535)) { panic(); } } /* Now scan this big bucket so as to synthesise the sorted order for small buckets [t, ss] for all t != ss. */ for (j = 0; j <= 255; j++) { copy[j] = ftab[(j << 8) + ss] & CLEARMASK; } for (j = ftab[ss << 8] & CLEARMASK; j < (ftab[(ss + 1) << 8] & CLEARMASK); j++) { c1 = block[zptr[j]]; if (!bigDone[c1]) { zptr[copy[c1]] = zptr[j] == 0 ? last : zptr[j] - 1; copy[c1]++; } } for (j = 0; j <= 255; j++) { ftab[(j << 8) + ss] |= SETMASK; } } } } private void randomiseBlock() { int i; int rNToGo = 0; int rTPos = 0; for (i = 0; i < 256; i++) { inUse[i] = false; } for (i = 0; i <= last; i++) { if (rNToGo == 0) { rNToGo = (char) rNums[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; block[i + 1] ^= ((rNToGo == 1) ? 1 : 0); // handle 16 bit signed numbers block[i + 1] &= 0xFF; inUse[block[i + 1]] = true; } } private void doReversibleTransformation() { int i; workLimit = workFactor * last; workDone = 0; blockRandomised = false; firstAttempt = true; mainSort(); if (workDone > workLimit && firstAttempt) { randomiseBlock(); workLimit = workDone = 0; blockRandomised = true; firstAttempt = false; mainSort(); } origPtr = -1; for (i = 0; i <= last; i++) { if (zptr[i] == 0) { origPtr = i; break; } }; if (origPtr == -1) { panic(); } } private boolean fullGtU(int i1, int i2) { int k; char c1, c2; int s1, s2; c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } i1++; i2++; c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } i1++; i2++; c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } i1++; i2++; c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } i1++; i2++; c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } i1++; i2++; c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } i1++; i2++; k = last + 1; do { c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) { return (s1 > s2); } i1++; i2++; c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) { return (s1 > s2); } i1++; i2++; c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) { return (s1 > s2); } i1++; i2++; c1 = block[i1 + 1]; c2 = block[i2 + 1]; if (c1 != c2) { return (c1 > c2); } s1 = quadrant[i1]; s2 = quadrant[i2]; if (s1 != s2) { return (s1 > s2); } i1++; i2++; if (i1 > last) { i1 -= last; i1--; }; if (i2 > last) { i2 -= last; i2--; }; k -= 4; workDone++; } while (k >= 0); return false; } /* Knuth's increments seem to work better than Incerpi-Sedgewick here. Possibly because the number of elems to sort is usually small, typically <= 20. */ private int[] incs = { 1, 4, 13, 40, 121, 364, 1093, 3280, 9841, 29524, 88573, 265720, 797161, 2391484 }; private void allocateCompressStructures () { int n = baseBlockSize * blockSize100k; block = new char[(n + 1 + NUM_OVERSHOOT_BYTES)]; quadrant = new int[(n + NUM_OVERSHOOT_BYTES)]; zptr = new int[n]; ftab = new int[65537]; if (block == null || quadrant == null || zptr == null || ftab == null) { //int totalDraw = (n + 1 + NUM_OVERSHOOT_BYTES) + (n + NUM_OVERSHOOT_BYTES) + n + 65537; //compressOutOfMemory ( totalDraw, n ); } /* The back end needs a place to store the MTF values whilst it calculates the coding tables. We could put them in the zptr array. However, these values will fit in a short, so we overlay szptr at the start of zptr, in the hope of reducing the number of cache misses induced by the multiple traversals of the MTF values when calculating coding tables. Seems to improve compression speed by about 1%. */ // szptr = zptr; szptr = new short[2 * n]; } private void generateMTFValues() { char[] yy = new char[256]; int i, j; char tmp; char tmp2; int zPend; int wr; int EOB; makeMaps(); EOB = nInUse + 1; for (i = 0; i <= EOB; i++) { mtfFreq[i] = 0; } wr = 0; zPend = 0; for (i = 0; i < nInUse; i++) { yy[i] = (char) i; } for (i = 0; i <= last; i++) { char ll_i; ll_i = unseqToSeq[block[zptr[i]]]; j = 0; tmp = yy[j]; while (ll_i != tmp) { j++; tmp2 = tmp; tmp = yy[j]; yy[j] = tmp2; }; yy[0] = tmp; if (j == 0) { zPend++; } else { if (zPend > 0) { zPend--; while (true) { switch (zPend % 2) { case 0: szptr[wr] = (short) RUNA; wr++; mtfFreq[RUNA]++; break; case 1: szptr[wr] = (short) RUNB; wr++; mtfFreq[RUNB]++; break; }; if (zPend < 2) { break; } zPend = (zPend - 2) / 2; }; zPend = 0; } szptr[wr] = (short) (j + 1); wr++; mtfFreq[j + 1]++; } } if (zPend > 0) { zPend--; while (true) { switch (zPend % 2) { case 0: szptr[wr] = (short) RUNA; wr++; mtfFreq[RUNA]++; break; case 1: szptr[wr] = (short) RUNB; wr++; mtfFreq[RUNB]++; break; } if (zPend < 2) { break; } zPend = (zPend - 2) / 2; } } szptr[wr] = (short) EOB; wr++; mtfFreq[EOB]++; nMTF = wr; } }
mit
PhaedrusTheGreek/elasticsearch
core/src/main/java/org/elasticsearch/action/admin/cluster/validate/template/RenderSearchTemplateRequestBuilder.java
1603
/* * 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.action.admin.cluster.validate.template; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.client.ElasticsearchClient; import org.elasticsearch.script.Template; public class RenderSearchTemplateRequestBuilder extends ActionRequestBuilder<RenderSearchTemplateRequest, RenderSearchTemplateResponse, RenderSearchTemplateRequestBuilder> { public RenderSearchTemplateRequestBuilder(ElasticsearchClient client, RenderSearchTemplateAction action) { super(client, action, new RenderSearchTemplateRequest()); } public RenderSearchTemplateRequestBuilder template(Template template) { request.template(template); return this; } public Template template() { return request.template(); } }
apache-2.0
akosyakov/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrInplaceParameterIntroducer.java
10716
/* * 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 org.jetbrains.plugins.groovy.refactoring.introduce.parameter; import com.intellij.codeInsight.template.TextResult; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.openapi.editor.event.DocumentAdapter; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.impl.DocumentMarkupModel; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.HighlighterTargetArea; import com.intellij.openapi.editor.markup.MarkupModel; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiParameter; import com.intellij.psi.PsiType; import com.intellij.refactoring.IntroduceParameterRefactoring; import com.intellij.refactoring.introduce.inplace.OccurrencesChooser; import com.intellij.refactoring.rename.inplace.InplaceRefactoring; import com.intellij.ui.JBColor; import com.intellij.ui.components.JBCheckBox; import com.intellij.usageView.UsageInfo; import com.intellij.util.ArrayUtil; import gnu.trove.TIntArrayList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrParametersOwner; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.refactoring.introduce.GrAbstractInplaceIntroducer; import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceContext; import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceHandlerBase; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; /** * Created by Max Medvedev on 9/1/13 */ public class GrInplaceParameterIntroducer extends GrAbstractInplaceIntroducer<GrIntroduceParameterSettings> { private final IntroduceParameterInfo myInfo; private final TIntArrayList myParametersToRemove; private JBCheckBox myDelegateCB; private final LinkedHashSet<String> mySuggestedNames; public GrInplaceParameterIntroducer(IntroduceParameterInfo info, GrIntroduceContext context, OccurrencesChooser.ReplaceChoice choice) { super(GrIntroduceParameterHandler.REFACTORING_NAME, choice, context); myInfo = info; GrVariable localVar = GrIntroduceHandlerBase.resolveLocalVar(context); mySuggestedNames = GroovyIntroduceParameterUtil.suggestNames(localVar, context.getExpression(), context.getStringPart(), info.getToReplaceIn(), context.getProject()); myParametersToRemove = new TIntArrayList(GroovyIntroduceParameterUtil.findParametersToRemove(info).getValues()); } @Override protected String getActionName() { return GrIntroduceParameterHandler.REFACTORING_NAME; } @Override protected String[] suggestNames(boolean replaceAll, @Nullable GrVariable variable) { return ArrayUtil.toStringArray(mySuggestedNames); } @Override protected JComponent getComponent() { JPanel previewPanel = new JPanel(new BorderLayout()); previewPanel.add(getPreviewEditor().getComponent(), BorderLayout.CENTER); previewPanel.setBorder(new EmptyBorder(2, 2, 6, 2)); DocumentAdapter documentAdapter = new DocumentAdapter() { @Override public void documentChanged(DocumentEvent e) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); if (templateState != null) { final TextResult value = templateState.getVariableValue(InplaceRefactoring.PRIMARY_VARIABLE_NAME); if (value != null) { updateTitle(getVariable(), value.getText()); } } } }; myEditor.getDocument().addDocumentListener(documentAdapter); myDelegateCB = new JBCheckBox("Delegate via overloading method"); myDelegateCB.setMnemonic('l'); myDelegateCB.setFocusable(false); JPanel panel = new JPanel(new BorderLayout()); panel.add(previewPanel, BorderLayout.CENTER); panel.add(myDelegateCB, BorderLayout.SOUTH); return panel; } @Override protected void saveSettings(@NotNull GrVariable variable) { } @Override protected void updateTitle(@Nullable GrVariable variable) { if (variable == null) return; updateTitle(variable, variable.getName()); } @Override protected void updateTitle(@Nullable GrVariable variable, String value) { if (getPreviewEditor() == null || variable == null) return; final PsiElement declarationScope = ((PsiParameter)variable).getDeclarationScope(); if (declarationScope instanceof PsiMethod) { final PsiMethod psiMethod = (PsiMethod)declarationScope; final StringBuilder buf = new StringBuilder(); buf.append(psiMethod.getName()).append(" ("); boolean frst = true; final List<TextRange> ranges2Remove = new ArrayList<TextRange>(); TextRange addedRange = null; int i = 0; for (PsiParameter parameter : psiMethod.getParameterList().getParameters()) { if (frst) { frst = false; } else { buf.append(", "); } int startOffset = buf.length(); /*if (myMustBeFinal || myPanel.isGenerateFinal()) { buf.append("final "); }*/ buf.append(parameter.getType().getPresentableText()).append(" ").append(variable == parameter ? value : parameter.getName()); int endOffset = buf.length(); if (variable == parameter) { addedRange = new TextRange(startOffset, endOffset); } else if (myParametersToRemove.contains(i)) { ranges2Remove.add(new TextRange(startOffset, endOffset)); } i++; } assert addedRange != null; buf.append(")"); setPreviewText(buf.toString()); final MarkupModel markupModel = DocumentMarkupModel.forDocument(getPreviewEditor().getDocument(), myProject, true); markupModel.removeAllHighlighters(); for (TextRange textRange : ranges2Remove) { markupModel.addRangeHighlighter(textRange.getStartOffset(), textRange.getEndOffset(), 0, getTestAttributesForRemoval(), HighlighterTargetArea.EXACT_RANGE); } markupModel.addRangeHighlighter(addedRange.getStartOffset(), addedRange.getEndOffset(), 0, getTextAttributesForAdd(), HighlighterTargetArea.EXACT_RANGE); //revalidate(); } } private static TextAttributes getTextAttributesForAdd() { final TextAttributes textAttributes = new TextAttributes(); textAttributes.setEffectType(EffectType.ROUNDED_BOX); textAttributes.setEffectColor(JBColor.RED); return textAttributes; } private static TextAttributes getTestAttributesForRemoval() { final TextAttributes textAttributes = new TextAttributes(); textAttributes.setEffectType(EffectType.STRIKEOUT); textAttributes.setEffectColor(JBColor.BLACK); return textAttributes; } @Override protected GrVariable runRefactoring(GrIntroduceContext context, GrIntroduceParameterSettings settings, boolean processUsages) { GrExpressionWrapper wrapper = createExpressionWrapper(context); if (processUsages) { GrIntroduceExpressionSettingsImpl patchedSettings = new GrIntroduceExpressionSettingsImpl(settings, settings.getName(), settings.declareFinal(), settings.parametersToRemove(), settings.generateDelegate(), settings.replaceFieldsWithGetters(), context.getExpression(), context.getVar(), settings.getSelectedType(), context.getVar() != null || settings.replaceAllOccurrences(), context.getVar() != null, settings.isForceReturn()); GrIntroduceParameterProcessor processor = new GrIntroduceParameterProcessor(patchedSettings, wrapper); processor.run(); } else { GrIntroduceParameterProcessor processor = new GrIntroduceParameterProcessor(settings, wrapper); processor.performRefactoring(UsageInfo.EMPTY_ARRAY); } GrParametersOwner owner = settings.getToReplaceIn(); return ArrayUtil.getLastElement(owner.getParameters()); } @NotNull private static GrExpressionWrapper createExpressionWrapper(@NotNull GrIntroduceContext context) { GrExpression expression = context.getExpression(); GrVariable var = context.getVar(); assert expression != null || var != null ; GrExpression initializer = expression != null ? expression : var.getInitializerGroovy(); return new GrExpressionWrapper(initializer); } @Nullable @Override protected GrIntroduceParameterSettings getInitialSettingsForInplace(@NotNull GrIntroduceContext context, @NotNull OccurrencesChooser.ReplaceChoice choice, String[] names) { GrExpression expression = context.getExpression(); GrVariable var = context.getVar(); PsiType type = var != null ? var.getDeclaredType() : expression != null ? expression.getType() : null; return new GrIntroduceExpressionSettingsImpl(myInfo, names[0], false, new TIntArrayList(), false, IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, expression, var, type, false, false, false); } @Override protected GrIntroduceParameterSettings getSettings() { return new GrIntroduceExpressionSettingsImpl(myInfo, getInputName(), false, myParametersToRemove, myDelegateCB.isSelected(), IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, null, null, getSelectedType(), isReplaceAllOccurrences(), false, false); } }
apache-2.0
wfuedu/sakai
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/ConfirmDeleteTemplateListener.java
3335
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.tool.assessment.ui.listener.author; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import org.sakaiproject.tool.assessment.facade.AssessmentTemplateFacade; import org.sakaiproject.tool.assessment.services.assessment.AssessmentService; import org.sakaiproject.tool.assessment.ui.bean.author.TemplateBean; import org.sakaiproject.user.cover.UserDirectoryService; /** * <p> Stub</p> * <p>Description: Action Listener to confrim deletion of template.</p> * <p>Copyright: Copyright (c) 2004</p> * <p>Organization: Sakai Project</p> * @author Ed Smiley * @version $Id$ */ public class ConfirmDeleteTemplateListener extends TemplateBaseListener implements ActionListener { public void processAction(ActionEvent ae) throws AbortProcessingException { FacesContext context = FacesContext.getCurrentInstance(); //Map reqMap = context.getExternalContext().getRequestMap(); //Map requestParams = context.getExternalContext().getRequestParameterMap(); //log.info("CONFIRM DELETE TEMPLATE LISTENER."); String templateId = (String) FacesContext.getCurrentInstance(). getExternalContext().getRequestParameterMap().get("templateId"); AssessmentService assessmentService = new AssessmentService(); AssessmentTemplateFacade template = assessmentService.getAssessmentTemplate(templateId); TemplateBean templateBean = lookupTemplateBean(context); String author = (String)template.getCreatedBy(); if (author == null || !author.equals(UserDirectoryService.getCurrentUser().getId())) { throw new AbortProcessingException("Attempted to delete template owned by another " + author + " " + UserDirectoryService.getCurrentUser().getId()); } templateBean.setIdString(templateId); templateBean.setTemplateName(template.getTitle()); } /** * Obtain the deleteId parameter. * @param requestParams params passed * @return true if we have no id parameter */ /* private String lookupKey(String key, Map requestParams) { Iterator iter = requestParams.keySet().iterator(); while (iter.hasNext()) { String currKey = (String) iter.next(); if (currKey.endsWith(key)) { return (String) requestParams.get(currKey); } } return null; } */ }
apache-2.0
snadakuduru/camel
components/camel-jetty8/src/main/java/org/apache/camel/component/jetty8/JettyHttpEndpoint8.java
1683
/** * 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.jetty8; import java.net.URI; import java.net.URISyntaxException; import org.apache.camel.component.jetty.JettyContentExchange; import org.apache.camel.component.jetty.JettyHttpComponent; import org.apache.camel.component.jetty.JettyHttpEndpoint; import org.apache.camel.http.common.HttpConsumer; import org.apache.camel.spi.UriEndpoint; @UriEndpoint(scheme = "jetty", extendsScheme = "http", title = "Jetty", syntax = "jetty:httpUri", consumerClass = HttpConsumer.class, label = "http") public class JettyHttpEndpoint8 extends JettyHttpEndpoint { public JettyHttpEndpoint8(JettyHttpComponent component, String uri, URI httpURL) throws URISyntaxException { super(component, uri, httpURL); } @Override public JettyContentExchange createContentExchange() { return new JettyContentExchange8(); } }
apache-2.0
KlaasDeNys/Arduino
app/src/cc/arduino/contributions/libraries/ui/LibraryManagerUI.java
9916
/* * This file is part of Arduino. * * Copyright 2015 Arduino LLC (http://www.arduino.cc/) * * Arduino is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. */ package cc.arduino.contributions.libraries.ui; import cc.arduino.contributions.DownloadableContribution; import cc.arduino.contributions.libraries.ContributedLibrary; import cc.arduino.contributions.libraries.LibrariesIndexer; import cc.arduino.contributions.libraries.LibraryInstaller; import cc.arduino.contributions.libraries.LibraryTypeComparator; import cc.arduino.contributions.ui.*; import cc.arduino.utils.Progress; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.function.Predicate; import static processing.app.I18n.tr; @SuppressWarnings("serial") public class LibraryManagerUI extends InstallerJDialog<ContributedLibrary> { private final JComboBox typeChooser; private final LibrariesIndexer indexer; private final LibraryInstaller installer; private Predicate<ContributedLibrary> typeFilter; @Override protected FilteredAbstractTableModel createContribModel() { return new LibrariesIndexTableModel(); } private LibrariesIndexTableModel getContribModel() { return (LibrariesIndexTableModel) contribModel; } @Override protected InstallerTableCell createCellRenderer() { return new ContributedLibraryTableCell(); } @Override protected InstallerTableCell createCellEditor() { return new ContributedLibraryTableCell() { @Override protected void onInstall(ContributedLibrary selectedLibrary, ContributedLibrary installedLibrary) { if (selectedLibrary.isReadOnly()) { onRemovePressed(installedLibrary); } else { onInstallPressed(selectedLibrary, installedLibrary); } } @Override protected void onRemove(ContributedLibrary library) { onRemovePressed(library); } }; } public LibraryManagerUI(Frame parent, LibrariesIndexer indexer, LibraryInstaller installer) { super(parent, tr("Library Manager"), Dialog.ModalityType.APPLICATION_MODAL, tr("Unable to reach Arduino.cc due to possible network issues.")); this.indexer = indexer; this.installer = installer; filtersContainer.add(new JLabel(tr("Topic")), 1); filtersContainer.remove(2); typeChooser = new JComboBox(); typeChooser.setMaximumRowCount(20); typeChooser.setEnabled(false); filtersContainer.add(Box.createHorizontalStrut(5), 0); filtersContainer.add(new JLabel(tr("Type")), 1); filtersContainer.add(Box.createHorizontalStrut(5), 2); filtersContainer.add(typeChooser, 3); } protected final ActionListener typeChooserActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { DropdownItem<ContributedLibrary> selected = (DropdownItem<ContributedLibrary>) typeChooser.getSelectedItem(); if (typeFilter == null || !typeFilter.equals(selected)) { typeFilter = selected.getFilterPredicate(); if (contribTable.getCellEditor() != null) { contribTable.getCellEditor().stopCellEditing(); } updateIndexFilter(filters, categoryFilter, typeFilter); } } }; @Override public void updateIndexFilter(String[] filters, Predicate<ContributedLibrary>... additionalFilters) { if (additionalFilters.length == 1) { additionalFilters = new Predicate[]{additionalFilters[0], typeFilter}; } super.updateIndexFilter(filters, additionalFilters); } public void updateUI() { DropdownItem<DownloadableContribution> previouslySelectedCategory = (DropdownItem<DownloadableContribution>) categoryChooser.getSelectedItem(); DropdownItem<DownloadableContribution> previouslySelectedType = (DropdownItem<DownloadableContribution>) typeChooser.getSelectedItem(); categoryChooser.removeActionListener(categoryChooserActionListener); typeChooser.removeActionListener(typeChooserActionListener); // TODO: Remove setIndexer and make getContribModel // return a FilteredAbstractTableModel getContribModel().setIndexer(indexer); categoryFilter = null; categoryChooser.removeAllItems(); // Load categories categoryChooser.addItem(new DropdownAllItem()); Collection<String> categories = indexer.getIndex().getCategories(); for (String category : categories) { categoryChooser.addItem(new DropdownLibraryOfCategoryItem(category)); } categoryChooser.setEnabled(categoryChooser.getItemCount() > 1); categoryChooser.addActionListener(categoryChooserActionListener); if (previouslySelectedCategory != null) { categoryChooser.setSelectedItem(previouslySelectedCategory); } else { categoryChooser.setSelectedIndex(0); } typeFilter = null; typeChooser.removeAllItems(); typeChooser.addItem(new DropdownAllItem()); typeChooser.addItem(new DropdownUpdatableLibrariesItem(indexer)); typeChooser.addItem(new DropdownInstalledLibraryItem(indexer.getIndex())); java.util.List<String> types = new LinkedList<>(indexer.getIndex().getTypes()); Collections.sort(types, new LibraryTypeComparator()); for (String type : types) { typeChooser.addItem(new DropdownLibraryOfTypeItem(type)); } typeChooser.setEnabled(typeChooser.getItemCount() > 1); typeChooser.addActionListener(typeChooserActionListener); if (previouslySelectedType != null) { typeChooser.setSelectedItem(previouslySelectedType); } else { typeChooser.setSelectedIndex(0); } filterField.setEnabled(contribModel.getRowCount() > 0); } public void selectDropdownItemByClassName(String dropdownItem) { selectDropdownItemByClassName(typeChooser, dropdownItem); } public void setProgress(Progress progress) { progressBar.setValue(progress); } private Thread installerThread = null; @Override protected void onCancelPressed() { super.onUpdatePressed(); if (installerThread != null) { installerThread.interrupt(); } } @Override protected void onUpdatePressed() { super.onUpdatePressed(); installerThread = new Thread(() -> { try { setProgressVisible(true, ""); installer.updateIndex(this::setProgress); onIndexesUpdated(); } catch (Exception e) { throw new RuntimeException(e); } finally { setProgressVisible(false, ""); } }); installerThread.setUncaughtExceptionHandler(new InstallerJDialogUncaughtExceptionHandler(this, noConnectionErrorMessage)); installerThread.start(); } public void onInstallPressed(final ContributedLibrary lib, final ContributedLibrary replaced) { clearErrorMessage(); installerThread = new Thread(() -> { try { setProgressVisible(true, tr("Installing...")); installer.install(lib, replaced, this::setProgress); onIndexesUpdated(); // TODO: Do a better job in refreshing only the needed element //getContribModel().updateLibrary(lib); } catch (Exception e) { throw new RuntimeException(e); } finally { setProgressVisible(false, ""); } }); installerThread.setUncaughtExceptionHandler(new InstallerJDialogUncaughtExceptionHandler(this, noConnectionErrorMessage)); installerThread.start(); } public void onRemovePressed(final ContributedLibrary lib) { boolean managedByIndex = indexer.getIndex().getLibraries().contains(lib); if (!managedByIndex) { int chosenOption = JOptionPane.showConfirmDialog(this, tr("This library is not listed on Library Manager. You won't be able to reinstall it from here.\nAre you sure you want to delete it?"), tr("Please confirm library deletion"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (chosenOption != JOptionPane.YES_OPTION) { return; } } clearErrorMessage(); installerThread = new Thread(() -> { try { setProgressVisible(true, tr("Removing...")); installer.remove(lib, this::setProgress); onIndexesUpdated(); // TODO: Do a better job in refreshing only the needed element //getContribModel().updateLibrary(lib); } catch (Exception e) { throw new RuntimeException(e); } finally { setProgressVisible(false, ""); } }); installerThread.setUncaughtExceptionHandler(new InstallerJDialogUncaughtExceptionHandler(this, noConnectionErrorMessage)); installerThread.start(); } protected void onIndexesUpdated() throws Exception { // Empty } }
lgpl-2.1
jstrachan/guicey
struts2/example/src/com/google/inject/struts2/example/ServiceImpl.java
161
package com.google.inject.struts2.example; public class ServiceImpl implements Service { public String getStatus() { return "We're looking good."; } }
apache-2.0
idea4bsd/idea4bsd
platform/core-api/src/com/intellij/pom/event/PomModelEvent.java
2607
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.pom.event; import com.intellij.pom.PomModel; import com.intellij.pom.PomModelAspect; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class PomModelEvent extends EventObject { private Map<PomModelAspect, PomChangeSet> myChangeSets; public PomModelEvent(PomModel source) { super(source); } @NotNull public Set<PomModelAspect> getChangedAspects() { if (myChangeSets != null) { return myChangeSets.keySet(); } else { return Collections.emptySet(); } } public void registerChangeSet(PomModelAspect aspect, PomChangeSet set) { if (myChangeSets == null) { myChangeSets = new HashMap<PomModelAspect, PomChangeSet>(); } if (set == null) { myChangeSets.remove(aspect); } else { myChangeSets.put(aspect, set); } } public <T extends PomChangeSet> T registerChangeSetIfAbsent(PomModelAspect aspect, @NotNull T set) { final PomChangeSet oldSet = getChangeSet(aspect); if (oldSet != null) return (T)oldSet; registerChangeSet(aspect, set); return set; } @Nullable public PomChangeSet getChangeSet(PomModelAspect aspect) { if (myChangeSets == null) return null; return myChangeSets.get(aspect); } public void merge(@NotNull PomModelEvent event) { if(event.myChangeSets == null) return; if(myChangeSets == null){ myChangeSets = new HashMap<PomModelAspect, PomChangeSet>(event.myChangeSets); return; } for (final Map.Entry<PomModelAspect, PomChangeSet> entry : event.myChangeSets.entrySet()) { final PomModelAspect aspect = entry.getKey(); final PomChangeSet pomChangeSet = myChangeSets.get(aspect); if (pomChangeSet != null) { pomChangeSet.merge(entry.getValue()); } else { myChangeSets.put(aspect, entry.getValue()); } } } @Override public PomModel getSource() { return (PomModel)super.getSource(); } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/corba/src/share/classes/com/sun/tools/corba/se/idl/PrimitiveEntry.java
2839
/* * Copyright (c) 1999, 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. */ /* * COMPONENT_NAME: idl.parser * * ORIGINS: 27 * * Licensed Materials - Property of IBM * 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999 * RMI-IIOP v1.0 * */ package com.sun.tools.corba.se.idl; // NOTES: import java.io.PrintWriter; import java.util.Hashtable; /** * This is the symbol table entry for primitive types: octet, char, * short, long, long long (and unsigned versions), float, double, string. **/ public class PrimitiveEntry extends SymtabEntry { protected PrimitiveEntry () { super (); repositoryID (Util.emptyID); } // ctor protected PrimitiveEntry (String name) { name (name); module (""); repositoryID (Util.emptyID); } // ctor protected PrimitiveEntry (PrimitiveEntry that) { super (that); } // ctor public Object clone () { return new PrimitiveEntry (this); } // clone /** Invoke the primitive type generator. @param symbolTable the symbol table is a hash table whose key is a fully qualified type name and whose value is a SymtabEntry or a subclass of SymtabEntry. @param stream the stream to which the generator should sent its output. @see SymtabEntry */ public void generate (Hashtable symbolTable, PrintWriter stream) { primitiveGen.generate (symbolTable, this, stream); } // generate /** Access the primitive type generator. @returns an object which implements the PrimitiveGen interface. @see PrimitiveGen */ public Generator generator () { return primitiveGen; } // generator static PrimitiveGen primitiveGen; } // class PrimitiveEntry
mit
jerome-jacob/selenium
java/client/src/com/thoughtworks/selenium/condition/ConditionRunner.java
3165
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.thoughtworks.selenium.condition; import com.thoughtworks.selenium.Selenium; /** * A ConditionRunner is a class that can execute a {@link Condition}, which need certain basic * pieces that it needs to execute (e.g. an instance of {@link Selenium}). This is achieved through * the {@link Context} interface. */ public interface ConditionRunner { /** * This method will, every so often, evaluate the given {@code condition}'s * {@link Condition#isTrue(ConditionRunner.Context)} method, until: * <p> * <ul> * <li>it becomes true, in which case it simply returns * <li>a certain amount of time is passed, in which case it fails by throwing an failure exception * tailored to a given test framework -- e.g. {@link junit.framework.AssertionFailedError} in the * case of JUnit * <li>it throws an exception, in which case that is wrapped inside a {@link RuntimeException} and * rethrown * </ul> * <p> * How often if "every so often" and how long is the "certain amount of time" is left to the * specific implementations of this interface. */ void waitFor(Condition condition); /** * As above but with an additional 'should' phrase narrative used in the event of the condition * failing to become true */ void waitFor(String narrative, Condition condition); /** * Used by implementations of {@link ConditionRunner#waitFor(Condition)} to provide context to the * {@link Condition isTrue(com.google.testing.selenium.condition.ConditionRunner.Context)} method */ public interface Context { /** * Returns the condition runner inside which this condition is being run. * <p> * This allows for a condition to chain to other conditions. */ ConditionRunner getConditionRunner(); /** * Returns the {@link Selenium} associated with this instance. This method will almost always be * called by any {@link Condition#isTrue(ConditionRunner.Context)}. */ Selenium getSelenium(); /** * A {@link Condition#isTrue(ConditionRunner.Context)} can call this method to set extra * information to be displayed upon a failure. */ void info(String string); /** * Returns the amount of time elapsed since the {@link #waitFor(Condition)} method for this * context was called. */ long elapsed(); } }
apache-2.0
qwerty4030/elasticsearch
server/src/main/java/org/elasticsearch/client/node/NodeClient.java
4981
/* * 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.client.node; import org.elasticsearch.action.Action; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.GenericAction; import org.elasticsearch.action.support.TransportAction; import org.elasticsearch.client.Client; import org.elasticsearch.client.support.AbstractClient; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.tasks.Task; import org.elasticsearch.tasks.TaskListener; import org.elasticsearch.threadpool.ThreadPool; import java.util.Map; import java.util.function.Supplier; /** * Client that executes actions on the local node. */ public class NodeClient extends AbstractClient { private Map<GenericAction, TransportAction> actions; /** * The id of the local {@link DiscoveryNode}. Useful for generating task ids from tasks returned by * {@link #executeLocally(GenericAction, ActionRequest, TaskListener)}. */ private Supplier<String> localNodeId; public NodeClient(Settings settings, ThreadPool threadPool) { super(settings, threadPool); } public void initialize(Map<GenericAction, TransportAction> actions, Supplier<String> localNodeId) { this.actions = actions; this.localNodeId = localNodeId; } @Override public void close() { // nothing really to do } @Override public < Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder> > void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) { // Discard the task because the Client interface doesn't use it. executeLocally(action, request, listener); } /** * Execute an {@link Action} locally, returning that {@link Task} used to track it, and linking an {@link ActionListener}. Prefer this * method if you don't need access to the task when listening for the response. This is the method used to implement the {@link Client} * interface. */ public < Request extends ActionRequest, Response extends ActionResponse > Task executeLocally(GenericAction<Request, Response> action, Request request, ActionListener<Response> listener) { return transportAction(action).execute(request, listener); } /** * Execute an {@link Action} locally, returning that {@link Task} used to track it, and linking an {@link TaskListener}. Prefer this * method if you need access to the task when listening for the response. */ public < Request extends ActionRequest, Response extends ActionResponse > Task executeLocally(GenericAction<Request, Response> action, Request request, TaskListener<Response> listener) { return transportAction(action).execute(request, listener); } /** * The id of the local {@link DiscoveryNode}. Useful for generating task ids from tasks returned by * {@link #executeLocally(GenericAction, ActionRequest, TaskListener)}. */ public String getLocalNodeId() { return localNodeId.get(); } /** * Get the {@link TransportAction} for an {@link Action}, throwing exceptions if the action isn't available. */ @SuppressWarnings("unchecked") private < Request extends ActionRequest, Response extends ActionResponse > TransportAction<Request, Response> transportAction(GenericAction<Request, Response> action) { if (actions == null) { throw new IllegalStateException("NodeClient has not been initialized"); } TransportAction<Request, Response> transportAction = actions.get(action); if (transportAction == null) { throw new IllegalStateException("failed to find action [" + action + "] to execute"); } return transportAction; } }
apache-2.0
coryb/SimianArmy
src/main/java/com/netflix/simianarmy/conformity/ConformityRuleEngine.java
2950
/* * * Copyright 2013 Netflix, 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.netflix.simianarmy.conformity; import com.google.common.collect.Lists; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; /** * The class implementing the conformity rule engine. */ public class ConformityRuleEngine { private static final Logger LOGGER = LoggerFactory.getLogger(ConformityRuleEngine.class); private final Collection<ConformityRule> rules = Lists.newArrayList(); /** * Checks whether a cluster is conforming or not against the rules in the engine. This * method runs the checks the cluster against all the rules. * * @param cluster * the cluster * @return true if the cluster is conforming, false otherwise. */ public boolean check(Cluster cluster) { Validate.notNull(cluster); cluster.clearConformities(); for (ConformityRule rule : rules) { if (!cluster.getExcludedRules().contains(rule.getName())) { LOGGER.info(String.format("Running conformity rule %s on cluster %s", rule.getName(), cluster.getName())); cluster.updateConformity(rule.check(cluster)); } else { LOGGER.info(String.format("Conformity rule %s is excluded on cluster %s", rule.getName(), cluster.getName())); } } boolean isConforming = true; for (Conformity conformity : cluster.getConformties()) { if (!conformity.getFailedComponents().isEmpty()) { isConforming = false; } } cluster.setConforming(isConforming); return isConforming; } /** * Add a conformity rule. * * @param rule * The conformity rule to add. * @return The Conformity rule engine object. */ public ConformityRuleEngine addRule(ConformityRule rule) { Validate.notNull(rule); rules.add(rule); return this; } /** * Gets all conformity rules in the rule engine. * @return all conformity rules in the rule engine */ public Collection<ConformityRule> rules() { return Collections.unmodifiableCollection(rules); } }
apache-2.0
dmiszkiewicz/elasticsearch
src/main/java/org/elasticsearch/index/mapper/MapperParsingException.java
1232
/* * 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.mapper; import org.elasticsearch.rest.RestStatus; /** * */ public class MapperParsingException extends MapperException { public MapperParsingException(String message) { super(message); } public MapperParsingException(String message, Throwable cause) { super(message, cause); } @Override public RestStatus status() { return RestStatus.BAD_REQUEST; } }
apache-2.0
YMartsynkevych/camel
camel-core/src/test/java/org/apache/camel/component/properties/PropertiesEnvironmentVariableOverrideTest.java
2567
/** * 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.properties; import org.apache.camel.CamelContext; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; /** * @version */ public class PropertiesEnvironmentVariableOverrideTest extends ContextTestSupport { @Override public boolean isUseRouteBuilder() { return false; } public void testPropertiesComponentCacheDisabled() throws Exception { PropertiesComponent pc = context.getComponent("properties", PropertiesComponent.class); pc.setCache(false); System.setProperty("cool.end", "mock:override"); System.setProperty("cool.result", "override"); context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("properties:cool.end"); from("direct:foo").to("properties:mock:{{cool.result}}"); } }); context.start(); getMockEndpoint("mock:override").expectedMessageCount(2); template.sendBody("direct:start", "Hello World"); template.sendBody("direct:foo", "Hello Foo"); System.clearProperty("cool.end"); System.clearProperty("cool.result"); assertMockEndpointsSatisfied(); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); PropertiesComponent pc = new PropertiesComponent(); pc.setCamelContext(context); pc.setLocations(new String[]{"classpath:org/apache/camel/component/properties/myproperties.properties"}); context.addComponent("properties", pc); return context; } }
apache-2.0
jianlinwei/connectbot
src/com/trilead/ssh2/crypto/dh/DhExchange.java
4200
/** * */ package com.trilead.ssh2.crypto.dh; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.KeyAgreement; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.DHPublicKeySpec; /** * @author kenny * */ public class DhExchange extends GenericDhExchange { /* Given by the standard */ private static final BigInteger P1 = new BigInteger( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381" + "FFFFFFFFFFFFFFFF", 16); private static final BigInteger P14 = new BigInteger( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AACAA68FFFFFFFFFFFFFFFF", 16); private static final BigInteger G = BigInteger.valueOf(2); /* Client public and private */ private DHPrivateKey clientPrivate; private DHPublicKey clientPublic; /* Server public */ private DHPublicKey serverPublic; @Override public void init(String name) throws IOException { final DHParameterSpec spec; if ("diffie-hellman-group1-sha1".equals(name)) { spec = new DHParameterSpec(P1, G); } else if ("diffie-hellman-group14-sha1".equals(name)) { spec = new DHParameterSpec(P14, G); } else { throw new IllegalArgumentException("Unknown DH group " + name); } try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH"); kpg.initialize(spec); KeyPair pair = kpg.generateKeyPair(); clientPrivate = (DHPrivateKey) pair.getPrivate(); clientPublic = (DHPublicKey) pair.getPublic(); } catch (NoSuchAlgorithmException e) { throw (IOException) new IOException("No DH keypair generator").initCause(e); } catch (InvalidAlgorithmParameterException e) { throw (IOException) new IOException("Invalid DH parameters").initCause(e); } } @Override public byte[] getE() { if (clientPublic == null) throw new IllegalStateException("DhExchange not initialized!"); return clientPublic.getY().toByteArray(); } @Override protected byte[] getServerE() { if (serverPublic == null) throw new IllegalStateException("DhExchange not initialized!"); return serverPublic.getY().toByteArray(); } @Override public void setF(byte[] f) throws IOException { if (clientPublic == null) throw new IllegalStateException("DhExchange not initialized!"); final KeyAgreement ka; try { KeyFactory kf = KeyFactory.getInstance("DH"); DHParameterSpec params = clientPublic.getParams(); this.serverPublic = (DHPublicKey) kf.generatePublic(new DHPublicKeySpec( new BigInteger(f), params.getP(), params.getG())); ka = KeyAgreement.getInstance("DH"); ka.init(clientPrivate); ka.doPhase(serverPublic, true); } catch (NoSuchAlgorithmException e) { throw (IOException) new IOException("No DH key agreement method").initCause(e); } catch (InvalidKeyException e) { throw (IOException) new IOException("Invalid DH key").initCause(e); } catch (InvalidKeySpecException e) { throw (IOException) new IOException("Invalid DH key").initCause(e); } sharedSecret = new BigInteger(ka.generateSecret()); } @Override public String getHashAlgo() { return "SHA1"; } }
apache-2.0
nulakasatish/guava-libraries
guava/src/com/google/common/collect/EvictingQueue.java
3817
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.io.Serializable; import java.util.ArrayDeque; import java.util.Collection; import java.util.Queue; /** * A non-blocking queue which automatically evicts elements from the head of the queue when * attempting to add new elements onto the queue and it is full. * * <p>An evicting queue must be configured with a maximum size. Each time an element is added * to a full queue, the queue automatically removes its head element. This is different from * conventional bounded queues, which either block or reject new elements when full. * * <p>This class is not thread-safe, and does not accept null elements. * * @author Kurt Alfred Kluever * @since 15.0 */ @Beta @GwtIncompatible("java.util.ArrayDeque") public final class EvictingQueue<E> extends ForwardingQueue<E> implements Serializable { private final Queue<E> delegate; @VisibleForTesting final int maxSize; private EvictingQueue(int maxSize) { checkArgument(maxSize >= 0, "maxSize (%s) must >= 0", maxSize); this.delegate = new ArrayDeque<E>(maxSize); this.maxSize = maxSize; } /** * Creates and returns a new evicting queue that will hold up to {@code maxSize} elements. * * <p>When {@code maxSize} is zero, elements will be evicted immediately after being added to the * queue. */ public static <E> EvictingQueue<E> create(int maxSize) { return new EvictingQueue<E>(maxSize); } /** * Returns the number of additional elements that this queue can accept without evicting; * zero if the queue is currently full. * * @since 16.0 */ public int remainingCapacity() { return maxSize - size(); } @Override protected Queue<E> delegate() { return delegate; } /** * Adds the given element to this queue. If the queue is currently full, the element at the head * of the queue is evicted to make room. * * @return {@code true} always */ @Override public boolean offer(E e) { return add(e); } /** * Adds the given element to this queue. If the queue is currently full, the element at the head * of the queue is evicted to make room. * * @return {@code true} always */ @Override public boolean add(E e) { checkNotNull(e); // check before removing if (maxSize == 0) { return true; } if (size() == maxSize) { delegate.remove(); } delegate.add(e); return true; } @Override public boolean addAll(Collection<? extends E> collection) { return standardAddAll(collection); } @Override public boolean contains(Object object) { return delegate().contains(checkNotNull(object)); } @Override public boolean remove(Object object) { return delegate().remove(checkNotNull(object)); } // TODO(user): Do we want to checkNotNull each element in containsAll, removeAll, and retainAll? private static final long serialVersionUID = 0L; }
apache-2.0
ivan-fedorov/intellij-community
plugins/InspectionGadgets/test/com/siyeh/igtest/style/unqualified_inner_class_access/Test.java
573
package com.siyeh.igtest.style.unqualified_inner_class_access; import java.util.Map.Entry; import com.siyeh.igtest.style.unqualified_inner_class_access.A.X; public class Test<T> { private Class<Entry> entryClass; public Test() { Entry entry; entryClass = Entry.class; } public Test(int i) { final String test = Inner.TEST; } static class Inner { public static final String TEST = "test"; } } class A { class X {} } class B extends A { void foo(X x) {} } class C { void m(X x) { new A().new X(); } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/demo/jfc/TableExample/TableExample2.java
4139
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. 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 Oracle 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. */ /* * This source code is provided to illustrate the usage of a given feature * or technique and has been deliberately simplified. Additional steps * required for a production-quality application, such as security checks, * input validation and proper error handling, might not be present in * this sample code. */ import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.Dimension; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; /** * A minimal example, using the JTable to view data from a database. * * @author Philip Milne */ public class TableExample2 { public TableExample2(String URL, String driver, String user, String passwd, String query) { JFrame frame = new JFrame("Table"); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); JDBCAdapter dt = new JDBCAdapter(URL, driver, user, passwd); dt.executeQuery(query); // Create the table JTable tableView = new JTable(dt); JScrollPane scrollpane = new JScrollPane(tableView); scrollpane.setPreferredSize(new Dimension(700, 300)); frame.getContentPane().add(scrollpane); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { if (args.length != 5) { System.err.println("Needs database parameters eg. ..."); System.err.println( "java TableExample2 \"jdbc:derby://localhost:1527/sample\" " + "org.apache.derby.jdbc.ClientDriver app app " + "\"select * from app.customer\""); return; } // Trying to set Nimbus look and feel try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception ex) { Logger.getLogger(TableExample2.class.getName()).log(Level.SEVERE, "Failed to apply Nimbus look and feel", ex); } new TableExample2(args[0], args[1], args[2], args[3], args[4]); } }
mit
guiquanz/binnavi
src/main/java/com/google/security/zynamics/binnavi/Gui/FunctionSelection/CModuleNode.java
4868
/* Copyright 2015 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.security.zynamics.binnavi.Gui.FunctionSelection; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.tree.DefaultTreeModel; import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.CMain; import com.google.security.zynamics.binnavi.disassembly.INaviFunction; import com.google.security.zynamics.binnavi.disassembly.INaviModule; import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleListenerAdapter; import com.google.security.zynamics.binnavi.disassembly.Modules.IModuleListener; import com.google.security.zynamics.binnavi.disassembly.views.INaviView; import com.google.security.zynamics.zylib.disassembly.FunctionType; import com.google.security.zynamics.zylib.gui.jtree.IconNode; /** * Module node class for the function selection dialog. */ public final class CModuleNode extends IconNode implements IFunctionTreeNode { /** * Used for serialization. */ private static final long serialVersionUID = -7938396730896978085L; /** * Icon used for loaded modules. */ private static final ImageIcon ICON_MODULE = new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module.png")); /** * Icon used for grayed modules. */ private static final ImageIcon ICON_MODULE_GRAY = new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_gray.png")); /** * The module represented by the node. */ private final INaviModule m_module; /** * The tree model of the function selection tree. */ private final DefaultTreeModel m_model; /** * Provides the implementations of the available actions. */ private final IActionProvider m_actionProvider; /** * Updates the module node when the module changes in some relevant way. */ private final IModuleListener m_internalModuleListener = new InternalModuleListener(); /** * Creates a new module node object. * * @param module The module represented by the node. * @param model The tree model of the function selection tree. * @param actionProvider Provides the implementations of the available actions. */ public CModuleNode(final INaviModule module, final DefaultTreeModel model, final IActionProvider actionProvider) { Preconditions.checkNotNull(module, "IE01577: Module argument can not be null"); Preconditions.checkNotNull(model, "IE01578: Model argument can not be null"); Preconditions.checkNotNull(actionProvider, "IE01579: Action provider argument can not be null"); m_module = module; m_model = model; m_actionProvider = actionProvider; m_module.addListener(m_internalModuleListener); createChildren(); } /** * Creates one child node for each function of a module except for imported functions. */ private void createChildren() { if (m_module.isLoaded()) { for (final INaviFunction function : m_module.getContent().getFunctionContainer().getFunctions()) { if (function.getType() != FunctionType.IMPORT) { add(new CFunctionIconNode(function)); } } } } @Override public void doubleClicked() { // Load modules on double-click if (!m_module.isLoaded()) { m_actionProvider.loadModule(m_module); } } @Override public Icon getIcon() { return m_module.isLoaded() ? ICON_MODULE : ICON_MODULE_GRAY; } @Override public String toString() { return String.format("%s (%d/%d)", m_module.getConfiguration().getName(), m_module.getFunctionCount(), m_module.getCustomViewCount()); } /** * Updates the module node when the module changes in some relevant way. */ private class InternalModuleListener extends CModuleListenerAdapter { @Override public void addedView(final INaviModule module, final INaviView view) { m_model.nodeChanged(CModuleNode.this); } @Override public void changedName(final INaviModule module, final String name) { m_model.nodeChanged(CModuleNode.this); } /** * When the module is loaded, create the child nodes. */ @Override public void loadedModule(final INaviModule module) { createChildren(); m_model.nodeStructureChanged(CModuleNode.this); } } }
apache-2.0
flasheryu/RedisTest
src/main/java/redis/clients/jedis/BitOP.java
73
package redis.clients.jedis; public enum BitOP { AND, OR, XOR, NOT; }
mit
android-ia/platform_tools_idea
java/java-tests/testData/codeInsight/completion/smartType/BreakLabel.java
108
public class Util { void foo(int labInt) { label: while (true) { break l<caret> } } }
apache-2.0
asedunov/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/overloadResolution/IgnoreNonFunctionalArgumentsWhenCheckIfFunctionalMoreSpecific.java
478
import java.util.List; import java.util.function.Function; class Test { { transform(1, (String l) -> null); } public static <I, O> void transform(int input, Function<I, O> function) { System.out.println(input); System.out.println(function); } interface IFunction<F, T> { List<T> apply(F var1); } public static <I, O> void transform(int input, IFunction<I, O> function) { System.out.println(input); System.out.println(function); } }
apache-2.0
vaibhavbhatnagar/CrossoverProb
src/uk/co/jemos/podam/test/unit/features/dataProviderStrategy/RandomDataProviderStrategyImplInitialisationUnitTest.java
6981
/** * */ package uk.co.jemos.podam.test.unit.features.dataProviderStrategy; import net.serenitybdd.junit.runners.SerenityRunner; import net.thucydides.core.annotations.Title; import org.junit.Test; import org.junit.runner.RunWith; import uk.co.jemos.podam.api.AbstractRandomDataProviderStrategy; import uk.co.jemos.podam.api.DataProviderStrategy; import uk.co.jemos.podam.api.PodamFactory; import uk.co.jemos.podam.api.RandomDataProviderStrategyImpl; import uk.co.jemos.podam.common.AbstractConstructorComparator; import uk.co.jemos.podam.common.AbstractMethodComparator; import uk.co.jemos.podam.common.PodamConstants; import uk.co.jemos.podam.test.dto.PojoWithMapsAndCollections; import uk.co.jemos.podam.test.unit.AbstractPodamSteps; import java.util.HashMap; import java.util.Map; /** * It checks that the {@link RandomDataProviderStrategyImpl} is initialised properly * * @author Marco Tedone * */ @RunWith(SerenityRunner.class) public class RandomDataProviderStrategyImplInitialisationUnitTest extends AbstractPodamSteps { @Test @Title("The Random Data Provider Strategy should be initialised correctly and allow for changes in " + "the number of collection elements") public void randomDataProviderStrategyShouldBeInitialisedCorrectlyAndAllowForChangesInNbrOfCollectionElements() { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); podamValidationSteps.theTwoObjectsShouldBeEqual(PodamConstants.DEFAULT_NBR_COLLECTION_ELEMENTS, dataProviderStrategy.getNumberOfCollectionElements(Object.class)); int aNumberOfCollectionElements = 3; dataProviderStrategy.setDefaultNumberOfCollectionElements(aNumberOfCollectionElements); podamValidationSteps.theTwoObjectsShouldBeEqual(aNumberOfCollectionElements, dataProviderStrategy.getNumberOfCollectionElements(Object.class)); } @Test @Title("Podam should create POJOs in accordance with custom data provider strategies") public void podamShouldCreatePojosInAccordanceWithCustomDataProviderStrategies() throws Exception { DataProviderStrategy strategy = podamFactorySteps.givenACustomRandomDataProviderStrategy(); PodamFactory podamFactory = podamFactorySteps.givenAPodamFactoryWithCustomDataProviderStrategy(strategy); PojoWithMapsAndCollections pojo = podamInvocationSteps.whenIInvokeTheFactoryForClass(PojoWithMapsAndCollections.class, podamFactory); podamValidationSteps.theObjectShouldNotBeNull(pojo); podamValidationSteps.theArrayOfTheGivenTypeShouldNotBeNullOrEmptyAndContainExactlyTheGivenNumberOfElements( pojo.getArray(), 2); podamValidationSteps.theCollectionShouldNotBeNullOrEmpty(pojo.getList()); podamValidationSteps.theCollectionShouldHaveExactlyTheExpectedNumberOfElements(pojo.getList(), 3); podamValidationSteps.theMapShouldNotBeNullOrEmpty(pojo.getMap()); podamValidationSteps.theMapShouldHaveExactlyTheExpectedNumberOfElements(pojo.getMap(), 4); } @Test @Title("Podam should correctly generate HashMaps with Long as key type") public void podamShouldCorrectGenerateHashMapsWithLongAsKeyType() throws Exception { DataProviderStrategy strategy = podamFactorySteps.givenACustomRandomDataProviderStrategy(); PodamFactory podamFactory = podamFactorySteps.givenAPodamFactoryWithCustomDataProviderStrategy(strategy); Map<?, ?> pojo = podamInvocationSteps.whenIInvokeTheFactoryForGenericTypeWithSpecificType( HashMap.class, podamFactory, Long.class, String.class); podamValidationSteps.theObjectShouldNotBeNull(pojo); podamValidationSteps.theTwoObjectsShouldBeEqual(strategy.getNumberOfCollectionElements( String.class), pojo.size()); } @Test @Title("Creating a Random Data Provider Strategy should create a constructor light comparator") public void creatingARandomDataProviderStrategyShouldCreateAConstructorLightComparator() throws Exception { AbstractRandomDataProviderStrategy randomStrategy = (AbstractRandomDataProviderStrategy) podamFactorySteps.givenARandomDataProviderStrategy(); AbstractConstructorComparator comparator = randomStrategy.getConstructorLightComparator(); podamValidationSteps.theObjectShouldNotBeNull(comparator); randomStrategy.setConstructorLightComparator(null); podamValidationSteps.theTwoObjectsShouldBeEqual(null, randomStrategy.getConstructorLightComparator()); randomStrategy.setConstructorLightComparator(comparator); podamValidationSteps.theTwoObjectsShouldBeEqual(comparator, randomStrategy.getConstructorLightComparator()); } @Test @Title("Creating a Random Data Provider Strategy should create a constructor heavy comparator") public void creatingARandomDataProviderStrategyShouldCreateAConstructorHeavyComparator() throws Exception { AbstractRandomDataProviderStrategy randomStrategy = (AbstractRandomDataProviderStrategy) podamFactorySteps.givenARandomDataProviderStrategy(); AbstractConstructorComparator comparator = randomStrategy.getConstructorHeavyComparator(); podamValidationSteps.theObjectShouldNotBeNull(comparator); randomStrategy.setConstructorHeavyComparator(null); podamValidationSteps.theTwoObjectsShouldBeEqual(null, randomStrategy.getConstructorHeavyComparator()); randomStrategy.setConstructorHeavyComparator(comparator); podamValidationSteps.theTwoObjectsShouldBeEqual(comparator, randomStrategy.getConstructorHeavyComparator()); } @Test @Title("Creating a Random Data Provider Strategy should create a Method light comparator") public void creatingARandomDataProviderStrategyShouldCreateAMethodLightComparator() throws Exception { AbstractRandomDataProviderStrategy randomStrategy = (AbstractRandomDataProviderStrategy) podamFactorySteps.givenARandomDataProviderStrategy(); AbstractMethodComparator comparator = randomStrategy.getMethodLightComparator(); podamValidationSteps.theObjectShouldNotBeNull(comparator); randomStrategy.setMethodLightComparator(null); podamValidationSteps.theTwoObjectsShouldBeEqual(null, randomStrategy.getMethodLightComparator()); randomStrategy.setMethodLightComparator(comparator); podamValidationSteps.theTwoObjectsShouldBeEqual(comparator, randomStrategy.getMethodLightComparator()); } @Test @Title("Creating a Random Data Provider Strategy should create a Method heavy comparator") public void creatingARandomDataProviderStrategyShouldCreateAMethodHeavyComparator() throws Exception { AbstractRandomDataProviderStrategy randomStrategy = (AbstractRandomDataProviderStrategy) podamFactorySteps.givenARandomDataProviderStrategy(); AbstractMethodComparator comparator = randomStrategy.getMethodHeavyComparator(); podamValidationSteps.theObjectShouldNotBeNull(comparator); randomStrategy.setMethodHeavyComparator(null); podamValidationSteps.theTwoObjectsShouldBeEqual(null, randomStrategy.getMethodHeavyComparator()); randomStrategy.setMethodHeavyComparator(comparator); podamValidationSteps.theTwoObjectsShouldBeEqual(comparator, randomStrategy.getMethodHeavyComparator()); } }
mit
cnfire/hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/conf/TestReconfiguration.java
15413
/** * 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.conf; import com.google.common.base.Optional; import com.google.common.collect.Lists; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.util.Time; import org.apache.hadoop.conf.ReconfigurationUtil.PropertyChange; import org.junit.Test; import org.junit.Before; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import java.io.IOException; import java.util.Collection; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; public class TestReconfiguration { private Configuration conf1; private Configuration conf2; private static final String PROP1 = "test.prop.one"; private static final String PROP2 = "test.prop.two"; private static final String PROP3 = "test.prop.three"; private static final String PROP4 = "test.prop.four"; private static final String PROP5 = "test.prop.five"; private static final String VAL1 = "val1"; private static final String VAL2 = "val2"; @Before public void setUp () { conf1 = new Configuration(); conf2 = new Configuration(); // set some test properties conf1.set(PROP1, VAL1); conf1.set(PROP2, VAL1); conf1.set(PROP3, VAL1); conf2.set(PROP1, VAL1); // same as conf1 conf2.set(PROP2, VAL2); // different value as conf1 // PROP3 not set in conf2 conf2.set(PROP4, VAL1); // not set in conf1 } /** * Test ReconfigurationUtil.getChangedProperties. */ @Test public void testGetChangedProperties() { Collection<ReconfigurationUtil.PropertyChange> changes = ReconfigurationUtil.getChangedProperties(conf2, conf1); assertTrue("expected 3 changed properties but got " + changes.size(), changes.size() == 3); boolean changeFound = false; boolean unsetFound = false; boolean setFound = false; for (ReconfigurationUtil.PropertyChange c: changes) { if (c.prop.equals(PROP2) && c.oldVal != null && c.oldVal.equals(VAL1) && c.newVal != null && c.newVal.equals(VAL2)) { changeFound = true; } else if (c.prop.equals(PROP3) && c.oldVal != null && c.oldVal.equals(VAL1) && c.newVal == null) { unsetFound = true; } else if (c.prop.equals(PROP4) && c.oldVal == null && c.newVal != null && c.newVal.equals(VAL1)) { setFound = true; } } assertTrue("not all changes have been applied", changeFound && unsetFound && setFound); } /** * a simple reconfigurable class */ public static class ReconfigurableDummy extends ReconfigurableBase implements Runnable { public volatile boolean running = true; public ReconfigurableDummy(Configuration conf) { super(conf); } @Override protected Configuration getNewConf() { return new Configuration(); } @Override public Collection<String> getReconfigurableProperties() { return Arrays.asList(PROP1, PROP2, PROP4); } @Override public synchronized void reconfigurePropertyImpl( String property, String newVal) throws ReconfigurationException { // do nothing } /** * Run until PROP1 is no longer VAL1. */ @Override public void run() { while (running && getConf().get(PROP1).equals(VAL1)) { try { Thread.sleep(1); } catch (InterruptedException ignore) { // do nothing } } } } /** * Test reconfiguring a Reconfigurable. */ @Test public void testReconfigure() { ReconfigurableDummy dummy = new ReconfigurableDummy(conf1); assertTrue(PROP1 + " set to wrong value ", dummy.getConf().get(PROP1).equals(VAL1)); assertTrue(PROP2 + " set to wrong value ", dummy.getConf().get(PROP2).equals(VAL1)); assertTrue(PROP3 + " set to wrong value ", dummy.getConf().get(PROP3).equals(VAL1)); assertTrue(PROP4 + " set to wrong value ", dummy.getConf().get(PROP4) == null); assertTrue(PROP5 + " set to wrong value ", dummy.getConf().get(PROP5) == null); assertTrue(PROP1 + " should be reconfigurable ", dummy.isPropertyReconfigurable(PROP1)); assertTrue(PROP2 + " should be reconfigurable ", dummy.isPropertyReconfigurable(PROP2)); assertFalse(PROP3 + " should not be reconfigurable ", dummy.isPropertyReconfigurable(PROP3)); assertTrue(PROP4 + " should be reconfigurable ", dummy.isPropertyReconfigurable(PROP4)); assertFalse(PROP5 + " should not be reconfigurable ", dummy.isPropertyReconfigurable(PROP5)); // change something to the same value as before { boolean exceptionCaught = false; try { dummy.reconfigureProperty(PROP1, VAL1); assertTrue(PROP1 + " set to wrong value ", dummy.getConf().get(PROP1).equals(VAL1)); } catch (ReconfigurationException e) { exceptionCaught = true; } assertFalse("received unexpected exception", exceptionCaught); } // change something to null { boolean exceptionCaught = false; try { dummy.reconfigureProperty(PROP1, null); assertTrue(PROP1 + "set to wrong value ", dummy.getConf().get(PROP1) == null); } catch (ReconfigurationException e) { exceptionCaught = true; } assertFalse("received unexpected exception", exceptionCaught); } // change something to a different value than before { boolean exceptionCaught = false; try { dummy.reconfigureProperty(PROP1, VAL2); assertTrue(PROP1 + "set to wrong value ", dummy.getConf().get(PROP1).equals(VAL2)); } catch (ReconfigurationException e) { exceptionCaught = true; } assertFalse("received unexpected exception", exceptionCaught); } // set unset property to null { boolean exceptionCaught = false; try { dummy.reconfigureProperty(PROP4, null); assertTrue(PROP4 + "set to wrong value ", dummy.getConf().get(PROP4) == null); } catch (ReconfigurationException e) { exceptionCaught = true; } assertFalse("received unexpected exception", exceptionCaught); } // set unset property { boolean exceptionCaught = false; try { dummy.reconfigureProperty(PROP4, VAL1); assertTrue(PROP4 + "set to wrong value ", dummy.getConf().get(PROP4).equals(VAL1)); } catch (ReconfigurationException e) { exceptionCaught = true; } assertFalse("received unexpected exception", exceptionCaught); } // try to set unset property to null (not reconfigurable) { boolean exceptionCaught = false; try { dummy.reconfigureProperty(PROP5, null); } catch (ReconfigurationException e) { exceptionCaught = true; } assertTrue("did not receive expected exception", exceptionCaught); } // try to set unset property to value (not reconfigurable) { boolean exceptionCaught = false; try { dummy.reconfigureProperty(PROP5, VAL1); } catch (ReconfigurationException e) { exceptionCaught = true; } assertTrue("did not receive expected exception", exceptionCaught); } // try to change property to value (not reconfigurable) { boolean exceptionCaught = false; try { dummy.reconfigureProperty(PROP3, VAL2); } catch (ReconfigurationException e) { exceptionCaught = true; } assertTrue("did not receive expected exception", exceptionCaught); } // try to change property to null (not reconfigurable) { boolean exceptionCaught = false; try { dummy.reconfigureProperty(PROP3, null); } catch (ReconfigurationException e) { exceptionCaught = true; } assertTrue("did not receive expected exception", exceptionCaught); } } /** * Test whether configuration changes are visible in another thread. */ @Test public void testThread() throws ReconfigurationException { ReconfigurableDummy dummy = new ReconfigurableDummy(conf1); assertTrue(dummy.getConf().get(PROP1).equals(VAL1)); Thread dummyThread = new Thread(dummy); dummyThread.start(); try { Thread.sleep(500); } catch (InterruptedException ignore) { // do nothing } dummy.reconfigureProperty(PROP1, VAL2); long endWait = Time.now() + 2000; while (dummyThread.isAlive() && Time.now() < endWait) { try { Thread.sleep(50); } catch (InterruptedException ignore) { // do nothing } } assertFalse("dummy thread should not be alive", dummyThread.isAlive()); dummy.running = false; try { dummyThread.join(); } catch (InterruptedException ignore) { // do nothing } assertTrue(PROP1 + " is set to wrong value", dummy.getConf().get(PROP1).equals(VAL2)); } private static class AsyncReconfigurableDummy extends ReconfigurableBase { AsyncReconfigurableDummy(Configuration conf) { super(conf); } @Override protected Configuration getNewConf() { return new Configuration(); } final CountDownLatch latch = new CountDownLatch(1); @Override public Collection<String> getReconfigurableProperties() { return Arrays.asList(PROP1, PROP2, PROP4); } @Override public synchronized void reconfigurePropertyImpl(String property, String newVal) throws ReconfigurationException { try { latch.await(); } catch (InterruptedException e) { // Ignore } } } private static void waitAsyncReconfigureTaskFinish(ReconfigurableBase rb) throws InterruptedException { ReconfigurationTaskStatus status = null; int count = 20; while (count > 0) { status = rb.getReconfigurationTaskStatus(); if (status.stopped()) { break; } count--; Thread.sleep(500); } assert(status.stopped()); } @Test public void testAsyncReconfigure() throws ReconfigurationException, IOException, InterruptedException { AsyncReconfigurableDummy dummy = spy(new AsyncReconfigurableDummy(conf1)); List<PropertyChange> changes = Lists.newArrayList(); changes.add(new PropertyChange("name1", "new1", "old1")); changes.add(new PropertyChange("name2", "new2", "old2")); changes.add(new PropertyChange("name3", "new3", "old3")); doReturn(changes).when(dummy).getChangedProperties( any(Configuration.class), any(Configuration.class)); doReturn(true).when(dummy).isPropertyReconfigurable(eq("name1")); doReturn(false).when(dummy).isPropertyReconfigurable(eq("name2")); doReturn(true).when(dummy).isPropertyReconfigurable(eq("name3")); doNothing().when(dummy) .reconfigurePropertyImpl(eq("name1"), anyString()); doNothing().when(dummy) .reconfigurePropertyImpl(eq("name2"), anyString()); doThrow(new ReconfigurationException("NAME3", "NEW3", "OLD3", new IOException("io exception"))) .when(dummy).reconfigurePropertyImpl(eq("name3"), anyString()); dummy.startReconfigurationTask(); waitAsyncReconfigureTaskFinish(dummy); ReconfigurationTaskStatus status = dummy.getReconfigurationTaskStatus(); assertEquals(2, status.getStatus().size()); for (Map.Entry<PropertyChange, Optional<String>> result : status.getStatus().entrySet()) { PropertyChange change = result.getKey(); if (change.prop.equals("name1")) { assertFalse(result.getValue().isPresent()); } else if (change.prop.equals("name2")) { assertThat(result.getValue().get(), containsString("Property name2 is not reconfigurable")); } else if (change.prop.equals("name3")) { assertThat(result.getValue().get(), containsString("io exception")); } else { fail("Unknown property: " + change.prop); } } } @Test(timeout=30000) public void testStartReconfigurationFailureDueToExistingRunningTask() throws InterruptedException, IOException { AsyncReconfigurableDummy dummy = spy(new AsyncReconfigurableDummy(conf1)); List<PropertyChange> changes = Lists.newArrayList( new PropertyChange(PROP1, "new1", "old1") ); doReturn(changes).when(dummy).getChangedProperties( any(Configuration.class), any(Configuration.class)); ReconfigurationTaskStatus status = dummy.getReconfigurationTaskStatus(); assertFalse(status.hasTask()); dummy.startReconfigurationTask(); status = dummy.getReconfigurationTaskStatus(); assertTrue(status.hasTask()); assertFalse(status.stopped()); // An active reconfiguration task is running. try { dummy.startReconfigurationTask(); fail("Expect to throw IOException."); } catch (IOException e) { GenericTestUtils.assertExceptionContains( "Another reconfiguration task is running", e); } status = dummy.getReconfigurationTaskStatus(); assertTrue(status.hasTask()); assertFalse(status.stopped()); dummy.latch.countDown(); waitAsyncReconfigureTaskFinish(dummy); status = dummy.getReconfigurationTaskStatus(); assertTrue(status.hasTask()); assertTrue(status.stopped()); // The first task has finished. dummy.startReconfigurationTask(); waitAsyncReconfigureTaskFinish(dummy); ReconfigurationTaskStatus status2 = dummy.getReconfigurationTaskStatus(); assertTrue(status2.getStartTime() >= status.getEndTime()); dummy.shutdownReconfigurationTask(); try { dummy.startReconfigurationTask(); fail("Expect to throw IOException"); } catch (IOException e) { GenericTestUtils.assertExceptionContains("The server is stopped", e); } } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/langtools/test/tools/javac/6835430/A.java
1204
/* * Copyright (c) 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. * * 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. */ class A<T extends A<T>> { class C { public T getT() { return null; } } } class B extends A<B> { public class D extends A<B>.C {} }
mit
jwren/intellij-community
plugins/rareJavaRefactorings/testData/wrapReturnValue/strip/before/Test.java
119
class Test { String foo() { return new Wrapper("").getMyField(); } void bar() { String s = foo(); } }
apache-2.0
smmribeiro/intellij-community
plugins/InspectionGadgets/test/com/siyeh/igtest/threading/WaitNotInLoopInspection.java
254
package com.siyeh.igtest.threading; public class WaitNotInLoopInspection { private Object lock; public void foo() { try { lock.wait(); } catch(InterruptedException e) { } } }
apache-2.0
daedric/buck
third-party/java/dx/src/com/android/dx/dex/code/form/Form23x.java
2994
/* * Copyright (C) 2007 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.android.dx.dex.code.form; import com.android.dx.dex.code.DalvInsn; import com.android.dx.dex.code.InsnFormat; import com.android.dx.dex.code.SimpleInsn; import com.android.dx.rop.code.RegisterSpecList; import com.android.dx.util.AnnotatedOutput; import java.util.BitSet; /** * Instruction format {@code 23x}. See the instruction format spec * for details. */ public final class Form23x extends InsnFormat { /** {@code non-null;} unique instance of this class */ public static final InsnFormat THE_ONE = new Form23x(); /** * Constructs an instance. This class is not publicly * instantiable. Use {@link #THE_ONE}. */ private Form23x() { // This space intentionally left blank. } /** {@inheritDoc} */ @Override public String insnArgString(DalvInsn insn) { RegisterSpecList regs = insn.getRegisters(); return regs.get(0).regString() + ", " + regs.get(1).regString() + ", " + regs.get(2).regString(); } /** {@inheritDoc} */ @Override public String insnCommentString(DalvInsn insn, boolean noteIndices) { // This format has no comment. return ""; } /** {@inheritDoc} */ @Override public int codeSize() { return 2; } /** {@inheritDoc} */ @Override public boolean isCompatible(DalvInsn insn) { RegisterSpecList regs = insn.getRegisters(); return (insn instanceof SimpleInsn) && (regs.size() == 3) && unsignedFitsInByte(regs.get(0).getReg()) && unsignedFitsInByte(regs.get(1).getReg()) && unsignedFitsInByte(regs.get(2).getReg()); } /** {@inheritDoc} */ @Override public BitSet compatibleRegs(DalvInsn insn) { RegisterSpecList regs = insn.getRegisters(); BitSet bits = new BitSet(3); bits.set(0, unsignedFitsInByte(regs.get(0).getReg())); bits.set(1, unsignedFitsInByte(regs.get(1).getReg())); bits.set(2, unsignedFitsInByte(regs.get(2).getReg())); return bits; } /** {@inheritDoc} */ @Override public void writeTo(AnnotatedOutput out, DalvInsn insn) { RegisterSpecList regs = insn.getRegisters(); write(out, opcodeUnit(insn, regs.get(0).getReg()), codeUnit(regs.get(1).getReg(), regs.get(2).getReg())); } }
apache-2.0
unix1986/universe
tool/kafka-0.8.1.1-src/clients/src/main/java/org/apache/kafka/common/utils/Time.java
1249
/** * 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.kafka.common.utils; /** * An interface abstracting the clock to use in unit testing classes that make use of clock time */ public interface Time { /** * The current time in milliseconds */ public long milliseconds(); /** * The current time in nanoseconds */ public long nanoseconds(); /** * Sleep for the given number of milliseconds */ public void sleep(long ms); }
bsd-2-clause
ZhangXFeng/hadoop
src/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/NetworkTopologyWithNodeGroup.java
11591
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.net; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; /** * The class extends NetworkTopology to represents a cluster of computer with * a 4-layers hierarchical network topology. * In this network topology, leaves represent data nodes (computers) and inner * nodes represent switches/routers that manage traffic in/out of data centers, * racks or physical host (with virtual switch). * * @see NetworkTopology */ @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"}) @InterfaceStability.Unstable public class NetworkTopologyWithNodeGroup extends NetworkTopology { public final static String DEFAULT_NODEGROUP = "/default-nodegroup"; public NetworkTopologyWithNodeGroup() { clusterMap = new InnerNodeWithNodeGroup(InnerNode.ROOT); } @Override protected Node getNodeForNetworkLocation(Node node) { // if node only with default rack info, here we need to add default // nodegroup info if (NetworkTopology.DEFAULT_RACK.equals(node.getNetworkLocation())) { node.setNetworkLocation(node.getNetworkLocation() + DEFAULT_NODEGROUP); } Node nodeGroup = getNode(node.getNetworkLocation()); if (nodeGroup == null) { nodeGroup = new InnerNodeWithNodeGroup(node.getNetworkLocation()); } return getNode(nodeGroup.getNetworkLocation()); } @Override public String getRack(String loc) { netlock.readLock().lock(); try { loc = InnerNode.normalize(loc); Node locNode = getNode(loc); if (locNode instanceof InnerNodeWithNodeGroup) { InnerNodeWithNodeGroup node = (InnerNodeWithNodeGroup) locNode; if (node.isRack()) { return loc; } else if (node.isNodeGroup()) { return node.getNetworkLocation(); } else { // may be a data center return null; } } else { // not in cluster map, don't handle it return loc; } } finally { netlock.readLock().unlock(); } } /** * Given a string representation of a node group for a specific network * location * * @param loc * a path-like string representation of a network location * @return a node group string */ public String getNodeGroup(String loc) { netlock.readLock().lock(); try { loc = InnerNode.normalize(loc); Node locNode = getNode(loc); if (locNode instanceof InnerNodeWithNodeGroup) { InnerNodeWithNodeGroup node = (InnerNodeWithNodeGroup) locNode; if (node.isNodeGroup()) { return loc; } else if (node.isRack()) { // not sure the node group for a rack return null; } else { // may be a leaf node return getNodeGroup(node.getNetworkLocation()); } } else { // not in cluster map, don't handle it return loc; } } finally { netlock.readLock().unlock(); } } @Override public boolean isOnSameRack( Node node1, Node node2) { if (node1 == null || node2 == null || node1.getParent() == null || node2.getParent() == null) { return false; } netlock.readLock().lock(); try { return isSameParents(node1.getParent(), node2.getParent()); } finally { netlock.readLock().unlock(); } } /** * Check if two nodes are on the same node group (hypervisor) The * assumption here is: each nodes are leaf nodes. * * @param node1 * one node (can be null) * @param node2 * another node (can be null) * @return true if node1 and node2 are on the same node group; false * otherwise * @exception IllegalArgumentException * when either node1 or node2 is null, or node1 or node2 do * not belong to the cluster */ @Override public boolean isOnSameNodeGroup(Node node1, Node node2) { if (node1 == null || node2 == null) { return false; } netlock.readLock().lock(); try { return isSameParents(node1, node2); } finally { netlock.readLock().unlock(); } } /** * Check if network topology is aware of NodeGroup */ @Override public boolean isNodeGroupAware() { return true; } /** Add a leaf node * Update node counter & rack counter if necessary * @param node node to be added; can be null * @exception IllegalArgumentException if add a node to a leave * or node to be added is not a leaf */ @Override public void add(Node node) { if (node==null) return; if( node instanceof InnerNode ) { throw new IllegalArgumentException( "Not allow to add an inner node: "+NodeBase.getPath(node)); } netlock.writeLock().lock(); try { Node rack = null; // if node only with default rack info, here we need to add default // nodegroup info if (NetworkTopology.DEFAULT_RACK.equals(node.getNetworkLocation())) { node.setNetworkLocation(node.getNetworkLocation() + NetworkTopologyWithNodeGroup.DEFAULT_NODEGROUP); } Node nodeGroup = getNode(node.getNetworkLocation()); if (nodeGroup == null) { nodeGroup = new InnerNodeWithNodeGroup(node.getNetworkLocation()); } rack = getNode(nodeGroup.getNetworkLocation()); // rack should be an innerNode and with parent. // note: rack's null parent case is: node's topology only has one layer, // so rack is recognized as "/" and no parent. // This will be recognized as a node with fault topology. if (rack != null && (!(rack instanceof InnerNode) || rack.getParent() == null)) { throw new IllegalArgumentException("Unexpected data node " + node.toString() + " at an illegal network location"); } if (clusterMap.add(node)) { LOG.info("Adding a new node: " + NodeBase.getPath(node)); if (rack == null) { // We only track rack number here numOfRacks++; } } if(LOG.isDebugEnabled()) { LOG.debug("NetworkTopology became:\n" + this.toString()); } } finally { netlock.writeLock().unlock(); } } /** Remove a node * Update node counter and rack counter if necessary * @param node node to be removed; can be null */ @Override public void remove(Node node) { if (node==null) return; if( node instanceof InnerNode ) { throw new IllegalArgumentException( "Not allow to remove an inner node: "+NodeBase.getPath(node)); } LOG.info("Removing a node: "+NodeBase.getPath(node)); netlock.writeLock().lock(); try { if (clusterMap.remove(node)) { Node nodeGroup = getNode(node.getNetworkLocation()); if (nodeGroup == null) { nodeGroup = new InnerNode(node.getNetworkLocation()); } InnerNode rack = (InnerNode)getNode(nodeGroup.getNetworkLocation()); if (rack == null) { numOfRacks--; } } if(LOG.isDebugEnabled()) { LOG.debug("NetworkTopology became:\n" + this.toString()); } } finally { netlock.writeLock().unlock(); } } @Override protected int getWeight(Node reader, Node node) { // 0 is local, 1 is same node group, 2 is same rack, 3 is off rack // Start off by initializing to off rack int weight = 3; if (reader != null) { if (reader.equals(node)) { weight = 0; } else if (isOnSameNodeGroup(reader, node)) { weight = 1; } else if (isOnSameRack(reader, node)) { weight = 2; } } return weight; } /** * Sort nodes array by their distances to <i>reader</i>. * <p/> * This is the same as {@link NetworkTopology#sortByDistance(Node, Node[], * int)} except with a four-level network topology which contains the * additional network distance of a "node group" which is between local and * same rack. * * @param reader Node where data will be read * @param nodes Available replicas with the requested data * @param activeLen Number of active nodes at the front of the array */ @Override public void sortByDistance(Node reader, Node[] nodes, int activeLen) { // If reader is not a datanode (not in NetworkTopology tree), we need to // replace this reader with a sibling leaf node in tree. if (reader != null && !this.contains(reader)) { Node nodeGroup = getNode(reader.getNetworkLocation()); if (nodeGroup != null && nodeGroup instanceof InnerNode) { InnerNode parentNode = (InnerNode) nodeGroup; // replace reader with the first children of its parent in tree reader = parentNode.getLeaf(0, null); } else { return; } } super.sortByDistance(reader, nodes, activeLen); } /** InnerNodeWithNodeGroup represents a switch/router of a data center, rack * or physical host. Different from a leaf node, it has non-null children. */ static class InnerNodeWithNodeGroup extends InnerNode { public InnerNodeWithNodeGroup(String name, String location, InnerNode parent, int level) { super(name, location, parent, level); } public InnerNodeWithNodeGroup(String name, String location) { super(name, location); } public InnerNodeWithNodeGroup(String path) { super(path); } @Override boolean isRack() { // it is node group if (getChildren().isEmpty()) { return false; } Node firstChild = children.get(0); if (firstChild instanceof InnerNode) { Node firstGrandChild = (((InnerNode) firstChild).children).get(0); if (firstGrandChild instanceof InnerNode) { // it is datacenter return false; } else { return true; } } return false; } /** * Judge if this node represents a node group * * @return true if it has no child or its children are not InnerNodes */ boolean isNodeGroup() { if (children.isEmpty()) { return true; } Node firstChild = children.get(0); if (firstChild instanceof InnerNode) { // it is rack or datacenter return false; } return true; } @Override protected boolean isLeafParent() { return isNodeGroup(); } @Override protected InnerNode createParentNode(String parentName) { return new InnerNodeWithNodeGroup(parentName, getPath(this), this, this.getLevel() + 1); } @Override protected boolean areChildrenLeaves() { return isNodeGroup(); } } }
apache-2.0
lbchen/odl-mod
opendaylight/samples/northbound/loadbalancer/target/enunciate-scratch/enunciate36928727411227568915205/OSGI-OPT/src/org/osgi/service/wireadmin/Producer.java
5678
/* * Copyright (c) OSGi Alliance (2002, 2008). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.service.wireadmin; /** * Data Producer, a service that can generate values to be used by * {@link Consumer} services. * * <p> * Service objects registered under the Producer interface are expected to * produce values (internally generated or from external sensors). The value can * be of different types. When delivering a value to a <code>Wire</code> object, * the Producer service should coerce the value to be an instance of one of the * types specified by {@link Wire#getFlavors}. The classes are specified in * order of preference. * * <p> * When the data represented by the Producer object changes, this object should * send the updated value by calling the <code>update</code> method on each of * <code>Wire</code> objects passed in the most recent call to this object's * {@link #consumersConnected} method. These <code>Wire</code> objects will pass * the value on to the associated <code>Consumer</code> service object. * * <p> * The Producer service may use the information in the <code>Wire</code> object's * properties to schedule the delivery of values to the <code>Wire</code> object. * * <p> * Producer service objects must register with a <code>service.pid</code> and a * {@link WireConstants#WIREADMIN_PRODUCER_FLAVORS} property. It is recommended * that a Producer service object also registers with a * <code>service.description</code> property. Producer service objects must * register with a {@link WireConstants#WIREADMIN_PRODUCER_FILTERS} property if * the Producer service will be performing filtering instead of the * <code>Wire</code> object. * * <p> * If an exception is thrown by a Producer object method, a * <code>WireAdminEvent</code> of type {@link WireAdminEvent#PRODUCER_EXCEPTION} * is broadcast by the Wire Admin service. * * <p> * Security Considerations. Data producing bundles will require * <code>ServicePermission[Producer,REGISTER]</code> to register a Producer * service. In general, only the Wire Admin service should have * <code>ServicePermission[Producer,GET]</code>. Thus only the Wire Admin service * may directly call a Producer service. Care must be taken in the sharing of * <code>Wire</code> objects with other bundles. * <p> * Producer services must be registered with scope names when they can send * different types of objects (composite) to the Consumer service. The Producer * service should have <code>WirePermission</code> for each of these scope names. * * @version $Revision: 5673 $ */ public interface Producer { /** * Return the current value of this <code>Producer</code> object. * * <p> * This method is called by a <code>Wire</code> object in response to the * Consumer service calling the <code>Wire</code> object's <code>poll</code> * method. The Producer should coerce the value to be an instance of one of * the types specified by {@link Wire#getFlavors}. The types are specified * in order of of preference. The returned value should be as new or newer * than the last value furnished by this object. * * <p> * Note: This method may be called by a <code>Wire</code> object prior to this * object being notified that it is connected to that <code>Wire</code> object * (via the {@link #consumersConnected} method). * <p> * If the Producer service returns an <code>Envelope</code> object that has an * unpermitted scope name, then the Wire object must ignore (or remove) the * transfer. * <p> * If the <code>Wire</code> object has a scope set, the return value must be * an array of <code>Envelope</code> objects (<code>Envelope[]</code>). The * <code>Wire</code> object must have removed any <code>Envelope</code> objects * that have a scope name that is not in the Wire object's scope. * * @param wire The <code>Wire</code> object which is polling this service. * @return The current value of the Producer service or <code>null</code> if * the value cannot be coerced into a compatible type. Or an array * of <code>Envelope</code> objects. */ public Object polled(Wire wire); /** * Update the list of <code>Wire</code> objects to which this * <code>Producer</code> object is connected. * * <p> * This method is called when the Producer service is first registered and * subsequently whenever a <code>Wire</code> associated with this Producer * becomes connected, is modified or becomes disconnected. * * <p> * The Wire Admin service must call this method asynchronously. This implies * that implementors of a Producer service can be assured that the callback * will not take place during registration when they execute the * registration in a synchronized method. * * @param wires An array of the current and complete list of <code>Wire</code> * objects to which this Producer service is connected. May be * <code>null</code> if the Producer is not currently connected to any * <code>Wire</code> objects. */ public void consumersConnected(Wire[] wires); }
epl-1.0
dsimansk/camel
camel-core/src/test/java/org/apache/camel/processor/LogProcessorTest.java
2997
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor; import org.apache.camel.ContextTestSupport; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; /** * @version */ public class LogProcessorTest extends ContextTestSupport { public void testLogProcessorFoo() throws Exception { getMockEndpoint("mock:foo").expectedMessageCount(1); template.sendBody("direct:foo", "Hello World"); assertMockEndpointsSatisfied(); } public void testLogProcessorBar() throws Exception { getMockEndpoint("mock:bar").expectedMessageCount(1); template.sendBody("direct:bar", "Bye World"); assertMockEndpointsSatisfied(); } public void testLogProcessorBaz() throws Exception { getMockEndpoint("mock:baz").expectedMessageCount(1); template.sendBody("direct:baz", "Hi World"); assertMockEndpointsSatisfied(); } public void testLogProcessorMarker() throws Exception { getMockEndpoint("mock:wombat").expectedMessageCount(1); template.sendBody("direct:wombat", "Hi Wombat"); assertMockEndpointsSatisfied(); } public void testNoLog() throws Exception { getMockEndpoint("mock:bar").expectedMessageCount(1); template.sendBody("direct:nolog", "Hi World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:foo").routeId("foo").log("Got ${body}").to("mock:foo"); from("direct:bar").routeId("bar").log(LoggingLevel.WARN, "Also got ${body}").to("mock:bar"); from("direct:baz").routeId("baz").log(LoggingLevel.ERROR, "cool", "Me got ${body}").to("mock:baz"); from("direct:wombat").routeId("wombat") .log(LoggingLevel.INFO, "cool", "mymarker", "Me got ${body}") .to("mock:wombat"); from("direct:nolog").routeId("nolog").log(LoggingLevel.TRACE, "Should not log ${body}").to("mock:bar"); } }; } }
apache-2.0
YMartsynkevych/camel
camel-core/src/test/java/org/apache/camel/component/bean/RouteMethodCallStaticTest.java
1889
/** * 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.bean; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; /** * */ public class RouteMethodCallStaticTest extends ContextTestSupport { public void testStaticMethodCall() throws Exception { getMockEndpoint("mock:camel").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:other").expectedBodiesReceived("Hello World"); template.sendBody("direct:start", "Hello World"); template.sendBody("direct:start", "Hello Camel"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .choice() .when().method(MyStaticClass.class, "isCamel") .to("mock:camel") .otherwise() .to("mock:other"); } }; } }
apache-2.0
Flipkart/elasticsearch
src/main/java/org/elasticsearch/common/util/concurrent/SizeBlockingQueue.java
5391
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.common.util.concurrent; import java.util.AbstractQueue; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * A size based queue wrapping another blocking queue to provide (somewhat relaxed) capacity checks. * Mainly makes sense to use with blocking queues that are unbounded to provide the ability to do * capacity verification. */ public class SizeBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> { private final BlockingQueue<E> queue; private final int capacity; private final AtomicInteger size = new AtomicInteger(); public SizeBlockingQueue(BlockingQueue<E> queue, int capacity) { assert capacity >= 0; this.queue = queue; this.capacity = capacity; } @Override public int size() { return size.get(); } public int capacity() { return this.capacity; } @Override public Iterator<E> iterator() { final Iterator<E> it = queue.iterator(); return new Iterator<E>() { E current; @Override public boolean hasNext() { return it.hasNext(); } @Override public E next() { current = it.next(); return current; } @Override public void remove() { // note, we can't call #remove on the iterator because we need to know // if it was removed or not if (queue.remove(current)) { size.decrementAndGet(); } } }; } @Override public E peek() { return queue.peek(); } @Override public E poll() { E e = queue.poll(); if (e != null) { size.decrementAndGet(); } return e; } @Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { E e = queue.poll(timeout, unit); if (e != null) { size.decrementAndGet(); } return e; } @Override public boolean remove(Object o) { boolean v = queue.remove(o); if (v) { size.decrementAndGet(); } return v; } /** * Forces adding an element to the queue, without doing size checks. */ public void forcePut(E e) throws InterruptedException { size.incrementAndGet(); try { queue.put(e); } catch (InterruptedException ie) { size.decrementAndGet(); throw ie; } } @Override public boolean offer(E e) { int count = size.incrementAndGet(); if (count > capacity) { size.decrementAndGet(); return false; } boolean offered = queue.offer(e); if (!offered) { size.decrementAndGet(); } return offered; } @Override public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { // note, not used in ThreadPoolExecutor throw new IllegalStateException("offer with timeout not allowed on size queue"); } @Override public void put(E e) throws InterruptedException { // note, not used in ThreadPoolExecutor throw new IllegalStateException("put not allowed on size queue"); } @Override public E take() throws InterruptedException { E e; try { e = queue.take(); size.decrementAndGet(); } catch (InterruptedException ie) { throw ie; } return e; } @Override public int remainingCapacity() { return capacity - size.get(); } @Override public int drainTo(Collection<? super E> c) { int v = queue.drainTo(c); size.addAndGet(-v); return v; } @Override public int drainTo(Collection<? super E> c, int maxElements) { int v = queue.drainTo(c, maxElements); size.addAndGet(-v); return v; } @Override public Object[] toArray() { return queue.toArray(); } @Override public <T> T[] toArray(T[] a) { return (T[]) queue.toArray(a); } @Override public boolean contains(Object o) { return queue.contains(o); } @Override public boolean containsAll(Collection<?> c) { return queue.containsAll(c); } }
apache-2.0
j256/ormlite-android
src/main/java/com/j256/ormlite/android/apptools/OrmLiteBaseListActivity.java
2719
package com.j256.ormlite.android.apptools; import com.j256.ormlite.support.ConnectionSource; import android.app.ListActivity; import android.content.Context; import android.os.Bundle; /** * Base class to use for Tab activities in Android. * * For more information, see {@link OrmLiteBaseActivity}. * * @author graywatson, kevingalligan */ public abstract class OrmLiteBaseListActivity<H extends OrmLiteSqliteOpenHelper> extends ListActivity { private volatile H helper; private volatile boolean created = false; private volatile boolean destroyed = false; /** * Get a helper for this action. */ public H getHelper() { if (helper == null) { if (!created) { throw new IllegalStateException("A call has not been made to onCreate() yet so the helper is null"); } else if (destroyed) { throw new IllegalStateException( "A call to onDestroy has already been made and the helper cannot be used after that point"); } else { throw new IllegalStateException("Helper is null for some unknown reason"); } } else { return helper; } } /** * Get a connection source for this action. */ public ConnectionSource getConnectionSource() { return getHelper().getConnectionSource(); } @Override protected void onCreate(Bundle savedInstanceState) { if (helper == null) { helper = getHelperInternal(this); created = true; } super.onCreate(savedInstanceState); } @Override protected void onDestroy() { super.onDestroy(); releaseHelper(helper); destroyed = true; } /** * This is called internally by the class to populate the helper object instance. This should not be called directly * by client code unless you know what you are doing. Use {@link #getHelper()} to get a helper instance. If you are * managing your own helper creation, override this method to supply this activity with a helper instance. * * <p> * <b> NOTE: </b> If you override this method, you most likely will need to override the * {@link #releaseHelper(OrmLiteSqliteOpenHelper)} method as well. * </p> */ protected H getHelperInternal(Context context) { @SuppressWarnings({ "unchecked", "deprecation" }) H newHelper = (H) OpenHelperManager.getHelper(context); return newHelper; } /** * Release the helper instance created in {@link #getHelperInternal(Context)}. You most likely will not need to call * this directly since {@link #onDestroy()} does it for you. * * <p> * <b> NOTE: </b> If you override this method, you most likely will need to override the * {@link #getHelperInternal(Context)} method as well. * </p> */ protected void releaseHelper(H helper) { OpenHelperManager.releaseHelper(); this.helper = null; } }
isc
HackWars/hackwars-classic
HWTomcatServer/webapps/ROOT/WEB-INF/classes/org/xamjwg/html/domimpl/NodeImpl.java
18274
/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: info@xamjwg.org */ /* * Created on Sep 3, 2005 */ package org.xamjwg.html.domimpl; import java.util.*; import org.w3c.dom.*; import org.xamjwg.util.*; import org.xamjwg.html.*; public abstract class NodeImpl implements Node { private static final NodeImpl[] EMPTY_ARRAY = new NodeImpl[0]; public NodeImpl() { super(); } protected ContainingBlockContext containingBlockContext; public void setContainingBlockContext(ContainingBlockContext containingBlockContext) { this.containingBlockContext = containingBlockContext; } public ContainingBlockContext getContainingBlockContext() { return this.containingBlockContext; } protected final Object getTreeLock() { Object doc = this.getOwnerDocument(); return doc == null ? this : doc; } protected ListSet nodeList; public Node appendChild(Node newChild) throws DOMException { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; if(nl == null) { nl = new ListSet(); this.nodeList = nl; } nl.add(newChild); } if(newChild instanceof NodeImpl) { ((NodeImpl) newChild).addNotify(this); } return newChild; } protected void removeAllChildren() { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; if(nl != null) { nl.clear(); //this.nodeList = null; } } } protected NodeList getNodeList(NodeFilter filter) { Collection collection = new ArrayList(); synchronized(this.getTreeLock()) { this.appendChildrenToCollection(filter, collection); } return new NodeListImpl(collection); } public NodeImpl[] getChildrenArray() { ListSet nl = this.nodeList; synchronized(this.getTreeLock()) { return nl == null ? null : (NodeImpl[]) nl.toArray(NodeImpl.EMPTY_ARRAY); } } /** * Gets descendent nodes that match according to * the filter, but it does not nest into matching nodes. */ public ArrayList getDescendents(NodeFilter filter) { ArrayList al = new ArrayList(); synchronized(this.getTreeLock()) { this.extractDescendentsArrayImpl(filter, al); } return al; } private void extractDescendentsArrayImpl(NodeFilter filter, ArrayList al) { ListSet nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { NodeImpl n = (NodeImpl) i.next(); if(filter.accept(n)) { al.add(n); } else if(n.getNodeType() == Node.ELEMENT_NODE) { n.extractDescendentsArrayImpl(filter, al); } } } } private void appendChildrenToCollection(NodeFilter filter, Collection collection) { ListSet nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { NodeImpl node = (NodeImpl) i.next(); if(filter.accept(node)) { collection.add(node); } node.appendChildrenToCollection(filter, collection); } } } public Node cloneNode(boolean deep) { try { Class thisClass = this.getClass(); Node newNode = (Node) thisClass.newInstance(); NodeList children = this.getChildNodes(); int length = children.getLength(); for(int i = 0; i < length; i++) { Node child = (Node) children.item(i); Node newChild = deep ? child.cloneNode(deep) : child; newNode.appendChild(newChild); } if(newNode instanceof Element) { Element elem = (Element) newNode; NamedNodeMap nnmap = this.getAttributes(); if(nnmap != null) { int nnlength = nnmap.getLength(); for(int i = 0; i < nnlength; i++) { Attr attr = (Attr) nnmap.item(i); elem.setAttributeNode((Attr) attr.cloneNode(true)); } } } return newNode; } catch(Exception err) { throw new IllegalStateException(err.getMessage()); } } private int getNodeIndex() { NodeImpl parent = (NodeImpl) this.getParentNode(); return parent == null ? -1 : parent.getChildIndex(this); } private int getChildIndex(Node child) { synchronized(this.getTreeLock()) { return this.nodeList.indexOf(child); } } private boolean isAncestorOf(Node other) { NodeImpl parent = (NodeImpl) other.getParentNode(); if(parent == this) { return true; } else if(parent == null) { return false; } else { return this.isAncestorOf(parent); } } public short compareDocumentPosition(Node other) throws DOMException { Node parent = this.getParentNode(); if(!(other instanceof NodeImpl)) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Unknwon node implementation"); } if(parent != null && parent == other.getParentNode()) { int thisIndex = this.getNodeIndex(); int otherIndex = ((NodeImpl) other).getNodeIndex(); if(thisIndex == -1 || otherIndex == -1) { return Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC; } if(thisIndex < otherIndex) { return Node.DOCUMENT_POSITION_FOLLOWING; } else { return Node.DOCUMENT_POSITION_PRECEDING; } } else if(this.isAncestorOf(other)) { return Node.DOCUMENT_POSITION_CONTAINED_BY; } else if(((NodeImpl) other).isAncestorOf(this)) { return Node.DOCUMENT_POSITION_CONTAINS; } else { return Node.DOCUMENT_POSITION_DISCONNECTED; } } public NamedNodeMap getAttributes() { return null; } protected volatile Document document; public Document getOwnerDocument() { return this.document; } void setOwnerDocument(Document value) { this.document = value; } void setOwnerDocument(Document value, boolean deep) { this.document = value; if(deep) { ListSet nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { NodeImpl child = (NodeImpl) i.next(); child.setOwnerDocument(value, deep); } } } } void visitImpl(NodeVisitor visitor) { try { visitor.visit(this); } catch(SkipVisitorException sve) { return; } catch(StopVisitorException sve) { throw sve; } ListSet nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { NodeImpl child = (NodeImpl) i.next(); try { child.visitImpl(visitor); } catch(StopVisitorException sve) { throw sve; } } } } void visit(NodeVisitor visitor) { synchronized(this.getTreeLock()) { this.visitImpl(visitor); } } public Node insertBefore(Node newChild, Node refChild) throws DOMException { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(refChild); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "refChild not found"); } nl.add(idx, newChild); } if(newChild instanceof NodeImpl) { ((NodeImpl) newChild).addNotify(this); } return newChild; } protected Node insertAt(Node newChild, int idx) throws DOMException { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; nl.add(idx, newChild); } if(newChild instanceof NodeImpl) { ((NodeImpl) newChild).addNotify(this); } return newChild; } public Node replaceChild(Node newChild, Node oldChild) throws DOMException { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(oldChild); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "oldChild not found"); } nl.set(idx, newChild); } return newChild; } public Node removeChild(Node oldChild) throws DOMException { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; if(nl == null || !nl.remove(oldChild)) { throw new DOMException(DOMException.NOT_FOUND_ERR, "oldChild not found"); } } return oldChild; } public Node removeChildAt(int index) throws DOMException { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; if(nl == null) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "Empty list of children"); } Node n = (Node) nl.remove(index); if (n == null) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "No node with that index"); } return n; } } public boolean hasChildNodes() { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; return nl != null && !nl.isEmpty(); } } public String getBaseURI() { Document document = this.getOwnerDocument(); return document == null ? null : document.getBaseURI(); } public NodeList getChildNodes() { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; return new NodeListImpl(nl == null ? Collections.EMPTY_LIST : nl); } } public Node getFirstChild() { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; try { return nl == null ? null : (Node) nl.get(0); } catch(IndexOutOfBoundsException iob) { return null; } } } public Node getLastChild() { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; try { return nl == null ? null : (Node) nl.get(nl.size() - 1); } catch(IndexOutOfBoundsException iob) { return null; } } } private Node getPreviousTo(Node node) { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(node); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "node not found"); } try { return (Node) nl.get(idx-1); } catch(IndexOutOfBoundsException iob) { return null; } } } private Node getNextTo(Node node) { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(node); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "node not found"); } try { return (Node) nl.get(idx+1); } catch(IndexOutOfBoundsException iob) { return null; } } } public Node getPreviousSibling() { NodeImpl parent = (NodeImpl) this.getParentNode(); return parent == null ? null : parent.getPreviousTo(this); } public Node getNextSibling() { NodeImpl parent = (NodeImpl) this.getParentNode(); return parent == null ? null : parent.getNextTo(this); } public Object getFeature(String feature, String version) { //TODO What should this do? return null; } private Map userData; //TODO: Inform handlers on cloning, etc. private List userDataHandlers; public Object setUserData(String key, Object data, UserDataHandler handler) { synchronized(this.getTreeLock()) { if(this.userDataHandlers == null) { this.userDataHandlers = new LinkedList(); } this.userDataHandlers.add(handler); if(this.userData == null) { this.userData = new HashMap(); } return this.userData.put(key, data); } } public Object getUserData(String key) { synchronized(this.getTreeLock()) { Map ud = this.userData; return ud == null ? null : ud.get(key); } } public abstract String getLocalName(); public boolean hasAttributes() { return false; } public String getNamespaceURI() { return null; } public abstract String getNodeName(); public abstract String getNodeValue() throws DOMException; private volatile String prefix; public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) throws DOMException { this.prefix = prefix; } public abstract void setNodeValue(String nodeValue) throws DOMException; public abstract short getNodeType(); public String getTextContent() throws DOMException { StringBuffer sb = new StringBuffer(); synchronized(this.getTreeLock()) { Iterator i = this.nodeList.iterator(); while(i.hasNext()) { Node node = (Node) i.next(); short type = node.getNodeType(); switch(type) { case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: String textContent = node.getTextContent(); if(textContent != null) { sb.append(textContent); } break; default: break; } } } return sb.toString(); } public void setTextContent(String textContent) throws DOMException { synchronized(this.getTreeLock()) { this.removeChildrenImpl(new TextFilter()); if(textContent != null && !"".equals(textContent)) { TextImpl t = new TextImpl(textContent); t.setOwnerDocument(this.getOwnerDocument()); this.nodeList.add(t); } } } protected void removeChildrenImpl(NodeFilter filter) { ListSet nl = this.nodeList; int len = nl.size(); for(int i = len; --i >= 0;) { Node node = (Node) nl.get(i); if(filter.accept(node)) { nl.remove(i); } } } public Node insertAfter(Node newChild, Node refChild) { synchronized(this.getTreeLock()) { ListSet nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(refChild); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "refChild not found"); } nl.add(idx+1, newChild); } if(newChild instanceof NodeImpl) { ((NodeImpl) newChild).addNotify(this); } return newChild; } public Text replaceAdjacentTextNodes(Text node, String textContent) { synchronized(this.getTreeLock()) { int idx = this.nodeList.indexOf(node); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "Node not a child"); } int firstIdx = idx; List toDelete = new LinkedList(); for(int adjIdx = idx; --adjIdx >= 0;) { Object child = this.nodeList.get(adjIdx); if(child instanceof Text) { firstIdx = adjIdx; toDelete.add(child); } } int length = this.nodeList.size(); for(int adjIdx = idx; ++adjIdx < length;) { Object child = this.nodeList.get(adjIdx); if(child instanceof Text) { toDelete.add(child); } } this.nodeList.removeAll(toDelete); TextImpl textNode = new TextImpl(textContent); this.nodeList.add(firstIdx, textNode); return textNode; } } public Text replaceAdjacentTextNodes(Text node) { synchronized(this.getTreeLock()) { int idx = this.nodeList.indexOf(node); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "Node not a child"); } StringBuffer textBuffer = new StringBuffer(); int firstIdx = idx; List toDelete = new LinkedList(); for(int adjIdx = idx; --adjIdx >= 0;) { Object child = this.nodeList.get(adjIdx); if(child instanceof Text) { firstIdx = adjIdx; toDelete.add(child); textBuffer.append(((Text) child).getNodeValue()); } } int length = this.nodeList.size(); for(int adjIdx = idx; ++adjIdx < length;) { Object child = this.nodeList.get(adjIdx); if(child instanceof Text) { toDelete.add(child); textBuffer.append(((Text) child).getNodeValue()); } } this.nodeList.removeAll(toDelete); TextImpl textNode = new TextImpl(textBuffer.toString()); this.nodeList.add(firstIdx, textNode); return textNode; } } protected volatile Node parentNode; public Node getParentNode() { return this.parentNode; } public boolean isSameNode(Node other) { return this == other; } public boolean isSupported(String feature, String version) { return ("HTML".equals(feature) && version.compareTo("4.01") <= 0); } public String lookupNamespaceURI(String prefix) { return null; } public boolean equalAttributes(Node arg) { return false; } public boolean isEqualNode(Node arg) { return arg instanceof NodeImpl && this.getNodeType() == arg.getNodeType() && Objects.equals(this.getNodeName(), arg.getNodeName()) && Objects.equals(this.getNodeValue(), arg.getNodeValue()) && Objects.equals(this.getLocalName(), arg.getLocalName()) && Objects.equals(this.nodeList, ((NodeImpl) arg).nodeList) && this.equalAttributes(arg); } public boolean isDefaultNamespace(String namespaceURI) { return namespaceURI == null; } public String lookupPrefix(String namespaceURI) { return null; } public void normalize() { synchronized(this.getTreeLock()) { List textNodes = new LinkedList(); Iterator i = this.nodeList.iterator(); boolean prevText = false; while(i.hasNext()) { Node child = (Node) i.next(); if(child.getNodeType() == Node.TEXT_NODE) { if(!prevText) { prevText = true; textNodes.add(child); } } else { prevText = false; } } i = textNodes.iterator(); while(i.hasNext()) { Text text = (Text) i.next(); this.replaceAdjacentTextNodes(text); } } } public String toString() { return this.getNodeName(); } public HtmlParserContext getHtmlParserContext() { Object doc = this.document; if(doc instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) doc).getHtmlParserContext(); } else { return null; } } public HtmlRendererContext getHtmlRendererContext() { Object doc = this.document; if(doc instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) doc).getHtmlRendererContext(); } else { return null; } } protected void addNotify(Node parent) { this.parentNode = parent; } }
isc
akefirad/datamill
core/src/main/java/foundation/stack/datamill/http/ResponseBuilder.java
3641
package foundation.stack.datamill.http; import foundation.stack.datamill.json.Json; import rx.Observable; import rx.Observer; import rx.functions.Func1; import java.nio.ByteBuffer; import java.util.function.Function; /** * Should be used to build HTTP {@link Response}s. A builder instance is passed to the lambda specified in the * {@link ServerRequest#respond(Function)} method. This builder should be used to construct responses. * * @author Ravi Chodavarapu (rchodava@gmail.com) */ public interface ResponseBuilder { /** Build a response with a 400 Bad Request status, and an empty body. */ Response badRequest(); /** Build a response with a 400 Bad Request status, and the given string body. */ Response badRequest(String content); /** Add a header to the response being built. */ <T> ResponseBuilder header(String name, T value); /** Build a response with a 500 Internal Server Error status, and an empty body. */ Response internalServerError(); /** Build a response with a 500 Internal Server Error status, and the given string body. */ Response internalServerError(String content); /** Build a response with a 20 No Content status, and an empty body. */ Response noContent(); /** Build a response with a 404 Not Found status, and an empty body. */ Response notFound(); /** Build a response with a 200 OK status, and an empty body. */ Response ok(); /** Build a response with a 200 OK status, and the given string body. */ Response ok(String content); /** Build a response with a 200 OK status, and the given byte array body. */ Response ok(byte[] content); /** * Add a body to the response being built which is made up of byte buffer data emissions. The lambda will receive a * {@link Observer} on which it can call {@link Observer#onNext(Object)} to emit data as byte buffers. These * emissions are sent out first, followed by the emissions made by the Observable returned by the lambda. */ ResponseBuilder streamingBodyAsBufferChunks(Func1<Observer<ByteBuffer>, Observable<ByteBuffer>> bodyStreamer); /** * Add a body to the response being built which is made up of byte array data emissions. The lambda will receive a * {@link Observer} on which it can call {@link Observer#onNext(Object)} to emit data as byte arrays. These * emissions are sent out first, followed by the byte array emissions made by the Observable returned by the lambda. */ ResponseBuilder streamingBody(Func1<Observer<byte[]>, Observable<byte[]>> bodyStreamer); /** * Add a body to the response being built which is made up of JSON object emissions. The lambda will receive a * {@link Observer} on which it can call {@link Observer#onNext(Object)} to emit JSON objects. These emissions are * sent out first, followed by the JSON objects emissions made by the Observable returned by the lambda. */ ResponseBuilder streamingJson(Func1<Observer<Json>, Observable<Json>> jsonStreamer); /** Build a response with a 401 Unauthorized status, and an empty body. */ Response unauthorized(); /** Build a response with a 401 Unauthorized status, and the given string body. */ Response unauthorized(String content); /** Build a response with a 403 Forbidden status, and an empty body. */ Response forbidden(); /** Build a response with a 403 Forbidden status, and the given string body. */ Response forbidden(String content); /** Build a response with a 409 Conflict status, and the given string body. */ Response conflict(String content); }
isc