gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * 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.search; import org.apache.lucene.search.TotalHits; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.OriginalIndices; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchShard; import org.elasticsearch.action.search.ShardSearchFailure; import org.elasticsearch.common.breaker.CircuitBreaker; import org.elasticsearch.common.breaker.CircuitBreakingException; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.search.DocValueFormat; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.bucket.terms.StringTerms; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.internal.InternalSearchResponse; import org.elasticsearch.tasks.TaskId; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.client.NoOpClient; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.xpack.core.async.AsyncExecutionId; import org.elasticsearch.xpack.core.search.action.AsyncSearchResponse; import org.junit.After; import org.junit.Before; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; public class AsyncSearchTaskTests extends ESTestCase { private ThreadPool threadPool; private boolean throwOnSchedule = false; @Before public void beforeTest() { threadPool = new TestThreadPool(getTestName()) { @Override public ScheduledCancellable schedule(Runnable command, TimeValue delay, String executor) { if (throwOnSchedule) { throw new RuntimeException(); } return super.schedule(command, delay, executor); } }; } @After public void afterTest() { threadPool.shutdownNow(); } private AsyncSearchTask createAsyncSearchTask() { return new AsyncSearchTask(0L, "", "", new TaskId("node1", 0), () -> null, TimeValue.timeValueHours(1), Collections.emptyMap(), Collections.emptyMap(), new AsyncExecutionId("0", new TaskId("node1", 1)), new NoOpClient(threadPool), threadPool, null); } public void testTaskDescription() { SearchRequest searchRequest = new SearchRequest("index1", "index2").source( new SearchSourceBuilder().query(QueryBuilders.termQuery("field", "value"))); AsyncSearchTask asyncSearchTask = new AsyncSearchTask(0L, "", "", new TaskId("node1", 0), searchRequest::buildDescription, TimeValue.timeValueHours(1), Collections.emptyMap(), Collections.emptyMap(), new AsyncExecutionId("0", new TaskId("node1", 1)), new NoOpClient(threadPool), threadPool, null); assertEquals("async_search{indices[index1,index2], search_type[QUERY_THEN_FETCH], " + "source[{\"query\":{\"term\":{\"field\":{\"value\":\"value\",\"boost\":1.0}}}}]}", asyncSearchTask.getDescription()); } public void testWaitForInit() throws InterruptedException { AsyncSearchTask task = new AsyncSearchTask(0L, "", "", new TaskId("node1", 0), () -> null, TimeValue.timeValueHours(1), Collections.emptyMap(), Collections.emptyMap(), new AsyncExecutionId("0", new TaskId("node1", 1)), new NoOpClient(threadPool), threadPool, null); int numShards = randomIntBetween(0, 10); List<SearchShard> shards = new ArrayList<>(); for (int i = 0; i < numShards; i++) { shards.add(new SearchShard(null, new ShardId("0", "0", 1))); } List<SearchShard> skippedShards = new ArrayList<>(); int numSkippedShards = randomIntBetween(0, 10); for (int i = 0; i < numSkippedShards; i++) { skippedShards.add(new SearchShard(null, new ShardId("0", "0", 1))); } int numThreads = randomIntBetween(1, 10); CountDownLatch latch = new CountDownLatch(numThreads); for (int i = 0; i < numThreads; i++) { Thread thread = new Thread(() -> task.addCompletionListener(new ActionListener<>() { @Override public void onResponse(AsyncSearchResponse resp) { assertThat(numShards + numSkippedShards, equalTo(resp.getSearchResponse().getTotalShards())); assertThat(numSkippedShards, equalTo(resp.getSearchResponse().getSkippedShards())); assertThat(0, equalTo(resp.getSearchResponse().getFailedShards())); latch.countDown(); } @Override public void onFailure(Exception e) { throw new AssertionError(e); } }, TimeValue.timeValueMillis(1))); thread.start(); } assertFalse(latch.await(numThreads*2, TimeUnit.MILLISECONDS)); task.getSearchProgressActionListener().onListShards(shards, skippedShards, SearchResponse.Clusters.EMPTY, false); latch.await(); } public void testWithFailure() throws InterruptedException { AsyncSearchTask task = createAsyncSearchTask(); int numThreads = randomIntBetween(1, 10); CountDownLatch latch = new CountDownLatch(numThreads); for (int i = 0; i < numThreads; i++) { Thread thread = new Thread(() -> task.addCompletionListener(new ActionListener<>() { @Override public void onResponse(AsyncSearchResponse resp) { assertNull(resp.getSearchResponse()); assertNotNull(resp.getFailure()); assertTrue(resp.isPartial()); latch.countDown(); } @Override public void onFailure(Exception e) { throw new AssertionError(e); } }, TimeValue.timeValueMillis(1))); thread.start(); } assertFalse(latch.await(numThreads*2, TimeUnit.MILLISECONDS)); task.getSearchProgressActionListener().onFailure(new Exception("boom")); latch.await(); } public void testWithFailureAndGetResponseFailureDuringReduction() throws InterruptedException { AsyncSearchTask task = createAsyncSearchTask(); task.getSearchProgressActionListener().onListShards(Collections.emptyList(), Collections.emptyList(), SearchResponse.Clusters.EMPTY, false); InternalAggregations aggs = InternalAggregations.from(Collections.singletonList(new StringTerms("name", BucketOrder.key(true), BucketOrder.key(true), 1, 1, Collections.emptyMap(), DocValueFormat.RAW, 1, false, 1, Collections.emptyList(), 0))); task.getSearchProgressActionListener().onPartialReduce(Collections.emptyList(), new TotalHits(0, TotalHits.Relation.EQUAL_TO), aggs, 1); task.getSearchProgressActionListener().onFailure(new CircuitBreakingException("boom", CircuitBreaker.Durability.TRANSIENT)); AtomicReference<AsyncSearchResponse> response = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); task.addCompletionListener(new ActionListener<>() { @Override public void onResponse(AsyncSearchResponse asyncSearchResponse) { assertTrue(response.compareAndSet(null, asyncSearchResponse)); latch.countDown(); } @Override public void onFailure(Exception e) { throw new AssertionError("onFailure should not be called"); } }, TimeValue.timeValueMillis(10L)); assertTrue(latch.await(1, TimeUnit.SECONDS)); AsyncSearchResponse asyncSearchResponse = response.get(); assertNotNull(response.get().getSearchResponse()); assertEquals(0, response.get().getSearchResponse().getTotalShards()); assertEquals(0, response.get().getSearchResponse().getSuccessfulShards()); assertEquals(0, response.get().getSearchResponse().getFailedShards()); Exception failure = asyncSearchResponse.getFailure(); assertThat(failure, instanceOf(ElasticsearchException.class)); assertEquals("Async search: error while reducing partial results", failure.getMessage()); assertEquals(1, failure.getSuppressed().length); assertThat(failure.getSuppressed()[0], instanceOf(ElasticsearchException.class)); assertEquals("error while executing search", failure.getSuppressed()[0].getMessage()); assertThat(failure.getSuppressed()[0].getCause(), instanceOf(CircuitBreakingException.class)); assertEquals("boom", failure.getSuppressed()[0].getCause().getMessage()); } public void testWaitForCompletion() throws InterruptedException { AsyncSearchTask task = createAsyncSearchTask(); int numShards = randomIntBetween(0, 10); List<SearchShard> shards = new ArrayList<>(); for (int i = 0; i < numShards; i++) { shards.add(new SearchShard(null, new ShardId("0", "0", 1))); } List<SearchShard> skippedShards = new ArrayList<>(); int numSkippedShards = randomIntBetween(0, 10); for (int i = 0; i < numSkippedShards; i++) { skippedShards.add(new SearchShard(null, new ShardId("0", "0", 1))); } int totalShards = numShards + numSkippedShards; task.getSearchProgressActionListener().onListShards(shards, skippedShards, SearchResponse.Clusters.EMPTY, false); for (int i = 0; i < numShards; i++) { task.getSearchProgressActionListener().onPartialReduce(shards.subList(i, i+1), new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0); assertCompletionListeners(task, totalShards, 1 + numSkippedShards, numSkippedShards, 0, true, false); } task.getSearchProgressActionListener().onFinalReduce(shards, new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0); assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, 0, true, false); ((AsyncSearchTask.Listener)task.getProgressListener()).onResponse( newSearchResponse(totalShards, totalShards, numSkippedShards)); assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, 0, false, false); } public void testWithFetchFailures() throws InterruptedException { AsyncSearchTask task = createAsyncSearchTask(); int numShards = randomIntBetween(2, 10); List<SearchShard> shards = new ArrayList<>(); for (int i = 0; i < numShards; i++) { shards.add(new SearchShard(null, new ShardId("0", "0", 1))); } List<SearchShard> skippedShards = new ArrayList<>(); int numSkippedShards = randomIntBetween(0, 10); for (int i = 0; i < numSkippedShards; i++) { skippedShards.add(new SearchShard(null, new ShardId("0", "0", 1))); } int totalShards = numShards + numSkippedShards; task.getSearchProgressActionListener().onListShards(shards, skippedShards, SearchResponse.Clusters.EMPTY, false); for (int i = 0; i < numShards; i++) { task.getSearchProgressActionListener().onPartialReduce(shards.subList(i, i+1), new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0); assertCompletionListeners(task, totalShards, 1 + numSkippedShards, numSkippedShards, 0, true, false); } task.getSearchProgressActionListener().onFinalReduce(shards, new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0); int numFetchFailures = randomIntBetween(1, numShards - 1); ShardSearchFailure[] shardSearchFailures = new ShardSearchFailure[numFetchFailures]; for (int i = 0; i < numFetchFailures; i++) { IOException failure = new IOException("boum"); //fetch failures are currently ignored, they come back with onFailure or onResponse anyways task.getSearchProgressActionListener().onFetchFailure(i, new SearchShardTarget("0", new ShardId("0", "0", 1), null, OriginalIndices.NONE), failure); shardSearchFailures[i] = new ShardSearchFailure(failure); } assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, 0, true, false); ((AsyncSearchTask.Listener)task.getProgressListener()).onResponse( newSearchResponse(totalShards, totalShards - numFetchFailures, numSkippedShards, shardSearchFailures)); assertCompletionListeners(task, totalShards, totalShards - numFetchFailures, numSkippedShards, numFetchFailures, false, false); } public void testFatalFailureDuringFetch() throws InterruptedException { AsyncSearchTask task = createAsyncSearchTask(); int numShards = randomIntBetween(0, 10); List<SearchShard> shards = new ArrayList<>(); for (int i = 0; i < numShards; i++) { shards.add(new SearchShard(null, new ShardId("0", "0", 1))); } List<SearchShard> skippedShards = new ArrayList<>(); int numSkippedShards = randomIntBetween(0, 10); for (int i = 0; i < numSkippedShards; i++) { skippedShards.add(new SearchShard(null, new ShardId("0", "0", 1))); } int totalShards = numShards + numSkippedShards; task.getSearchProgressActionListener().onListShards(shards, skippedShards, SearchResponse.Clusters.EMPTY, false); for (int i = 0; i < numShards; i++) { task.getSearchProgressActionListener().onPartialReduce(shards.subList(0, i+1), new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0); assertCompletionListeners(task, totalShards, i + 1 + numSkippedShards, numSkippedShards, 0, true, false); } task.getSearchProgressActionListener().onFinalReduce(shards, new TotalHits(0, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO), null, 0); for (int i = 0; i < numShards; i++) { //fetch failures are currently ignored, they come back with onFailure or onResponse anyways task.getSearchProgressActionListener().onFetchFailure(i, new SearchShardTarget("0", new ShardId("0", "0", 1), null, OriginalIndices.NONE), new IOException("boum")); } assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, 0, true, false); ((AsyncSearchTask.Listener)task.getProgressListener()).onFailure(new IOException("boum")); assertCompletionListeners(task, totalShards, totalShards, numSkippedShards, 0, true, true); } public void testFatalFailureWithNoCause() throws InterruptedException { AsyncSearchTask task = createAsyncSearchTask(); AsyncSearchTask.Listener listener = task.getSearchProgressActionListener(); int numShards = randomIntBetween(0, 10); List<SearchShard> shards = new ArrayList<>(); for (int i = 0; i < numShards; i++) { shards.add(new SearchShard(null, new ShardId("0", "0", 1))); } List<SearchShard> skippedShards = new ArrayList<>(); int numSkippedShards = randomIntBetween(0, 10); for (int i = 0; i < numSkippedShards; i++) { skippedShards.add(new SearchShard(null, new ShardId("0", "0", 1))); } int totalShards = numShards + numSkippedShards; task.getSearchProgressActionListener().onListShards(shards, skippedShards, SearchResponse.Clusters.EMPTY, false); listener.onFailure(new SearchPhaseExecutionException("fetch", "boum", ShardSearchFailure.EMPTY_ARRAY)); assertCompletionListeners(task, totalShards, 0, numSkippedShards, 0, true, true); } public void testAddCompletionListenerScheduleErrorWaitForInitListener() throws InterruptedException { throwOnSchedule = true; AsyncSearchTask asyncSearchTask = createAsyncSearchTask(); AtomicReference<Exception> failure = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); //onListShards has not been executed, then addCompletionListener has to wait for the // onListShards call and is executed as init listener asyncSearchTask.addCompletionListener(new ActionListener<>() { @Override public void onResponse(AsyncSearchResponse asyncSearchResponse) { throw new AssertionError("onResponse should not be called"); } @Override public void onFailure(Exception e) { assertTrue(failure.compareAndSet(null, e)); latch.countDown(); } }, TimeValue.timeValueMillis(500L)); asyncSearchTask.getSearchProgressActionListener().onListShards(Collections.emptyList(), Collections.emptyList(), SearchResponse.Clusters.EMPTY, false); assertTrue(latch.await(1000, TimeUnit.SECONDS)); assertThat(failure.get(), instanceOf(RuntimeException.class)); } public void testAddCompletionListenerScheduleErrorInitListenerExecutedImmediately() throws InterruptedException { throwOnSchedule = true; AsyncSearchTask asyncSearchTask = createAsyncSearchTask(); asyncSearchTask.getSearchProgressActionListener().onListShards(Collections.emptyList(), Collections.emptyList(), SearchResponse.Clusters.EMPTY, false); CountDownLatch latch = new CountDownLatch(1); AtomicReference<Exception> failure = new AtomicReference<>(); //onListShards has already been executed, then addCompletionListener is executed immediately asyncSearchTask.addCompletionListener(new ActionListener<>() { @Override public void onResponse(AsyncSearchResponse asyncSearchResponse) { throw new AssertionError("onResponse should not be called"); } @Override public void onFailure(Exception e) { assertTrue(failure.compareAndSet(null, e)); latch.countDown(); } }, TimeValue.timeValueMillis(500L)); assertTrue(latch.await(1000, TimeUnit.SECONDS)); assertThat(failure.get(), instanceOf(RuntimeException.class)); } private static SearchResponse newSearchResponse(int totalShards, int successfulShards, int skippedShards, ShardSearchFailure... failures) { InternalSearchResponse response = new InternalSearchResponse(SearchHits.empty(), InternalAggregations.EMPTY, null, null, false, null, 1); return new SearchResponse(response, null, totalShards, successfulShards, skippedShards, 100, failures, SearchResponse.Clusters.EMPTY); } private static void assertCompletionListeners(AsyncSearchTask task, int expectedTotalShards, int expectedSuccessfulShards, int expectedSkippedShards, int expectedShardFailures, boolean isPartial, boolean totalFailureExpected) throws InterruptedException { int numThreads = randomIntBetween(1, 10); CountDownLatch latch = new CountDownLatch(numThreads); for (int i = 0; i < numThreads; i++) { Thread thread = new Thread(() -> task.addCompletionListener(new ActionListener<>() { @Override public void onResponse(AsyncSearchResponse resp) { assertThat(resp.getSearchResponse().getTotalShards(), equalTo(expectedTotalShards)); assertThat(resp.getSearchResponse().getSuccessfulShards(), equalTo(expectedSuccessfulShards)); assertThat(resp.getSearchResponse().getSkippedShards(), equalTo(expectedSkippedShards)); assertThat(resp.getSearchResponse().getFailedShards(), equalTo(expectedShardFailures)); assertThat(resp.isPartial(), equalTo(isPartial)); if (expectedShardFailures > 0) { assertThat(resp.getSearchResponse().getShardFailures().length, equalTo(expectedShardFailures)); for (ShardSearchFailure failure : resp.getSearchResponse().getShardFailures()) { assertThat(failure.getCause(), instanceOf(IOException.class)); assertThat(failure.getCause().getMessage(), equalTo("boum")); } } if (totalFailureExpected) { assertNotNull(resp.getFailure()); } else { assertNull(resp.getFailure()); } latch.countDown(); } @Override public void onFailure(Exception e) { throw new AssertionError(e); } }, TimeValue.timeValueMillis(1))); thread.start(); } latch.await(); } }
package org.hisp.dhis.light.utils; /* * Copyright (c) 2004-2016, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project 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. */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.Validate; import org.hisp.dhis.common.comparator.IdentifiableObjectNameComparator; import org.hisp.dhis.dataanalysis.DataAnalysisService; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.dataset.DataSetService; import org.hisp.dhis.datavalue.DataValue; import org.hisp.dhis.datavalue.DataValueService; import org.hisp.dhis.datavalue.DeflatedDataValue; import org.hisp.dhis.expression.ExpressionService; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitService; import org.hisp.dhis.period.CalendarPeriodType; import org.hisp.dhis.period.Period; import org.hisp.dhis.period.YearlyPeriodType; import org.hisp.dhis.setting.SettingKey; import org.hisp.dhis.setting.SystemSettingManager; import org.hisp.dhis.system.filter.OrganisationUnitWithDataSetsFilter; import org.hisp.dhis.system.filter.PastAndCurrentPeriodFilter; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.hisp.dhis.user.UserCredentials; import org.hisp.dhis.commons.filter.FilterUtils; import org.hisp.dhis.validation.ValidationResult; import org.hisp.dhis.validation.ValidationRule; import org.hisp.dhis.validation.ValidationRuleService; import org.joda.time.DateTime; import com.google.common.collect.Sets; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ public class FormUtilsImpl implements FormUtils { public static final Integer DEFAULT_MAX_PERIODS = 10; // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- private CurrentUserService currentUserService; public void setCurrentUserService( CurrentUserService currentUserService ) { this.currentUserService = currentUserService; } private OrganisationUnitService organisationUnitService; public void setOrganisationUnitService( OrganisationUnitService organisationUnitService ) { this.organisationUnitService = organisationUnitService; } private DataValueService dataValueService; public void setDataValueService( DataValueService dataValueService ) { this.dataValueService = dataValueService; } private DataSetService dataSetService; public void setDataSetService( DataSetService dataSetService ) { this.dataSetService = dataSetService; } private DataAnalysisService stdDevOutlierAnalysisService; public void setStdDevOutlierAnalysisService( DataAnalysisService stdDevOutlierAnalysisService ) { this.stdDevOutlierAnalysisService = stdDevOutlierAnalysisService; } private DataAnalysisService minMaxOutlierAnalysisService; public void setMinMaxOutlierAnalysisService( DataAnalysisService minMaxOutlierAnalysisService ) { this.minMaxOutlierAnalysisService = minMaxOutlierAnalysisService; } private SystemSettingManager systemSettingManager; public void setSystemSettingManager( SystemSettingManager systemSettingManager ) { this.systemSettingManager = systemSettingManager; } private ValidationRuleService validationRuleService; public void setValidationRuleService( ValidationRuleService validationRuleService ) { this.validationRuleService = validationRuleService; } private ExpressionService expressionService; public void setExpressionService( ExpressionService expressionService ) { this.expressionService = expressionService; } // ------------------------------------------------------------------------- // Utils // ------------------------------------------------------------------------- @Override @SuppressWarnings("unchecked") public Map<String, DeflatedDataValue> getValidationViolations( OrganisationUnit organisationUnit, Collection<DataElement> dataElements, Period period ) { Map<String, DeflatedDataValue> validationErrorMap = new HashMap<>(); Double factor = (Double) systemSettingManager.getSystemSetting( SettingKey.FACTOR_OF_DEVIATION ); Date from = new DateTime( period.getStartDate() ).minusYears( 2 ).toDate(); Collection<DeflatedDataValue> stdDevs = stdDevOutlierAnalysisService.analyse( Sets.newHashSet( organisationUnit ), dataElements, Sets.newHashSet( period ), factor, from ); Collection<DeflatedDataValue> minMaxs = minMaxOutlierAnalysisService.analyse( Sets.newHashSet( organisationUnit ), dataElements, Sets.newHashSet( period ), null, from ); Collection<DeflatedDataValue> deflatedDataValues = CollectionUtils.union( stdDevs, minMaxs ); for ( DeflatedDataValue deflatedDataValue : deflatedDataValues ) { String key = String.format( "DE%dOC%d", deflatedDataValue.getDataElementId(), deflatedDataValue.getCategoryOptionComboId() ); validationErrorMap.put( key, deflatedDataValue ); } return validationErrorMap; } @Override public List<String> getValidationRuleViolations( OrganisationUnit organisationUnit, DataSet dataSet, Period period ) { List<ValidationResult> validationRuleResults = new ArrayList<>( validationRuleService.validate( dataSet, period, organisationUnit, null ) ); List<String> validationRuleViolations = new ArrayList<>( validationRuleResults.size() ); for ( ValidationResult result : validationRuleResults ) { ValidationRule rule = result.getValidationRule(); StringBuilder sb = new StringBuilder(); sb.append( expressionService.getExpressionDescription( rule.getLeftSide().getExpression() ) ); sb.append( " " ).append( rule.getOperator().getMathematicalOperator() ).append( " " ); sb.append( expressionService.getExpressionDescription( rule.getRightSide().getExpression() ) ); validationRuleViolations.add( sb.toString() ); } return validationRuleViolations; } @Override public Map<String, String> getDataValueMap( OrganisationUnit organisationUnit, DataSet dataSet, Period period ) { Map<String, String> dataValueMap = new HashMap<>(); List<DataValue> values = new ArrayList<>( dataValueService.getDataValues( organisationUnit, period, dataSet.getDataElements() ) ); for ( DataValue dataValue : values ) { DataElement dataElement = dataValue.getDataElement(); DataElementCategoryOptionCombo optionCombo = dataValue.getCategoryOptionCombo(); String key = String.format( "DE%dOC%d", dataElement.getId(), optionCombo.getId() ); String value = dataValue.getValue(); dataValueMap.put( key, value ); } return dataValueMap; } @Override public List<OrganisationUnit> organisationUnitWithDataSetsFilter( Collection<OrganisationUnit> organisationUnits ) { List<OrganisationUnit> ous = new ArrayList<>( organisationUnits ); FilterUtils.filter( ous, new OrganisationUnitWithDataSetsFilter() ); return ous; } @Override public List<OrganisationUnit> getSortedOrganisationUnitsForCurrentUser() { User user = currentUserService.getCurrentUser(); Validate.notNull( user ); List<OrganisationUnit> organisationUnits = new ArrayList<>( user.getOrganisationUnits() ); Collections.sort( organisationUnits, IdentifiableObjectNameComparator.INSTANCE ); return organisationUnitWithDataSetsFilter( organisationUnits ); } @Override public List<DataSet> getDataSetsForCurrentUser( Integer organisationUnitId ) { Validate.notNull( organisationUnitId ); OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit( organisationUnitId ); List<DataSet> dataSets = new ArrayList<>( organisationUnit.getDataSets() ); UserCredentials userCredentials = currentUserService.getCurrentUser().getUserCredentials(); if ( !userCredentials.isSuper() ) { dataSets.retainAll( userCredentials.getAllDataSets() ); } return dataSets; } @Override public List<Period> getPeriodsForDataSet( Integer dataSetId ) { return getPeriodsForDataSet( dataSetId, 0, DEFAULT_MAX_PERIODS ); } @Override public List<Period> getPeriodsForDataSet( Integer dataSetId, int first, int max ) { Validate.notNull( dataSetId ); DataSet dataSet = dataSetService.getDataSet( dataSetId ); CalendarPeriodType periodType; if ( dataSet.getPeriodType().getName().equalsIgnoreCase( "Yearly" ) ) { periodType = new YearlyPeriodType(); } else { periodType = (CalendarPeriodType) dataSet.getPeriodType(); } //TODO implement properly if ( dataSet.getOpenFuturePeriods() > 0 ) { List<Period> periods = periodType.generatePeriods( new Date() ); Collections.reverse( periods ); return periods; } else { List<Period> periods = periodType.generateLast5Years( new Date() ); FilterUtils.filter( periods, new PastAndCurrentPeriodFilter() ); Collections.reverse( periods ); if ( periods.size() > (first + max) ) { periods = periods.subList( first, max ); } return periods; } } }
package com.google.sitebricks.compiler; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Singleton; import com.google.sitebricks.Evaluator; import com.google.sitebricks.Visible; import com.google.sitebricks.conversion.generics.Generics; import com.google.sitebricks.conversion.generics.ParameterizedTypeImpl; import org.jetbrains.annotations.Nullable; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExpressionCompiler; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Dhanji R. Prasanna (dhanji@gmail com) */ @Singleton public class MvelEvaluatorCompiler implements EvaluatorCompiler { private final Class<?> backingType; private final Map<String, Type> backingTypes; private static final String CLASS = "class"; private final Set<String> writeableProperties = Sets.newHashSet(); private final Map<String, Type> egressTypes = Maps.newHashMap(); private ParserContext cachedParserContext; public MvelEvaluatorCompiler(Class<?> backingType) { this.backingType = backingType; this.backingTypes = null; } public MvelEvaluatorCompiler(Map<String, Type> backingTypes) { this.backingTypes = Collections.unmodifiableMap(backingTypes); this.backingType = null; } //memo field caches compiled expressions private final Map<String, CompiledExpression> compiled = new HashMap<String, CompiledExpression>(); public Type resolveEgressType(String expression) throws ExpressionCompileException { // try to get the type from the cache Type type = egressTypes.get(expression); if (type != null) { return type; } CompiledExpression compiled = compileExpression(expression); final Class<?> egressClass = compiled.getKnownEgressType(); final Type[] parameters = getParserContext().getLastTypeParameters(); if (parameters == null) { // the class is not parameterised (generic) type = egressClass; } else { // reconstruct the Type from mvel's generics details type = new ParameterizedTypeImpl(egressClass, parameters, egressClass.getEnclosingClass()); } egressTypes.put(expression, type); return type; } public boolean isWritable(String property) throws ExpressionCompileException { // Ensure we have introspected. Relying on sidefx, ugh. getParserContext(); return writeableProperties.contains(property); } public Evaluator compile(String expression) throws ExpressionCompileException { //do *not* inline final CompiledExpression compiled = compileExpression(expression); return new Evaluator() { @Nullable public Object evaluate(String expr, Object bean) { return MVEL.executeExpression(compiled, bean); } public void write(String expr, Object bean, Object value) { //lets use mvel to store an expression MVEL.setProperty(bean, expr, value); } public Object read(String property, Object contextObject) { return MVEL.getProperty(property, contextObject); } }; } private CompiledExpression compileExpression(String expression) throws ExpressionCompileException { final CompiledExpression compiledExpression = compiled.get(expression); //use cached copy if (null != compiledExpression) return compiledExpression; //otherwise compile expression and cache final ExpressionCompiler compiler = new ExpressionCompiler(expression, getParserContext()); CompiledExpression tempCompiled; try { tempCompiled = compiler.compile(); } catch (CompileException ce) { throw new ExpressionCompileException(expression, ce.getErrors()); } //store in memo cache compiled.put(expression, tempCompiled); return tempCompiled; } private ParserContext getParserContext() throws ExpressionCompileException { if (null != cachedParserContext) { return cachedParserContext; } return cachedParserContext = (null != backingType) ? singleBackingTypeParserContext() : backingMapParserContext(); } @SuppressWarnings({ "unchecked", "rawtypes" }) private ParserContext backingMapParserContext() { ParserContext context = new ParserContext(); context.setStrongTyping(true); context.addInputs((Map) backingTypes); return context; } public List<Token> tokenizeAndCompile(String template) throws ExpressionCompileException { return Parsing.tokenize(template, this); } //generates a parsing context with type information from the backing type's javabean properties private ParserContext singleBackingTypeParserContext() throws ExpressionCompileException { ParserContext context = new ParserContext(); context.setStrongTyping(true); context.addInput("this", backingType); PropertyDescriptor[] propertyDescriptors; try { propertyDescriptors = Introspector.getBeanInfo(backingType).getPropertyDescriptors(); } catch (IntrospectionException e) { throw new ExpressionCompileException("Could not read class " + backingType); } // read @Visible annotated fields. for (Field field : backingType.getDeclaredFields()) { if (field.isAnnotationPresent(Visible.class)) { context.addInput(field.getName(), field.getType()); if (!field.getAnnotation(Visible.class).readOnly()) { writeableProperties.add(field.getName()); } } } // read javabean properties -- these override @Visible fields. for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { // skip getClass() if (CLASS.equals(propertyDescriptor.getName())) continue; if (null != propertyDescriptor.getWriteMethod()) { writeableProperties.add(propertyDescriptor.getName()); } // if this is a collection, determine its type parameter if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) { Type propertyType; if (propertyDescriptor.getReadMethod() != null) { propertyType = propertyDescriptor.getReadMethod().getGenericReturnType(); } else { propertyType = propertyDescriptor.getWriteMethod().getGenericParameterTypes()[0]; } ParameterizedType collectionType = (ParameterizedType) Generics .getExactSuperType(propertyType, Collection.class); Class<?>[] parameterClasses = new Class[1]; Type parameterType = collectionType.getActualTypeArguments()[0]; parameterClasses[0] = Generics.erase(parameterType); context.addInput(propertyDescriptor.getName(), propertyDescriptor.getPropertyType(), parameterClasses); } else { context.addInput(propertyDescriptor.getName(), propertyDescriptor.getPropertyType()); } } return context; } }
/* * Copyright (c) 2009-2014, Peter Abeles. All Rights Reserved. * * This file is part of Efficient Java Matrix Library (EJML). * * 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.ejml.ops; import org.ejml.alg.dense.decomposition.lu.LUDecompositionAlt_D64; import org.ejml.alg.dense.linsol.lu.LinearSolverLu; import org.ejml.alg.dense.mult.CheckMatrixMultShape; import org.ejml.alg.dense.mult.MatrixMatrixMult; import org.ejml.data.DenseMatrix64F; import org.ejml.data.RowD1Matrix64F; import org.ejml.data.UtilTestMatrix; import org.junit.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Random; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Peter Abeles */ public class TestCommonOps { Random rand = new Random(0xFF); double tol = 1e-8; @Test public void checkInputShape() { CheckMatrixMultShape check = new CheckMatrixMultShape(CommonOps.class); check.checkAll(); } /** * Make sure the multiplication methods here have the same behavior as the ones in MatrixMatrixMult. */ @Test public void checkAllMatrixMults() { int numChecked = 0; Method methods[] = CommonOps.class.getMethods(); boolean oneFailed = false; for( Method method : methods ) { String name = method.getName(); // only look at function which perform matrix multiplication if( !name.contains("mult") || name.contains("Element") || name.contains("Inner") || name.contains("Outer")) continue; boolean hasAlpha = method.getGenericParameterTypes().length==4; Method checkMethod = findCheck(name,hasAlpha); boolean tranA = false; boolean tranB = false; if( name.contains("TransAB")) { tranA = true; tranB = true; } else if( name.contains("TransA")) { tranA = true; } else if( name.contains("TransB")) { tranB = true; } // System.out.println("Function = "+name+" alpha = "+hasAlpha); try { if( !checkMultMethod(method,checkMethod,hasAlpha,tranA,tranB) ) { System.out.println("Failed: Function = "+name+" alpha = "+hasAlpha); oneFailed = true; } } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } numChecked++; } assertEquals(16,numChecked); assertTrue(!oneFailed); } private Method findCheck( String name , boolean hasAlpha ) { Method checkMethod; try { if( hasAlpha ) checkMethod = MatrixMatrixMult.class.getMethod( name,double.class, RowD1Matrix64F.class, RowD1Matrix64F.class,RowD1Matrix64F.class); else checkMethod = MatrixMatrixMult.class.getMethod( name, RowD1Matrix64F.class, RowD1Matrix64F.class,RowD1Matrix64F.class); } catch (NoSuchMethodException e) { checkMethod = null; } if( checkMethod == null ) { try { if( hasAlpha ) checkMethod = MatrixMatrixMult.class.getMethod( name+"_reorder",double.class, RowD1Matrix64F.class, RowD1Matrix64F.class,RowD1Matrix64F.class); else checkMethod = MatrixMatrixMult.class.getMethod( name+"_reorder", RowD1Matrix64F.class, RowD1Matrix64F.class,RowD1Matrix64F.class); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } return checkMethod; } private boolean checkMultMethod(Method method, Method checkMethod, boolean hasAlpha, boolean tranA, boolean tranB ) throws InvocationTargetException, IllegalAccessException { // check various sizes for( int i = 1; i < 40; i++ ) { DenseMatrix64F a; if( tranA ) a = RandomMatrices.createRandom(i+1,i,rand); else a = RandomMatrices.createRandom(i,i+1,rand); DenseMatrix64F b; if( tranB ) b = RandomMatrices.createRandom(i,i+1,rand); else b = RandomMatrices.createRandom(i+1,i,rand); DenseMatrix64F c = RandomMatrices.createRandom(i,i,rand); DenseMatrix64F c_alt = c.copy(); if( hasAlpha ) { method.invoke(null,2.0,a,b,c); checkMethod.invoke(null,2.0,a,b,c_alt); } else { method.invoke(null,a,b,c); checkMethod.invoke(null,a,b,c_alt); } if( !MatrixFeatures.isIdentical(c_alt,c,tol)) return false; } // check various sizes column vector for( int i = 1; i < 4; i++ ) { DenseMatrix64F a; if( tranA ) a = RandomMatrices.createRandom(i,i+1,rand); else a = RandomMatrices.createRandom(i+1,i,rand); DenseMatrix64F b; if( tranB ) b = RandomMatrices.createRandom(1,i,rand); else b = RandomMatrices.createRandom(i,1,rand); DenseMatrix64F c = RandomMatrices.createRandom(i+1,1,rand); DenseMatrix64F c_alt = c.copy(); if( hasAlpha ) { method.invoke(null,2.0,a,b,c); checkMethod.invoke(null,2.0,a,b,c_alt); } else { method.invoke(null,a,b,c); checkMethod.invoke(null,a,b,c_alt); } if( !MatrixFeatures.isIdentical(c_alt,c,tol)) return false; } return true; } @Test public void multInner() { DenseMatrix64F a = RandomMatrices.createRandom(10,4,rand); DenseMatrix64F found = RandomMatrices.createRandom(4,4,rand); DenseMatrix64F expected = RandomMatrices.createRandom(4,4,rand); CommonOps.multTransA(a, a, expected); CommonOps.multInner(a,found); assertTrue(MatrixFeatures.isIdentical(expected,found,tol)); } @Test public void multOuter() { DenseMatrix64F a = RandomMatrices.createRandom(10,4,rand); DenseMatrix64F found = RandomMatrices.createRandom(10,10,rand); DenseMatrix64F expected = RandomMatrices.createRandom(10,10,rand); CommonOps.multTransB(a, a, expected); CommonOps.multOuter(a, found); assertTrue(MatrixFeatures.isIdentical(expected,found,tol)); } @Test public void elementMult_two() { DenseMatrix64F a = RandomMatrices.createRandom(5,4,rand); DenseMatrix64F b = RandomMatrices.createRandom(5,4,rand); DenseMatrix64F a_orig = a.copy(); CommonOps.elementMult(a,b); for( int i = 0; i < 20; i++ ) { assertEquals(a.get(i),b.get(i)*a_orig.get(i),1e-6); } } @Test public void elementMult_three() { DenseMatrix64F a = RandomMatrices.createRandom(5,4,rand); DenseMatrix64F b = RandomMatrices.createRandom(5,4,rand); DenseMatrix64F c = RandomMatrices.createRandom(5,4,rand); CommonOps.elementMult(a,b,c); for( int i = 0; i < 20; i++ ) { assertEquals(c.get(i),b.get(i)*a.get(i),1e-6); } } @Test public void elementDiv_two() { DenseMatrix64F a = RandomMatrices.createRandom(5,4,rand); DenseMatrix64F b = RandomMatrices.createRandom(5,4,rand); DenseMatrix64F a_orig = a.copy(); CommonOps.elementDiv(a,b); for( int i = 0; i < 20; i++ ) { assertEquals(a.get(i),a_orig.get(i)/b.get(i),1e-6); } } @Test public void elementDiv_three() { DenseMatrix64F a = RandomMatrices.createRandom(5,4,rand); DenseMatrix64F b = RandomMatrices.createRandom(5,4,rand); DenseMatrix64F c = RandomMatrices.createRandom(5,4,rand); CommonOps.elementDiv(a,b,c); for( int i = 0; i < 20; i++ ) { assertEquals(c.get(i),a.get(i)/b.get(i),1e-6); } } @Test public void solve() { DenseMatrix64F a = new DenseMatrix64F(2,2, true, 1, 2, 7, -3); DenseMatrix64F b = RandomMatrices.createRandom(2,5,rand); DenseMatrix64F c = RandomMatrices.createRandom(2,5,rand); DenseMatrix64F c_exp = RandomMatrices.createRandom(2,5,rand); assertTrue(CommonOps.solve(a,b,c)); LUDecompositionAlt_D64 alg = new LUDecompositionAlt_D64(); LinearSolverLu solver = new LinearSolverLu(alg); assertTrue(solver.setA(a)); solver.solve(b,c_exp); EjmlUnitTests.assertEquals(c_exp,c,1e-8); } @Test public void transpose_inplace() { DenseMatrix64F mat = new DenseMatrix64F(3,3, true, 0, 1, 2, 3, 4, 5, 6, 7, 8); DenseMatrix64F matTran = new DenseMatrix64F(3,3); CommonOps.transpose(mat,matTran); CommonOps.transpose(mat); EjmlUnitTests.assertEquals(mat,matTran,1e-8); } @Test public void transpose() { DenseMatrix64F mat = new DenseMatrix64F(3,2, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F matTran = new DenseMatrix64F(2,3); CommonOps.transpose(mat,matTran); assertEquals(mat.getNumCols(),matTran.getNumRows()); assertEquals(mat.getNumRows(),matTran.getNumCols()); for( int y = 0; y < mat.getNumRows(); y++ ){ for( int x = 0; x < mat.getNumCols(); x++ ) { assertEquals(mat.get(y,x),matTran.get(x,y),1e-6); } } } @Test public void trace() { DenseMatrix64F mat = new DenseMatrix64F(3,3, true, 0, 1, 2, 3, 4, 5, 6, 7, 8); double val = CommonOps.trace(mat); assertEquals(12,val,1e-6); } @Test public void invert() { for( int i = 1; i <= 10; i++ ) { DenseMatrix64F a = RandomMatrices.createRandom(i,i,rand); LUDecompositionAlt_D64 lu = new LUDecompositionAlt_D64(); LinearSolverLu solver = new LinearSolverLu(lu); assertTrue(solver.setA(a)); DenseMatrix64F a_inv = new DenseMatrix64F(i,i); DenseMatrix64F a_lu = new DenseMatrix64F(i,i); solver.invert(a_lu); CommonOps.invert(a,a_inv); CommonOps.invert(a); EjmlUnitTests.assertEquals(a,a_inv,1e-8); EjmlUnitTests.assertEquals(a_lu,a,1e-8); } } /** * Checked against by computing a solution to the linear system then * seeing if the solution produces the expected output */ @Test public void pinv() { // check wide matrix DenseMatrix64F A = new DenseMatrix64F(2,4,true,1,2,3,4,5,6,7,8); DenseMatrix64F A_inv = new DenseMatrix64F(4,2); DenseMatrix64F b = new DenseMatrix64F(2,1,true,3,4); DenseMatrix64F x = new DenseMatrix64F(4,1); DenseMatrix64F found = new DenseMatrix64F(2,1); CommonOps.pinv(A,A_inv); CommonOps.mult(A_inv,b,x); CommonOps.mult(A,x,found); assertTrue(MatrixFeatures.isIdentical(b,found,1e-4)); // check tall matrix CommonOps.transpose(A); CommonOps.transpose(A_inv); b = new DenseMatrix64F(4,1,true,3,4,5,6); x.reshape(2,1); found.reshape(4,1); CommonOps.mult(A_inv,b,x); CommonOps.mult(A, x, found); assertTrue(MatrixFeatures.isIdentical(b,found,1e-4)); } @Test public void columnsToVectors() { DenseMatrix64F M = RandomMatrices.createRandom(4,5,rand); DenseMatrix64F v[] = CommonOps.columnsToVector(M, null); assertEquals(M.numCols,v.length); for( int i = 0; i < v.length; i++ ) { DenseMatrix64F a = v[i]; assertEquals(M.numRows,a.numRows); assertEquals(1,a.numCols); for( int j = 0; j < M.numRows; j++ ) { assertEquals(a.get(j),M.get(j,i),1e-8); } } } @Test public void identity() { DenseMatrix64F A = CommonOps.identity(4); assertEquals(4,A.numRows); assertEquals(4,A.numCols); assertEquals(4,CommonOps.elementSum(A),1e-8); } @Test public void identity_rect() { DenseMatrix64F A = CommonOps.identity(4,6); assertEquals(4,A.numRows); assertEquals(6,A.numCols); assertEquals(4,CommonOps.elementSum(A),1e-8); } @Test public void setIdentity() { DenseMatrix64F A = RandomMatrices.createRandom(4,4,rand); CommonOps.setIdentity(A); assertEquals(4,A.numRows); assertEquals(4,A.numCols); assertEquals(4,CommonOps.elementSum(A),1e-8); } @Test public void diag() { DenseMatrix64F A = CommonOps.diag(2.0,3.0,6.0,7.0); assertEquals(4,A.numRows); assertEquals(4,A.numCols); assertEquals(2,A.get(0,0),1e-8); assertEquals(3,A.get(1,1),1e-8); assertEquals(6,A.get(2,2),1e-8); assertEquals(7,A.get(3,3),1e-8); assertEquals(18,CommonOps.elementSum(A),1e-8); } @Test public void diag_rect() { DenseMatrix64F A = CommonOps.diagR(4,6,2.0,3.0,6.0,7.0); assertEquals(4,A.numRows); assertEquals(6,A.numCols); assertEquals(2,A.get(0,0),1e-8); assertEquals(3,A.get(1,1),1e-8); assertEquals(6,A.get(2,2),1e-8); assertEquals(7,A.get(3,3),1e-8); assertEquals(18,CommonOps.elementSum(A),1e-8); } @Test public void kron() { DenseMatrix64F A = new DenseMatrix64F(2,2, true, 1, 2, 3, 4); DenseMatrix64F B = new DenseMatrix64F(1,2, true, 4, 5); DenseMatrix64F C = new DenseMatrix64F(2,4); DenseMatrix64F C_expected = new DenseMatrix64F(2,4, true, 4, 5, 8, 10, 12, 15, 16, 20); CommonOps.kron(A,B,C); assertTrue(MatrixFeatures.isIdentical(C,C_expected,1e-8)); // test various shapes for problems for( int i = 1; i <= 3; i++ ) { for( int j = 1; j <= 3; j++ ) { for( int k = 1; k <= 3; k++ ) { for( int l = 1; l <= 3; l++ ) { A = RandomMatrices.createRandom(i,j,rand); B = RandomMatrices.createRandom(k,l,rand); C = new DenseMatrix64F(A.numRows*B.numRows,A.numCols*B.numCols); CommonOps.kron(A,B,C); assertEquals(i*k,C.numRows); assertEquals(j*l,C.numCols); } } } } } @Test public void extract() { DenseMatrix64F A = RandomMatrices.createRandom(5,5, 0, 1, rand); DenseMatrix64F B = new DenseMatrix64F(2,3); CommonOps.extract(A,1,3,2,5,B,0,0); for( int i = 1; i < 3; i++ ) { for( int j = 2; j < 5; j++ ) { assertEquals(A.get(i,j),B.get(i-1,j-2),1e-8); } } } @Test public void extract_ret() { DenseMatrix64F A = RandomMatrices.createRandom(5,5, 0, 1, rand); DenseMatrix64F B = CommonOps.extract(A,1,3,2,5); assertEquals(B.numRows,2); assertEquals(B.numCols,3); for( int i = 1; i < 3; i++ ) { for( int j = 2; j < 5; j++ ) { assertEquals(A.get(i,j),B.get(i-1,j-2),1e-8); } } } @Test public void extractDiag() { DenseMatrix64F a = RandomMatrices.createRandom(3,4, 0, 1, rand); for( int i = 0; i < 3; i++ ) { a.set(i,i,i+1); } DenseMatrix64F v = new DenseMatrix64F(3,1); CommonOps.extractDiag(a,v); for( int i = 0; i < 3; i++ ) { assertEquals( i+1 , v.get(i) , 1e-8 ); } } @Test public void insert() { DenseMatrix64F A = new DenseMatrix64F(5,5); for( int i = 0; i < A.numRows; i++ ) { for( int j = 0; j < A.numCols; j++ ) { A.set(i,j,i*A.numRows+j); } } DenseMatrix64F B = new DenseMatrix64F(8,8); CommonOps.insert(A, B, 1,2); for( int i = 1; i < 6; i++ ) { for( int j = 2; j < 7; j++ ) { assertEquals(A.get(i-1,j-2),B.get(i,j),1e-8); } } } @Test public void addEquals() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F b = new DenseMatrix64F(2,3, true, 5, 4, 3, 2, 1, 0); CommonOps.addEquals(a,b); UtilTestMatrix.checkMat(a,5,5,5,5,5,5); UtilTestMatrix.checkMat(b,5,4,3,2,1,0); } @Test public void addEquals_beta() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F b = new DenseMatrix64F(2,3, true, 5, 4, 3, 2, 1, 0); CommonOps.addEquals(a,2.0,b); UtilTestMatrix.checkMat(a,10,9,8,7,6,5); UtilTestMatrix.checkMat(b,5,4,3,2,1,0); } @Test public void add() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F b = new DenseMatrix64F(2,3, true, 5, 4, 3, 2, 1, 0); DenseMatrix64F c = RandomMatrices.createRandom(2,3,rand); CommonOps.add(a,b,c); UtilTestMatrix.checkMat(a,0,1,2,3,4,5); UtilTestMatrix.checkMat(b,5,4,3,2,1,0); UtilTestMatrix.checkMat(c,5,5,5,5,5,5); } @Test public void add_beta() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F b = new DenseMatrix64F(2,3, true, 5, 4, 3, 2, 1, 0); DenseMatrix64F c = RandomMatrices.createRandom(2,3,rand); CommonOps.add(a,2.0,b,c); UtilTestMatrix.checkMat(a,0,1,2,3,4,5); UtilTestMatrix.checkMat(b,5,4,3,2,1,0); UtilTestMatrix.checkMat(c,10,9,8,7,6,5); } @Test public void add_alpha_beta() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F b = new DenseMatrix64F(2,3, true, 5, 4, 3, 2, 1, 0); DenseMatrix64F c = RandomMatrices.createRandom(2,3,rand); CommonOps.add(2.0,a,2.0,b,c); UtilTestMatrix.checkMat(a,0,1,2,3,4,5); UtilTestMatrix.checkMat(b,5,4,3,2,1,0); UtilTestMatrix.checkMat(c,10,10,10,10,10,10); } @Test public void add_alpha() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F b = new DenseMatrix64F(2,3, true, 5, 4, 3, 2, 1, 0); DenseMatrix64F c = RandomMatrices.createRandom(2,3,rand); CommonOps.add(2.0,a,b,c); UtilTestMatrix.checkMat(a,0,1,2,3,4,5); UtilTestMatrix.checkMat(b,5,4,3,2,1,0); UtilTestMatrix.checkMat(c,5,6,7,8,9,10); } @Test public void add_scalar_c() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F c = RandomMatrices.createRandom(2,3,rand); CommonOps.add(a,2.0,c); UtilTestMatrix.checkMat(a,0,1,2,3,4,5); UtilTestMatrix.checkMat(c,2,3,4,5,6,7); } @Test public void add_scalar() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); CommonOps.add(a,2.0); UtilTestMatrix.checkMat(a,2,3,4,5,6,7); } @Test public void subEquals() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F b = new DenseMatrix64F(2,3, true, 5, 5, 5, 5, 5, 5); CommonOps.subEquals(a,b); UtilTestMatrix.checkMat(a,-5,-4,-3,-2,-1,0); UtilTestMatrix.checkMat(b,5,5,5,5,5,5); } @Test public void sub() { DenseMatrix64F a = new DenseMatrix64F(2,3, true, 0, 1, 2, 3, 4, 5); DenseMatrix64F b = new DenseMatrix64F(2,3, true, 5, 5, 5, 5, 5, 5); DenseMatrix64F c = RandomMatrices.createRandom(2,3,rand); CommonOps.sub(a,b,c); UtilTestMatrix.checkMat(a,0,1,2,3,4,5); UtilTestMatrix.checkMat(b,5,5,5,5,5,5); UtilTestMatrix.checkMat(c,-5,-4,-3,-2,-1,0); } @Test public void scale() { double s = 2.5; double d[] = new double[]{10,12.5,-2,5.5}; DenseMatrix64F mat = new DenseMatrix64F(2,2, true, d); CommonOps.scale(s,mat); assertEquals(d[0]*s,mat.get(0,0),1e-8); assertEquals(d[1]*s,mat.get(0,1),1e-8); assertEquals(d[2]*s,mat.get(1,0),1e-8); assertEquals(d[3]*s,mat.get(1,1),1e-8); } @Test public void scale_two_input() { double s = 2.5; double d[] = new double[]{10,12.5,-2,5.5}; DenseMatrix64F mat = new DenseMatrix64F(2,2, true, d); DenseMatrix64F r = new DenseMatrix64F(2,2, true, d); CommonOps.scale(s,mat,r); assertEquals(d[0],mat.get(0,0),1e-8); assertEquals(d[1],mat.get(0,1),1e-8); assertEquals(d[2],mat.get(1,0),1e-8); assertEquals(d[3],mat.get(1,1),1e-8); assertEquals(d[0]*s,r.get(0,0),1e-8); assertEquals(d[1]*s,r.get(0,1),1e-8); assertEquals(d[2]*s,r.get(1,0),1e-8); assertEquals(d[3]*s,r.get(1,1),1e-8); } @Test public void div() { double s = 2.5; double d[] = new double[]{10,12.5,-2,5.5}; DenseMatrix64F mat = new DenseMatrix64F(2,2, true, d); CommonOps.divide(s,mat); assertEquals(d[0]/s,mat.get(0,0),1e-8); assertEquals(d[1]/s,mat.get(0,1),1e-8); assertEquals(d[2]/s,mat.get(1,0),1e-8); assertEquals(d[3]/s,mat.get(1,1),1e-8); } @Test public void div_two_input() { double s = 2.5; double d[] = new double[]{10,12.5,-2,5.5}; DenseMatrix64F mat = new DenseMatrix64F(2,2, true, d); DenseMatrix64F r = new DenseMatrix64F(2,2, true, d); CommonOps.divide(s,mat,r); assertEquals(d[0],mat.get(0,0),1e-8); assertEquals(d[1],mat.get(0,1),1e-8); assertEquals(d[2],mat.get(1,0),1e-8); assertEquals(d[3],mat.get(1,1),1e-8); assertEquals(d[0]/s,r.get(0,0),1e-8); assertEquals(d[1]/s,r.get(0,1),1e-8); assertEquals(d[2]/s,r.get(1,0),1e-8); assertEquals(d[3]/s,r.get(1,1),1e-8); } @Test public void fill() { double d[] = new double[]{10,12.5,-2,5.5}; DenseMatrix64F mat = new DenseMatrix64F(2,2, true, d); CommonOps.fill(mat, 1); for( int i = 0; i < mat.getNumElements(); i++ ) { assertEquals(1,mat.get(i),1e-8); } } @Test public void zero() { double d[] = new double[]{10,12.5,-2,5.5}; DenseMatrix64F mat = new DenseMatrix64F(2,2, true, d); mat.zero(); for( int i = 0; i < mat.getNumElements(); i++ ) { assertEquals(0,mat.get(i),1e-8); } } @Test public void elementMax() { DenseMatrix64F mat = new DenseMatrix64F(3,3, true, 0, 1, -2, 3, 4, 5, 6, 7, -8); double m = CommonOps.elementMax(mat); assertEquals(7,m,1e-8); } @Test public void elementMin() { DenseMatrix64F mat = new DenseMatrix64F(3,3, true, 0, 1, 2, -3, 4, 5, 6, 7, 8); double m = CommonOps.elementMin(mat); assertEquals(-3,m,1e-8); } @Test public void elementMinAbs() { DenseMatrix64F mat = new DenseMatrix64F(3,3, true, 0, 1, -2, 3, 4, 5, 6, 7, -8); double m = CommonOps.elementMinAbs(mat); assertEquals(0,m,1e-8); } @Test public void elementMaxAbs() { DenseMatrix64F mat = new DenseMatrix64F(3,3, true, 0, 1, 2, 3, 4, 5, -6, 7, -8); double m = CommonOps.elementMaxAbs(mat); assertEquals(8,m,1e-8); } @Test public void elementSum() { DenseMatrix64F M = RandomMatrices.createRandom(5,5,rand); // make it smaller than the original size to make sure it is bounding // the summation correctly M.reshape(4,3, false); double sum = 0; for( int i = 0; i < M.numRows; i++ ) { for( int j = 0; j < M.numCols; j++ ) { sum += M.get(i,j); } } assertEquals(sum,CommonOps.elementSum(M),1e-8); } @Test public void elementSumAbs() { DenseMatrix64F M = RandomMatrices.createRandom(5,5,rand); // make it smaller than the original size to make sure it is bounding // the summation correctly M.reshape(4,3, false); double sum = 0; for( int i = 0; i < M.numRows; i++ ) { for( int j = 0; j < M.numCols; j++ ) { sum += Math.abs(M.get(i,j)); } } assertEquals(sum,CommonOps.elementSum(M),1e-8); } @Test public void sumRows() { DenseMatrix64F input = RandomMatrices.createRandom(4,5,rand); DenseMatrix64F output = new DenseMatrix64F(4,1); assertTrue( output == CommonOps.sumRows(input,output)); for( int i = 0; i < input.numRows; i++ ) { double total = 0; for( int j = 0; j < input.numCols; j++ ) { total += input.get(i,j); } assertEquals( total, output.get(i),1e-8); } // check with a null output DenseMatrix64F output2 = CommonOps.sumRows(input,null); EjmlUnitTests.assertEquals(output,output2,1e-8); } @Test public void sumCols() { DenseMatrix64F input = RandomMatrices.createRandom(4,5,rand); DenseMatrix64F output = new DenseMatrix64F(1,5); assertTrue( output == CommonOps.sumCols(input,output)); for( int i = 0; i < input.numCols; i++ ) { double total = 0; for( int j = 0; j < input.numRows; j++ ) { total += input.get(j,i); } assertEquals( total, output.get(i),1e-8); } // check with a null output DenseMatrix64F output2 = CommonOps.sumCols(input,null); EjmlUnitTests.assertEquals(output,output2,1e-8); } @Test public void rref() { DenseMatrix64F A = new DenseMatrix64F(4,6,true, 0,0,1,-1,-1,4, 2,4,2,4,2,4, 2,4,3,3,3,4, 3,6,6,3,6,6); DenseMatrix64F expected = new DenseMatrix64F(4,6,true, 1,2,0,3,0,2, 0,0,1,-1,0,2, 0,0,0,0,1,-2, 0,0,0,0,0,0); DenseMatrix64F found = CommonOps.rref(A,5, null); assertTrue(MatrixFeatures.isEquals(found,expected)); } }
package sexy.code; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class CallTest { public static final MediaType MEDIA_TYPE_PLAIN_TEXT = MediaType.parse("text/plain; charset=utf-8"); private CallTestCase getTestCase = new CallTestCase() { @Override protected Request prepareRequest(HttpUrl url) throws Exception { MockResponse mockResponse = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) .setBody("body") .addHeader("Content-Type: text/plain"); server.enqueue(mockResponse); return client.newRequest() .url(url) .header("User-Agent", "UnitTest") .get() .build(); } @Override protected void verifyRequest(HttpUrl url, RecordedRequest recordedRequest) throws Exception { assertEquals("GET", recordedRequest.getMethod()); assertEquals(urlPathWithQuery(url), recordedRequest.getPath()); assertEquals(0, recordedRequest.getBody().size()); assertEquals("UnitTest", recordedRequest.getHeader("User-Agent")); assertNull(recordedRequest.getHeader("Content-Length")); } @Override protected void verifyResponse(HttpUrl url, Response response) throws Exception { assertEquals(200, response.code()); assertEquals("text/plain", response.headers().get("Content-Type").get(0)); assertEquals("body", response.body().string()); assertTrue(response.isSuccessful()); } }; @Test public void get() throws Exception { getTestCase.test("/path?query1=1&query2=2"); getTestCase.testAsync("/path?query1=1&query2=2"); } private CallTestCase postTestCase = new CallTestCase() { @Override protected Request prepareRequest(HttpUrl url) throws Exception { MockResponse mockResponse = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) .setBody("body") .addHeader("Content-Type: text/plain"); server.enqueue(mockResponse); return client.newRequest() .url(url) .header("User-Agent", "UnitTest") .post(RequestBody.create(MEDIA_TYPE_PLAIN_TEXT, "requestBody")) .build(); } @Override protected void verifyRequest(HttpUrl url, RecordedRequest recordedRequest) throws Exception { assertEquals("POST", recordedRequest.getMethod()); assertEquals(urlPathWithQuery(url), recordedRequest.getPath()); assertEquals(11, recordedRequest.getBody().size()); assertEquals("11", recordedRequest.getHeader("Content-Length")); assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); assertEquals("UnitTest", recordedRequest.getHeader("User-Agent")); } @Override protected void verifyResponse(HttpUrl url, Response response) throws Exception { assertEquals(200, response.code()); assertEquals("text/plain", response.headers().get("Content-Type").get(0)); assertEquals("body", response.body().string()); assertTrue(response.isSuccessful()); } }; @Test public void post() throws Exception { postTestCase.test("/path?query1=1&query2=2"); postTestCase.testAsync("/path?query1=1&query2=2"); } private CallTestCase zeroLengthPostTestCase = new CallTestCase() { @Override protected Request prepareRequest(HttpUrl url) throws Exception { MockResponse mockResponse = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) .setBody("body") .addHeader("Content-Type: text/plain"); server.enqueue(mockResponse); return client.newRequest() .url(url) .header("User-Agent", "UnitTest") .post(RequestBody.create(MEDIA_TYPE_PLAIN_TEXT, "")) .build(); } @Override protected void verifyRequest(HttpUrl url, RecordedRequest recordedRequest) throws Exception { assertEquals("POST", recordedRequest.getMethod()); assertEquals(urlPathWithQuery(url), recordedRequest.getPath()); assertEquals(0, recordedRequest.getBody().size()); assertEquals(null, recordedRequest.getHeader("Content-Length")); assertEquals("UnitTest", recordedRequest.getHeader("User-Agent")); } @Override protected void verifyResponse(HttpUrl url, Response response) throws Exception { assertEquals(200, response.code()); assertEquals("text/plain", response.headers().get("Content-Type").get(0)); assertEquals("body", response.body().string()); assertTrue(response.isSuccessful()); } }; @Test public void postZeroLength() throws Exception { zeroLengthPostTestCase.test("/path?query1=1&query2=2"); zeroLengthPostTestCase.testAsync("/path?query1=1&query2=2"); } private CallTestCase putTestCase = new CallTestCase() { @Override protected Request prepareRequest(HttpUrl url) throws Exception { MockResponse mockResponse = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) .setBody("body") .addHeader("Content-Type: text/plain"); server.enqueue(mockResponse); return client.newRequest() .url(url) .header("User-Agent", "UnitTest") .put(RequestBody.create(MEDIA_TYPE_PLAIN_TEXT, "requestBody")) .build(); } @Override protected void verifyRequest(HttpUrl url, RecordedRequest recordedRequest) throws Exception { assertEquals("PUT", recordedRequest.getMethod()); assertEquals(urlPathWithQuery(url), recordedRequest.getPath()); assertEquals(11, recordedRequest.getBody().size()); assertEquals("11", recordedRequest.getHeader("Content-Length")); assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); assertEquals("UnitTest", recordedRequest.getHeader("User-Agent")); } @Override protected void verifyResponse(HttpUrl url, Response response) throws Exception { assertEquals(200, response.code()); assertEquals("text/plain", response.headers().get("Content-Type").get(0)); assertEquals("body", response.body().string()); assertTrue(response.isSuccessful()); } }; @Test public void put() throws Exception { putTestCase.test("/path?query1=1&query2=2"); putTestCase.testAsync("/path?query1=1&query2=2"); } private CallTestCase deleteTestCase = new CallTestCase() { @Override protected Request prepareRequest(HttpUrl url) throws Exception { MockResponse mockResponse = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) .setBody("body") .addHeader("Content-Type: text/plain"); server.enqueue(mockResponse); return client.newRequest() .url(url) .header("User-Agent", "UnitTest") .delete() .build(); } @Override protected void verifyRequest(HttpUrl url, RecordedRequest recordedRequest) throws Exception { assertEquals("DELETE", recordedRequest.getMethod()); assertEquals(urlPathWithQuery(url), recordedRequest.getPath()); assertEquals(0, recordedRequest.getBody().size()); assertEquals(null, recordedRequest.getHeader("Content-Length")); assertNull(recordedRequest.getHeader("Content-Type")); assertEquals("UnitTest", recordedRequest.getHeader("User-Agent")); } @Override protected void verifyResponse(HttpUrl url, Response response) throws Exception { assertEquals(200, response.code()); assertEquals("text/plain", response.headers().get("Content-Type").get(0)); assertEquals("body", response.body().string()); assertTrue(response.isSuccessful()); } }; @Test public void delete() throws Exception { deleteTestCase.test("/path?query1=1&query2=2"); deleteTestCase.testAsync("/path?query1=1&query2=2"); } private CallTestCase headTestCase = new CallTestCase() { @Override protected Request prepareRequest(HttpUrl url) throws Exception { MockResponse mockResponse = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) .addHeader("Content-Type: text/plain"); server.enqueue(mockResponse); return client.newRequest() .url(url) .header("User-Agent", "UnitTest") .method("HEAD", null) .build(); } @Override protected void verifyRequest(HttpUrl url, RecordedRequest recordedRequest) throws Exception { assertEquals("HEAD", recordedRequest.getMethod()); assertEquals(urlPathWithQuery(url), recordedRequest.getPath()); assertEquals(0, recordedRequest.getBody().size()); assertEquals(null, recordedRequest.getHeader("Content-Length")); assertNull(recordedRequest.getHeader("Content-Type")); assertEquals("UnitTest", recordedRequest.getHeader("User-Agent")); } @Override protected void verifyResponse(HttpUrl url, Response response) throws Exception { assertEquals(200, response.code()); assertEquals("text/plain", response.headers().get("Content-Type").get(0)); assertTrue(response.isSuccessful()); } }; @Test public void head() throws Exception { headTestCase.test("/path?query1=1&query2=2"); headTestCase.testAsync("/path?query1=1&query2=2"); } }
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.get; import com.google.common.collect.ImmutableMap; import org.elasticsearch.ElasticSearchParseException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.compress.BasicCompressorFactory; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilderString; import org.elasticsearch.common.xcontent.XContentHelper; import java.io.IOException; import java.util.Iterator; import java.util.Map; import static com.google.common.collect.Iterators.emptyIterator; import static com.google.common.collect.Maps.newHashMapWithExpectedSize; import static org.elasticsearch.index.get.GetField.readGetField; /** */ public class GetResult implements Streamable, Iterable<GetField>, ToXContent { private String index; private String type; private String id; private long version; private boolean exists; private Map<String, GetField> fields; private BytesReference source; private byte[] sourceAsBytes; GetResult() { } public GetResult(String index, String type, String id, long version, boolean exists, BytesReference source, Map<String, GetField> fields) { this.index = index; this.type = type; this.id = id; this.version = version; this.exists = exists; this.source = source; this.fields = fields; if (this.fields == null) { this.fields = ImmutableMap.of(); } } /** * Does the document exists. */ public boolean exists() { return exists; } /** * Does the document exists. */ public boolean isExists() { return exists; } /** * The index the document was fetched from. */ public String index() { return this.index; } /** * The index the document was fetched from. */ public String getIndex() { return index; } /** * The type of the document. */ public String type() { return type; } /** * The type of the document. */ public String getType() { return type; } /** * The id of the document. */ public String id() { return id; } /** * The id of the document. */ public String getId() { return id; } /** * The version of the doc. */ public long version() { return this.version; } /** * The version of the doc. */ public long getVersion() { return this.version; } /** * The source of the document if exists. */ public byte[] source() { if (source == null) { return null; } if (sourceAsBytes != null) { return sourceAsBytes; } this.sourceAsBytes = sourceRef().toBytes(); return this.sourceAsBytes; } /** * Returns bytes reference, also un compress the source if needed. */ public BytesReference sourceRef() { try { this.source = BasicCompressorFactory.uncompressIfNeeded(this.source); return this.source; } catch (IOException e) { throw new ElasticSearchParseException("failed to decompress source", e); } } /** * Internal source representation, might be compressed.... */ public BytesReference internalSourceRef() { return source; } /** * Is the source empty (not available) or not. */ public boolean isSourceEmpty() { return source == null; } /** * The source of the document (as a string). */ public String sourceAsString() { if (source == null) { return null; } BytesReference source = sourceRef(); try { return XContentHelper.convertToJson(source, false); } catch (IOException e) { throw new ElasticSearchParseException("failed to convert source to a json string"); } } public Map<String, GetField> fields() { return this.fields; } public Map<String, GetField> getFields() { return fields; } public GetField field(String name) { return fields.get(name); } public Iterator<GetField> iterator() { if (fields == null) { return emptyIterator(); } return fields.values().iterator(); } static final class Fields { static final XContentBuilderString _INDEX = new XContentBuilderString("_index"); static final XContentBuilderString _TYPE = new XContentBuilderString("_type"); static final XContentBuilderString _ID = new XContentBuilderString("_id"); static final XContentBuilderString _VERSION = new XContentBuilderString("_version"); static final XContentBuilderString EXISTS = new XContentBuilderString("exists"); static final XContentBuilderString FIELDS = new XContentBuilderString("fields"); } public XContentBuilder toXContentEmbedded(XContentBuilder builder, Params params) throws IOException { builder.field(Fields.EXISTS, exists); /*if (source != null) { RestXContentBuilder.restDocumentSource(source, builder, params); }*/ if (fields != null && !fields.isEmpty()) { builder.startObject(Fields.FIELDS); for (GetField field : fields.values()) { if (field.values().isEmpty()) { continue; } if (field.values().size() == 1) { builder.field(field.name(), field.values().get(0)); } else { builder.field(field.name()); builder.startArray(); for (Object value : field.values()) { builder.value(value); } builder.endArray(); } } builder.endObject(); } return builder; } public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (!exists()) { builder.startObject(); builder.field(Fields._INDEX, index); builder.field(Fields._TYPE, type); builder.field(Fields._ID, id); builder.field(Fields.EXISTS, false); builder.endObject(); } else { builder.startObject(); builder.field(Fields._INDEX, index); builder.field(Fields._TYPE, type); builder.field(Fields._ID, id); if (version != -1) { builder.field(Fields._VERSION, version); } toXContentEmbedded(builder, params); builder.endObject(); } return builder; } public static GetResult readGetResult(StreamInput in) throws IOException { GetResult result = new GetResult(); result.readFrom(in); return result; } public void readFrom(StreamInput in) throws IOException { index = in.readUTF(); type = in.readOptionalUTF(); id = in.readUTF(); version = in.readLong(); exists = in.readBoolean(); if (exists) { source = in.readBytesReference(); if (source.length() == 0) { source = null; } int size = in.readVInt(); if (size == 0) { fields = ImmutableMap.of(); } else { fields = newHashMapWithExpectedSize(size); for (int i = 0; i < size; i++) { GetField field = readGetField(in); fields.put(field.name(), field); } } } } public void writeTo(StreamOutput out) throws IOException { out.writeUTF(index); out.writeOptionalUTF(type); out.writeUTF(id); out.writeLong(version); out.writeBoolean(exists); if (exists) { out.writeBytesReference(source); if (fields == null) { out.writeVInt(0); } else { out.writeVInt(fields.size()); for (GetField field : fields.values()) { field.writeTo(out); } } } } }
/* * Copyright 1997-2011 teatrove.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teatrove.trove.util; import org.teatrove.trove.io.SourceInfo; import org.teatrove.trove.io.SourceReader; import java.io.IOException; import java.io.Reader; import java.util.Map; import java.util.Stack; import java.util.Vector; /** * Parses a properties file similar to how {@link java.util.Properties} does, * except: * * <ul> * <li>Values have trailing whitespace trimmed. * <li>Quotation marks ( " or ' ) can be used to define keys and values that * have embedded spaces. * <li>Quotation marks can also be used to define multi-line keys and values * without having to use continuation characters. * <li>Properties may be nested using braces '{' and '}'. * </ul> * * Just like Properties, comment lines start with optional whitespace followed * by a '#' or '!'. Keys and values may have an optional '=' or ':' as a * separator, unicode escapes are supported as well as other common escapes. * A line may end in a backslash so that it continues to the next line. * Escapes for brace characters '{' and '}' are also supported. * * Example: * * <pre> * # Properties file * * foo = bar * foo.sub = blink * empty * * block { * inner { * foo = bar * item * } * next.item = "true" * } * * section = test { * level = 4 * message = "Message: " * } * </pre> * * is equivalent to * * <pre> * # Properties file * * foo = bar * foo.sub = blink * empty * * block.inner.foo = bar * block.inner.item * block.next.item = true * * section = test * section.level = 4 * section.message = Message: * </pre> * * @author Brian S O'Neill */ public class PropertyParser { // Parsed grammer (EBNF) is: // // Properties ::= { PropertyList } // PropertyList ::= { Property | COMMENT } // Property ::= KEY [ VALUE ] [ Block ] // Block ::= LBRACE PropertyList RBRACE private Map mMap; private Vector mPropertyListeners = new Vector(64); private Vector mErrorListeners = new Vector(1); private int mErrorCount = 0; private Scanner mScanner; /** * @param map Map to receive properties */ public PropertyParser(Map map) { mMap = map; } public void addPropertyChangeListener(PropertyChangeListener listener) { mPropertyListeners.addElement(listener); } public void removePropertyChangeListener(PropertyChangeListener listener){ mPropertyListeners.removeElement(listener); } private void dispatchPropertyChange(PropertyChangeEvent e) { synchronized (mPropertyListeners) { for (int i= 0; i<mPropertyListeners.size(); i++) { ((PropertyChangeListener)mPropertyListeners.elementAt(i)). propertyChanged(e); } } } private void propertyChange(String key, String value, SourceInfo info) { dispatchPropertyChange(new PropertyChangeEvent(this, key, value, info)); } public void addErrorListener(ErrorListener listener) { mErrorListeners.addElement(listener); } public void removeErrorListener(ErrorListener listener) { mErrorListeners.removeElement(listener); } private void dispatchParseError(ErrorEvent e) { mErrorCount++; synchronized (mErrorListeners) { for (int i = 0; i < mErrorListeners.size(); i++) { ((ErrorListener)mErrorListeners.elementAt(i)).parseError(e); } } } private void error(String str, SourceInfo info) { dispatchParseError(new ErrorEvent(this, str, info)); } private void error(String str, Token token) { error(str, token.getSourceInfo()); } /** * Parses properties from the given reader and stores them in the Map. To * capture any parsing errors, call addErrorListener prior to parsing. */ public void parse(Reader reader) throws IOException { mScanner = new Scanner(reader); mScanner.addErrorListener(new ErrorListener() { public void parseError(ErrorEvent e) { dispatchParseError(e); } }); try { parseProperties(); } finally { mScanner.close(); } } private void parseProperties() throws IOException { Token token; while ((token = peek()).getId() != Token.EOF) { switch (token.getId()) { case Token.KEY: case Token.LBRACE: case Token.COMMENT: parsePropertyList(null); break; case Token.RBRACE: token = read(); error("No matching left brace", token); break; default: token = read(); error("Unexpected token: " + token.getValue(), token); break; } } } private void parsePropertyList(String keyPrefix) throws IOException { Token token; loop: while ((token = peek()).getId() != Token.EOF) { switch (token.getId()) { case Token.KEY: token = read(); parseProperty(keyPrefix, token); break; case Token.COMMENT: read(); break; case Token.LBRACE: read(); error("Nested properties must have a base name", token); parseBlock(keyPrefix); break; default: break loop; } } } private void parseProperty(String keyPrefix, Token token) throws IOException { String key = token.getValue(); if (keyPrefix != null) { key = keyPrefix + key; } String value = null; if (peek().getId() == Token.VALUE) { token = read(); value = token.getValue(); } if (peek().getId() == Token.LBRACE) { read(); parseBlock(key + '.'); } else if (value == null) { value = ""; } if (value != null) { putProperty(key, value, token); propertyChange(key, value, token.getSourceInfo()); } } // When this is called, the LBRACE token has already been read. private void parseBlock(String keyPrefix) throws IOException { parsePropertyList(keyPrefix); Token token; if ((token = peek()).getId() == Token.RBRACE) { read(); } else { error("Right brace expected", token); } } private void putProperty(String key, String value, Token token) { if (mMap.containsKey(key)) { error("Property \"" + key + "\" already defined", token); } mMap.put(key, value); } /** * Total number of errors accumulated by this PropertyParser instance. */ public int getErrorCount() { return mErrorCount; } private Token read() throws IOException { return mScanner.readToken(); } private Token peek() throws IOException { return mScanner.peekToken(); } /** * * @author Brian S O'Neill * @version */ public static interface ErrorListener extends java.util.EventListener { public void parseError(ErrorEvent e); } /** * * @author Brian S O'Neill * @version */ public static class ErrorEvent extends java.util.EventObject { private String mErrorMsg; private SourceInfo mInfo; ErrorEvent(Object source, String errorMsg, SourceInfo info) { super(source); mErrorMsg = errorMsg; mInfo = info; } public String getErrorMessage() { return mErrorMsg; } /** * Returns the error message prepended with source file information. */ public String getDetailedErrorMessage() { String prepend = getSourceInfoMessage(); if (prepend == null || prepend.length() == 0) { return mErrorMsg; } else { return prepend + ": " + mErrorMsg; } } public String getSourceInfoMessage() { if (mInfo == null) { return ""; } else { return String.valueOf(mInfo.getLine()); } } /** * This method reports on where in the source code an error was found. * * @return Source information on this error or null if not known. */ public SourceInfo getSourceInfo() { return mInfo; } } /** * * @author Brian S O'Neill * @version */ private static class Token implements java.io.Serializable { public final static int UNKNOWN = 0; public final static int EOF = 1; public final static int COMMENT = 2; public final static int KEY = 3; public final static int VALUE = 4; public final static int LBRACE = 5; public final static int RBRACE = 6; private final static int LAST_ID = 6; private int mTokenId; private String mValue; private SourceInfo mInfo; Token(int sourceLine, int sourceStartPos, int sourceEndPos, int tokenId, String value) { mTokenId = tokenId; mValue = value; if (tokenId > LAST_ID) { throw new IllegalArgumentException("Token Id out of range: " + tokenId); } mInfo = new SourceInfo(sourceLine, sourceStartPos, sourceEndPos); if (sourceStartPos > sourceEndPos) { // This is an internal error. throw new IllegalArgumentException ("Token start position greater than " + "end position at line: " + sourceLine); } } public Token(SourceInfo info, int tokenId, String value) { mTokenId = tokenId; if (tokenId > LAST_ID) { throw new IllegalArgumentException("Token Id out of range: " + tokenId); } mInfo = info; } public final int getId() { return mTokenId; } /** * Token code is non-null, and is exactly the same as the name for * its Id. */ public String getCode() { return Code.TOKEN_CODES[mTokenId]; } public final SourceInfo getSourceInfo() { return mInfo; } public String getValue() { return mValue; } public String toString() { StringBuffer buf = new StringBuffer(10); String image = getCode(); if (image != null) { buf.append(image); } String str = getValue(); if (str != null) { if (image != null) { buf.append(' '); } buf.append('"'); buf.append(str); buf.append('"'); } return buf.toString(); } private static class Code { public static final String[] TOKEN_CODES = { "UNKNOWN", "EOF", "COMMENT", "KEY", "VALUE", "LBRACE", "RBRACE", }; } } /** * * @author Brian S O'Neill * @version */ private static class Scanner { private SourceReader mSource; /** The scanner supports any amount of lookahead. */ private Stack mLookahead = new Stack(); private boolean mScanKey = true; private Token mEOFToken; private Vector mListeners = new Vector(1); private int mErrorCount = 0; public Scanner(Reader in) { mSource = new SourceReader(in, null, null); } public void addErrorListener(ErrorListener listener) { mListeners.addElement(listener); } public void removeErrorListener(ErrorListener listener) { mListeners.removeElement(listener); } private void dispatchParseError(ErrorEvent e) { mErrorCount++; synchronized (mListeners) { for (int i = 0; i < mListeners.size(); i++) { ((ErrorListener)mListeners.elementAt(i)).parseError(e); } } } private void error(String str, SourceInfo info) { dispatchParseError(new ErrorEvent(this, str, info)); } private void error(String str) { error(str, new SourceInfo(mSource.getLineNumber(), mSource.getStartPosition(), mSource.getEndPosition())); } /** * Returns EOF as the last token. */ public synchronized Token readToken() throws IOException { if (mLookahead.empty()) { return scanToken(); } else { return (Token)mLookahead.pop(); } } /** * Returns EOF as the last token. */ public synchronized Token peekToken() throws IOException { if (mLookahead.empty()) { return (Token)mLookahead.push(scanToken()); } else { return (Token)mLookahead.peek(); } } public synchronized void unreadToken(Token token) throws IOException { mLookahead.push(token); } public void close() throws IOException { mSource.close(); } public int getErrorCount() { return mErrorCount; } private Token scanToken() throws IOException { if (mSource.isClosed()) { if (mEOFToken == null) { mEOFToken = makeToken(Token.EOF, null); } return mEOFToken; } int c; while ( (c = mSource.read()) != -1 ) { switch (c) { case SourceReader.ENTER_CODE: case SourceReader.ENTER_TEXT: continue; case '#': case '!': mScanKey = true; return scanComment(); case '{': mScanKey = true; return makeToken(Token.LBRACE, "{"); case '}': mScanKey = true; return makeToken(Token.RBRACE, "}"); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '.': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': mSource.unread(); return scanKeyOrValue(); case '\n': mScanKey = true; // fall through case ' ': case '\0': case '\t': continue; default: if (Character.isWhitespace((char)c)) { continue; } else { mSource.unread(); return scanKeyOrValue(); } } } if (mEOFToken == null) { mEOFToken = makeToken(Token.EOF, null); } return mEOFToken; } private Token scanKeyOrValue() throws IOException { StringBuffer buf = new StringBuffer(40); boolean trim = true; int startLine = mSource.getLineNumber(); int startPos = mSource.getStartPosition(); int endPos = mSource.getEndPosition(); boolean skipWhitespace = true; boolean skipSeparator = true; int c; loop: while ( (c = mSource.read()) != -1 ) { switch (c) { case '\n': mSource.unread(); break loop; case '\\': int next = mSource.read(); if (next == -1 || next == '\n') { // line continuation skipWhitespace = true; continue; } c = processEscape(c, next); skipWhitespace = false; break; case '{': case '}': mSource.unread(); break loop; case '=': case ':': if (mScanKey) { mSource.unread(); break loop; } else if (skipSeparator) { skipSeparator = false; continue; } skipWhitespace = false; break; case '\'': case '"': if (buf.length() == 0) { scanStringLiteral(c, buf); endPos = mSource.getEndPosition(); trim = false; break loop; } // fall through case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '.': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': skipWhitespace = false; break; case ' ': case '\0': case '\t': if (skipWhitespace) { continue; } if (mScanKey) { break loop; } break; default: if (Character.isWhitespace((char)c)) { if (skipWhitespace) { continue; } if (mScanKey) { break loop; } } else { skipWhitespace = false; } break; } buf.append((char)c); endPos = mSource.getEndPosition(); skipSeparator = false; } int tokenId; if (mScanKey) { tokenId = Token.KEY; mScanKey = false; } else { tokenId = Token.VALUE; mScanKey = true; } String value = buf.toString(); if (trim) { value = value.trim(); } return new Token(startLine, startPos, endPos, tokenId, value); } private Token scanComment() throws IOException { StringBuffer buf = new StringBuffer(40); int startLine = mSource.getLineNumber(); int startPos = mSource.getStartPosition(); int endPos = mSource.getEndPosition(); int c; while ( (c = mSource.peek()) != -1 ) { if (c == '\n') { break; } mSource.read(); buf.append((char)c); endPos = mSource.getEndPosition(); } return new Token(startLine, startPos, endPos, Token.COMMENT, buf.toString()); } private void scanStringLiteral(int quote, StringBuffer buf) throws IOException { int c; while ( (c = mSource.read()) != -1 ) { if (c == quote) { return; } if (c == '\\') { int next = mSource.read(); if (next == -1 || next == '\n') { // line continuation continue; } c = processEscape(c, next); } buf.append((char)c); } } private int processEscape(int c, int next) { switch (next) { case '0': return '\0'; case 't': return '\t'; case 'n': return '\n'; case 'f': return '\f'; case 'r': return '\r'; case '\\': case '\'': case '\"': case '=': case ':': case '{': case '}': return next; default: error("Invalid escape code: \\" + (char)next); return next; } } private Token makeToken(int Id, String value) { return new Token(mSource.getLineNumber(), mSource.getStartPosition(), mSource.getEndPosition(), Id, value); } } }
/* * 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.unscramble; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.configurable.VcsContentAnnotationConfigurable; import com.intellij.ui.GuiUtils; import com.intellij.ui.ListCellRendererWrapper; import com.intellij.ui.TextFieldWithHistory; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import static com.intellij.util.containers.ContainerUtil.ar; /** * @author cdr */ public class UnscrambleDialog extends DialogWrapper { @NonNls private static final String PROPERTY_LOG_FILE_HISTORY_URLS = "UNSCRAMBLE_LOG_FILE_URL"; @NonNls private static final String PROPERTY_LOG_FILE_LAST_URL = "UNSCRAMBLE_LOG_FILE_LAST_URL"; @NonNls private static final String PROPERTY_UNSCRAMBLER_NAME_USED = "UNSCRAMBLER_NAME_USED"; private static final Condition<ThreadState> DEADLOCK_CONDITION = state -> state.isDeadlocked(); private static final String[] IMPORTANT_THREAD_DUMP_WORDS = ar("tid", "nid", "wait", "parking", "prio", "os_prio", "java"); private final Project myProject; private JPanel myEditorPanel; private JPanel myLogFileChooserPanel; private JComboBox myUnscrambleChooser; private JPanel myPanel; private TextFieldWithHistory myLogFile; private JCheckBox myUseUnscrambler; private JPanel myUnscramblePanel; private JCheckBox myOnTheFly; private JPanel myBottomPanel; private JPanel mySettingsPanel; protected AnalyzeStacktraceUtil.StacktraceEditorPanel myStacktraceEditorPanel; private VcsContentAnnotationConfigurable myConfigurable; public UnscrambleDialog(@NotNull Project project) { super(false); myProject = project; populateRegisteredUnscramblerList(); myUnscrambleChooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { UnscrambleSupport unscrambleSupport = getSelectedUnscrambler(); GuiUtils.enableChildren(myLogFileChooserPanel, unscrambleSupport != null); updateUnscramblerSettings(); } }); myUseUnscrambler.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { useUnscramblerChanged(); } }); myOnTheFly.setSelected(Registry.get("analyze.exceptions.on.the.fly").asBoolean()); myOnTheFly.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Registry.get("analyze.exceptions.on.the.fly").setValue(myOnTheFly.isSelected()); } }); createLogFileChooser(); createEditor(); reset(); setTitle(IdeBundle.message("unscramble.dialog.title")); init(); } private void useUnscramblerChanged() { boolean selected = myUseUnscrambler.isSelected(); GuiUtils.enableChildren(myUnscramblePanel, selected, myUseUnscrambler); if (selected) { updateUnscramblerSettings(); } } private void updateUnscramblerSettings() { UnscrambleSupport unscrambleSupport = (UnscrambleSupport)myUnscrambleChooser.getSelectedItem(); JComponent settingsComponent = unscrambleSupport == null ? null : unscrambleSupport.createSettingsComponent(); mySettingsPanel.removeAll(); if (settingsComponent != null) { mySettingsPanel.add(settingsComponent, BorderLayout.CENTER); } myUnscramblePanel.validate(); } private void reset() { final List<String> savedUrls = getSavedLogFileUrls(); myLogFile.setHistorySize(10); myLogFile.setHistory(savedUrls); String lastUrl = getPropertyValue(PROPERTY_LOG_FILE_LAST_URL); if (lastUrl == null && !savedUrls.isEmpty()) { lastUrl = savedUrls.get(savedUrls.size() - 1); } if (lastUrl != null) { myLogFile.setText(lastUrl); myLogFile.setSelectedItem(lastUrl); } final UnscrambleSupport selectedUnscrambler = getSavedUnscrambler(); final int count = myUnscrambleChooser.getItemCount(); int index = 0; if (selectedUnscrambler != null) { for (int i = 0; i < count; i++) { final UnscrambleSupport unscrambleSupport = (UnscrambleSupport)myUnscrambleChooser.getItemAt(i); if (unscrambleSupport != null && Comparing.strEqual(unscrambleSupport.getPresentableName(), selectedUnscrambler.getPresentableName())) { index = i; break; } } } if (count > 0) { myUseUnscrambler.setEnabled(true); myUnscrambleChooser.setSelectedIndex(index); myUseUnscrambler.setSelected(selectedUnscrambler != null); } else { myUseUnscrambler.setEnabled(false); } useUnscramblerChanged(); updateUnscramblerSettings(); myStacktraceEditorPanel.pasteTextFromClipboard(); } private void createUIComponents() { myBottomPanel = new JPanel(new BorderLayout()); if (ProjectLevelVcsManager.getInstance(myProject).hasActiveVcss()) { myConfigurable = new VcsContentAnnotationConfigurable(myProject); myBottomPanel.add(myConfigurable.createComponent(), BorderLayout.CENTER); myConfigurable.reset(); } } @Nullable private UnscrambleSupport getSavedUnscrambler() { final String savedUnscramblerName = getPropertyValue(PROPERTY_UNSCRAMBLER_NAME_USED); UnscrambleSupport selectedUnscrambler = null; for (UnscrambleSupport unscrambleSupport : UnscrambleSupport.EP_NAME.getExtensions()) { if (Comparing.strEqual(unscrambleSupport.getPresentableName(), savedUnscramblerName)) { selectedUnscrambler = unscrambleSupport; } } return selectedUnscrambler; } @NotNull public static List<String> getSavedLogFileUrls() { final List<String> res = new ArrayList<>(); final String savedUrl = PropertiesComponent.getInstance().getValue(PROPERTY_LOG_FILE_HISTORY_URLS); final String[] strings = savedUrl == null ? ArrayUtil.EMPTY_STRING_ARRAY : savedUrl.split(":::"); for (int i = 0; i != strings.length; ++i) { res.add(strings[i]); } return res; } @Nullable private UnscrambleSupport getSelectedUnscrambler() { if (!myUseUnscrambler.isSelected()) return null; return (UnscrambleSupport)myUnscrambleChooser.getSelectedItem(); } private void createEditor() { myStacktraceEditorPanel = AnalyzeStacktraceUtil.createEditorPanel(myProject, myDisposable); myEditorPanel.setLayout(new BorderLayout()); myEditorPanel.add(myStacktraceEditorPanel, BorderLayout.CENTER); } @Override @NotNull protected Action[] createActions(){ return new Action[]{createNormalizeTextAction(), getOKAction(), getCancelAction(), getHelpAction()}; } @Override public JComponent getPreferredFocusedComponent() { JRootPane pane = getRootPane(); return pane != null ? pane.getDefaultButton() : super.getPreferredFocusedComponent(); } private void createLogFileChooser() { myLogFile = new TextFieldWithHistory(); JPanel panel = GuiUtils.constructFieldWithBrowseButton(myLogFile, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(); FileChooser.chooseFiles(descriptor, myProject, null, files -> myLogFile.setText(FileUtil.toSystemDependentName(files.get(files.size() - 1).getPath()))); } }); myLogFileChooserPanel.setLayout(new BorderLayout()); myLogFileChooserPanel.add(panel, BorderLayout.CENTER); } private void populateRegisteredUnscramblerList() { for (UnscrambleSupport unscrambleSupport : UnscrambleSupport.EP_NAME.getExtensions()) { //noinspection unchecked myUnscrambleChooser.addItem(unscrambleSupport); } //noinspection unchecked myUnscrambleChooser.setRenderer(new ListCellRendererWrapper<UnscrambleSupport>() { @Override public void customize(JList list, UnscrambleSupport unscrambleSupport, int index, boolean selected, boolean hasFocus) { setText(unscrambleSupport == null ? IdeBundle.message("unscramble.no.unscrambler.item") : unscrambleSupport.getPresentableName()); } }); } @Override protected JComponent createCenterPanel() { return myPanel; } @Override public void dispose() { if (isOK()){ final List<String> list = myLogFile.getHistory(); PropertiesComponent.getInstance().setValue(PROPERTY_LOG_FILE_HISTORY_URLS, list.isEmpty() ? null : StringUtil.join(list, ":::"), null); UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); saveProperty(PROPERTY_UNSCRAMBLER_NAME_USED, selectedUnscrambler == null ? null : selectedUnscrambler.getPresentableName()); saveProperty(PROPERTY_LOG_FILE_LAST_URL, StringUtil.nullize(myLogFile.getText())); } super.dispose(); } // IDEA-125302 The Analyze Stacktrace menu option remembers only one log file across multiple projects private void saveProperty(@NotNull String name, @Nullable String value) { PropertiesComponent.getInstance(myProject).setValue(name, value); PropertiesComponent.getInstance().setValue(name, value); } @Nullable private String getPropertyValue(@NotNull String name) { String projectValue = PropertiesComponent.getInstance(myProject).getValue(name); if (projectValue != null) { return projectValue; } return PropertiesComponent.getInstance().getValue(name); } public void setText(String trace) { myStacktraceEditorPanel.setText(trace); } public Action createNormalizeTextAction() { return new NormalizeTextAction(); } private final class NormalizeTextAction extends AbstractAction { public NormalizeTextAction(){ putValue(NAME, IdeBundle.message("unscramble.normalize.button")); putValue(DEFAULT_ACTION, Boolean.FALSE); } @Override public void actionPerformed(ActionEvent e){ String text = myStacktraceEditorPanel.getText(); myStacktraceEditorPanel.setText(normalizeText(text)); } } public static String normalizeText(@NonNls String text) { StringBuilder builder = new StringBuilder(text.length()); text = text.replaceAll("(\\S[ \\t\\x0B\\f\\r]+)(at\\s+)", "$1\n$2"); String[] lines = text.split("\n"); boolean first = true; boolean inAuxInfo = false; for (final String line : lines) { //noinspection HardCodedStringLiteral if (!inAuxInfo && (line.startsWith("JNI global references") || line.trim().equals("Heap"))) { builder.append("\n"); inAuxInfo = true; } if (inAuxInfo) { builder.append(trimSuffix(line)).append("\n"); continue; } if (line.startsWith("at breakpoint")) { // possible thread status mixed with "at ..." builder.append(" ").append(trimSuffix(line)); continue; } if (!first && (mustHaveNewLineBefore(line) || StringUtil.endsWith(builder, ")"))) { if (!StringUtil.endsWith(builder, "\n")) builder.append("\n"); if (line.startsWith("\"")) builder.append("\n"); // Additional line break for thread names } first = false; int i = builder.lastIndexOf("\n"); CharSequence lastLine = i == -1 ? builder : builder.subSequence(i + 1, builder.length()); if (!line.matches("\\s+.*") && lastLine.length() > 0) { if (lastLine.toString().matches("\\s*at") //separate 'at' from filename || ContainerUtil.or(IMPORTANT_THREAD_DUMP_WORDS, word -> line.startsWith(word))) { builder.append(" "); } } builder.append(trimSuffix(line)); } return builder.toString(); } private static String trimSuffix(final String line) { int len = line.length(); while ((0 < len) && (line.charAt(len-1) <= ' ')) { len--; } return (len < line.length()) ? line.substring(0, len) : line; } private static boolean mustHaveNewLineBefore(String line) { final int nonWs = CharArrayUtil.shiftForward(line, 0, " \t"); if (nonWs < line.length()) { line = line.substring(nonWs); } if (line.startsWith("at")) return true; // Start of the new stack frame entry if (line.startsWith("Caused")) return true; // Caused by message if (line.startsWith("- locked")) return true; // "Locked a monitor" logging if (line.startsWith("- waiting")) return true; // "Waiting for monitor" logging if (line.startsWith("- parking to wait")) return true; if (line.startsWith("java.lang.Thread.State")) return true; if (line.startsWith("\"")) return true; // Start of the new thread (thread name) return false; } @Override protected void doOKAction() { if (myConfigurable != null && myConfigurable.isModified()) { try { myConfigurable.apply(); } catch (ConfigurationException e) { setText(e.getMessage()); return; } } DumbService.getInstance(myProject).withAlternativeResolveEnabled(() -> { if (performUnscramble()) { myLogFile.addCurrentTextToHistory(); close(OK_EXIT_CODE); } }); } @Override public void doHelpAction() { HelpManager.getInstance().invokeHelp("find.analyzeStackTrace"); } private boolean performUnscramble() { UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); JComponent settings = mySettingsPanel.getComponentCount() == 0 ? null : (JComponent)mySettingsPanel.getComponent(0); return showUnscrambledText(selectedUnscrambler, myLogFile.getText(), settings, myProject, myStacktraceEditorPanel.getText()) != null; } @Nullable static <T extends JComponent> RunContentDescriptor showUnscrambledText(@Nullable UnscrambleSupport<T> unscrambleSupport, String logName, @Nullable T settings, Project project, String textToUnscramble) { String unscrambledTrace = unscrambleSupport == null ? textToUnscramble : unscrambleSupport.unscramble(project,textToUnscramble, logName, settings); if (unscrambledTrace == null) return null; List<ThreadState> threadStates = ThreadDumpParser.parse(unscrambledTrace); return addConsole(project, threadStates, unscrambledTrace); } private static RunContentDescriptor addConsole(final Project project, final List<ThreadState> threadDump, String unscrambledTrace) { Icon icon = null; String message = IdeBundle.message("unscramble.unscrambled.stacktrace.tab"); if (!threadDump.isEmpty()) { message = IdeBundle.message("unscramble.unscrambled.threaddump.tab"); icon = AllIcons.Debugger.ThreadStates.Threaddump; } else { String name = getExceptionName(unscrambledTrace); if (name != null) { message = name; icon = AllIcons.Debugger.ThreadStates.Exception; } } if (ContainerUtil.find(threadDump, DEADLOCK_CONDITION) != null) { message = IdeBundle.message("unscramble.unscrambled.deadlock.tab"); icon = AllIcons.Debugger.KillProcess; } return AnalyzeStacktraceUtil.addConsole(project, threadDump.size() > 1 ? new ThreadDumpConsoleFactory(project, threadDump) : null, message, unscrambledTrace, icon); } @Override protected String getDimensionServiceKey(){ return "#com.intellij.unscramble.UnscrambleDialog"; } @Nullable private static String getExceptionName(String unscrambledTrace) { @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") BufferedReader reader = new BufferedReader(new StringReader(unscrambledTrace)); for (int i = 0; i < 3; i++) { try { String line = reader.readLine(); if (line == null) return null; line = line.trim(); String name = getExceptionAbbreviation(line); if (name != null) return name; } catch (IOException e) { return null; } } return null; } @Nullable private static String getExceptionAbbreviation(String line) { int lastDelimiter = 0; for (int j = 0; j < line.length(); j++) { char c = line.charAt(j); if (c == '.' || c == '$') { lastDelimiter = j; continue; } if (!StringUtil.isJavaIdentifierPart(c)) { return null; } } String clazz = line.substring(lastDelimiter); String abbreviate = abbreviate(clazz); return abbreviate.length() > 1 ? abbreviate : clazz; } private static String abbreviate(String s) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isUpperCase(c)) { builder.append(c); } } return builder.toString(); } }
package com.github.felixgail.gplaymusic.api; import com.github.felixgail.gplaymusic.exceptions.InitializationException; import com.github.felixgail.gplaymusic.exceptions.NetworkException; import com.github.felixgail.gplaymusic.model.Album; import com.github.felixgail.gplaymusic.model.Artist; import com.github.felixgail.gplaymusic.model.Config; import com.github.felixgail.gplaymusic.model.DeviceInfo; import com.github.felixgail.gplaymusic.model.Genre; import com.github.felixgail.gplaymusic.model.Model; import com.github.felixgail.gplaymusic.model.PodcastSeries; import com.github.felixgail.gplaymusic.model.Track; import com.github.felixgail.gplaymusic.model.listennow.ListenNowItem; import com.github.felixgail.gplaymusic.model.listennow.ListenNowSituation; import com.github.felixgail.gplaymusic.model.listennow.ListenNowStation; import com.github.felixgail.gplaymusic.model.requests.SearchTypes; import com.github.felixgail.gplaymusic.model.requests.TimeZoneOffset; import com.github.felixgail.gplaymusic.model.responses.ListResult; import com.github.felixgail.gplaymusic.model.responses.Result; import com.github.felixgail.gplaymusic.model.responses.SearchResponse; import com.github.felixgail.gplaymusic.util.TokenProvider; import com.github.felixgail.gplaymusic.util.deserializer.ListenNowStationDeserializer; import com.github.felixgail.gplaymusic.util.deserializer.ModelPostProcessor; import com.github.felixgail.gplaymusic.util.deserializer.ResultDeserializer; import com.github.felixgail.gplaymusic.util.interceptor.ErrorInterceptor; import com.github.felixgail.gplaymusic.util.interceptor.LoggingInterceptor; import com.github.felixgail.gplaymusic.util.interceptor.RequestInterceptor; import com.github.felixgail.gplaymusic.util.language.Language; import com.google.gson.GsonBuilder; import io.gsonfire.GsonFireBuilder; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Optional; import javax.validation.constraints.NotNull; import okhttp3.CipherSuite; import okhttp3.ConnectionSpec; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.TlsVersion; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import svarzee.gps.gpsoauth.AuthToken; /** * The main API, wrapping calls to the service. Use the {@link GPlayMusic.Builder} to create a new * instance. */ public final class GPlayMusic { private GPlayService service; private Config config; private RequestInterceptor interceptor; private GenreApi genreApi; private PlaylistApi playlistApi; private PlaylistEntryApi playlistEntryApi; private StationApi stationApi; private TrackApi trackApi; private GPlayMusic(GPlayService service, RequestInterceptor interceptor) { this.service = service; this.interceptor = interceptor; this.genreApi = new GenreApi(this); this.playlistEntryApi = new PlaylistEntryApi(this); this.playlistApi = new PlaylistApi(this, playlistEntryApi); this.stationApi = new StationApi(this); this.trackApi = new TrackApi(this); } public Config getConfig() { return config; } private void setConfig(Config config) { this.config = config; } public Album getAlbum(String albumID, boolean includeTracks) throws IOException { return getService().getAlbum(albumID, includeTracks).execute().body(); } /** * Fetches for an artist by {@code artistID}. * * @param artistID {@link Artist#getArtistId()} of the artist searched for. * @param includeAlbums whether albums of the artist shall be included in the response. * @param numTopTracks response includes up to provided number of most heard songs in response * @param numRelArtist response includes up to provided number of similar artist in response * @return An executable call which returns an artist on execution. */ public Artist getArtist(String artistID, boolean includeAlbums, int numTopTracks, int numRelArtist) throws IOException { return getService().getArtist(artistID, includeAlbums, numTopTracks, numRelArtist) .execute().body(); } /** * This method will return the service used to make calls to google play, and therefore allows for * low level and asynchronous calls. Be sure to check the response for error codes. * * @return {@link GPlayService} instance used by the current API. */ public GPlayService getService() { return this.service; } /** * Queries Google Play Music for content. Content can be every combination of {@link SearchTypes} * enum. * * @param query Query String * @param maxResults Limits the results. Keep in mind that higher numbers increase loading time. * @param types Content types that should be queried for * @return A SearchResponse instance holding all content returned * @throws IOException Throws an IOException on severe failures (no internet connection...) or a * {@link NetworkException} on request failures. */ public SearchResponse search(String query, int maxResults, SearchTypes types) throws IOException { return getService().search(query, maxResults, types).execute().body(); } /** * Provides convenience by wrapping the {@link #search(String, int, SearchTypes)} method and * setting the maxResults parameter to 50. */ public SearchResponse search(String query, SearchTypes types) throws IOException { return search(query, 50, types); } /** * Fetches a list of all devices connected with the current google play account. * * @return A DeviceList instance containing all devices connected to the current Google Play * account. * @throws IOException Throws an IOException on severe failures (no internet connection...) or a * {@link NetworkException} on request failures. */ public ListResult<DeviceInfo> getRegisteredDevices() throws IOException { return getService().getDevices().execute().body(); } /** * Returns a list of promoted {@link Track}s. Which tracks are in the returned list is determined * by google * * @throws IOException on severe failures (no internet connection...) or a {@link * NetworkException} on request failures. */ public List<Track> getPromotedTracks() throws IOException { return getService().getPromotedTracks().execute().body().toList(); //TODO: set api } public List<PodcastSeries> listPodcastSeries(Genre genre) throws IOException { return service.listBrowsePodcastSeries(genre.getId()).execute().body().toList(); } /** * Returns a selection of {@link ListenNowItem}s consisting of {@link ListenNowStation} and {@link * com.github.felixgail.gplaymusic.model.listennow.ListenNowAlbum}. */ public List<ListenNowItem> listListenNowItems() throws IOException { return service.listListenNowItems().execute().body().getListenNowItems(); } /** * Returns the current {@link ListenNowStation} for your timezone. */ public ListenNowSituation getListenNowSituation() throws IOException { return service.getListenNowSituation(new TimeZoneOffset()).execute().body(); } /** * Returns the current {@link ListenNowStation} with a set offset. * * @param offsetInSeconds the offset in seconds to UTC. */ public ListenNowSituation getListenNowSituation(int offsetInSeconds) throws IOException { return service.getListenNowSituation(new TimeZoneOffset(String.valueOf(offsetInSeconds))) .execute().body(); } public GenreApi getGenreApi() { return genreApi; } public PlaylistApi getPlaylistApi() { return playlistApi; } public PlaylistEntryApi getPlaylistEntryApi() { return playlistEntryApi; } public StationApi getStationApi() { return stationApi; } public TrackApi getTrackApi() { return trackApi; } /** * Changes the token used to authenticate the client. * * @param token a new valid token to access the google service */ public void changeToken(@NotNull AuthToken token) { interceptor.setToken(token); } /** * Use this class to create a {@link GPlayMusic} instance. */ public final static class Builder { private OkHttpClient.Builder httpClientBuilder; private AuthToken authToken; private Locale locale = Locale.US; private String androidID; private ErrorInterceptor.InterceptorBehaviour interceptorBehaviour = ErrorInterceptor.InterceptorBehaviour.THROW_EXCEPTION; private boolean debug = false; /** * Used while building the {@link GPlayMusic} instance. If no {@link OkHttpClient.Builder} is * provided via {@link #setHttpClientBuilder(OkHttpClient.Builder)} the instance returned by * this method will be used for building. * * @return Returns the default {@link OkHttpClient.Builder} instance */ public static OkHttpClient.Builder getDefaultHttpBuilder() { ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .cipherSuites( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) .build(); return new OkHttpClient.Builder() .connectionSpecs(Collections.singletonList(spec)); } public boolean isDebug() { return debug; } /** * If set to <em>true</em>, will log every request and response made by the Client.<br> <b> Be * careful as this can easily leak personal information. Be sure to always check the output. * </b> */ public GPlayMusic.Builder setDebug(boolean debug) { this.debug = debug; return this; } /** * Set a custom {@link OkHttpClient.Builder} to build the {@link GPlayMusic} instance with. If * left untouched the Builder will use the default instance accessible through {@link * #getDefaultHttpBuilder()}. * * @return This {@link Builder} instance. */ public Builder setHttpClientBuilder(OkHttpClient.Builder builder) { this.httpClientBuilder = builder; return this; } /** * Set an {@link AuthToken} to access the Google Play Service. This method has to be called * before building the {@link GPlayMusic} instance. * * @param token An {@link AuthToken} either saved from a prior session or created through the * {@link TokenProvider#provideToken(String, String, String)} method. * @return This {@link Builder} instance. */ public Builder setAuthToken(AuthToken token) { this.authToken = token; return this; } /** * Set a local to use during calls to the Google Play Service. Defaults to {@link Locale#US}. * * @return This {@link Builder} instance. */ public Builder setLocale(Locale locale) { this.locale = locale; return this; } /** * Set a Behaviour for the {@link ErrorInterceptor} appended to the {@link * OkHttpClient.Builder}. Throws Exceptions on default. May cause instability when set to {@link * com.github.felixgail.gplaymusic.util.interceptor.ErrorInterceptor.InterceptorBehaviour#LOG}. * * @return This {@link Builder} instance. */ public Builder setInterceptorBehaviour( ErrorInterceptor.InterceptorBehaviour interceptorBehaviour) { this.interceptorBehaviour = interceptorBehaviour; return this; } /** * Set an AndroidID used for stream calls to the Google Play Service. In general the IMEI used * for logging in should be sufficient. If logged in with a MAC use {@link * GPlayMusic#getRegisteredDevices()} for a list of connected devices or leave empty. On empty * the {@link #build()}-method will use search online for a suitable device. * * @return This {@link Builder} instance. */ public Builder setAndroidID(String androidID) { this.androidID = androidID; return this; } /** * Builds a new {@link GPlayMusic} instance with the customizations set to this builder. Make * sure to call {@link #setAuthToken(AuthToken)} before building with this method. * * @return Returns a new {@link GPlayMusic} instance */ public GPlayMusic build() { try { if (this.authToken == null) { throw new InitializationException(Language.get("api.init.EmptyToken")); } if (this.httpClientBuilder == null) { this.httpClientBuilder = getDefaultHttpBuilder(); } RequestInterceptor parameterInterceptor = new RequestInterceptor(authToken); this.httpClientBuilder .addInterceptor(parameterInterceptor) .addInterceptor(new ErrorInterceptor(this.interceptorBehaviour)) .followRedirects(false); if (this.debug) { this.httpClientBuilder.addInterceptor(new LoggingInterceptor()); } OkHttpClient httpClient = this.httpClientBuilder.build(); ModelPostProcessor postProcessor = new ModelPostProcessor(); GsonBuilder builder = new GsonFireBuilder() .registerPostProcessor(Model.class, postProcessor) .createGsonBuilder() .registerTypeAdapter(Result.class, new ResultDeserializer()) .registerTypeAdapter(ListenNowStation.class, new ListenNowStationDeserializer()); Retrofit retrofit = new Retrofit.Builder() .baseUrl(HttpUrl.parse("https://mclients.googleapis.com/")) .addConverterFactory(GsonConverterFactory.create(builder.create())) .client(httpClient) .build(); GPlayMusic gPlay = new GPlayMusic(retrofit.create(GPlayService.class), parameterInterceptor); postProcessor.setApi(gPlay); retrofit2.Response<Config> configResponse = gPlay.getService().config(this.locale).execute(); if (!configResponse.isSuccessful()) { throw new InitializationException(Language.get("network.GenericError"), NetworkException.parse(configResponse.raw())); } Config config = configResponse.body(); if (config == null) { throw new InitializationException(Language.get("api.init.EmptyConfig")); } config.setLocale(locale); Language.setLocale(locale); gPlay.setConfig(config); parameterInterceptor.addParameter("dv", "0") .addParameter("hl", locale.toString()) .addParameter("tier", config.getSubscription().getValue()); if (androidID == null) { Optional<DeviceInfo> optional = gPlay.getRegisteredDevices().toList().stream() .filter(deviceInfo -> (deviceInfo.getType().equals("ANDROID"))) .findFirst(); if (optional.isPresent()) { config.setAndroidID(optional.get().getId()); } else { throw new InitializationException(Language.get("api.init.NoAndroidId")); } } else { config.setAndroidID(androidID); } return gPlay; } catch (IOException e) { throw new InitializationException(e); } } } }
package com.gmail.st3venau.plugins.armorstandtools; import org.jetbrains.annotations.NotNull; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; class Commands implements CommandExecutor, TabCompleter { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player p)) { AST.plugin.getLogger().warning(Config.notConsole); return false; } String cmd = command.getName().toLowerCase(); if(cmd.equals("astools") || cmd.equals("ast")) { if(Config.useCommandForTextInput && args.length > 0) { StringBuilder sb = new StringBuilder(); boolean space = false; for(String s : args) { if(space) sb.append(' '); space = true; sb.append(s); } if(AST.processInput(p, sb.toString())) { return true; } } if (!Utils.hasPermissionNode(p, "astools.command")) { p.sendMessage(ChatColor.RED + Config.noCommandPerm); return true; } if (args.length == 0) { UUID uuid = p.getUniqueId(); if (AST.savedInventories.containsKey(uuid)) { AST.restoreInventory(p); } else { AST.plugin.saveInventoryAndClear(p); ArmorStandTool.give(p); p.sendMessage(ChatColor.GREEN + Config.giveMsg1); p.sendMessage(ChatColor.AQUA + Config.giveMsg2); } return true; } if (args[0].equalsIgnoreCase("reload")) { if (Utils.hasPermissionNode(p, "astools.reload")) { Config.reload(); p.sendMessage(ChatColor.GREEN + Config.conReload); return true; } else { p.sendMessage(ChatColor.RED + Config.noRelPerm); return true; } } } else if(cmd.equals("ascmd")) { ArmorStand as = getNearbyArmorStand(p); if(as == null) { p.sendMessage("\n" + Config.noASNearBy); return true; } String name = " "; if(as.getName().length() > 0 && !as.getName().equalsIgnoreCase("armor stand")) { name = ChatColor.RESET + " (" + ChatColor.AQUA + as.getName() + ChatColor.RESET + ") "; } ArmorStandCmdManager asCmdManager = new ArmorStandCmdManager(as); if(args.length >= 1 && args[0].equalsIgnoreCase("list")) { // [0] // ascmd list if (!Utils.hasPermissionNode(p, "astools.ascmd.list")) { p.sendMessage(ChatColor.RED + Config.noCommandPerm); return true; } listAssignedCommands(asCmdManager, name, p); return true; } else if(args.length >= 2 && args[0].equalsIgnoreCase("remove")) { // [0] [1] // ascmd remove <command_number> if (!Utils.hasPermissionNode(p, "astools.ascmd.remove")) { p.sendMessage(ChatColor.RED + Config.noCommandPerm); return true; } int n; try { n = Integer.parseInt(args[1]); } catch (NumberFormatException e) { p.sendMessage(ChatColor.RED + args[1] + " " + Config.isNotValidNumber); return true; } if(asCmdManager.removeCommand(n - 1)) { p.sendMessage("\n" + Config.command + ChatColor.GREEN + " #" + n + ChatColor.RESET + " " + Config.removedFromAs + name); } else { p.sendMessage(ChatColor.RED + args[1] + " " + Config.isNotValidNumber); } listAssignedCommands(asCmdManager, name, p); return true; } else if(args.length >= 5 && args[0].equalsIgnoreCase("add")) { // [0] [1] [2] [3] [4 - ...] // ascmd add <priority> <delay> <player/console/bungee> <command/bungee_server_name> CommandType type = CommandType.fromName(args[3]); if(type == null) { ascmdHelp(p); return true; } if (!Utils.hasPermissionNode(p, type.getAddPermission())) { p.sendMessage(ChatColor.RED + Config.noCommandPerm); return true; } int priority; try { priority = Integer.parseInt(args[1]); } catch (NumberFormatException e) { p.sendMessage(ChatColor.RED + args[1] + " " + Config.isNotValidNumber); return true; } int delay; try { delay = Integer.parseInt(args[2]); } catch (NumberFormatException e) { p.sendMessage(ChatColor.RED + args[2] + " " + Config.isNotValidNumber); return true; } if(delay < 0) { p.sendMessage(ChatColor.RED + args[2] + " " + Config.isNotValidNumber); return true; } StringBuilder sb = new StringBuilder(); for(int i = 4; i < args.length; i++) { sb.append(args[i]).append(" "); } int startAt = sb.charAt(0) == '/' ? 1 : 0; String c = sb.substring(startAt, sb.length() - 1); if(c.length() == 0) { ascmdHelp(p); return true; } asCmdManager.addCommand(new ArmorStandCmd(c, type, priority, delay), true); listAssignedCommands(asCmdManager, name, p); return true; } else if(args.length >= 2 && args[0].equalsIgnoreCase("cooldown")) { //ascmd cooldown <ticks>/remove if (!Utils.hasPermissionNode(p, "astools.ascmd.cooldown")) { p.sendMessage(ChatColor.RED + Config.noCommandPerm); return true; } if(!asCmdManager.hasCommands()) { p.sendMessage(Config.closestAS + name + Config.hasNoCmds); return true; } if(args[1].equalsIgnoreCase("remove")) { asCmdManager.setCooldownTime(-1); p.sendMessage(Config.cooldownRemovedFrom + " " + Config.closestAS + name); } else { int ticks; try { ticks = Integer.parseInt(args[1]); } catch (NumberFormatException e) { p.sendMessage(args[1] + " " + Config.isAnInvalidCooldown); return true; } if(ticks < 0) { p.sendMessage(args[1] + " " + Config.isAnInvalidCooldown); return true; } asCmdManager.setCooldownTime(ticks); p.sendMessage(Config.cooldownSetTo + " " + ticks + " " + Config.ticksFor + " " + Config.closestAS + name); } return true; } else { ascmdHelp(p); return true; } } return false; } private void listAssignedCommands(ArmorStandCmdManager asCmdManager, String name, Player p) { if(asCmdManager.hasCommands()) { p.sendMessage("\n" + Config.closestAS + name + Config.hasTheseCmdsAssigned); List<ArmorStandCmd> list = asCmdManager.getCommands(); for(int n = 0; n < list.size(); n++) { ArmorStandCmd asCmd = list.get(n); // #1 Priority:0 Delay:0 Type:Player Command:cmd p.sendMessage( ChatColor.GREEN + "#" + (n + 1) + " " + ChatColor.LIGHT_PURPLE + Config.priority + ":" + ChatColor.RESET + asCmd.priority() + " " + ChatColor.YELLOW + Config.delay + ":" + ChatColor.RESET + asCmd.delay() + " " + ChatColor.GOLD + Config.type + ":" + ChatColor.RESET + asCmd.type().getName() + " " + ChatColor.AQUA + Config.command + ":" + ChatColor.RESET + asCmd.command() ); } } else { p.sendMessage("\n" + Config.closestAS + name + Config.hasNoCmds); } } private void ascmdHelp(Player p) { p.sendMessage("\n" + ChatColor.AQUA + Config.cmdHelp); p.sendMessage(Config.listAssignedCmds + ": " + ChatColor.YELLOW + "/ascmd list"); p.sendMessage(Config.addACmd + ":" + ChatColor.YELLOW + "/ascmd add <priority> <delay> <player/console/bungee> <command/bungee_server_name>"); p.sendMessage(Config.removeACmd + ": " + ChatColor.YELLOW + "/ascmd remove <command_number>"); p.sendMessage(Config.setCooldown + ":"); p.sendMessage(ChatColor.YELLOW + "/ascmd cooldown <ticks>"); p.sendMessage(Config.removeCooldown + ":"); p.sendMessage(ChatColor.YELLOW + "/ascmd cooldown remove"); } private ArmorStand getNearbyArmorStand(Player p) { ArmorStand closestAs = null; double closestDist = 1000000; for(Entity e : p.getNearbyEntities(4, 4, 4)) { if(!(e instanceof ArmorStand)) continue; double dist = e.getLocation().distanceSquared(p.getLocation()); if(dist < closestDist) { closestDist = dist; closestAs = (ArmorStand) e; } } return closestAs; } public List<String> onTabComplete(@NotNull CommandSender sender, Command command, @NotNull String alias, String[] args) { List<String> list = new ArrayList<>(); String cmd = command.getName().toLowerCase(); String typed = ""; if (args.length > 0) { typed = args[args.length - 1].toLowerCase(); } if (cmd.equals("ascmd")) { if (args.length == 1) { for(String s : Arrays.asList("list", "remove", "add", "cooldown")) { if(s.startsWith(typed)) { list.add(s); } } } else if (args[0].equalsIgnoreCase("add")) { if(args.length == 2 && typed.length() == 0) { list.add("priority"); } if(args.length == 3 && typed.length() == 0) { list.add("delay"); } else if(args.length == 4) { for (String s : Arrays.asList("player", "console", "bungee")) { if (s.startsWith(typed)) { list.add(s); } } } } else if (args.length == 2 && args[0].equalsIgnoreCase("cooldown")) { String s = "remove"; if(s.startsWith(typed)) { list.add(s); } } } return list; } }
/* * Copyright 2017-2022 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.glue.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/UnfilteredPartition" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UnfilteredPartition implements Serializable, Cloneable, StructuredPojo { private Partition partition; private java.util.List<String> authorizedColumns; private Boolean isRegisteredWithLakeFormation; /** * @param partition */ public void setPartition(Partition partition) { this.partition = partition; } /** * @return */ public Partition getPartition() { return this.partition; } /** * @param partition * @return Returns a reference to this object so that method calls can be chained together. */ public UnfilteredPartition withPartition(Partition partition) { setPartition(partition); return this; } /** * @return */ public java.util.List<String> getAuthorizedColumns() { return authorizedColumns; } /** * @param authorizedColumns */ public void setAuthorizedColumns(java.util.Collection<String> authorizedColumns) { if (authorizedColumns == null) { this.authorizedColumns = null; return; } this.authorizedColumns = new java.util.ArrayList<String>(authorizedColumns); } /** * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setAuthorizedColumns(java.util.Collection)} or {@link #withAuthorizedColumns(java.util.Collection)} if * you want to override the existing values. * </p> * * @param authorizedColumns * @return Returns a reference to this object so that method calls can be chained together. */ public UnfilteredPartition withAuthorizedColumns(String... authorizedColumns) { if (this.authorizedColumns == null) { setAuthorizedColumns(new java.util.ArrayList<String>(authorizedColumns.length)); } for (String ele : authorizedColumns) { this.authorizedColumns.add(ele); } return this; } /** * @param authorizedColumns * @return Returns a reference to this object so that method calls can be chained together. */ public UnfilteredPartition withAuthorizedColumns(java.util.Collection<String> authorizedColumns) { setAuthorizedColumns(authorizedColumns); return this; } /** * @param isRegisteredWithLakeFormation */ public void setIsRegisteredWithLakeFormation(Boolean isRegisteredWithLakeFormation) { this.isRegisteredWithLakeFormation = isRegisteredWithLakeFormation; } /** * @return */ public Boolean getIsRegisteredWithLakeFormation() { return this.isRegisteredWithLakeFormation; } /** * @param isRegisteredWithLakeFormation * @return Returns a reference to this object so that method calls can be chained together. */ public UnfilteredPartition withIsRegisteredWithLakeFormation(Boolean isRegisteredWithLakeFormation) { setIsRegisteredWithLakeFormation(isRegisteredWithLakeFormation); return this; } /** * @return */ public Boolean isRegisteredWithLakeFormation() { return this.isRegisteredWithLakeFormation; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPartition() != null) sb.append("Partition: ").append(getPartition()).append(","); if (getAuthorizedColumns() != null) sb.append("AuthorizedColumns: ").append(getAuthorizedColumns()).append(","); if (getIsRegisteredWithLakeFormation() != null) sb.append("IsRegisteredWithLakeFormation: ").append(getIsRegisteredWithLakeFormation()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UnfilteredPartition == false) return false; UnfilteredPartition other = (UnfilteredPartition) obj; if (other.getPartition() == null ^ this.getPartition() == null) return false; if (other.getPartition() != null && other.getPartition().equals(this.getPartition()) == false) return false; if (other.getAuthorizedColumns() == null ^ this.getAuthorizedColumns() == null) return false; if (other.getAuthorizedColumns() != null && other.getAuthorizedColumns().equals(this.getAuthorizedColumns()) == false) return false; if (other.getIsRegisteredWithLakeFormation() == null ^ this.getIsRegisteredWithLakeFormation() == null) return false; if (other.getIsRegisteredWithLakeFormation() != null && other.getIsRegisteredWithLakeFormation().equals(this.getIsRegisteredWithLakeFormation()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPartition() == null) ? 0 : getPartition().hashCode()); hashCode = prime * hashCode + ((getAuthorizedColumns() == null) ? 0 : getAuthorizedColumns().hashCode()); hashCode = prime * hashCode + ((getIsRegisteredWithLakeFormation() == null) ? 0 : getIsRegisteredWithLakeFormation().hashCode()); return hashCode; } @Override public UnfilteredPartition clone() { try { return (UnfilteredPartition) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.glue.model.transform.UnfilteredPartitionMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 2001, 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.xerces.internal.parsers; import com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl; import com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl; import com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator; import com.sun.org.apache.xerces.internal.impl.dtd.XMLNSDTDValidator; import com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator; import com.sun.org.apache.xerces.internal.impl.xs.XSMessageFormatter; import com.sun.org.apache.xerces.internal.util.SymbolTable; import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarPool; import com.sun.org.apache.xerces.internal.xni.parser.XMLComponent; import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager; import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentScanner; /** * This is configuration uses a scanner that integrates both scanning of the document * and binding namespaces. * * If namespace feature is turned on, the pipeline is constructured with the * following components: * XMLNSDocumentScannerImpl -> XMLNSDTDValidator -> (optional) XMLSchemaValidator * * If the namespace feature is turned off the default document scanner implementation * is used (XMLDocumentScannerImpl). * <p> * In addition to the features and properties recognized by the base * parser configuration, this class recognizes these additional * features and properties: * <ul> * <li>Features * <ul> * <li>http://apache.org/xml/features/validation/schema</li> * <li>http://apache.org/xml/features/validation/schema-full-checking</li> * <li>http://apache.org/xml/features/validation/schema/normalized-value</li> * <li>http://apache.org/xml/features/validation/schema/element-default</li> * </ul> * <li>Properties * <ul> * <li>http://apache.org/xml/properties/internal/error-reporter</li> * <li>http://apache.org/xml/properties/internal/entity-manager</li> * <li>http://apache.org/xml/properties/internal/document-scanner</li> * <li>http://apache.org/xml/properties/internal/dtd-scanner</li> * <li>http://apache.org/xml/properties/internal/grammar-pool</li> * <li>http://apache.org/xml/properties/internal/validator/dtd</li> * <li>http://apache.org/xml/properties/internal/datatype-validator-factory</li> * </ul> * </ul> * * @author Elena Litani, IBM * */ public class IntegratedParserConfiguration extends StandardParserConfiguration { // // REVISIT: should this configuration depend on the others // like DTD/Standard one? // /** Document scanner that does namespace binding. */ protected XMLNSDocumentScannerImpl fNamespaceScanner; /** Default Xerces implementation of scanner */ protected XMLDocumentScannerImpl fNonNSScanner; /** DTD Validator that does not bind namespaces */ protected XMLDTDValidator fNonNSDTDValidator; // // Constructors // /** Default constructor. */ public IntegratedParserConfiguration() { this(null, null, null); } // <init>() /** * Constructs a parser configuration using the specified symbol table. * * @param symbolTable The symbol table to use. */ public IntegratedParserConfiguration(SymbolTable symbolTable) { this(symbolTable, null, null); } // <init>(SymbolTable) /** * Constructs a parser configuration using the specified symbol table and * grammar pool. * <p> * <strong>REVISIT:</strong> * Grammar pool will be updated when the new validation engine is * implemented. * * @param symbolTable The symbol table to use. * @param grammarPool The grammar pool to use. */ public IntegratedParserConfiguration(SymbolTable symbolTable, XMLGrammarPool grammarPool) { this(symbolTable, grammarPool, null); } // <init>(SymbolTable,XMLGrammarPool) /** * Constructs a parser configuration using the specified symbol table, * grammar pool, and parent settings. * <p> * <strong>REVISIT:</strong> * Grammar pool will be updated when the new validation engine is * implemented. * * @param symbolTable The symbol table to use. * @param grammarPool The grammar pool to use. * @param parentSettings The parent settings. */ public IntegratedParserConfiguration(SymbolTable symbolTable, XMLGrammarPool grammarPool, XMLComponentManager parentSettings) { super(symbolTable, grammarPool, parentSettings); // create components fNonNSScanner = new XMLDocumentScannerImpl(); fNonNSDTDValidator = new XMLDTDValidator(); // add components addComponent((XMLComponent)fNonNSScanner); addComponent((XMLComponent)fNonNSDTDValidator); } // <init>(SymbolTable,XMLGrammarPool) /** Configures the pipeline. */ protected void configurePipeline() { // use XML 1.0 datatype library setProperty(DATATYPE_VALIDATOR_FACTORY, fDatatypeValidatorFactory); // setup DTD pipeline configureDTDPipeline(); // setup document pipeline if (fFeatures.get(NAMESPACES) == Boolean.TRUE) { fProperties.put(NAMESPACE_BINDER, fNamespaceBinder); fScanner = fNamespaceScanner; fProperties.put(DOCUMENT_SCANNER, fNamespaceScanner); if (fDTDValidator != null) { fProperties.put(DTD_VALIDATOR, fDTDValidator); fNamespaceScanner.setDTDValidator(fDTDValidator); fNamespaceScanner.setDocumentHandler(fDTDValidator); fDTDValidator.setDocumentSource(fNamespaceScanner); fDTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fDTDValidator); } fLastComponent = fDTDValidator; } else { fNamespaceScanner.setDocumentHandler(fDocumentHandler); fNamespaceScanner.setDTDValidator(null); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fNamespaceScanner); } fLastComponent = fNamespaceScanner; } } else { fScanner = fNonNSScanner; fProperties.put(DOCUMENT_SCANNER, fNonNSScanner); if (fNonNSDTDValidator != null) { fProperties.put(DTD_VALIDATOR, fNonNSDTDValidator); fNonNSScanner.setDocumentHandler(fNonNSDTDValidator); fNonNSDTDValidator.setDocumentSource(fNonNSScanner); fNonNSDTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fNonNSDTDValidator); } fLastComponent = fNonNSDTDValidator; } else { fScanner.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fScanner); } fLastComponent = fScanner; } } // setup document pipeline if (fFeatures.get(XMLSCHEMA_VALIDATION) == Boolean.TRUE) { // If schema validator was not in the pipeline insert it. if (fSchemaValidator == null) { fSchemaValidator = new XMLSchemaValidator(); // add schema component fProperties.put(SCHEMA_VALIDATOR, fSchemaValidator); addComponent(fSchemaValidator); // add schema message formatter if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) { XSMessageFormatter xmft = new XSMessageFormatter(); fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, xmft); } } fLastComponent.setDocumentHandler(fSchemaValidator); fSchemaValidator.setDocumentSource(fLastComponent); fSchemaValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fSchemaValidator); } fLastComponent = fSchemaValidator; } } // configurePipeline() /** Create a document scanner: this scanner performs namespace binding */ protected XMLDocumentScanner createDocumentScanner() { fNamespaceScanner = new XMLNSDocumentScannerImpl(); return fNamespaceScanner; } // createDocumentScanner():XMLDocumentScanner /** Create a DTD validator: this validator performs namespace binding. */ protected XMLDTDValidator createDTDValidator() { return new XMLNSDTDValidator(); } // createDTDValidator():XMLDTDValidator } // class IntegratedParserConfiguration
/* * Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.map.impl; import com.hazelcast.config.CacheDeserializedValues; import com.hazelcast.internal.nearcache.impl.invalidation.MetaDataGenerator; import com.hazelcast.internal.partition.FragmentedMigrationAwareService; import com.hazelcast.internal.partition.MigrationEndpoint; import com.hazelcast.internal.partition.PartitionMigrationEvent; import com.hazelcast.internal.partition.PartitionReplicationEvent; import com.hazelcast.internal.serialization.SerializationService; import com.hazelcast.internal.services.ObjectNamespace; import com.hazelcast.internal.services.ServiceNamespace; import com.hazelcast.internal.util.Clock; import com.hazelcast.logging.ILogger; import com.hazelcast.map.impl.operation.MapReplicationOperation; import com.hazelcast.map.impl.querycache.QueryCacheContext; import com.hazelcast.map.impl.querycache.publisher.PublisherContext; import com.hazelcast.map.impl.record.Record; import com.hazelcast.map.impl.record.Records; import com.hazelcast.map.impl.recordstore.RecordStore; import com.hazelcast.query.impl.CachedQueryEntry; import com.hazelcast.query.impl.Index; import com.hazelcast.query.impl.Indexes; import com.hazelcast.query.impl.InternalIndex; import com.hazelcast.query.impl.QueryableEntry; import com.hazelcast.spi.impl.operationservice.Operation; import java.util.Collection; import java.util.function.Predicate; import static com.hazelcast.config.CacheDeserializedValues.NEVER; import static com.hazelcast.internal.partition.MigrationEndpoint.DESTINATION; import static com.hazelcast.internal.partition.MigrationEndpoint.SOURCE; import static com.hazelcast.map.impl.querycache.publisher.AccumulatorSweeper.flushAccumulator; import static com.hazelcast.map.impl.querycache.publisher.AccumulatorSweeper.removeAccumulator; import static com.hazelcast.map.impl.querycache.publisher.AccumulatorSweeper.sendEndOfSequenceEvents; /** * Defines migration behavior of map service. * * @see MapService */ class MapMigrationAwareService implements FragmentedMigrationAwareService { protected final PartitionContainer[] containers; protected final MapServiceContext mapServiceContext; protected final SerializationService serializationService; private final ILogger logger; MapMigrationAwareService(MapServiceContext mapServiceContext) { this.mapServiceContext = mapServiceContext; this.serializationService = mapServiceContext.getNodeEngine().getSerializationService(); this.containers = mapServiceContext.getPartitionContainers(); this.logger = mapServiceContext.getNodeEngine().getLogger(getClass()); } @Override public Collection<ServiceNamespace> getAllServiceNamespaces(PartitionReplicationEvent event) { return containers[event.getPartitionId()].getAllNamespaces(event.getReplicaIndex()); } @Override public boolean isKnownServiceNamespace(ServiceNamespace namespace) { return namespace instanceof ObjectNamespace && MapService.SERVICE_NAME.equals(namespace.getServiceName()); } @Override public void beforeMigration(PartitionMigrationEvent event) { if (isLocalPromotion(event)) { // It's a local partition promotion. We need to populate non-global indexes here since // there is no map replication performed in this case. Global indexes are populated // during promotion finalization phase. // 1. Defensively clear possible stale leftovers from the previous failed promotion attempt. clearNonGlobalIndexes(event); // 2. Populate non-global partitioned indexes. populateIndexes(event, TargetIndexes.NON_GLOBAL, "beforeMigration"); } flushAndRemoveQueryCaches(event); } /** * Flush and remove query cache on this source partition. */ private void flushAndRemoveQueryCaches(PartitionMigrationEvent event) { int partitionId = event.getPartitionId(); QueryCacheContext queryCacheContext = mapServiceContext.getQueryCacheContext(); PublisherContext publisherContext = queryCacheContext.getPublisherContext(); if (event.getMigrationEndpoint() == MigrationEndpoint.SOURCE) { flushAccumulator(publisherContext, partitionId); removeAccumulator(publisherContext, partitionId); return; } if (isLocalPromotion(event)) { removeAccumulator(publisherContext, partitionId); sendEndOfSequenceEvents(publisherContext, partitionId); return; } } @Override public Operation prepareReplicationOperation(PartitionReplicationEvent event) { return prepareReplicationOperation(event, containers[event.getPartitionId()].getAllNamespaces(event.getReplicaIndex())); } @Override public Operation prepareReplicationOperation(PartitionReplicationEvent event, Collection<ServiceNamespace> namespaces) { assert assertAllKnownNamespaces(namespaces); int partitionId = event.getPartitionId(); Operation operation = new MapReplicationOperation(containers[partitionId], namespaces, partitionId, event.getReplicaIndex()); operation.setService(mapServiceContext.getService()); operation.setNodeEngine(mapServiceContext.getNodeEngine()); return operation; } private boolean assertAllKnownNamespaces(Collection<ServiceNamespace> namespaces) { for (ServiceNamespace namespace : namespaces) { assert isKnownServiceNamespace(namespace) : namespace + " is not a MapService namespace!"; } return true; } @Override public void commitMigration(PartitionMigrationEvent event) { if (event.getMigrationEndpoint() == DESTINATION) { populateIndexes(event, TargetIndexes.GLOBAL, "commitMigration"); } else { depopulateIndexes(event, "commitMigration"); } if (SOURCE == event.getMigrationEndpoint()) { // Do not change order of below methods removeWbqCountersHavingLesserBackupCountThan(event.getPartitionId(), event.getNewReplicaIndex()); removeRecordStoresHavingLesserBackupCountThan(event.getPartitionId(), event.getNewReplicaIndex()); } PartitionContainer partitionContainer = mapServiceContext.getPartitionContainer(event.getPartitionId()); for (RecordStore recordStore : partitionContainer.getAllRecordStores()) { // in case the record store has been created without loading during migration trigger again // if loading has been already started this call will do nothing recordStore.startLoading(); } mapServiceContext.nullifyOwnedPartitions(); removeOrRegenerateNearCacheUuid(event); } private void removeOrRegenerateNearCacheUuid(PartitionMigrationEvent event) { if (SOURCE == event.getMigrationEndpoint()) { getMetaDataGenerator().removeUuidAndSequence(event.getPartitionId()); return; } if (DESTINATION == event.getMigrationEndpoint() && event.getNewReplicaIndex() != 0) { getMetaDataGenerator().regenerateUuid(event.getPartitionId()); return; } } @Override public void rollbackMigration(PartitionMigrationEvent event) { if (DESTINATION == event.getMigrationEndpoint()) { // Do not change order of below methods removeWbqCountersHavingLesserBackupCountThan(event.getPartitionId(), event.getCurrentReplicaIndex()); removeRecordStoresHavingLesserBackupCountThan(event.getPartitionId(), event.getCurrentReplicaIndex()); getMetaDataGenerator().removeUuidAndSequence(event.getPartitionId()); } mapServiceContext.nullifyOwnedPartitions(); } private void clearNonGlobalIndexes(PartitionMigrationEvent event) { final PartitionContainer container = mapServiceContext.getPartitionContainer(event.getPartitionId()); for (RecordStore recordStore : container.getMaps().values()) { final MapContainer mapContainer = mapServiceContext.getMapContainer(recordStore.getName()); final Indexes indexes = mapContainer.getIndexes(event.getPartitionId()); if (!indexes.haveAtLeastOneIndex() || indexes.isGlobal()) { // no indexes to work with continue; } indexes.clearAll(); } } private void removeRecordStoresHavingLesserBackupCountThan(int partitionId, int thresholdReplicaIndex) { if (thresholdReplicaIndex < 0) { mapServiceContext.removeRecordStoresFromPartitionMatchingWith(recordStore -> true, partitionId, false, true); } else { mapServiceContext.removeRecordStoresFromPartitionMatchingWith(lesserBackupMapsThen(thresholdReplicaIndex), partitionId, false, true); } } /** * Removes write-behind-queue-reservation-counters inside * supplied partition from matching record-stores. */ private void removeWbqCountersHavingLesserBackupCountThan(int partitionId, int thresholdReplicaIndex) { if (thresholdReplicaIndex < 0) { mapServiceContext.removeWbqCountersFromMatchingPartitionsWith( recordStore -> true, partitionId); } else { mapServiceContext.removeWbqCountersFromMatchingPartitionsWith( lesserBackupMapsThen(thresholdReplicaIndex), partitionId); } } /** * @param backupCount number of backups of a maps' partition * @return predicate to find all map partitions which are expected to have * lesser backups than given backupCount. */ private static Predicate<RecordStore> lesserBackupMapsThen(final int backupCount) { return recordStore -> recordStore.getMapContainer().getTotalBackupCount() < backupCount; } private MetaDataGenerator getMetaDataGenerator() { return mapServiceContext.getMapNearCacheManager().getInvalidator().getMetaDataGenerator(); } @SuppressWarnings("checkstyle:NPathComplexity") private void populateIndexes(PartitionMigrationEvent event, TargetIndexes targetIndexes, String stepName) { assert event.getMigrationEndpoint() == DESTINATION; assert targetIndexes != null; if (event.getNewReplicaIndex() != 0) { // backup partitions have no indexes to populate return; } PartitionContainer container = mapServiceContext.getPartitionContainer(event.getPartitionId()); for (RecordStore<Record> recordStore : container.getMaps().values()) { MapContainer mapContainer = mapServiceContext.getMapContainer(recordStore.getName()); Indexes indexes = mapContainer.getIndexes(event.getPartitionId()); indexes.createIndexesFromRecordedDefinitions(); if (!indexes.haveAtLeastOneIndex()) { // no indexes to work with continue; } if (indexes.isGlobal() && targetIndexes == TargetIndexes.NON_GLOBAL) { continue; } if (!indexes.isGlobal() && targetIndexes == TargetIndexes.GLOBAL) { continue; } InternalIndex[] indexesSnapshot = indexes.getIndexes(); Indexes.beginPartitionUpdate(indexesSnapshot); CacheDeserializedValues cacheDeserializedValues = mapContainer.getMapConfig().getCacheDeserializedValues(); CachedQueryEntry<?, ?> cachedEntry = cacheDeserializedValues == NEVER ? new CachedQueryEntry<>(serializationService, mapContainer.getExtractors()) : null; recordStore.forEach((key, record) -> { Object value = Records.getValueOrCachedValue(record, serializationService); if (value != null) { QueryableEntry queryEntry = mapContainer.newQueryEntry(key, value); queryEntry.setRecord(record); CachedQueryEntry<?, ?> newEntry = cachedEntry == null ? (CachedQueryEntry<?, ?>) queryEntry : cachedEntry.init(key, value); indexes.putEntry(newEntry, null, queryEntry, Index.OperationSource.SYSTEM); } }, false); Indexes.markPartitionAsIndexed(event.getPartitionId(), indexesSnapshot); } if (logger.isFinestEnabled()) { logger.finest(String.format("Populated indexes at step `%s`:[%s]", stepName, event)); } } private void depopulateIndexes(PartitionMigrationEvent event, String stepName) { assert event.getMigrationEndpoint() == SOURCE; assert event.getNewReplicaIndex() != 0 : "Invalid migration event: " + event; if (event.getCurrentReplicaIndex() != 0) { // backup partitions have no indexes to depopulate return; } PartitionContainer container = mapServiceContext.getPartitionContainer(event.getPartitionId()); for (RecordStore<Record> recordStore : container.getMaps().values()) { MapContainer mapContainer = mapServiceContext.getMapContainer(recordStore.getName()); Indexes indexes = mapContainer.getIndexes(event.getPartitionId()); if (!indexes.haveAtLeastOneIndex()) { // no indexes to work with continue; } InternalIndex[] indexesSnapshot = indexes.getIndexes(); Indexes.beginPartitionUpdate(indexesSnapshot); CachedQueryEntry<?, ?> entry = new CachedQueryEntry<>(serializationService, mapContainer.getExtractors()); recordStore.forEach((key, record) -> { Object value = Records.getValueOrCachedValue(record, serializationService); entry.init(key, value); indexes.removeEntry(entry, Index.OperationSource.SYSTEM); }, false); Indexes.markPartitionAsUnindexed(event.getPartitionId(), indexesSnapshot); } if (logger.isFinestEnabled()) { logger.finest(String.format("Depopulated indexes at step `%s`:[%s]", stepName, event)); } } private enum TargetIndexes { GLOBAL, NON_GLOBAL } private static boolean isLocalPromotion(PartitionMigrationEvent event) { return event.getMigrationEndpoint() == DESTINATION && event.getCurrentReplicaIndex() > 0 && event.getNewReplicaIndex() == 0; } protected long getNow() { return Clock.currentTimeMillis(); } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.partition; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.AutoFailTestSupport; import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.partition.dto.Partitioning; import org.apache.activemq.partition.dto.Target; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.jms.*; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; /** * Unit tests for the PartitionBroker plugin. */ public class PartitionBrokerTest { protected HashMap<String, BrokerService> brokers = new HashMap<String, BrokerService>(); protected ArrayList<Connection> connections = new ArrayList<Connection>(); Partitioning partitioning; @Before public void setUp() throws Exception { partitioning = new Partitioning(); partitioning.brokers = new HashMap<String, String>(); } /** * Partitioning can only re-direct failover clients since those * can re-connect and re-establish their state with another broker. */ @Test(timeout = 1000*60*60) public void testNonFailoverClientHasNoPartitionEffect() throws Exception { partitioning.byClientId = new HashMap<String, Target>(); partitioning.byClientId.put("client1", new Target("broker1")); createBrokerCluster(2); Connection connection = createConnectionToUrl(getConnectURL("broker2")); within(5, TimeUnit.SECONDS, new Task() { public void run() throws Exception { assertEquals(0, getTransportConnector("broker1").getConnections().size()); assertEquals(1, getTransportConnector("broker2").getConnections().size()); } }); connection.setClientID("client1"); connection.start(); Thread.sleep(1000); assertEquals(0, getTransportConnector("broker1").getConnections().size()); assertEquals(1, getTransportConnector("broker2").getConnections().size()); } @Test(timeout = 1000*60*60) public void testPartitionByClientId() throws Exception { partitioning.byClientId = new HashMap<String, Target>(); partitioning.byClientId.put("client1", new Target("broker1")); partitioning.byClientId.put("client2", new Target("broker2")); createBrokerCluster(2); Connection connection = createConnectionTo("broker2"); within(5, TimeUnit.SECONDS, new Task() { public void run() throws Exception { assertEquals(0, getTransportConnector("broker1").getConnections().size()); assertEquals(1, getTransportConnector("broker2").getConnections().size()); } }); connection.setClientID("client1"); connection.start(); within(5, TimeUnit.SECONDS, new Task() { public void run() throws Exception { assertEquals(1, getTransportConnector("broker1").getConnections().size()); assertEquals(0, getTransportConnector("broker2").getConnections().size()); } }); } @Test(timeout = 1000*60*60) public void testPartitionByQueue() throws Exception { partitioning.byQueue = new HashMap<String, Target>(); partitioning.byQueue.put("foo", new Target("broker1")); createBrokerCluster(2); Connection connection2 = createConnectionTo("broker2"); within(5, TimeUnit.SECONDS, new Task() { public void run() throws Exception { assertEquals(0, getTransportConnector("broker1").getConnections().size()); assertEquals(1, getTransportConnector("broker2").getConnections().size()); } }); Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session2.createConsumer(session2.createQueue("foo")); within(5, TimeUnit.SECONDS, new Task() { public void run() throws Exception { assertEquals(1, getTransportConnector("broker1").getConnections().size()); assertEquals(0, getTransportConnector("broker2").getConnections().size()); } }); Connection connection1 = createConnectionTo("broker2"); Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session1.createProducer(session1.createQueue("foo")); within(5, TimeUnit.SECONDS, new Task() { public void run() throws Exception { assertEquals(1, getTransportConnector("broker1").getConnections().size()); assertEquals(1, getTransportConnector("broker2").getConnections().size()); } }); for (int i = 0; i < 100; i++) { producer.send(session1.createTextMessage("#" + i)); } within(5, TimeUnit.SECONDS, new Task() { public void run() throws Exception { assertEquals(2, getTransportConnector("broker1").getConnections().size()); assertEquals(0, getTransportConnector("broker2").getConnections().size()); } }); } static interface Task { public void run() throws Exception; } private void within(int time, TimeUnit unit, Task task) throws InterruptedException { long timeMS = unit.toMillis(time); long deadline = System.currentTimeMillis() + timeMS; while (true) { try { task.run(); return; } catch (Throwable e) { long remaining = deadline - System.currentTimeMillis(); if( remaining <=0 ) { if( e instanceof RuntimeException ) { throw (RuntimeException)e; } if( e instanceof Error ) { throw (Error)e; } throw new RuntimeException(e); } Thread.sleep(Math.min(timeMS/10, remaining)); } } } protected Connection createConnectionTo(String brokerId) throws IOException, URISyntaxException, JMSException { return createConnectionToUrl("failover://(" + getConnectURL(brokerId) + ")"); } private Connection createConnectionToUrl(String url) throws JMSException { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url); Connection connection = factory.createConnection(); connections.add(connection); return connection; } protected String getConnectURL(String broker) throws IOException, URISyntaxException { TransportConnector tcp = getTransportConnector(broker); return tcp.getConnectUri().toString(); } private TransportConnector getTransportConnector(String broker) { BrokerService brokerService = brokers.get(broker); if( brokerService==null ) { throw new IllegalArgumentException("Invalid broker id"); } return brokerService.getTransportConnectorByName("tcp"); } protected void createBrokerCluster(int brokerCount) throws Exception { for (int i = 1; i <= brokerCount; i++) { String brokerId = "broker" + i; BrokerService broker = createBroker(brokerId); broker.setPersistent(false); broker.addConnector("tcp://localhost:0").setName("tcp"); addPartitionBrokerPlugin(broker); broker.start(); broker.waitUntilStarted(); partitioning.brokers.put(brokerId, getConnectURL(brokerId)); } } protected void addPartitionBrokerPlugin(BrokerService broker) { PartitionBrokerPlugin plugin = new PartitionBrokerPlugin(); plugin.setConfig(partitioning); broker.setPlugins(new BrokerPlugin[]{plugin}); } protected BrokerService createBroker(String name) { BrokerService broker = new BrokerService(); broker.setBrokerName(name); brokers.put(name, broker); return broker; } @After public void tearDown() throws Exception { for (Connection connection : connections) { try { connection.close(); } catch (Throwable e) { } } connections.clear(); for (BrokerService broker : brokers.values()) { try { broker.stop(); broker.waitUntilStopped(); } catch (Throwable e) { } } brokers.clear(); } }
package org.onvif.ver10.schema; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.cxf.xjc.runtime.JAXBToStringStyle; /** * <p>Java class for ExposureOptions complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ExposureOptions"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Mode" type="{http://www.onvif.org/ver10/schema}ExposureMode" maxOccurs="unbounded"/&gt; * &lt;element name="Priority" type="{http://www.onvif.org/ver10/schema}ExposurePriority" maxOccurs="unbounded"/&gt; * &lt;element name="MinExposureTime" type="{http://www.onvif.org/ver10/schema}FloatRange"/&gt; * &lt;element name="MaxExposureTime" type="{http://www.onvif.org/ver10/schema}FloatRange"/&gt; * &lt;element name="MinGain" type="{http://www.onvif.org/ver10/schema}FloatRange"/&gt; * &lt;element name="MaxGain" type="{http://www.onvif.org/ver10/schema}FloatRange"/&gt; * &lt;element name="MinIris" type="{http://www.onvif.org/ver10/schema}FloatRange"/&gt; * &lt;element name="MaxIris" type="{http://www.onvif.org/ver10/schema}FloatRange"/&gt; * &lt;element name="ExposureTime" type="{http://www.onvif.org/ver10/schema}FloatRange"/&gt; * &lt;element name="Gain" type="{http://www.onvif.org/ver10/schema}FloatRange"/&gt; * &lt;element name="Iris" type="{http://www.onvif.org/ver10/schema}FloatRange"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ExposureOptions", propOrder = { "mode", "priority", "minExposureTime", "maxExposureTime", "minGain", "maxGain", "minIris", "maxIris", "exposureTime", "gain", "iris" }) public class ExposureOptions { @XmlElement(name = "Mode", required = true) @XmlSchemaType(name = "string") protected List<ExposureMode> mode; @XmlElement(name = "Priority", required = true) @XmlSchemaType(name = "string") protected List<ExposurePriority> priority; @XmlElement(name = "MinExposureTime", required = true) protected FloatRange minExposureTime; @XmlElement(name = "MaxExposureTime", required = true) protected FloatRange maxExposureTime; @XmlElement(name = "MinGain", required = true) protected FloatRange minGain; @XmlElement(name = "MaxGain", required = true) protected FloatRange maxGain; @XmlElement(name = "MinIris", required = true) protected FloatRange minIris; @XmlElement(name = "MaxIris", required = true) protected FloatRange maxIris; @XmlElement(name = "ExposureTime", required = true) protected FloatRange exposureTime; @XmlElement(name = "Gain", required = true) protected FloatRange gain; @XmlElement(name = "Iris", required = true) protected FloatRange iris; /** * Gets the value of the mode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the mode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ExposureMode } * * */ public List<ExposureMode> getMode() { if (mode == null) { mode = new ArrayList<ExposureMode>(); } return this.mode; } /** * Gets the value of the priority property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the priority property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPriority().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ExposurePriority } * * */ public List<ExposurePriority> getPriority() { if (priority == null) { priority = new ArrayList<ExposurePriority>(); } return this.priority; } /** * Gets the value of the minExposureTime property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getMinExposureTime() { return minExposureTime; } /** * Sets the value of the minExposureTime property. * * @param value * allowed object is * {@link FloatRange } * */ public void setMinExposureTime(FloatRange value) { this.minExposureTime = value; } /** * Gets the value of the maxExposureTime property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getMaxExposureTime() { return maxExposureTime; } /** * Sets the value of the maxExposureTime property. * * @param value * allowed object is * {@link FloatRange } * */ public void setMaxExposureTime(FloatRange value) { this.maxExposureTime = value; } /** * Gets the value of the minGain property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getMinGain() { return minGain; } /** * Sets the value of the minGain property. * * @param value * allowed object is * {@link FloatRange } * */ public void setMinGain(FloatRange value) { this.minGain = value; } /** * Gets the value of the maxGain property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getMaxGain() { return maxGain; } /** * Sets the value of the maxGain property. * * @param value * allowed object is * {@link FloatRange } * */ public void setMaxGain(FloatRange value) { this.maxGain = value; } /** * Gets the value of the minIris property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getMinIris() { return minIris; } /** * Sets the value of the minIris property. * * @param value * allowed object is * {@link FloatRange } * */ public void setMinIris(FloatRange value) { this.minIris = value; } /** * Gets the value of the maxIris property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getMaxIris() { return maxIris; } /** * Sets the value of the maxIris property. * * @param value * allowed object is * {@link FloatRange } * */ public void setMaxIris(FloatRange value) { this.maxIris = value; } /** * Gets the value of the exposureTime property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getExposureTime() { return exposureTime; } /** * Sets the value of the exposureTime property. * * @param value * allowed object is * {@link FloatRange } * */ public void setExposureTime(FloatRange value) { this.exposureTime = value; } /** * Gets the value of the gain property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getGain() { return gain; } /** * Sets the value of the gain property. * * @param value * allowed object is * {@link FloatRange } * */ public void setGain(FloatRange value) { this.gain = value; } /** * Gets the value of the iris property. * * @return * possible object is * {@link FloatRange } * */ public FloatRange getIris() { return iris; } /** * Sets the value of the iris property. * * @param value * allowed object is * {@link FloatRange } * */ public void setIris(FloatRange value) { this.iris = value; } /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin * */ @Override public String toString() { return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE); } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.jbpm.test.functional.timer; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.Statement; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.Scanner; import java.util.Set; import javax.naming.InitialContext; import javax.sql.DataSource; import org.jbpm.persistence.util.PersistenceUtil; import org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory; import org.jbpm.test.AbstractBaseTest; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.kie.api.event.process.ProcessEventListener; import org.kie.api.event.rule.AgendaEventListener; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.task.TaskLifeCycleEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import bitronix.tm.resource.ResourceRegistrar; import bitronix.tm.resource.common.XAResourceProducer; import bitronix.tm.resource.jdbc.PoolingDataSource; public abstract class TimerBaseTest extends AbstractBaseTest { private static final Logger logger = LoggerFactory.getLogger(TimerBaseTest.class); private static PoolingDataSource pds; protected static final String DATASOURCE_PROPERTIES = "/datasource.properties"; protected static final String MAX_POOL_SIZE = "maxPoolSize"; protected static final String ALLOW_LOCAL_TXS = "allowLocalTransactions"; protected static final String DATASOURCE_CLASS_NAME = "className"; protected static final String DRIVER_CLASS_NAME = "driverClassName"; protected static final String USER = "user"; protected static final String PASSWORD = "password"; protected static final String JDBC_URL = "url"; public static PoolingDataSource setupPoolingDataSource() { Properties dsProps = getDatasourceProperties(); PoolingDataSource pds = PersistenceUtil.setupPoolingDataSource(dsProps, "jdbc/jbpm-ds", false); try { pds.init(); } catch (Exception e) { logger.warn("DBPOOL_MGR:Looks like there is an issue with creating db pool because of " + e.getMessage() + " cleaing up..."); Set<String> resources = ResourceRegistrar.getResourcesUniqueNames(); for (String resource : resources) { XAResourceProducer producer = ResourceRegistrar.get(resource); producer.close(); ResourceRegistrar.unregister(producer); logger.info("DBPOOL_MGR:Removed resource " + resource); } logger.info("DBPOOL_MGR: attempting to create db pool again..."); pds = PersistenceUtil.setupPoolingDataSource(dsProps, "jdbc/jbpm-ds", false); pds.init(); logger.info("DBPOOL_MGR:Pool created after cleanup of leftover resources"); } return pds; } /** * This reads in the (maven filtered) datasource properties from the test * resource directory. * * @return Properties containing the datasource properties. */ private static Properties getDatasourceProperties() { boolean propertiesNotFound = false; // Central place to set additional H2 properties System.setProperty("h2.lobInDatabase", "true"); InputStream propsInputStream = TimerBaseTest.class.getResourceAsStream(DATASOURCE_PROPERTIES); Properties props = new Properties(); if (propsInputStream != null) { try { props.load(propsInputStream); } catch (IOException ioe) { propertiesNotFound = true; logger.warn("Unable to find properties, using default H2 properties: " + ioe.getMessage()); ioe.printStackTrace(); } } else { propertiesNotFound = true; } String password = props.getProperty("password"); if ("${maven.jdbc.password}".equals(password) || propertiesNotFound) { logger.warn( "Unable to load datasource properties [" + DATASOURCE_PROPERTIES + "]" ); } // If maven filtering somehow doesn't work the way it should.. setDefaultProperties(props); return props; } /** * Return the default database/datasource properties - These properties use * an in-memory H2 database * * This is used when the developer is somehow running the tests but * bypassing the maven filtering that's been turned on in the pom. * * @return Properties containing the default properties */ private static void setDefaultProperties(Properties props) { String[] keyArr = { "serverName", "portNumber", "databaseName", JDBC_URL, USER, PASSWORD, DRIVER_CLASS_NAME, DATASOURCE_CLASS_NAME, MAX_POOL_SIZE, ALLOW_LOCAL_TXS }; String[] defaultPropArr = { "", "", "", "jdbc:h2:mem:jbpm-db;MVCC=true", "sa", "", "org.h2.Driver", "bitronix.tm.resource.jdbc.lrc.LrcXADataSource", "5", "true" }; Assert.assertTrue("Unequal number of keys for default properties", keyArr.length == defaultPropArr.length); for (int i = 0; i < keyArr.length; ++i) { if( ! props.containsKey(keyArr[i]) ) { props.put(keyArr[i], defaultPropArr[i]); } } } @BeforeClass public static void setUpOnce() { if (pds == null) { pds = setupPoolingDataSource(); } } @AfterClass public static void tearDownOnce() { if (pds != null) { pds.close(); pds = null; } } protected void testCreateQuartzSchema() { Scanner scanner = new Scanner(this.getClass().getResourceAsStream("/quartz_tables_h2.sql")).useDelimiter(";"); try { Connection connection = ((DataSource)InitialContext.doLookup("jdbc/jbpm-ds")).getConnection(); Statement stmt = connection.createStatement(); while (scanner.hasNext()) { String sql = scanner.next(); stmt.executeUpdate(sql); } stmt.close(); connection.close(); } catch (Exception e) { } } protected class TestRegisterableItemsFactory extends DefaultRegisterableItemsFactory { private ProcessEventListener[] plistener; private AgendaEventListener[] alistener; private TaskLifeCycleEventListener[] tlistener; public TestRegisterableItemsFactory(ProcessEventListener... listener) { this.plistener = listener; } public TestRegisterableItemsFactory(AgendaEventListener... listener) { this.alistener = listener; } public TestRegisterableItemsFactory(TaskLifeCycleEventListener... tlistener) { this.tlistener = tlistener; } @Override public List<ProcessEventListener> getProcessEventListeners( RuntimeEngine runtime) { List<ProcessEventListener> listeners = super.getProcessEventListeners(runtime); if (plistener != null) { listeners.addAll(Arrays.asList(plistener)); } return listeners; } @Override public List<AgendaEventListener> getAgendaEventListeners( RuntimeEngine runtime) { List<AgendaEventListener> listeners = super.getAgendaEventListeners(runtime); if (alistener != null) { listeners.addAll(Arrays.asList(alistener)); } return listeners; } @Override public List<TaskLifeCycleEventListener> getTaskListeners() { List<TaskLifeCycleEventListener> listeners = super.getTaskListeners(); if (tlistener != null) { listeners.addAll(Arrays.asList(tlistener)); } return listeners; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.openwire.amq; import javax.jms.Connection; import javax.jms.ConnectionConsumer; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.ServerSessionPool; import javax.jms.Session; import javax.jms.Topic; import org.apache.activemq.command.ActiveMQDestination; /** * adapted from: org.apache.activemq.test.JmsResourceProvider */ public class JmsResourceProvider { private boolean transacted; private int ackMode = Session.AUTO_ACKNOWLEDGE; private boolean isTopic; private int deliveryMode = DeliveryMode.PERSISTENT; private String durableName = "DummyName"; private String clientID = getClass().getName(); /** * Creates a connection. * * @see org.apache.activemq.test.JmsResourceProvider#createConnection(javax.jms.ConnectionFactory) */ public Connection createConnection(ConnectionFactory cf) throws JMSException { Connection connection = cf.createConnection(); if (getClientID() != null) { connection.setClientID(getClientID()); } return connection; } /** * @see org.apache.activemq.test.JmsResourceProvider#createSession(javax.jms.Connection) */ public Session createSession(Connection conn) throws JMSException { System.out.println("createing a session tx ? " + transacted); return conn.createSession(transacted, ackMode); } /** * @see org.apache.activemq.test.JmsResourceProvider#createConsumer(javax.jms.Session, * javax.jms.Destination) */ public MessageConsumer createConsumer(Session session, Destination destination) throws JMSException { if (isDurableSubscriber()) { return session.createDurableSubscriber((Topic) destination, durableName); } return session.createConsumer(destination); } /** * Creates a connection for a consumer. * * @param ssp - ServerSessionPool * @return ConnectionConsumer */ public ConnectionConsumer createConnectionConsumer(Connection connection, Destination destination, ServerSessionPool ssp) throws JMSException { return connection.createConnectionConsumer(destination, null, ssp, 1); } /** * Creates a producer. * * @see org.apache.activemq.test.JmsResourceProvider#createProducer(javax.jms.Session, * javax.jms.Destination) */ public MessageProducer createProducer(Session session, Destination destination) throws JMSException { MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(deliveryMode); return producer; } /** * Creates a destination, which can either a topic or a queue. * * @see org.apache.activemq.test.JmsResourceProvider#createDestination(javax.jms.Session, * java.lang.String) */ public Destination createDestination(Session session, JmsTransactionTestSupport support) throws JMSException { if (isTopic) { return (Destination) support.createDestination(session, ActiveMQDestination.TOPIC_TYPE); } else { return (Destination) support.createDestination(session, ActiveMQDestination.QUEUE_TYPE); } } /** * Returns true if the subscriber is durable. * * @return isDurableSubscriber */ public boolean isDurableSubscriber() { return isTopic && durableName != null; } /** * Returns the acknowledgement mode. * * @return Returns the ackMode. */ public int getAckMode() { return ackMode; } /** * Sets the acnknowledgement mode. * * @param ackMode The ackMode to set. */ public void setAckMode(int ackMode) { this.ackMode = ackMode; } /** * Returns true if the destination is a topic, false if the destination is a * queue. * * @return Returns the isTopic. */ public boolean isTopic() { return isTopic; } /** * @param isTopic The isTopic to set. */ public void setTopic(boolean isTopic) { this.isTopic = isTopic; } /** * Return true if the session is transacted. * * @return Returns the transacted. */ public boolean isTransacted() { return transacted; } /** * Sets the session to be transacted. * * @param transacted */ public void setTransacted(boolean transacted) { this.transacted = transacted; if (transacted) { setAckMode(Session.SESSION_TRANSACTED); } } /** * Returns the delivery mode. * * @return deliveryMode */ public int getDeliveryMode() { return deliveryMode; } /** * Sets the delivery mode. * * @param deliveryMode */ public void setDeliveryMode(int deliveryMode) { this.deliveryMode = deliveryMode; } /** * Returns the client id. * * @return clientID */ public String getClientID() { return clientID; } /** * Sets the client id. * * @param clientID */ public void setClientID(String clientID) { this.clientID = clientID; } /** * Returns the durable name of the provider. * * @return durableName */ public String getDurableName() { return durableName; } /** * Sets the durable name of the provider. * * @param durableName */ public void setDurableName(String durableName) { this.durableName = durableName; } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : 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.trans.steps.simplemapping; import java.util.ArrayList; import java.util.List; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.RowProducer; import org.pentaho.di.trans.StepWithMappingMeta; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.TransMeta.TransformationType; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.RowListener; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.steps.TransStepUtil; import org.pentaho.di.trans.steps.mapping.MappingValueRename; import org.pentaho.di.trans.steps.mappinginput.MappingInput; import org.pentaho.di.trans.steps.mappingoutput.MappingOutput; /** * Execute a mapping: a re-usuable transformation * * @author Matt * @since 22-nov-2005 */ public class SimpleMapping extends BaseStep implements StepInterface { private static Class<?> PKG = SimpleMappingMeta.class; // for i18n purposes, needed by Translator2!! private SimpleMappingMeta meta; private SimpleMappingData data; public SimpleMapping( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans ) { super( stepMeta, stepDataInterface, copyNr, transMeta, trans ); } /** * Process a single row. In our case, we send one row of data to a piece of transformation. In the transformation, we * look up the MappingInput step to send our rows to it. As a consequence, for the time being, there can only be one * MappingInput and one MappingOutput step in the Mapping. */ public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException { meta = (SimpleMappingMeta) smi; setData( (SimpleMappingData) sdi ); SimpleMappingData simpleMappingData = getData(); try { if ( first ) { first = false; simpleMappingData.wasStarted = true; // Rows read are injected into the one available Mapping Input step // String mappingInputStepname = simpleMappingData.mappingInput.getStepname(); RowProducer rowProducer = simpleMappingData.mappingTrans.addRowProducer( mappingInputStepname, 0 ); simpleMappingData.rowDataInputMapper = new RowDataInputMapper( meta.getInputMapping(), rowProducer ); // Rows produced by the mapping are read and passed on. // String mappingOutputStepname = simpleMappingData.mappingOutput.getStepname(); StepInterface outputStepInterface = simpleMappingData.mappingTrans.findStepInterface( mappingOutputStepname, 0 ); RowOutputDataMapper outputDataMapper = new RowOutputDataMapper( meta.getInputMapping(), meta.getOutputMapping(), new PutRowInterface() { @Override public void putRow( RowMetaInterface rowMeta, Object[] rowData ) throws KettleStepException { SimpleMapping.this.putRow( rowMeta, rowData ); } } ); outputStepInterface.addRowListener( outputDataMapper ); // Start the mapping/sub-transformation threads // simpleMappingData.mappingTrans.startThreads(); } // The data we read we pass to the mapping // Object[] row = getRow(); boolean rowWasPut = false; if ( row != null ) { while ( !( data.mappingTrans.isFinishedOrStopped() || rowWasPut ) ) { rowWasPut = data.rowDataInputMapper.putRow( getInputRowMeta(), row ); } } if ( !rowWasPut ) { simpleMappingData.rowDataInputMapper.finished(); simpleMappingData.mappingTrans.waitUntilFinished(); setOutputDone(); return false; } return true; } catch ( Throwable t ) { // Some unexpected situation occurred. // Better to stop the mapping transformation. // if ( simpleMappingData.mappingTrans != null ) { simpleMappingData.mappingTrans.stopAll(); } // Forward the exception... // throw new KettleException( t ); } } public void prepareMappingExecution() throws KettleException { SimpleMappingData simpleMappingData = getData(); // Create the transformation from meta-data... simpleMappingData.mappingTrans = new Trans( simpleMappingData.mappingTransMeta, this ); // Set the parameters values in the mapping. // StepWithMappingMeta.activateParams( simpleMappingData.mappingTrans, simpleMappingData.mappingTrans, this, simpleMappingData.mappingTransMeta.listParameters(), meta.getMappingParameters().getVariable(), meta.getMappingParameters().getInputField() ); if ( simpleMappingData.mappingTransMeta.getTransformationType() != TransformationType.Normal ) { simpleMappingData.mappingTrans.getTransMeta().setUsingThreadPriorityManagment( false ); } // Leave a path up so that we can set variables in sub-transformations... // simpleMappingData.mappingTrans.setParentTrans( getTrans() ); // Pass down the safe mode flag to the mapping... // simpleMappingData.mappingTrans.setSafeModeEnabled( getTrans().isSafeModeEnabled() ); // Pass down the metrics gathering flag: // simpleMappingData.mappingTrans.setGatheringMetrics( getTrans().isGatheringMetrics() ); // Also set the name of this step in the mapping transformation for logging // purposes // simpleMappingData.mappingTrans.setMappingStepName( getStepname() ); initServletConfig(); // We launch the transformation in the processRow when the first row is // received. // This will allow the correct variables to be passed. // Otherwise the parent is the init() thread which will be gone once the // init is done. // try { simpleMappingData.mappingTrans.prepareExecution( getTrans().getArguments() ); } catch ( KettleException e ) { throw new KettleException( BaseMessages.getString( PKG, "SimpleMapping.Exception.UnableToPrepareExecutionOfMapping" ), e ); } // If there is no read/write logging step set, we can insert the data from // the first mapping input/output step... // MappingInput[] mappingInputs = simpleMappingData.mappingTrans.findMappingInput(); if ( mappingInputs.length == 0 ) { throw new KettleException( "The simple mapping step needs one Mapping Input step to write to in the sub-transformation" ); } if ( mappingInputs.length > 1 ) { throw new KettleException( "The simple mapping step does not support multiple Mapping Input steps to write to in the sub-transformation" ); } simpleMappingData.mappingInput = mappingInputs[0]; simpleMappingData.mappingInput.setConnectorSteps( new StepInterface[0], new ArrayList<MappingValueRename>(), null ); // LogTableField readField = data.mappingTransMeta.getTransLogTable().findField(TransLogTable.ID.LINES_READ); // if (readField.getSubject() == null) { // readField.setSubject(data.mappingInput.getStepMeta()); // } MappingOutput[] mappingOutputs = simpleMappingData.mappingTrans.findMappingOutput(); if ( mappingOutputs.length == 0 ) { throw new KettleException( "The simple mapping step needs one Mapping Output step to read from in the sub-transformation" ); } if ( mappingOutputs.length > 1 ) { throw new KettleException( "The simple mapping step does not support " + "multiple Mapping Output steps to read from in the sub-transformation" ); } simpleMappingData.mappingOutput = mappingOutputs[0]; // LogTableField writeField = data.mappingTransMeta.getTransLogTable().findField(TransLogTable.ID.LINES_WRITTEN); // if (writeField.getSubject() == null && data.mappingOutputs != null && data.mappingOutputs.length >= 1) { // writeField.setSubject(data.mappingOutputs[0].getStepMeta()); // } // Finally, add the mapping transformation to the active sub-transformations // map in the parent transformation // getTrans().addActiveSubTransformation( getStepname(), simpleMappingData.mappingTrans ); } void initServletConfig() { TransStepUtil.initServletConfig( getTrans(), getData().getMappingTrans() ); } public static void addInputRenames( List<MappingValueRename> renameList, List<MappingValueRename> addRenameList ) { for ( MappingValueRename rename : addRenameList ) { if ( renameList.indexOf( rename ) < 0 ) { renameList.add( rename ); } } } public boolean init( StepMetaInterface smi, StepDataInterface sdi ) { meta = (SimpleMappingMeta) smi; setData( (SimpleMappingData) sdi ); SimpleMappingData simpleMappingData = getData(); if ( super.init( smi, sdi ) ) { // First we need to load the mapping (transformation) try { // Pass the repository down to the metadata object... // meta.setRepository( getTransMeta().getRepository() ); simpleMappingData.mappingTransMeta = SimpleMappingMeta.loadMappingMeta( meta, meta.getRepository(), meta.getMetaStore(), this, meta.getMappingParameters().isInheritingAllVariables() ); if ( simpleMappingData.mappingTransMeta != null ) { // Do we have a mapping at all? // OK, now prepare the execution of the mapping. // This includes the allocation of RowSet buffers, the creation of the // sub-transformation threads, etc. // prepareMappingExecution(); // That's all for now... return true; } else { logError( "No valid mapping was specified!" ); return false; } } catch ( Exception e ) { logError( "Unable to load the mapping transformation because of an error : " + e.toString() ); logError( Const.getStackTracker( e ) ); } } return false; } public void dispose( StepMetaInterface smi, StepDataInterface sdi ) { // Close the running transformation if ( getData().wasStarted ) { if ( !getData().mappingTrans.isFinished() ) { // Wait until the child transformation has finished. getData().mappingTrans.waitUntilFinished(); } // Remove it from the list of active sub-transformations... // getTrans().removeActiveSubTransformation( getStepname() ); // See if there was an error in the sub-transformation, in that case, flag error etc. if ( getData().mappingTrans.getErrors() > 0 ) { logError( BaseMessages.getString( PKG, "SimpleMapping.Log.ErrorOccurredInSubTransformation" ) ); setErrors( 1 ); } } super.dispose( smi, sdi ); } public void stopRunning( StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface ) throws KettleException { if ( getData().mappingTrans != null ) { getData().mappingTrans.stopAll(); } } public void stopAll() { // Stop the mapping step. if ( getData().mappingTrans != null ) { getData().mappingTrans.stopAll(); } // Also stop this step super.stopAll(); } public Trans getMappingTrans() { return getData().mappingTrans; } /** * For preview of the main data path, make sure we pass the row listener down to the Mapping Output step... */ public void addRowListener( RowListener rowListener ) { MappingOutput[] mappingOutputs = getData().mappingTrans.findMappingOutput(); if ( mappingOutputs == null || mappingOutputs.length == 0 ) { return; // Nothing to do here... } // Simple case: one output mapping step : add the row listener over there // /* * if (mappingOutputs.length==1) { mappingOutputs[0].addRowListener(rowListener); } else { // Find the main data * path... // * * * } */ // Add the row listener to all the outputs in the mapping... // for ( MappingOutput mappingOutput : mappingOutputs ) { mappingOutput.addRowListener( rowListener ); } } public SimpleMappingData getData() { return data; } private void setData( SimpleMappingData data ) { this.data = data; } }
/** * Copyright 2016 LinkedIn Corp. 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. */ package com.github.ambry.clustermap; import com.github.ambry.config.ClusterMapConfig; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An Ambry hardwareLayout consists of a set of {@link Datacenter}s. */ public class HardwareLayout { private final String clusterName; private final long version; private final ArrayList<Datacenter> datacenters; private final Map<Byte, Datacenter> datacenterById; private final long rawCapacityInBytes; private final long dataNodeCount; private final long diskCount; private final Map<HardwareState, Long> dataNodeInHardStateCount; private final Map<HardwareState, Long> diskInHardStateCount; private final ClusterMapConfig clusterMapConfig; private static final Logger logger = LoggerFactory.getLogger(HardwareLayout.class); public HardwareLayout(JSONObject jsonObject, ClusterMapConfig clusterMapConfig) throws JSONException { if (logger.isTraceEnabled()) { logger.trace("HardwareLayout {}", jsonObject.toString()); } this.clusterName = jsonObject.getString("clusterName"); this.version = jsonObject.getLong("version"); this.clusterMapConfig = clusterMapConfig; this.datacenters = new ArrayList<Datacenter>(jsonObject.getJSONArray("datacenters").length()); this.datacenterById = new HashMap<>(); for (int i = 0; i < jsonObject.getJSONArray("datacenters").length(); ++i) { Datacenter datacenter = new Datacenter(this, jsonObject.getJSONArray("datacenters").getJSONObject(i), clusterMapConfig); this.datacenters.add(datacenter); datacenterById.put(datacenter.getId(), datacenter); } this.rawCapacityInBytes = calculateRawCapacityInBytes(); this.dataNodeCount = calculateDataNodeCount(); this.diskCount = calculateDiskCount(); this.dataNodeInHardStateCount = calculateDataNodeInHardStateCount(); this.diskInHardStateCount = calculateDiskInHardStateCount(); validate(); } public String getClusterName() { return clusterName; } public long getVersion() { return version; } public List<Datacenter> getDatacenters() { return datacenters; } public long getRawCapacityInBytes() { return rawCapacityInBytes; } private long calculateRawCapacityInBytes() { long capacityInBytes = 0; for (Datacenter datacenter : datacenters) { capacityInBytes += datacenter.getRawCapacityInBytes(); } return capacityInBytes; } public long getDatacenterCount() { return datacenters.size(); } public long getDataNodeCount() { return dataNodeCount; } private long calculateDataNodeCount() { long count = 0; for (Datacenter datacenter : datacenters) { count += datacenter.getDataNodes().size(); } return count; } public long getDiskCount() { return diskCount; } private long calculateDiskCount() { long count = 0; for (Datacenter datacenter : datacenters) { for (DataNode dataNode : datacenter.getDataNodes()) { count += dataNode.getDisks().size(); } } return count; } public long getDataNodeInHardStateCount(HardwareState hardwareState) { return dataNodeInHardStateCount.get(hardwareState); } ClusterMapConfig getClusterMapConfig() { return clusterMapConfig; } private Map<HardwareState, Long> calculateDataNodeInHardStateCount() { Map<HardwareState, Long> dataNodeInStateCount = new HashMap<HardwareState, Long>(); for (HardwareState hardwareState : HardwareState.values()) { dataNodeInStateCount.put(hardwareState, new Long(0)); } for (Datacenter datacenter : datacenters) { for (DataNode dataNode : datacenter.getDataNodes()) { dataNodeInStateCount.put(dataNode.getState(), dataNodeInStateCount.get(dataNode.getState()) + 1); } } return dataNodeInStateCount; } public long calculateUnavailableDataNodeCount() { long count = 0; for (Datacenter datacenter : datacenters) { for (DataNode dataNode : datacenter.getDataNodes()) { if (dataNode.isDown()) { count++; } } } return count; } public long getDiskInHardStateCount(HardwareState hardwareState) { return diskInHardStateCount.get(hardwareState); } private Map<HardwareState, Long> calculateDiskInHardStateCount() { Map<HardwareState, Long> diskInStateCount = new HashMap<HardwareState, Long>(); for (HardwareState hardwareState : HardwareState.values()) { diskInStateCount.put(hardwareState, new Long(0)); } for (Datacenter datacenter : datacenters) { for (DataNode dataNode : datacenter.getDataNodes()) { for (Disk disk : dataNode.getDisks()) { diskInStateCount.put(disk.getState(), diskInStateCount.get(disk.getState()) + 1); } } } return diskInStateCount; } public long calculateUnavailableDiskCount() { long count = 0; for (Datacenter datacenter : datacenters) { for (DataNode dataNode : datacenter.getDataNodes()) { for (Disk disk : dataNode.getDisks()) { if (disk.isDown()) { count++; } } } } return count; } /** * Finds Datacenter by name * * @param datacenterName name of datacenter to be found * @return Datacenter or null if not found. */ public Datacenter findDatacenter(String datacenterName) { for (Datacenter datacenter : datacenters) { if (datacenter.getName().compareToIgnoreCase(datacenterName) == 0) { return datacenter; } } return null; } /** * Finds Datacenter by id * * @param id id of datacenter to find * @return Datacenter or null if not found. */ public Datacenter findDatacenter(byte id) { return datacenterById.get(id); } /** * Finds DataNode by hostname and port. Note that hostname is converted to canonical hostname for comparison. * * @param hostname of datanode * @param port of datanode * @return DataNode or null if not found. */ public DataNode findDataNode(String hostname, int port) { String canonicalHostname = clusterMapConfig.clusterMapResolveHostnames ? ClusterMapUtils.getFullyQualifiedDomainName(hostname) : hostname; logger.trace("host to find host {} port {}", canonicalHostname, port); for (Datacenter datacenter : datacenters) { logger.trace("datacenter {}", datacenter.getName()); for (DataNode dataNode : datacenter.getDataNodes()) { if (dataNode.getHostname().equals(canonicalHostname) && (dataNode.getPort() == port)) { return dataNode; } } } return null; } /** * Finds Disk by hostname, port, and mount path. * * @param hostname of datanode * @param port of datanode * @param mountPath of disk * @return Disk or null if not found. */ public Disk findDisk(String hostname, int port, String mountPath) { DataNode dataNode = findDataNode(hostname, port); if (dataNode != null) { for (Disk disk : dataNode.getDisks()) { if (disk.getMountPath().equals(mountPath)) { return disk; } } } return null; } protected void validateClusterName() { if (clusterName == null) { throw new IllegalStateException("HardwareLayout clusterName cannot be null."); } else if (clusterName.length() == 0) { throw new IllegalStateException("HardwareLayout clusterName cannot be zero length."); } } // Validate each hardware component (Datacenter, DataNode, and Disk) are unique protected void validateUniqueness() throws IllegalStateException { logger.trace("begin validateUniqueness."); HashSet<Datacenter> datacenterSet = new HashSet<Datacenter>(); HashSet<DataNode> dataNodeSet = new HashSet<DataNode>(); HashSet<Disk> diskSet = new HashSet<Disk>(); for (Datacenter datacenter : datacenters) { if (!datacenterSet.add(datacenter)) { throw new IllegalStateException("Duplicate Datacenter detected: " + datacenter.toString()); } for (DataNode dataNode : datacenter.getDataNodes()) { if (!dataNodeSet.add(dataNode)) { throw new IllegalStateException("Duplicate DataNode detected: " + dataNode.toString()); } for (Disk disk : dataNode.getDisks()) { if (!diskSet.add(disk)) { throw new IllegalStateException("Duplicate Disk detected: " + disk.toString()); } } } } logger.trace("complete validateUniqueness."); } protected void validate() { logger.trace("begin validate."); validateClusterName(); validateUniqueness(); logger.trace("complete validate."); } public JSONObject toJSONObject() throws JSONException { JSONObject jsonObject = new JSONObject().put("clusterName", clusterName).put("version", version).put("datacenters", new JSONArray()); for (Datacenter datacenter : datacenters) { jsonObject.accumulate("datacenters", datacenter.toJSONObject()); } return jsonObject; } @Override public String toString() { try { return toJSONObject().toString(2); } catch (JSONException e) { logger.error("JSONException caught in toString: {}", e.getCause()); } return null; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } HardwareLayout that = (HardwareLayout) o; if (!clusterName.equals(that.clusterName)) { return false; } return datacenters.equals(that.datacenters); } }
package org.bouncycastle.openssl.jcajce; import java.io.IOException; import java.io.OutputStream; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.Provider; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.CipherOutputStream; import javax.crypto.SecretKey; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.KeyDerivationFunc; import org.bouncycastle.asn1.pkcs.PBES2Parameters; import org.bouncycastle.asn1.pkcs.PBKDF2Params; import org.bouncycastle.asn1.pkcs.PKCS12PBEParams; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.jcajce.PKCS12KeyWithParameters; import org.bouncycastle.jcajce.util.DefaultJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jcajce.util.NamedJcaJceHelper; import org.bouncycastle.jcajce.util.ProviderJcaJceHelper; import org.bouncycastle.operator.GenericKey; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.OutputEncryptor; import org.bouncycastle.operator.jcajce.JceGenericKey; public class JceOpenSSLPKCS8EncryptorBuilder { public static final String AES_128_CBC = NISTObjectIdentifiers.id_aes128_CBC.getId(); public static final String AES_192_CBC = NISTObjectIdentifiers.id_aes192_CBC.getId(); public static final String AES_256_CBC = NISTObjectIdentifiers.id_aes256_CBC.getId(); public static final String DES3_CBC = PKCSObjectIdentifiers.des_EDE3_CBC.getId(); public static final String PBE_SHA1_RC4_128 = PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC4.getId(); public static final String PBE_SHA1_RC4_40 = PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC4.getId(); public static final String PBE_SHA1_3DES = PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC.getId(); public static final String PBE_SHA1_2DES = PKCSObjectIdentifiers.pbeWithSHAAnd2_KeyTripleDES_CBC.getId(); public static final String PBE_SHA1_RC2_128 = PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC.getId(); public static final String PBE_SHA1_RC2_40 = PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC.getId(); private JcaJceHelper helper = new DefaultJcaJceHelper(); private AlgorithmParameters params; private ASN1ObjectIdentifier algOID; byte[] salt; int iterationCount; private Cipher cipher; private SecureRandom random; private AlgorithmParameterGenerator paramGen; private char[] password; private SecretKey key; public JceOpenSSLPKCS8EncryptorBuilder(ASN1ObjectIdentifier algorithm) { algOID = algorithm; this.iterationCount = 2048; } public JceOpenSSLPKCS8EncryptorBuilder setRandom(SecureRandom random) { this.random = random; return this; } public JceOpenSSLPKCS8EncryptorBuilder setPasssword(char[] password) { this.password = password; return this; } public JceOpenSSLPKCS8EncryptorBuilder setIterationCount(int iterationCount) { this.iterationCount = iterationCount; return this; } public JceOpenSSLPKCS8EncryptorBuilder setProvider(String providerName) { helper = new NamedJcaJceHelper(providerName); return this; } public JceOpenSSLPKCS8EncryptorBuilder setProvider(Provider provider) { helper = new ProviderJcaJceHelper(provider); return this; } public OutputEncryptor build() throws OperatorCreationException { final AlgorithmIdentifier algID; salt = new byte[20]; if (random == null) { random = new SecureRandom(); } random.nextBytes(salt); try { this.cipher = helper.createCipher(algOID.getId()); if (PEMUtilities.isPKCS5Scheme2(algOID)) { this.paramGen = helper.createAlgorithmParameterGenerator(algOID.getId()); } } catch (GeneralSecurityException e) { throw new OperatorCreationException(algOID + " not available: " + e.getMessage(), e); } if (PEMUtilities.isPKCS5Scheme2(algOID)) { params = paramGen.generateParameters(); try { KeyDerivationFunc scheme = new KeyDerivationFunc(algOID, ASN1Primitive.fromByteArray(params.getEncoded())); KeyDerivationFunc func = new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, iterationCount)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(func); v.add(scheme); algID = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, PBES2Parameters.getInstance(new DERSequence(v))); } catch (IOException e) { throw new OperatorCreationException(e.getMessage(), e); } try { key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(helper, algOID.getId(), password, salt, iterationCount); cipher.init(Cipher.ENCRYPT_MODE, key, params); } catch (GeneralSecurityException e) { throw new OperatorCreationException(e.getMessage(), e); } } else if (PEMUtilities.isPKCS12(algOID)) { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DEROctetString(salt)); v.add(new ASN1Integer(iterationCount)); algID = new AlgorithmIdentifier(algOID, PKCS12PBEParams.getInstance(new DERSequence(v))); try { cipher.init(Cipher.ENCRYPT_MODE, new PKCS12KeyWithParameters(password, salt, iterationCount)); } catch (GeneralSecurityException e) { throw new OperatorCreationException(e.getMessage(), e); } } else { throw new OperatorCreationException("unknown algorithm: " + algOID, null); } return new OutputEncryptor() { public AlgorithmIdentifier getAlgorithmIdentifier() { return algID; } public OutputStream getOutputStream(OutputStream encOut) { return new CipherOutputStream(encOut, cipher); } public GenericKey getKey() { return new JceGenericKey(algID, key); } }; } }
/* * 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.zookeepermaster.group; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.camel.component.zookeepermaster.ZKContainer; import org.apache.camel.component.zookeepermaster.group.internal.ChildData; import org.apache.camel.component.zookeepermaster.group.internal.ZooKeeperGroup; import org.apache.camel.test.AvailablePortFinder; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryNTimes; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.BindMode; import org.testcontainers.containers.SelinuxContext; import org.testcontainers.shaded.org.apache.commons.io.FileUtils; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.springframework.test.util.AssertionErrors.assertNotEquals; public class GroupTest { private static final Logger LOGGER = LoggerFactory.getLogger(GroupTest.class); private static String beforeTmpdir; private GroupListener listener = new GroupListener<NodeState>() { @Override public void groupEvent(Group<NodeState> group, GroupListener.GroupEvent event) { boolean connected = group.isConnected(); boolean master = group.isMaster(); if (connected) { Collection<NodeState> members = group.members().values(); LOGGER.info("GroupEvent: " + event + " (connected=" + connected + ", master=" + master + ", members=" + members + ")"); } else { LOGGER.info("GroupEvent: " + event + " (connected=" + connected + ", master=false)"); } } }; private ZKContainer startZooKeeper(int port, Path root) throws Exception { LOGGER.info("****************************************"); LOGGER.info("* Starting ZooKeeper container *"); LOGGER.info("****************************************"); ZKContainer container = new ZKContainer(port); container.withNetworkAliases("zk-" + port); if (root != null) { Path data = root.resolve("data"); Path datalog = root.resolve("datalog"); if (!Files.exists(data)) { Files.createDirectories(data); } if (!Files.exists(datalog)) { Files.createDirectories(datalog); } LOGGER.debug("data: {}", data); LOGGER.debug("datalog: {}", datalog); container.addFileSystemBind(data.toAbsolutePath().toString(), "/data", BindMode.READ_WRITE, SelinuxContext.SHARED); container.addFileSystemBind(datalog.toAbsolutePath().toString(), "/datalog", BindMode.READ_WRITE, SelinuxContext.SHARED); } container.start(); LOGGER.info("****************************************"); LOGGER.info("* ZooKeeper container started *"); LOGGER.info("****************************************"); return container; } @BeforeClass public static void before() { // workaround macos issue with docker/testcontainers expecting to use /tmp/ folder beforeTmpdir = System.setProperty("java.io.tmpdir", "/tmp/"); } @AfterClass public static void after() { if (beforeTmpdir != null) { System.setProperty("java.io.tmpdir", beforeTmpdir); } } @Test public void testOrder() throws Exception { int port = AvailablePortFinder.getNextAvailable(); CuratorFramework curator = CuratorFrameworkFactory.builder() .connectString("localhost:" + port) .retryPolicy(new RetryNTimes(10, 100)) .build(); curator.start(); final String path = "/singletons/test/Order" + System.currentTimeMillis(); ArrayList<ZooKeeperGroup> members = new ArrayList<>(); for (int i = 0; i < 4; i++) { ZooKeeperGroup<NodeState> group = new ZooKeeperGroup<>(curator, path, NodeState.class); group.add(listener); members.add(group); } for (ZooKeeperGroup group : members) { assertFalse(group.isConnected()); assertFalse(group.isMaster()); } ZKContainer container = null; Path dataDir = Files.createTempDirectory("zk-"); try { container = startZooKeeper(port, dataDir); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); // first to start should be master if members are ordered... int i = 0; for (ZooKeeperGroup group : members) { group.start(); group.update(new NodeState("foo" + i)); i++; // wait for registration while (group.getId() == null) { TimeUnit.MILLISECONDS.sleep(100); } } boolean firsStartedIsMaster = members.get(0).isMaster(); for (ZooKeeperGroup group : members) { group.close(); } curator.close(); assertTrue("first started is master", firsStartedIsMaster); } finally { if (container != null) { container.stop(); } FileUtils.deleteDirectory(dataDir.toFile()); } } @Test public void testJoinAfterConnect() throws Exception { int port = AvailablePortFinder.getNextAvailable(); CuratorFramework curator = CuratorFrameworkFactory.builder() .connectString("localhost:" + port) .retryPolicy(new RetryNTimes(10, 100)) .build(); curator.start(); final Group<NodeState> group = new ZooKeeperGroup<>(curator, "/singletons/test" + System.currentTimeMillis(), NodeState.class); group.add(listener); group.start(); assertFalse(group.isConnected()); assertFalse(group.isMaster()); GroupCondition groupCondition = new GroupCondition(); group.add(groupCondition); ZKContainer container = null; Path dataDir = Files.createTempDirectory("zk-"); try { container = startZooKeeper(port, dataDir); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); assertTrue(groupCondition.waitForConnected(5, TimeUnit.SECONDS)); assertFalse(group.isMaster()); group.update(new NodeState("foo")); assertTrue(groupCondition.waitForMaster(5, TimeUnit.SECONDS)); group.close(); curator.close(); } finally { if (container != null) { container.stop(); } try { FileUtils.deleteDirectory(dataDir.toFile()); } catch (Throwable e) { // ignore } } } @Test public void testJoinBeforeConnect() throws Exception { int port = AvailablePortFinder.getNextAvailable(); CuratorFramework curator = CuratorFrameworkFactory.builder() .connectString("localhost:" + port) .retryPolicy(new RetryNTimes(10, 100)) .build(); curator.start(); Group<NodeState> group = new ZooKeeperGroup<>(curator, "/singletons/test" + System.currentTimeMillis(), NodeState.class); group.add(listener); group.start(); GroupCondition groupCondition = new GroupCondition(); group.add(groupCondition); assertFalse(group.isConnected()); assertFalse(group.isMaster()); group.update(new NodeState("foo")); ZKContainer container = null; Path dataDir = Files.createTempDirectory("zk-"); try { container = startZooKeeper(port, dataDir); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); assertTrue(groupCondition.waitForConnected(5, TimeUnit.SECONDS)); assertTrue(groupCondition.waitForMaster(5, TimeUnit.SECONDS)); group.close(); curator.close(); } finally { if (container != null) { container.stop(); } FileUtils.deleteDirectory(dataDir.toFile()); } } @Test public void testRejoinAfterDisconnect() throws Exception { int port = AvailablePortFinder.getNextAvailable(); CuratorFramework curator = CuratorFrameworkFactory.builder() .connectString("localhost:" + port) .retryPolicy(new RetryNTimes(10, 100)) .build(); curator.start(); ZKContainer container = null; Path dataDir = Files.createTempDirectory("zk-"); try { container = startZooKeeper(port, dataDir); Group<NodeState> group = new ZooKeeperGroup<>(curator, "/singletons/test" + System.currentTimeMillis(), NodeState.class); group.add(listener); group.update(new NodeState("foo")); group.start(); GroupCondition groupCondition = new GroupCondition(); group.add(groupCondition); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); assertTrue(groupCondition.waitForConnected(5, TimeUnit.SECONDS)); assertTrue(groupCondition.waitForMaster(5, TimeUnit.SECONDS)); container.stop(); groupCondition.waitForDisconnected(5, TimeUnit.SECONDS); group.remove(groupCondition); assertFalse(group.isConnected()); assertFalse(group.isMaster()); groupCondition = new GroupCondition(); group.add(groupCondition); container = startZooKeeper(port, dataDir); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); assertTrue(groupCondition.waitForConnected(5, TimeUnit.SECONDS)); assertTrue(groupCondition.waitForMaster(5, TimeUnit.SECONDS)); group.close(); curator.close(); } finally { if (container != null) { container.stop(); } FileUtils.deleteDirectory(dataDir.toFile()); } } //Tests that if close() is executed right after start(), there are no left over entries. //(see https://github.com/jboss-fuse/fuse/issues/133) @Test public void testGroupClose() throws Exception { int port = AvailablePortFinder.getNextAvailable(); ZKContainer container = null; Path dataDir = Files.createTempDirectory("zk-"); try { container = startZooKeeper(port, dataDir); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() .connectString("localhost:" + port) .connectionTimeoutMs(6000) .sessionTimeoutMs(6000) .retryPolicy(new RetryNTimes(10, 100)); CuratorFramework curator = builder.build(); curator.start(); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); String groupNode = "/singletons/test" + System.currentTimeMillis(); curator.create().creatingParentsIfNeeded().forPath(groupNode); for (int i = 0; i < 100; i++) { ZooKeeperGroup<NodeState> group = new ZooKeeperGroup<>(curator, groupNode, NodeState.class); group.add(listener); group.update(new NodeState("foo")); group.start(); group.close(); List<String> entries = curator.getChildren().forPath(groupNode); assertTrue(entries.isEmpty() || group.isUnstable()); if (group.isUnstable()) { // let's wait for session timeout curator.close(); curator = builder.build(); curator.start(); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); } } curator.close(); } finally { if (container != null) { container.stop(); } FileUtils.deleteDirectory(dataDir.toFile()); } } @Test public void testAddFieldIgnoredOnParse() throws Exception { int port = AvailablePortFinder.getNextAvailable(); ZKContainer container = null; Path dataDir = Files.createTempDirectory("zk-"); try { container = startZooKeeper(port, dataDir); CuratorFramework curator = CuratorFrameworkFactory.builder() .connectString("localhost:" + port) .retryPolicy(new RetryNTimes(10, 100)) .build(); curator.start(); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); String groupNode = "/singletons/test" + System.currentTimeMillis(); curator.create().creatingParentsIfNeeded().forPath(groupNode); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); final ZooKeeperGroup<NodeState> group = new ZooKeeperGroup<>(curator, groupNode, NodeState.class); group.add(listener); group.start(); GroupCondition groupCondition = new GroupCondition(); group.add(groupCondition); group.update(new NodeState("foo")); assertTrue(groupCondition.waitForConnected(5, TimeUnit.SECONDS)); assertTrue(groupCondition.waitForMaster(5, TimeUnit.SECONDS)); ChildData currentData = group.getCurrentData().get(0); final int version = currentData.getStat().getVersion(); NodeState lastState = group.getLastState(); String json = lastState.toString(); LOGGER.info("JSON:" + json); String newValWithNewField = json.substring(0, json.lastIndexOf('}')) + ",\"Rubbish\":\"Rubbish\"}"; curator.getZookeeperClient().getZooKeeper().setData(group.getId(), newValWithNewField.getBytes(), version); assertTrue(group.isMaster()); int attempts = 0; while (attempts++ < 5 && version == group.getCurrentData().get(0).getStat().getVersion()) { TimeUnit.SECONDS.sleep(1); } assertNotEquals("We see the updated version", version, group.getCurrentData().get(0).getStat().getVersion()); LOGGER.info("CurrentData:" + group.getCurrentData()); group.close(); curator.close(); } finally { if (container != null) { container.stop(); } FileUtils.deleteDirectory(dataDir.toFile()); } } private class GroupCondition implements GroupListener<NodeState> { private CountDownLatch connected = new CountDownLatch(1); private CountDownLatch master = new CountDownLatch(1); private CountDownLatch disconnected = new CountDownLatch(1); @Override public void groupEvent(Group<NodeState> group, GroupEvent event) { switch (event) { case CONNECTED: case CHANGED: connected.countDown(); if (group.isMaster()) { master.countDown(); } break; case DISCONNECTED: disconnected.countDown(); break; default: // noop } } public boolean waitForConnected(long time, TimeUnit timeUnit) throws InterruptedException { return connected.await(time, timeUnit); } public boolean waitForDisconnected(long time, TimeUnit timeUnit) throws InterruptedException { return disconnected.await(time, timeUnit); } public boolean waitForMaster(long time, TimeUnit timeUnit) throws InterruptedException { return master.await(time, timeUnit); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/errors/time_zone_error.proto package com.google.ads.googleads.v9.errors; /** * <pre> * Container for enum describing possible time zone errors. * </pre> * * Protobuf type {@code google.ads.googleads.v9.errors.TimeZoneErrorEnum} */ public final class TimeZoneErrorEnum extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v9.errors.TimeZoneErrorEnum) TimeZoneErrorEnumOrBuilder { private static final long serialVersionUID = 0L; // Use TimeZoneErrorEnum.newBuilder() to construct. private TimeZoneErrorEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TimeZoneErrorEnum() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new TimeZoneErrorEnum(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TimeZoneErrorEnum( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.errors.TimeZoneErrorProto.internal_static_google_ads_googleads_v9_errors_TimeZoneErrorEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.errors.TimeZoneErrorProto.internal_static_google_ads_googleads_v9_errors_TimeZoneErrorEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.errors.TimeZoneErrorEnum.class, com.google.ads.googleads.v9.errors.TimeZoneErrorEnum.Builder.class); } /** * <pre> * Enum describing possible currency code errors. * </pre> * * Protobuf enum {@code google.ads.googleads.v9.errors.TimeZoneErrorEnum.TimeZoneError} */ public enum TimeZoneError implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Enum unspecified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ UNSPECIFIED(0), /** * <pre> * The received error code is not known in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <pre> * Time zone is not valid. * </pre> * * <code>INVALID_TIME_ZONE = 5;</code> */ INVALID_TIME_ZONE(5), UNRECOGNIZED(-1), ; /** * <pre> * Enum unspecified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ public static final int UNSPECIFIED_VALUE = 0; /** * <pre> * The received error code is not known in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <pre> * Time zone is not valid. * </pre> * * <code>INVALID_TIME_ZONE = 5;</code> */ public static final int INVALID_TIME_ZONE_VALUE = 5; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static TimeZoneError valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static TimeZoneError forNumber(int value) { switch (value) { case 0: return UNSPECIFIED; case 1: return UNKNOWN; case 5: return INVALID_TIME_ZONE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<TimeZoneError> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< TimeZoneError> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<TimeZoneError>() { public TimeZoneError findValueByNumber(int number) { return TimeZoneError.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.ads.googleads.v9.errors.TimeZoneErrorEnum.getDescriptor().getEnumTypes().get(0); } private static final TimeZoneError[] VALUES = values(); public static TimeZoneError valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private TimeZoneError(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.ads.googleads.v9.errors.TimeZoneErrorEnum.TimeZoneError) } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v9.errors.TimeZoneErrorEnum)) { return super.equals(obj); } com.google.ads.googleads.v9.errors.TimeZoneErrorEnum other = (com.google.ads.googleads.v9.errors.TimeZoneErrorEnum) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v9.errors.TimeZoneErrorEnum prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Container for enum describing possible time zone errors. * </pre> * * Protobuf type {@code google.ads.googleads.v9.errors.TimeZoneErrorEnum} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v9.errors.TimeZoneErrorEnum) com.google.ads.googleads.v9.errors.TimeZoneErrorEnumOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.errors.TimeZoneErrorProto.internal_static_google_ads_googleads_v9_errors_TimeZoneErrorEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.errors.TimeZoneErrorProto.internal_static_google_ads_googleads_v9_errors_TimeZoneErrorEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.errors.TimeZoneErrorEnum.class, com.google.ads.googleads.v9.errors.TimeZoneErrorEnum.Builder.class); } // Construct using com.google.ads.googleads.v9.errors.TimeZoneErrorEnum.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v9.errors.TimeZoneErrorProto.internal_static_google_ads_googleads_v9_errors_TimeZoneErrorEnum_descriptor; } @java.lang.Override public com.google.ads.googleads.v9.errors.TimeZoneErrorEnum getDefaultInstanceForType() { return com.google.ads.googleads.v9.errors.TimeZoneErrorEnum.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v9.errors.TimeZoneErrorEnum build() { com.google.ads.googleads.v9.errors.TimeZoneErrorEnum result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v9.errors.TimeZoneErrorEnum buildPartial() { com.google.ads.googleads.v9.errors.TimeZoneErrorEnum result = new com.google.ads.googleads.v9.errors.TimeZoneErrorEnum(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v9.errors.TimeZoneErrorEnum) { return mergeFrom((com.google.ads.googleads.v9.errors.TimeZoneErrorEnum)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v9.errors.TimeZoneErrorEnum other) { if (other == com.google.ads.googleads.v9.errors.TimeZoneErrorEnum.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v9.errors.TimeZoneErrorEnum parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v9.errors.TimeZoneErrorEnum) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v9.errors.TimeZoneErrorEnum) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v9.errors.TimeZoneErrorEnum) private static final com.google.ads.googleads.v9.errors.TimeZoneErrorEnum DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v9.errors.TimeZoneErrorEnum(); } public static com.google.ads.googleads.v9.errors.TimeZoneErrorEnum getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TimeZoneErrorEnum> PARSER = new com.google.protobuf.AbstractParser<TimeZoneErrorEnum>() { @java.lang.Override public TimeZoneErrorEnum parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TimeZoneErrorEnum(input, extensionRegistry); } }; public static com.google.protobuf.Parser<TimeZoneErrorEnum> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TimeZoneErrorEnum> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v9.errors.TimeZoneErrorEnum getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import org.chromium.base.CalledByNative; import org.chromium.base.JNINamespace; import org.chromium.content.R; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Controller for Chrome's tracing feature. * * We don't have any UI per se. Just call startTracing() to start and * stopTracing() to stop. We'll report progress to the user with Toasts. * * If the host application registers this class's BroadcastReceiver, you can * also start and stop the tracer with a broadcast intent, as follows: * <ul> * <li>To start tracing: am broadcast -a org.chromium.content_shell_apk.GPU_PROFILER_START * <li>Add "-e file /foo/bar/xyzzy" to log trace data to a specific file. * <li>To stop tracing: am broadcast -a org.chromium.content_shell_apk.GPU_PROFILER_STOP * </ul> * Note that the name of these intents change depending on which application * is being traced, but the general form is [app package name].GPU_PROFILER_{START,STOP}. */ @JNINamespace("content") public class TracingControllerAndroid { private static final String TAG = "TracingControllerAndroid"; private static final String ACTION_START = "GPU_PROFILER_START"; private static final String ACTION_STOP = "GPU_PROFILER_STOP"; private static final String ACTION_LIST_CATEGORIES = "GPU_PROFILER_LIST_CATEGORIES"; private static final String FILE_EXTRA = "file"; private static final String CATEGORIES_EXTRA = "categories"; private static final String RECORD_CONTINUOUSLY_EXTRA = "continuous"; private static final String DEFAULT_CHROME_CATEGORIES_PLACE_HOLDER = "_DEFAULT_CHROME_CATEGORIES"; // These strings must match the ones expected by adb_profile_chrome. private static final String PROFILER_STARTED_FMT = "Profiler started: %s"; private static final String PROFILER_FINISHED_FMT = "Profiler finished. Results are in %s."; private final Context mContext; private final TracingBroadcastReceiver mBroadcastReceiver; private final TracingIntentFilter mIntentFilter; private boolean mIsTracing; // We might not want to always show toasts when we start the profiler, especially if // showing the toast impacts performance. This gives us the chance to disable them. private boolean mShowToasts = true; private String mFilename; public TracingControllerAndroid(Context context) { mContext = context; mBroadcastReceiver = new TracingBroadcastReceiver(); mIntentFilter = new TracingIntentFilter(context); } /** * Get a BroadcastReceiver that can handle profiler intents. */ public BroadcastReceiver getBroadcastReceiver() { return mBroadcastReceiver; } /** * Get an IntentFilter for profiler intents. */ public IntentFilter getIntentFilter() { return mIntentFilter; } /** * Register a BroadcastReceiver in the given context. */ public void registerReceiver(Context context) { context.registerReceiver(getBroadcastReceiver(), getIntentFilter()); } /** * Unregister the GPU BroadcastReceiver in the given context. * @param context */ public void unregisterReceiver(Context context) { context.unregisterReceiver(getBroadcastReceiver()); } /** * Returns true if we're currently profiling. */ public boolean isTracing() { return mIsTracing; } /** * Returns the path of the current output file. Null if isTracing() false. */ public String getOutputPath() { return mFilename; } /** * Generates a unique filename to be used for tracing in the Downloads directory. */ @CalledByNative private static String generateTracingFilePath() { String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { return null; } // Generate a hopefully-unique filename using the UTC timestamp. // (Not a huge problem if it isn't unique, we'll just append more data.) SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd-HHmmss", Locale.US); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); File dir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS); File file = new File( dir, "chrome-profile-results-" + formatter.format(new Date())); return file.getPath(); } /** * Start profiling to a new file in the Downloads directory. * * Calls #startTracing(String, boolean, String, String) with a new timestamped filename. * @see #startTracing(String, boolean, String, String) */ public boolean startTracing(boolean showToasts, String categories, String traceOptions) { mShowToasts = showToasts; String filePath = generateTracingFilePath(); if (filePath == null) { logAndToastError(mContext.getString(R.string.profiler_no_storage_toast)); } return startTracing(filePath, showToasts, categories, traceOptions); } private void initializeNativeControllerIfNeeded() { if (mNativeTracingControllerAndroid == 0) { mNativeTracingControllerAndroid = nativeInit(); } } /** * Start profiling to the specified file. Returns true on success. * * Only one TracingControllerAndroid can be running at the same time. If another profiler * is running when this method is called, it will be cancelled. If this * profiler is already running, this method does nothing and returns false. * * @param filename The name of the file to output the profile data to. * @param showToasts Whether or not we want to show toasts during this profiling session. * When we are timing the profile run we might not want to incur extra draw overhead of showing * notifications about the profiling system. * @param categories Which categories to trace. See TracingControllerAndroid::BeginTracing() * (in content/public/browser/trace_controller.h) for the format. * @param traceOptions Which trace options to use. See * TraceOptions::TraceOptions(const std::string& options_string) * (in base/trace_event/trace_event_impl.h) for the format. */ public boolean startTracing(String filename, boolean showToasts, String categories, String traceOptions) { mShowToasts = showToasts; if (isTracing()) { // Don't need a toast because this shouldn't happen via the UI. Log.e(TAG, "Received startTracing, but we're already tracing"); return false; } // Lazy initialize the native side, to allow construction before the library is loaded. initializeNativeControllerIfNeeded(); if (!nativeStartTracing(mNativeTracingControllerAndroid, categories, traceOptions.toString())) { logAndToastError(mContext.getString(R.string.profiler_error_toast)); return false; } logForProfiler(String.format(PROFILER_STARTED_FMT, categories)); showToast(mContext.getString(R.string.profiler_started_toast) + ": " + categories); mFilename = filename; mIsTracing = true; return true; } /** * Stop profiling. This won't take effect until Chrome has flushed its file. */ public void stopTracing() { if (isTracing()) { nativeStopTracing(mNativeTracingControllerAndroid, mFilename); } } /** * Called by native code when the profiler's output file is closed. */ @CalledByNative protected void onTracingStopped() { if (!isTracing()) { // Don't need a toast because this shouldn't happen via the UI. Log.e(TAG, "Received onTracingStopped, but we aren't tracing"); return; } logForProfiler(String.format(PROFILER_FINISHED_FMT, mFilename)); showToast(mContext.getString(R.string.profiler_stopped_toast, mFilename)); mIsTracing = false; mFilename = null; } /** * Get known category groups. */ public void getCategoryGroups() { // Lazy initialize the native side, to allow construction before the library is loaded. initializeNativeControllerIfNeeded(); if (!nativeGetKnownCategoryGroupsAsync(mNativeTracingControllerAndroid)) { Log.e(TAG, "Unable to fetch tracing record groups list."); } } /** * Clean up the C++ side of this class. * After the call, this class instance shouldn't be used. */ public void destroy() { if (mNativeTracingControllerAndroid != 0) { nativeDestroy(mNativeTracingControllerAndroid); mNativeTracingControllerAndroid = 0; } } private void logAndToastError(String str) { Log.e(TAG, str); if (mShowToasts) Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show(); } // The |str| string needs to match the ones that adb_chrome_profiler looks for. private void logForProfiler(String str) { Log.i(TAG, str); } private void showToast(String str) { if (mShowToasts) Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show(); } private static class TracingIntentFilter extends IntentFilter { TracingIntentFilter(Context context) { addAction(context.getPackageName() + "." + ACTION_START); addAction(context.getPackageName() + "." + ACTION_STOP); addAction(context.getPackageName() + "." + ACTION_LIST_CATEGORIES); } } class TracingBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().endsWith(ACTION_START)) { String categories = intent.getStringExtra(CATEGORIES_EXTRA); if (TextUtils.isEmpty(categories)) { categories = nativeGetDefaultCategories(); } else { categories = categories.replaceFirst( DEFAULT_CHROME_CATEGORIES_PLACE_HOLDER, nativeGetDefaultCategories()); } String traceOptions = intent.getStringExtra(RECORD_CONTINUOUSLY_EXTRA) == null ? "record-until-full" : "record-continuously"; String filename = intent.getStringExtra(FILE_EXTRA); if (filename != null) { startTracing(filename, true, categories, traceOptions); } else { startTracing(true, categories, traceOptions); } } else if (intent.getAction().endsWith(ACTION_STOP)) { stopTracing(); } else if (intent.getAction().endsWith(ACTION_LIST_CATEGORIES)) { getCategoryGroups(); } else { Log.e(TAG, "Unexpected intent: " + intent); } } } private long mNativeTracingControllerAndroid; private native long nativeInit(); private native void nativeDestroy(long nativeTracingControllerAndroid); private native boolean nativeStartTracing( long nativeTracingControllerAndroid, String categories, String traceOptions); private native void nativeStopTracing(long nativeTracingControllerAndroid, String filename); private native boolean nativeGetKnownCategoryGroupsAsync(long nativeTracingControllerAndroid); private native String nativeGetDefaultCategories(); }
package mil.army.usace.ehlschlaeger.rgik.gene; // Chromosome.java /** @author Chuck Ehlschlaeger * in alpha testing. * Copyright Charles R. Ehlschlaeger, * work: 309-298-1841, fax: 309-298-3003, * <http://faculty.wiu.edu/CR-Ehlschlaeger2/> * This software is freely usable for research and educational purposes. Contact C. R. Ehlschlaeger * for permission for other purposes. * Use of this software requires appropriate citation in all published and unpublished documentation. */ public class Chromosome { private boolean[] allele; private int parameters, totalAllele; private int[] startParameter; private int[] endParameter; private double[] minParameter; private double[] spreadParameter; private long[] maxAlleleValue; private String[] names; private double fitness; private int numMade; public Chromosome() { parameters = 0; numMade = -1; } public String getParameterName( int parameter) { if( parameter < 0 || parameter >= parameters) { throw new IndexOutOfBoundsException("Chromosome.getParameterName ERROR: parameter value [" + parameter + "] not within range of 0-" + (parameters - 1)); } return( names[parameter]); } public int getNumberAllele() { return totalAllele; } public boolean getAllele( int numAllele) { return allele[ numAllele]; } public void setNumberMade( int value) { numMade = value; } public int getNumberMade() { return numMade; } public Chromosome( Chromosome existing) { parameters = existing.parameters; startParameter = existing.startParameter; endParameter = existing.endParameter; minParameter = existing.minParameter; spreadParameter = existing.spreadParameter; maxAlleleValue = existing.maxAlleleValue; totalAllele = existing.totalAllele; names = existing.names; allele = new boolean[ totalAllele]; RandomizeChromosome(); fitness = Double.NEGATIVE_INFINITY; } public Chromosome copy() { Chromosome c = new Chromosome(); c.parameters = parameters; c.startParameter = startParameter; c.endParameter = endParameter; c.minParameter = minParameter; c.spreadParameter = spreadParameter; c.maxAlleleValue = maxAlleleValue; c.totalAllele = totalAllele; c.names = names; c.allele = new boolean[ totalAllele]; for( int i = 0; i < totalAllele; i++) { c.allele[ i] = allele[ i]; } c.fitness = fitness; return c; } public double getFitness() { return fitness; } public void setFitness( double value) { fitness = value; } public void setNumberParameters( int value) { if( value < 1) { throw new IllegalArgumentException("Chromosome.setNumberParameters ERROR: value must be greater than 0"); } startParameter = new int[ value]; startParameter[ 0] = 0; endParameter = new int[ value]; endParameter[ value - 1] = -1; minParameter = new double[ value]; spreadParameter = new double[ value]; maxAlleleValue = new long[ value]; names = new String[ value]; for( int i = 0; i < value; i++) { names[ i] = "parameter" + (Integer.toString( i)); } } public int getNumberParameters() { return parameters; } public void setParameter( int numAllele, double minValue, double maxValue, String name) { if( parameters == startParameter.length) { throw new IllegalStateException("Chromosome.setParameter ERROR: all parameters have already been set."); } names[ parameters] = name; setParameter( numAllele, minValue, maxValue); } public void setParameter( int numAllele, double minValue, double maxValue) { if( numAllele < 1 || numAllele >= 64) { throw new IllegalArgumentException("numAllele must be greater than 0 and must be less than 64"); } if( parameters == startParameter.length) { throw new IllegalStateException("All parameters have already been set."); } totalAllele += numAllele; endParameter[ parameters] = startParameter[ parameters] + numAllele - 1; maxAlleleValue[ parameters] = 0; for( int i = startParameter[ parameters]; i <= endParameter[ parameters]; i++) { maxAlleleValue[ parameters] = (maxAlleleValue[ parameters] << 1) + 1; } minParameter[ parameters] = minValue; spreadParameter[ parameters] = maxValue - minValue; parameters++; if( parameters < spreadParameter.length) { startParameter[ parameters] = endParameter[ parameters - 1] + 1; } else { allele = new boolean[ totalAllele]; RandomizeChromosome(); fitness = Double.NEGATIVE_INFINITY; } } private void RandomizeChromosome() { for( int i = 0; i < allele.length; i++) { if( Math.random() < 0.5) { allele[ i] = false; } else { allele[ i] = true; } } } public double getParameterValue( int parameter) { double value = minParameter[ parameter] + getParameterLocation( parameter) * spreadParameter[ parameter]; return value; } public boolean isMaximumValue( int parameter) { for( int i = startParameter[ parameter]; i <= endParameter[ parameter]; i++) { if( allele[ i] == false) { return false; } } return true; } public boolean isMinimumValue( int parameter) { for( int i = startParameter[ parameter]; i <= endParameter[ parameter]; i++) { if( allele[ i] == true) { return false; } } return true; } public void incrementParameter( int parameter) { for( int i = endParameter[ parameter]; i >= startParameter[ parameter]; i--) { if( allele[ i] == true) { allele[ i] = false; } else { allele[ i] = true; i = -1; } } } public void decrementParameter( int parameter) { for( int i = endParameter[ parameter]; i >= startParameter[ parameter]; i--) { if( allele[ i] == false) { allele[ i] = true; } else { allele[ i] = false; i = -1; } } } public double getParameterLocation( int parameter) { long alleleSum = 0; for( int i = startParameter[ parameter]; i <= endParameter[ parameter]; i++) { if( allele[ i]) { alleleSum = (alleleSum << 1) + 1; } else { alleleSum = alleleSum << 1; } } return( (1.0 * alleleSum) / maxAlleleValue[ parameter]); } /** * Swaps a random subset of alleles between chromosomes. * @param other * @return index-1 of first allele swapped */ public int cross( Chromosome other) { int crossLocation = (int) (Math.random() * (totalAllele - 1)); //System.out.println( "crossLocation: " + crossLocation); for( int i = crossLocation + 1; i < totalAllele; i++) { boolean tmp = other.allele[ i]; other.allele[ i] = allele[ i]; allele[ i] = tmp; } return crossLocation; } public int mutate( double mutationProbability) { int numberMutations = 0; for( int i = 0; i < parameters; i++) { if( Math.random() < mutationProbability) { numberMutations++; if( Math.random() < 0.5) { incrementParameter( i); } else { decrementParameter( i); } } } return numberMutations; } public int mutateAnyAllele( double mutationProbability) { int numberMutations = 0; for( int i = 0; i < totalAllele; i++) { if( Math.random() < mutationProbability) { numberMutations++; if( allele[ i] == true) { allele[ i] = false; } else { allele[ i] = true; } } } return numberMutations; } public void printHeader() { for( int i = 0; i < parameters; i++) { System.out.print( names[ i] + ","); } System.out.println( "fitness"); } public void printAllele() { for( int parameter = 0; parameter < parameters; parameter++) { for( int i = startParameter[ parameter]; i <= endParameter[ parameter]; i++) { if( allele[ i]) { System.out.print( "1"); } else { System.out.print( "0"); } // end of if } // end of i loop System.out.println( ""); } // end of parameter loop } public void print() { for( int i = 0; i < parameters; i++) { System.out.print( i + "," + (endParameter[i] - startParameter[i] + 1)); System.out.print( "," + getParameterValue( i) + ","); System.out.println( names[ i]); } } }
package io.cattle.platform.allocator.service.impl; import static io.cattle.platform.core.model.tables.InstanceHostMapTable.*; import static io.cattle.platform.core.model.tables.PortTable.*; import io.cattle.platform.agent.AgentLocator; import io.cattle.platform.agent.RemoteAgent; import io.cattle.platform.agent.instance.dao.AgentInstanceDao; import io.cattle.platform.allocator.constraint.Constraint; import io.cattle.platform.allocator.constraint.PortsConstraint; import io.cattle.platform.allocator.constraint.ValidHostsConstraint; import io.cattle.platform.allocator.constraint.provider.AllocationConstraintsProvider; import io.cattle.platform.allocator.constraint.provider.PortsConstraintProvider; import io.cattle.platform.allocator.dao.AllocatorDao; import io.cattle.platform.allocator.dao.impl.QueryOptions; import io.cattle.platform.allocator.exception.FailedToAllocate; import io.cattle.platform.allocator.lock.AllocateConstraintLock; import io.cattle.platform.allocator.lock.AllocateResourceLock; import io.cattle.platform.allocator.lock.AllocationBlockingMultiLock; import io.cattle.platform.allocator.service.AllocationAttempt; import io.cattle.platform.allocator.service.AllocationCandidate; import io.cattle.platform.allocator.service.AllocationHelper; import io.cattle.platform.allocator.service.AllocationLog; import io.cattle.platform.allocator.service.AllocatorService; import io.cattle.platform.archaius.util.ArchaiusUtil; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.constants.DockerInstanceConstants; import io.cattle.platform.core.constants.InstanceConstants; import io.cattle.platform.core.constants.StorageDriverConstants; import io.cattle.platform.core.constants.VolumeConstants; import io.cattle.platform.core.dao.GenericMapDao; import io.cattle.platform.core.dao.VolumeDao; import io.cattle.platform.core.model.Host; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.InstanceHostMap; import io.cattle.platform.core.model.Port; import io.cattle.platform.core.model.StorageDriver; import io.cattle.platform.core.model.Volume; import io.cattle.platform.core.util.InstanceHelpers; import io.cattle.platform.core.util.PortSpec; import io.cattle.platform.core.util.SystemLabels; import io.cattle.platform.docker.client.DockerImage; import io.cattle.platform.eventing.exception.EventExecutionException; import io.cattle.platform.eventing.model.Event; import io.cattle.platform.eventing.model.EventVO; import io.cattle.platform.lock.LockCallbackNoReturn; import io.cattle.platform.lock.LockManager; import io.cattle.platform.lock.definition.LockDefinition; import io.cattle.platform.metrics.util.MetricsUtil; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.object.process.ObjectProcessManager; import io.cattle.platform.object.util.DataAccessor; import io.cattle.platform.object.util.ObjectUtils; import io.cattle.platform.util.type.CollectionUtils; import io.cattle.platform.util.type.Named; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.Timer; import com.codahale.metrics.Timer.Context; import com.netflix.config.DynamicStringProperty; public class AllocatorServiceImpl implements AllocatorService, Named { private static final Logger log = LoggerFactory.getLogger(AllocatorServiceImpl.class); private static final DynamicStringProperty PORT_SCHEDULER_IMAGE_VERSION = ArchaiusUtil.getString("port.scheduler.image.version"); private static final String FORCE_RESERVE = "force"; private static final String HOST_ID = "hostID"; private static final String RESOURCE_REQUESTS = "resourceRequests"; private static final String CONTEXT = "context"; private static final String SCHEDULER_REQUEST_DATA_NAME = "schedulerRequest"; private static final String SCHEDULER_PRIORITIZE_EVENT = "scheduler.prioritize"; private static final String SCHEDULER_RESERVE_EVENT = "scheduler.reserve"; private static final String SCHEDULER_RELEASE_EVENT = "scheduler.release"; private static final String SCHEDULER_PRIORITIZE_RESPONSE = "prioritizedCandidates"; private static final String INSTANCE_RESERVATION = "instanceReservation"; private static final String MEMORY_RESERVATION = "memoryReservation"; private static final String CPU_RESERVATION = "cpuReservation"; private static final String STORAGE_SIZE = "storageSize"; private static final String PORT_RESERVATION = "portReservation"; private static final String COMPUTE_POOL = "computePool"; private static final String PORT_POOL = "portPool"; private static final String BIND_ADDRESS = "bindAddress"; private static final String PHASE = "phase"; Timer allocateLockTimer = MetricsUtil.getRegistry().timer("allocator.allocate.with.lock"); Timer allocateTimer = MetricsUtil.getRegistry().timer("allocator.allocate"); Timer deallocateTimer = MetricsUtil.getRegistry().timer("allocator.deallocate"); String name = getClass().getSimpleName(); @Inject AgentInstanceDao agentInstanceDao; @Inject AgentLocator agentLocator; @Inject GenericMapDao mapDao; @Inject protected AllocatorDao allocatorDao; @Inject protected LockManager lockManager; @Inject protected ObjectManager objectManager; @Inject protected ObjectProcessManager processManager; @Inject AllocationHelper allocationHelper; @Inject VolumeDao volumeDao; @Inject protected List<AllocationConstraintsProvider> allocationConstraintProviders; @Override public void instanceAllocate(final Instance instance) { log.info("Allocating instance [{}]", instance.getId()); lockManager.lock(new AllocateResourceLock(instance.getId()), new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { allocateInstance(instance); } }); log.info("Handled request for instance [{}]", instance.getId()); } @Override public void instanceDeallocate(final Instance instance) { log.info("Deallocating instance [{}]", instance.getId()); lockManager.lock(new AllocateResourceLock(instance.getId()), new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { Context c = deallocateTimer.time(); try { if (assertDeallocated(instance.getId(), instance.getAllocationState(), "Instance")) { return; } releaseAllocation(instance); } finally { c.stop(); } } }); log.info("Handled request for instance [{}]", instance.getId()); } @Override public void ensureResourcesReservedForStart(Instance instance) { List<Instance> instances = new ArrayList<>(); instances.add(instance); List<Long> agentIds = getAgentResource(instance.getAccountId(), instances); String hostUuid = getHostUuid(instance); for (Long agentId: agentIds) { if (agentId != null && hostUuid != null) { EventVO<Map<String, Object>> schedulerEvent = buildEvent(SCHEDULER_RESERVE_EVENT, InstanceConstants.PROCESS_START, instances, new HashSet<Volume>(), agentId); if (schedulerEvent != null) { Map<String, Object> reqData = CollectionUtils.toMap(schedulerEvent.getData().get(SCHEDULER_REQUEST_DATA_NAME)); reqData.put(HOST_ID, hostUuid); Long rhid = DataAccessor.fields(instance).withKey(InstanceConstants.FIELD_REQUESTED_HOST_ID).as(Long.class); if (rhid != null) { reqData.put(FORCE_RESERVE, true); } RemoteAgent agent = agentLocator.lookupAgent(agentId); Event eventResult = callScheduler("Error reserving resources: %s", schedulerEvent, agent); if (eventResult.getData() == null) { return; } } } } } @Override public void ensureResourcesReleasedForStop(Instance instance) { String hostUuid = getHostUuid(instance); if (hostUuid != null) { releaseResources(instance, hostUuid, InstanceConstants.PROCESS_STOP); } } @Override @SuppressWarnings("unchecked") public List<String> callExternalSchedulerForHostsSatisfyingLabels(Long accountId, Map<String, String> labels) { List<Long> agentIds = agentInstanceDao.getAgentProvider(SystemLabels.LABEL_AGENT_SERVICE_SCHEDULING_PROVIDER, accountId); List<String> hosts = null; List<Object> instances = new ArrayList<>(); Map<String, Object> instance = constructInstanceMapWithLabel(labels); instances.add(instance); for (Long agentId : agentIds) { EventVO<Map<String, Object>> schedulerEvent = buildEvent(SCHEDULER_PRIORITIZE_EVENT, "globalServicePlanning", instances); if (schedulerEvent != null) { RemoteAgent agent = agentLocator.lookupAgent(agentId); Event eventResult = callScheduler("Error getting hosts for resources for global service", schedulerEvent, agent); if (hosts == null) { hosts = (List<String>) CollectionUtils.getNestedValue(eventResult.getData(), SCHEDULER_PRIORITIZE_RESPONSE); } else { List<String> newHosts = (List<String>) CollectionUtils.getNestedValue(eventResult.getData(), SCHEDULER_PRIORITIZE_RESPONSE); hosts.retainAll(newHosts); } } } return hosts; } private EventVO<Map<String, Object>> buildEvent(String eventName, String phase, Object instances) { return newEvent(eventName, null, "instance", phase, null, instances); } private Map<String, Object> constructInstanceMapWithLabel(Map<String, String> labels) { Map<String, Object> fields = new HashMap<>(); fields.put("labels", labels); Map<String, Object> data = new HashMap<>(); data.put("fields", fields); Map<String, Object> instance = new HashMap<>(); instance.put("data", data); return instance; } protected List<Instance> getInstancesToAllocate(Instance instance) { if (instance.getDeploymentUnitUuid() != null) { return allocatorDao.getUnmappedDeploymentUnitInstances(instance.getDeploymentUnitId()); } else { List<Instance> instances = new ArrayList<>(); instances.add(instance); return instances; } } protected void allocateInstance(final Instance origInstance) { final List<Instance> instances = getInstancesToAllocate(origInstance); final Set<Long> volumeIds = new HashSet<>(); for (Instance instance : instances) { volumeIds.addAll(InstanceHelpers.extractVolumeIdsFromMounts(instance)); } LockDefinition lock = getInstanceLockDef(origInstance, instances, volumeIds); if (lock != null) { Context c = allocateLockTimer.time(); try { lockManager.lock(lock, new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { allocateInstanceInternal(origInstance, instances); } }); } finally { c.stop(); } } else { allocateInstanceInternal(origInstance, instances); } } protected void allocateInstanceInternal(Instance origInstance, List<Instance> instances) { boolean origAllocated = assertAllocated(origInstance.getId(), origInstance.getAllocationState(), "Instance", true); for (Instance instance : instances) { boolean allocated = assertAllocated(origInstance.getId(), instance.getAllocationState(), "Instance", false); if (origAllocated ^ allocated) { throw new FailedToAllocate(String.format("Instance %s is in allocation state %s and instance %s is in allocation state %s.", origInstance.getId(), origInstance.getAllocationState(), instance.getId(), instance.getAllocationState())); } } if (origAllocated) { return; } Host host = allocatorDao.getHost(origInstance); Long hostId = host != null ? host.getId() : null; Set<Volume> volumes = new HashSet<>(); Long requestedHostId = null; for (Instance instance : instances) { volumes.addAll(InstanceHelpers.extractVolumesFromMounts(instance, objectManager)); Long rhid = DataAccessor.fields(instance).withKey(InstanceConstants.FIELD_REQUESTED_HOST_ID).as(Long.class); if (rhid != null) { if (requestedHostId == null) { requestedHostId = rhid; } else if (!requestedHostId.equals(rhid)) { throw new FailedToAllocate(String.format( "Instances to allocate have conflicting requested host ids. Current instance id: %s. Requested host ids: %s, %s.", instance.getId(), requestedHostId, rhid)); } } } doAllocate(new AllocationAttempt(origInstance.getAccountId(), instances, hostId, requestedHostId, volumes)); } protected LockDefinition getInstanceLockDef(Instance origInstance, List<Instance> instances, Set<Long> volumeIds) { List<LockDefinition> locks = allocationHelper.extractAllocationLockDefinitions(origInstance, instances); if (origInstance.getDeploymentUnitUuid() != null) { locks.add(new AllocateConstraintLock(AllocateConstraintLock.Type.DEPLOYMENT_UNIT, origInstance.getDeploymentUnitUuid())); } List<Long> instancesIds = DataAccessor.fieldLongList(origInstance, DockerInstanceConstants.FIELD_VOLUMES_FROM); Long networkFromId = DataAccessor.fieldLong(origInstance, DockerInstanceConstants.FIELD_NETWORK_CONTAINER_ID); if (networkFromId != null) { instancesIds.add(networkFromId); } for (Long id : instancesIds) { locks.add(new AllocateResourceLock(id)); } for (Instance i : instances) { List<Port> ports = objectManager.find(Port.class, PORT.INSTANCE_ID, i.getId(), PORT.REMOVED, null); for (Port port : ports) { locks.add(new AllocateConstraintLock(AllocateConstraintLock.Type.PORT, String.format("%s.%s", port.getProtocol(), port.getPublicPort()))); } } List<? extends Volume> volsToLock = volumeDao.identifyUnmappedVolumes(origInstance.getAccountId(), volumeIds); for (Volume v : volsToLock) { locks.add(new AllocateConstraintLock(AllocateConstraintLock.Type.VOLUME, v.getId().toString())); } List<Volume> volumes = InstanceHelpers.extractVolumesFromMounts(origInstance, objectManager); for (Volume volume: volumes) { StorageDriver driver = objectManager.loadResource(StorageDriver.class, volume.getStorageDriverId()); if (driver != null) { String accessMode = DataAccessor.fieldString(driver, StorageDriverConstants.FIELD_VOLUME_ACCESS_MODE); if (VolumeConstants.ACCESS_MODE_SINGLE_HOST_RW.equals(accessMode) || VolumeConstants.ACCESS_MODE_SINGLE_INSTANCE_RW.equals(accessMode)) { locks.add(new AllocateConstraintLock(AllocateConstraintLock.Type.VOLUME, volume.getId().toString())); } } } return locks.size() > 0 ? new AllocationBlockingMultiLock(locks) : null; } protected void doAllocate(final AllocationAttempt attempt) { AllocationLog log = new AllocationLog(); populateConstraints(attempt, log); List<Constraint> finalFailedConstraints = new ArrayList<>(); Context c = allocateTimer.time(); try { do { Set<Constraint> failedConstraints = runAllocation(attempt); if (attempt.getMatchedCandidate() == null) { boolean removed = false; // iterate over failed constraints and remove first soft constraint if any Iterator<Constraint> failedIter = failedConstraints.iterator(); while (failedIter.hasNext() && !removed) { Constraint failedConstraint = failedIter.next(); if (failedConstraint.isHardConstraint()) { continue; } attempt.getConstraints().remove(failedConstraint); removed = true; } if (!removed) { finalFailedConstraints.addAll(failedConstraints); break; } } } while (attempt.getMatchedCandidate() == null); } finally { c.stop(); } if (attempt.getMatchedCandidate() == null) { if (finalFailedConstraints.size() > 0) { String resourceMsg = ""; List<ResourceRequest> requests = attempt.getResourceRequests(); if (requests != null) { for(ResourceRequest r: requests) { if (INSTANCE_RESERVATION.equals(r.getResource())) { requests.remove(r); break; } } if (requests.size() > 0) { resourceMsg = String.format("Host must satisfy resource constraints: %s. ", requests.toString()); } } throw new FailedToAllocate(String.format("%s%s", resourceMsg, toErrorMessage(finalFailedConstraints))); } throw new FailedToAllocate("Failed to find placement"); } } protected String toErrorMessage(List<Constraint> constraints) { List<String> result = new ArrayList<>(); for (Constraint c : constraints) { result.add(c.toString()); } return StringUtils.join(result, ", "); } protected Set<Constraint> runAllocation(AllocationAttempt attempt) { logStart(attempt); List<Set<Constraint>> candidateFailedConstraintSets = new ArrayList<>(); Iterator<AllocationCandidate> iter = getCandidates(attempt); try { boolean foundOne = false; while (iter.hasNext()) { foundOne = true; AllocationCandidate candidate = iter.next(); Set<Constraint> failedConstraints = new HashSet<>(); attempt.getCandidates().add(candidate); String prefix = String.format("[%s][%s]", attempt.getId(), candidate.getId()); logCandidate(prefix, attempt, candidate); StringBuilder lg = new StringBuilder(String.format("%s Checking constraints:\n", prefix)); boolean good = true; for (Constraint constraint : attempt.getConstraints()) { boolean match = constraint.matches(candidate); lg.append(String.format(" %s constraint result [%s] : %s\n", prefix, match, constraint)); if (!match) { good = false; failedConstraints.add(constraint); } } lg.append(String.format(" %s candidate result [%s]", prefix, good)); log.info(lg.toString()); if (good) { if (recordCandidate(attempt, candidate)) { attempt.setMatchedCandidate(candidate); return failedConstraints; } else { log.info("{} can not record result", prefix); } } candidateFailedConstraintSets.add(failedConstraints); } if (!foundOne) { throw new FailedToAllocate("No healthy hosts with sufficient resources available"); } return getWeakestConstraintSet(candidateFailedConstraintSets); } finally { if (iter != null) { close(iter); } } } // ideally we want zero hard constraints and the fewest soft constraints private Set<Constraint> getWeakestConstraintSet(List<Set<Constraint>> candidateFailedConstraintSets) { if (candidateFailedConstraintSets == null || candidateFailedConstraintSets.isEmpty()) { return Collections.emptySet(); } Collections.sort(candidateFailedConstraintSets, new Comparator<Set<Constraint>>() { @Override public int compare(Set<Constraint> o1, Set<Constraint> o2) { if (o1 == o2) return 0; if (o1 != null && o2 == null) return 1; if (o1 == null && o2 != null) return -1; int[] o1NumOfHardAndSoftConstraints = getNumberOfConstraints(o1); int[] o2NumOfHardAndSoftConstraints = getNumberOfConstraints(o2); if (o1NumOfHardAndSoftConstraints[0] > o2NumOfHardAndSoftConstraints[0]) return 1; if (o1NumOfHardAndSoftConstraints[0] < o2NumOfHardAndSoftConstraints[0]) return -1; if (o1NumOfHardAndSoftConstraints[1] > o2NumOfHardAndSoftConstraints[1]) return 1; if (o1NumOfHardAndSoftConstraints[1] < o2NumOfHardAndSoftConstraints[1]) return -1; return 0; } private int[] getNumberOfConstraints(Set<Constraint> failedConstraints) { int hard = 0; int soft = 0; Iterator<Constraint> iter = failedConstraints.iterator(); while (iter.hasNext()) { Constraint c = iter.next(); if (c.isHardConstraint()) { hard++; } else { soft++; } } return new int[] { hard, soft }; } }); return candidateFailedConstraintSets.get(0); } protected void logCandidate(String prefix, AllocationAttempt attempt, AllocationCandidate candidate) { StringBuilder candidateLog = new StringBuilder(String.format("%s Checking candidate:\n", prefix)); if (candidate.getHost() != null) { candidateLog.append(String.format(" %s host [%s]\n", prefix, candidate.getHost())); } candidateLog.deleteCharAt(candidateLog.length() - 1); // Remove trailing newline log.info(candidateLog.toString()); } protected void logStart(AllocationAttempt attempt) { String id = attempt.getId(); StringBuilder candidateLog = new StringBuilder(String.format("[%s] Attempting allocation for:\n", id)); if (attempt.getInstances() != null) { List<Long>instanceIds = new ArrayList<>(); for (Instance i : attempt.getInstances()) { instanceIds.add(i.getId()); } candidateLog.append(String.format(" [%s] instance [%s]\n", id, instanceIds)); } for (Volume volume : attempt.getVolumes()) { long volumeId = volume.getId(); candidateLog.append(String.format(" [%s] volume [%s]\n", id, volumeId)); } candidateLog.append(String.format(" [%s] constraints:\n", id)); for (Constraint constraint : attempt.getConstraints()) { candidateLog.append(String.format(" [%s] %s\n", id, constraint)); } candidateLog.deleteCharAt(candidateLog.length() - 1); // Remove trailing newline log.info(candidateLog.toString()); } protected void close(Iterator<AllocationCandidate> iter) { } protected void populateConstraints(AllocationAttempt attempt, AllocationLog log) { List<Constraint> constraints = attempt.getConstraints(); for (AllocationConstraintsProvider provider : allocationConstraintProviders) { if (attempt.getRequestedHostId() == null || provider.isCritical()) { if (provider instanceof PortsConstraintProvider && !useLegacyPortAllocation(attempt.getAccountId(), attempt.getInstances())) { continue; } provider.appendConstraints(attempt, log, constraints); } } Collections.sort(constraints, new Comparator<Constraint>() { @Override public int compare(Constraint o1, Constraint o2) { if (o1 == o2) return 0; if (o1 != null && o2 == null) return -1; if (o1 == null && o2 != null) return 1; if (o1.isHardConstraint() && o2.isHardConstraint()) return 0; if (o1.isHardConstraint() && !o2.isHardConstraint()) return -1; return 1; } }); } public boolean assertAllocated(long resourceId, String state, String type, boolean raiseOnBadState) { if (CommonStatesConstants.ACTIVE.equals(state) || ("instance".equalsIgnoreCase(type) && objectManager.findAny(InstanceHostMap.class, INSTANCE_HOST_MAP.INSTANCE_ID, resourceId, INSTANCE_HOST_MAP.REMOVED, null) != null)){ log.info("{} [{}] is already allocated", type, resourceId); return true; }else if (raiseOnBadState && !CommonStatesConstants.ACTIVATING.equals(state)) { throw new FailedToAllocate(String.format("Illegal allocation state: %s", state)); } return false; } public static boolean assertDeallocated(long resourceId, String state, String logType) { if (CommonStatesConstants.INACTIVE.equals(state)) { log.info("{} [{}] is already deallocated", logType, resourceId); return true; } else if (!CommonStatesConstants.DEACTIVATING.equals(state)) { throw new FailedToAllocate(String.format("Illegal deallocation state: %s", state)); } return false; } protected Iterator<AllocationCandidate> getCandidates(AllocationAttempt attempt) { List<Long> volumeIds = new ArrayList<>(); for (Volume v : attempt.getVolumes()) { volumeIds.add(v.getId()); } QueryOptions options = new QueryOptions(); options.setAccountId(attempt.getAccountId()); options.setRequestedHostId(attempt.getRequestedHostId()); for (Constraint constraint : attempt.getConstraints()) { if (constraint instanceof ValidHostsConstraint) { options.getHosts().addAll(((ValidHostsConstraint) constraint).getHosts()); } if (constraint instanceof PortsConstraint) { options.setIncludeUsedPorts(true); } } List<String> orderedHostUUIDs = null; if (attempt.getRequestedHostId() == null) { orderedHostUUIDs = callExternalSchedulerForHosts(attempt); } return allocatorDao.iteratorHosts(orderedHostUUIDs, volumeIds, options); } protected void releaseAllocation(Instance instance) { // This is kind of strange logic to remove deallocate for every instance host map, but in truth there will be only one ihm Map<String, List<InstanceHostMap>> maps = allocatorDao.getInstanceHostMapsWithHostUuid(instance.getId()); for (Map.Entry<String, List<InstanceHostMap>> entry : maps.entrySet()) { for (InstanceHostMap map : entry.getValue()) { if (!allocatorDao.isAllocationReleased(map)) { allocatorDao.releaseAllocation(instance, map); releaseResources(instance, entry.getKey(), InstanceConstants.PROCESS_DEALLOCATE); } } } } protected boolean recordCandidate(AllocationAttempt attempt, AllocationCandidate candidate) { Long newHost = candidate.getHost(); if (newHost != null) { callExternalSchedulerToReserve(attempt, candidate); } return allocatorDao.recordCandidate(attempt, candidate); } private String getHostUuid(Instance instance) { List<? extends InstanceHostMap> maps = mapDao.findNonRemoved(InstanceHostMap.class, Instance.class, instance.getId()); Long hostId = null; if (maps.size() == 1) { hostId = maps.get(0).getHostId(); } else if (maps.size() > 1) { Set<Long> hostIds = new HashSet<>(); for (InstanceHostMap ihm : maps) { hostIds.add(ihm.getHostId()); } if (hostIds.size() == 1) { hostId = hostIds.iterator().next(); } else { log.warn("Instance {} has {} instance host maps. Cannot determine host uuid. Returning null.", instance.getId(), maps.size()); return null; } } if (hostId != null) { Host h = objectManager.loadResource(Host.class, hostId); return h != null ? h.getUuid() : null; } else { return null; } } @SuppressWarnings("unchecked") private void callExternalSchedulerToReserve(AllocationAttempt attempt, AllocationCandidate candidate) { List<Long> agentIds = getAgentResource(attempt.getAccountId(), attempt.getInstances()); for (Long agentId : agentIds) { EventVO<Map<String, Object>> schedulerEvent = buildEvent(SCHEDULER_RESERVE_EVENT, InstanceConstants.PROCESS_ALLOCATE, attempt.getInstances(), attempt.getVolumes(), agentId); if (schedulerEvent != null) { Map<String, Object> reqData = CollectionUtils.toMap(schedulerEvent.getData().get(SCHEDULER_REQUEST_DATA_NAME)); reqData.put(HOST_ID, candidate.getHostUuid()); if (attempt.getRequestedHostId() != null) { reqData.put(FORCE_RESERVE, true); } RemoteAgent agent = agentLocator.lookupAgent(agentId); Event eventResult = callScheduler("Error reserving resources: %s", schedulerEvent, agent); if (eventResult.getData() == null) { return; } List<Map<String, Object>> data = (List<Map<String, Object>>) CollectionUtils.getNestedValue(eventResult.getData(), PORT_RESERVATION); if (data != null) { attempt.setAllocatedIPs(data); } } } } private void releaseResources(Instance instance, String hostUuid, String process) { List<Long> agentIds = getAgentResource(instance); for (Long agentId : agentIds) { EventVO<Map<String, Object>> schedulerEvent = buildReleaseEvent(process, instance, agentId); if (schedulerEvent != null) { Map<String, Object> reqData = CollectionUtils.toMap(schedulerEvent.getData().get(SCHEDULER_REQUEST_DATA_NAME)); reqData.put(HOST_ID, hostUuid); List<Instance> instances = new ArrayList<>(); if (!InstanceConstants.PROCESS_STOP.equals(process)) { instances.add(instance); reqData.put(CONTEXT, instances); } RemoteAgent agent = agentLocator.lookupAgent(agentId); callScheduler("Error releasing resources: %s", schedulerEvent, agent); } } } @SuppressWarnings("unchecked") private List<String> callExternalSchedulerForHosts(AllocationAttempt attempt) { List<String> hosts = null; List<Long> agentIds = getAgentResource(attempt.getAccountId(), attempt.getInstances()); for (Long agentId : agentIds) { EventVO<Map<String, Object>> schedulerEvent = buildEvent(SCHEDULER_PRIORITIZE_EVENT, InstanceConstants.PROCESS_ALLOCATE, attempt.getInstances(), attempt.getVolumes(), agentId); List<ResourceRequest> requests = extractResourceRequests(schedulerEvent); attempt.setResourceRequests(requests); if (schedulerEvent != null) { RemoteAgent agent = agentLocator.lookupAgent(agentId); Event eventResult = callScheduler("Error getting hosts for resources: %s", schedulerEvent, agent); if (hosts == null) { hosts = (List<String>) CollectionUtils.getNestedValue(eventResult.getData(), SCHEDULER_PRIORITIZE_RESPONSE); } else { List<String> newHosts = (List<String>) CollectionUtils.getNestedValue(eventResult.getData(), SCHEDULER_PRIORITIZE_RESPONSE); hosts.retainAll(newHosts); } if (hosts.isEmpty()) { throw new FailedToAllocate(String.format("No healthy hosts meet the resource constraints: %s", extractResourceRequests(schedulerEvent))); } } } return hosts; } Event callScheduler(String message, EventVO<Map<String, Object>> schedulerEvent, RemoteAgent agent) { try { return agent.callSync(schedulerEvent); } catch (EventExecutionException e) { log.error("External scheduler replied with an error: {}", e.getMessage()); throw new FailedToAllocate(String.format(message, extractResourceRequests(schedulerEvent)), e); } } @SuppressWarnings("unchecked") private List<ResourceRequest> extractResourceRequests(EventVO<Map<String, Object>> schedulerEvent) { return (List<ResourceRequest>)((Map<String, Object>)schedulerEvent.getData().get(SCHEDULER_REQUEST_DATA_NAME)).get(RESOURCE_REQUESTS); } private EventVO<Map<String, Object>> buildReleaseEvent(String phase, Object resource, Long agentId) { List<ResourceRequest> resourceRequests = new ArrayList<>(); if (resource instanceof Instance) { String schedulerVersion = getSchedulerVersion(agentId); addInstanceResourceRequests(resourceRequests, (Instance)resource, schedulerVersion); } if (resourceRequests.isEmpty()) { return null; } return newEvent(SCHEDULER_RELEASE_EVENT, resourceRequests, resource.getClass().getSimpleName(), phase, ObjectUtils.getId(resource), null); } private EventVO<Map<String, Object>> buildEvent(String eventName, String phase, List<Instance> instances, Set<Volume> volumes, Long agentId) { List<ResourceRequest> resourceRequests = gatherResourceRequests(instances, volumes, agentId); if (resourceRequests.isEmpty()) { return null; } return newEvent(eventName, resourceRequests, "instance", phase, instances.get(0).getId(), instances); } private EventVO<Map<String, Object>> newEvent(String eventName, List<ResourceRequest> resourceRequests, String resourceType, String phase, Object resourceId, Object context) { Map<String, Object> eventData = new HashMap<>(); Map<String, Object> reqData = new HashMap<>(); if (resourceRequests != null) { reqData.put(RESOURCE_REQUESTS, resourceRequests); } reqData.put(CONTEXT, context); reqData.put(PHASE, phase); eventData.put(SCHEDULER_REQUEST_DATA_NAME, reqData); EventVO<Map<String, Object>> schedulerEvent = EventVO.<Map<String, Object>> newEvent(eventName).withData(eventData); schedulerEvent.setResourceType(resourceType); if (resourceId != null) { schedulerEvent.setResourceId(resourceId.toString()); } return schedulerEvent; } private List<ResourceRequest> gatherResourceRequests(List<Instance> instances, Set<Volume> volumes, Long agentId) { List<ResourceRequest> requests = new ArrayList<>(); String schedulerVersion = getSchedulerVersion(agentId); for (Instance instance : instances) { addInstanceResourceRequests(requests, instance, schedulerVersion); } addVolumeResourceRequests(requests, volumes.toArray(new Volume[volumes.size()])); return requests; } private void addVolumeResourceRequests(List<ResourceRequest> requests, Volume... volumes) { for (Volume v : volumes) { if (v.getSizeMb() != null) { ResourceRequest rr = new ComputeResourceRequest(STORAGE_SIZE, v.getSizeMb(), COMPUTE_POOL); requests.add(rr); } } } private void addInstanceResourceRequests(List<ResourceRequest> requests, Instance instance, String schedulerVersion) { ResourceRequest memoryRequest = populateResourceRequestFromInstance(instance, MEMORY_RESERVATION, COMPUTE_POOL, schedulerVersion); if (memoryRequest != null) { requests.add(memoryRequest); } ResourceRequest cpuRequest = populateResourceRequestFromInstance(instance, CPU_RESERVATION, COMPUTE_POOL, schedulerVersion); if (cpuRequest != null) { requests.add(cpuRequest); } ResourceRequest portRequests = populateResourceRequestFromInstance(instance, PORT_RESERVATION, PORT_POOL, schedulerVersion); if (portRequests != null) { requests.add(portRequests); } ResourceRequest instanceRequest = populateResourceRequestFromInstance(instance, INSTANCE_RESERVATION, COMPUTE_POOL, schedulerVersion); requests.add(instanceRequest); } private List<Long> getAgentResource(Long accountId, List<Instance> instances) { List<Long> agentIds = agentInstanceDao.getAgentProvider(SystemLabels.LABEL_AGENT_SERVICE_SCHEDULING_PROVIDER, accountId); for (Instance instance : instances) { if (agentIds.contains(instance.getAgentId())) { return new ArrayList<>(); } } return agentIds; } private List<Long> getAgentResource(Object resource) { Long accountId = (Long)ObjectUtils.getAccountId(resource); List<Long> agentIds = agentInstanceDao.getAgentProvider(SystemLabels.LABEL_AGENT_SERVICE_SCHEDULING_PROVIDER, accountId); // If the resource being allocated is a scheduling provider agent, return null so that we don't try to send the container to the scheduler. Long resourceAgentId = (Long)ObjectUtils.getPropertyIgnoreErrors(resource, "agentId"); if (resourceAgentId != null && agentIds.contains(resourceAgentId)) { return new ArrayList<>(); } return agentIds; } private ResourceRequest populateResourceRequestFromInstance(Instance instance, String resourceType, String poolType, String schedulerVersion) { switch (resourceType) { case PORT_RESERVATION: if (useLegacyPortAllocation(schedulerVersion)) { return null; } PortBindingResourceRequest request = new PortBindingResourceRequest(); request.setResource(resourceType); request.setInstanceId(instance.getId().toString()); request.setResourceUuid(instance.getUuid()); List<PortSpec> portReservation = new ArrayList<>(); for(Port port: objectManager.children(instance, Port.class)) { PortSpec spec = new PortSpec(); String bindAddress = DataAccessor.fieldString(port, BIND_ADDRESS); if (bindAddress != null) { spec.setIpAddress(bindAddress); } spec.setPrivatePort(port.getPrivatePort()); spec.setPublicPort(port.getPublicPort()); String proto = StringUtils.isEmpty(port.getProtocol()) ? "tcp" : port.getProtocol(); spec.setProtocol(proto); portReservation.add(spec); } if (portReservation.isEmpty()) { return null; } request.setPortRequests(portReservation); request.setType(poolType); return request; case INSTANCE_RESERVATION: return new ComputeResourceRequest(INSTANCE_RESERVATION, 1l, poolType); case MEMORY_RESERVATION: if (instance.getMemoryReservation() != null && instance.getMemoryReservation() > 0) { ResourceRequest rr = new ComputeResourceRequest(MEMORY_RESERVATION, instance.getMemoryReservation(), poolType); return rr; } return null; case CPU_RESERVATION: if (instance.getMilliCpuReservation() != null && instance.getMilliCpuReservation() > 0) { ResourceRequest rr = new ComputeResourceRequest(CPU_RESERVATION, instance.getMilliCpuReservation(), poolType); return rr; } return null; } return null; } protected boolean useLegacyPortAllocation(Long accountId, List<Instance> instances) { List<Long> agentIds = getAgentResource(accountId, instances); if (agentIds == null || agentIds.size() == 0) { return true; } return useLegacyPortAllocation(agentIds); } protected boolean useLegacyPortAllocation(List<Long> agentIds) { for(Long agentId: agentIds) { String schedulerVersion = getSchedulerVersion(agentId); if (useLegacyPortAllocation(schedulerVersion)) { return true; } } return false; } protected String getSchedulerVersion(Long agentId) { Instance instance = agentInstanceDao.getInstanceByAgent(agentId); String imageUuid = (String) DataAccessor.fields(instance).withKey(InstanceConstants.FIELD_IMAGE_UUID).get(); DockerImage img = DockerImage.parse(imageUuid); String[] imageParts = img.getFullName().split(":"); if (imageParts.length <= 1) { return ""; } if (!imageParts[0].equals("rancher/scheduler")) { return "NotApplicable"; } return imageParts[imageParts.length - 1]; } protected boolean useLegacyPortAllocation(String actualVersion) { String requiredVersion = PORT_SCHEDULER_IMAGE_VERSION.get(); if (StringUtils.isEmpty(requiredVersion)) { // Property not available. Use legacy return true; } String[] requiredParts = requiredVersion.split("\\."); if (requiredParts.length < 3) { // Required image is not following semantic versioning. Assume custom, don't use legacy return false; } int requiredMajor, requiredMinor = 0; try { String majorTemp = requiredParts[0].startsWith("v") ? requiredParts[0].substring(1, requiredParts[0].length()) : requiredParts[0]; requiredMajor = Integer.valueOf(majorTemp); requiredMinor = Integer.valueOf(requiredParts[1]); } catch (NumberFormatException e) { // Require image is not following semantic versioning. Assume custom, don't use legacy return false; } String[] actualParts = actualVersion.split("\\."); if (actualParts.length < 3) { // Image is not following semantic versioning. Assume custom, don't use legacy return false; } int actualMajor, actualMinor = 0; try { String majorTemp = actualParts[0].startsWith("v") ? actualParts[0].substring(1, actualParts[0].length()) : actualParts[0]; actualMajor = Integer.valueOf(majorTemp).intValue(); actualMinor = Integer.valueOf(actualParts[1]).intValue(); } catch (NumberFormatException e) { // Image is not following semantic versioning. Assume custom, don't use legacy return false; } if (actualMajor < requiredMajor) { return true; } else if (actualMajor == requiredMajor && actualMinor < requiredMinor) { return true; } return false; } @Override public String toString() { return getName(); } @Override public String getName() { return name; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.rel.rules; import org.apache.calcite.config.CalciteConnectionConfig; import org.apache.calcite.config.CalciteSystemProperty; import org.apache.calcite.jdbc.CalciteSchema; import org.apache.calcite.materialize.Lattice; import org.apache.calcite.materialize.TileKey; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelOptLattice; import org.apache.calcite.plan.RelOptPlanner; import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelOptRuleOperand; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.plan.SubstitutionVisitor; import org.apache.calcite.plan.ViewExpanders; import org.apache.calcite.prepare.RelOptTableImpl; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Aggregate; import org.apache.calcite.rel.core.AggregateCall; import org.apache.calcite.rel.core.Project; import org.apache.calcite.rel.core.RelFactories; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.schema.Table; import org.apache.calcite.schema.impl.StarTable; import org.apache.calcite.sql.SqlAggFunction; import org.apache.calcite.tools.RelBuilder; import org.apache.calcite.tools.RelBuilderFactory; import org.apache.calcite.util.ImmutableBitSet; import org.apache.calcite.util.Pair; import org.apache.calcite.util.mapping.AbstractSourceMapping; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; /** * Planner rule that matches an {@link org.apache.calcite.rel.core.Aggregate} on * top of a {@link org.apache.calcite.schema.impl.StarTable.StarTableScan}. * * <p>This pattern indicates that an aggregate table may exist. The rule asks * the star table for an aggregate table at the required level of aggregation. */ public class AggregateStarTableRule extends RelOptRule { public static final AggregateStarTableRule INSTANCE = new AggregateStarTableRule( operandJ(Aggregate.class, null, Aggregate::isSimple, some(operand(StarTable.StarTableScan.class, none()))), RelFactories.LOGICAL_BUILDER, "AggregateStarTableRule"); public static final AggregateStarTableRule INSTANCE2 = new AggregateStarTableRule( operandJ(Aggregate.class, null, Aggregate::isSimple, operand(Project.class, operand(StarTable.StarTableScan.class, none()))), RelFactories.LOGICAL_BUILDER, "AggregateStarTableRule:project") { @Override public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final Project project = call.rel(1); final StarTable.StarTableScan scan = call.rel(2); final RelNode rel = AggregateProjectMergeRule.apply(call, aggregate, project); final Aggregate aggregate2; final Project project2; if (rel instanceof Aggregate) { project2 = null; aggregate2 = (Aggregate) rel; } else if (rel instanceof Project) { project2 = (Project) rel; aggregate2 = (Aggregate) project2.getInput(); } else { return; } apply(call, project2, aggregate2, scan); } }; /** * Creates an AggregateStarTableRule. * * @param operand root operand, must not be null * @param description Description, or null to guess description * @param relBuilderFactory Builder for relational expressions */ public AggregateStarTableRule(RelOptRuleOperand operand, RelBuilderFactory relBuilderFactory, String description) { super(operand, relBuilderFactory, description); } @Override public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final StarTable.StarTableScan scan = call.rel(1); apply(call, null, aggregate, scan); } protected void apply(RelOptRuleCall call, Project postProject, final Aggregate aggregate, StarTable.StarTableScan scan) { final RelOptPlanner planner = call.getPlanner(); final CalciteConnectionConfig config = planner.getContext().unwrap(CalciteConnectionConfig.class); if (config == null || !config.createMaterializations()) { // Disable this rule if we if materializations are disabled - in // particular, if we are in a recursive statement that is being used to // populate a materialization return; } final RelOptCluster cluster = scan.getCluster(); final RelOptTable table = scan.getTable(); final RelOptLattice lattice = planner.getLattice(table); final List<Lattice.Measure> measures = lattice.lattice.toMeasures(aggregate.getAggCallList()); final Pair<CalciteSchema.TableEntry, TileKey> pair = lattice.getAggregate(planner, aggregate.getGroupSet(), measures); if (pair == null) { return; } final RelBuilder relBuilder = call.builder(); final CalciteSchema.TableEntry tableEntry = pair.left; final TileKey tileKey = pair.right; final RelMetadataQuery mq = call.getMetadataQuery(); final double rowCount = aggregate.estimateRowCount(mq); final Table aggregateTable = tableEntry.getTable(); final RelDataType aggregateTableRowType = aggregateTable.getRowType(cluster.getTypeFactory()); final RelOptTable aggregateRelOptTable = RelOptTableImpl.create( table.getRelOptSchema(), aggregateTableRowType, tableEntry, rowCount); relBuilder.push(aggregateRelOptTable.toRel(ViewExpanders.simpleContext(cluster))); if (tileKey == null) { if (CalciteSystemProperty.DEBUG.value()) { System.out.println("Using materialization " + aggregateRelOptTable.getQualifiedName() + " (exact match)"); } } else if (!tileKey.dimensions.equals(aggregate.getGroupSet())) { // Aggregate has finer granularity than we need. Roll up. if (CalciteSystemProperty.DEBUG.value()) { System.out.println("Using materialization " + aggregateRelOptTable.getQualifiedName() + ", rolling up " + tileKey.dimensions + " to " + aggregate.getGroupSet()); } assert tileKey.dimensions.contains(aggregate.getGroupSet()); final List<AggregateCall> aggCalls = new ArrayList<>(); ImmutableBitSet.Builder groupSet = ImmutableBitSet.builder(); for (int key : aggregate.getGroupSet()) { groupSet.set(tileKey.dimensions.indexOf(key)); } for (AggregateCall aggCall : aggregate.getAggCallList()) { final AggregateCall copy = rollUp(groupSet.cardinality(), relBuilder, aggCall, tileKey); if (copy == null) { return; } aggCalls.add(copy); } relBuilder.push( aggregate.copy(aggregate.getTraitSet(), relBuilder.build(), groupSet.build(), null, aggCalls)); } else if (!tileKey.measures.equals(measures)) { if (CalciteSystemProperty.DEBUG.value()) { System.out.println("Using materialization " + aggregateRelOptTable.getQualifiedName() + ", right granularity, but different measures " + aggregate.getAggCallList()); } relBuilder.project( relBuilder.fields( new AbstractSourceMapping( tileKey.dimensions.cardinality() + tileKey.measures.size(), aggregate.getRowType().getFieldCount()) { public int getSourceOpt(int source) { if (source < aggregate.getGroupCount()) { int in = tileKey.dimensions.nth(source); return aggregate.getGroupSet().indexOf(in); } Lattice.Measure measure = measures.get(source - aggregate.getGroupCount()); int i = tileKey.measures.indexOf(measure); assert i >= 0; return tileKey.dimensions.cardinality() + i; } } .inverse())); } if (postProject != null) { relBuilder.push( postProject.copy(postProject.getTraitSet(), ImmutableList.of(relBuilder.peek()))); } call.transformTo(relBuilder.build()); } private static AggregateCall rollUp(int groupCount, RelBuilder relBuilder, AggregateCall aggregateCall, TileKey tileKey) { if (aggregateCall.isDistinct()) { return null; } final SqlAggFunction aggregation = aggregateCall.getAggregation(); final Pair<SqlAggFunction, List<Integer>> seek = Pair.of(aggregation, aggregateCall.getArgList()); final int offset = tileKey.dimensions.cardinality(); final ImmutableList<Lattice.Measure> measures = tileKey.measures; // First, try to satisfy the aggregation by rolling up an aggregate in the // materialization. final int i = find(measures, seek); tryRoll: if (i >= 0) { final SqlAggFunction roll = SubstitutionVisitor.getRollup(aggregation); if (roll == null) { break tryRoll; } return AggregateCall.create(roll, false, aggregateCall.isApproximate(), aggregateCall.ignoreNulls(), ImmutableList.of(offset + i), -1, aggregateCall.collation, groupCount, relBuilder.peek(), null, aggregateCall.name); } // Second, try to satisfy the aggregation based on group set columns. tryGroup: { List<Integer> newArgs = new ArrayList<>(); for (Integer arg : aggregateCall.getArgList()) { int z = tileKey.dimensions.indexOf(arg); if (z < 0) { break tryGroup; } newArgs.add(z); } return AggregateCall.create(aggregation, false, aggregateCall.isApproximate(), aggregateCall.ignoreNulls(), newArgs, -1, aggregateCall.collation, groupCount, relBuilder.peek(), null, aggregateCall.name); } // No roll up possible. return null; } private static int find(ImmutableList<Lattice.Measure> measures, Pair<SqlAggFunction, List<Integer>> seek) { for (int i = 0; i < measures.size(); i++) { Lattice.Measure measure = measures.get(i); if (measure.agg.equals(seek.left) && measure.argOrdinals().equals(seek.right)) { return i; } } return -1; } } // End AggregateStarTableRule.java
/** * SIX OVAL - https://nakamura5akihito.github.io/ * Copyright (C) 2010 Akihito Nakamura * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.opensec.six.oval.model.windows; import io.opensec.six.oval.model.ComponentType; import io.opensec.six.oval.model.ElementRef; import io.opensec.six.oval.model.Family; import io.opensec.six.oval.model.definitions.EntityObjectStringType; import io.opensec.six.oval.model.definitions.Filter; import io.opensec.six.oval.model.definitions.Set; import io.opensec.six.oval.model.definitions.SystemObjectType; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * The interface object is used by an interface test * to define the specific interfaces(s) to be evaluated. * * @author Akihito Nakamura, AIST * @see <a href="http://oval.mitre.org/language/">OVAL Language</a> */ public class InterfaceObject extends SystemObjectType { //TODO: XSD model. // choice( // set // sequence( // name // filter // ) private Set set; //{1..1} private EntityObjectStringType name; //{1..1} private final Collection<Filter> filter = new ArrayList<Filter>(); //{0..*} /** * Constructor. */ public InterfaceObject() { this( null, 0 ); } public InterfaceObject( final String id, final int version ) { super( id, version ); // _oval_platform_type = OvalPlatformType.windows; // _oval_component_type = OvalComponentType.network_interface; _oval_family = Family.WINDOWS; _oval_component = ComponentType.INTERFACE; } // public FileObject( // final String id, // final int version, // final String comment // ) // { // super( id, version, comment ); // } // // // public FileObject( // final String id, // final int version, // final String path, // final String filename // ) // { // this( id, version, // new EntityObjectStringType( path ), // new EntityObjectStringType( filename ) // ); // } // // // public FileObject( // final String id, // final int version, // final EntityObjectStringType path, // final EntityObjectStringType filename // ) // { // super( id, version ); // setPath( path ); // setFilename( filename ); // } /** */ public void setSet( final Set set ) { this.set = set; } public Set getSet() { return set; } /** */ public void setName( final EntityObjectStringType name ) { this.name = name; } public EntityObjectStringType getName() { return name; } /** */ public void setFilter( final Collection<? extends Filter> filterList ) { if (filter != filterList) { filter.clear(); if (filterList != null && filterList.size() > 0) { filter.addAll( filterList ); } } } public boolean addFilter( final Filter filter ) { if (filter == null) { return false; } return this.filter.add( filter ); } public Collection<Filter> getFilter() { return filter; } public Iterator<Filter> iterateFilter() { return filter.iterator(); } //********************************************************************* // DefinitionsElement //********************************************************************* @Override public Collection<ElementRef> ovalGetElementRef() { Collection<ElementRef> ref_list = new ArrayList<ElementRef>(); ref_list.add( getName() ); ref_list.addAll( getFilter() ); return ref_list; } //************************************************************** // java.lang.Object //************************************************************** @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals( final Object obj ) { if (!(obj instanceof InterfaceObject)) { return false; } return super.equals( obj ); } @Override public String toString() { return "interface_object[" + super.toString() + ", set" + getSet() + ", name=" + getName() + ", filter=" + getFilter() + "]"; } } //
/* ==================================================================== 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.poi.hssf.usermodel; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.Paint; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ImageObserver; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderableImage; import java.io.PrintStream; import java.text.AttributedCharacterIterator; import java.util.Arrays; import java.util.Map; import org.apache.poi.util.Internal; public class DummyGraphics2d extends Graphics2D { private BufferedImage bufimg; private final Graphics2D g2D; private final PrintStream log; public DummyGraphics2d() { this(System.out); } public DummyGraphics2d(PrintStream log) { bufimg = new BufferedImage(1000, 1000, 2); g2D = (Graphics2D)bufimg.getGraphics(); this.log = log; } public DummyGraphics2d(PrintStream log, Graphics2D g2D) { this.g2D = g2D; this.log = log; } public void addRenderingHints(Map<?,?> hints) { String l = "addRenderingHinds(Map):" + "\n hints = " + hints; log.println( l ); g2D.addRenderingHints( hints ); } public void clip(Shape s) { String l = "clip(Shape):" + "\n s = " + s; log.println( l ); g2D.clip( s ); } public void draw(Shape s) { String l = "draw(Shape):" + "\n s = " + s; log.println( l ); g2D.draw( s ); } public void drawGlyphVector(GlyphVector g, float x, float y) { String l = "drawGlyphVector(GlyphVector, float, float):" + "\n g = " + g + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.drawGlyphVector( g, x, y ); } public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) { String l = "drawImage(BufferedImage, BufferedImageOp, x, y):" + "\n img = " + img + "\n op = " + op + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.drawImage( img, op, x, y ); } public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) { String l = "drawImage(Image,AfflineTransform,ImageObserver):" + "\n img = " + img + "\n xform = " + xform + "\n obs = " + obs; log.println( l ); return g2D.drawImage( img, xform, obs ); } public void drawRenderableImage(RenderableImage img, AffineTransform xform) { String l = "drawRenderableImage(RenderableImage, AfflineTransform):" + "\n img = " + img + "\n xform = " + xform; log.println( l ); g2D.drawRenderableImage( img, xform ); } public void drawRenderedImage(RenderedImage img, AffineTransform xform) { String l = "drawRenderedImage(RenderedImage, AffineTransform):" + "\n img = " + img + "\n xform = " + xform; log.println( l ); g2D.drawRenderedImage( img, xform ); } public void drawString(AttributedCharacterIterator iterator, float x, float y) { String l = "drawString(AttributedCharacterIterator):" + "\n iterator = " + iterator + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.drawString( iterator, x, y ); } public void drawString(String s, float x, float y) { String l = "drawString(s,x,y):" + "\n s = " + s + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.drawString( s, x, y ); } public void fill(Shape s) { String l = "fill(Shape):" + "\n s = " + s; log.println( l ); g2D.fill( s ); } public Color getBackground() { log.println( "getBackground():" ); return g2D.getBackground(); } public Composite getComposite() { log.println( "getComposite():" ); return g2D.getComposite(); } public GraphicsConfiguration getDeviceConfiguration() { log.println( "getDeviceConfiguration():" ); return g2D.getDeviceConfiguration(); } public FontRenderContext getFontRenderContext() { log.println( "getFontRenderContext():" ); return g2D.getFontRenderContext(); } public Paint getPaint() { log.println( "getPaint():" ); return g2D.getPaint(); } public Object getRenderingHint(RenderingHints.Key hintKey) { String l = "getRenderingHint(RenderingHints.Key):" + "\n hintKey = " + hintKey; log.println( l ); return g2D.getRenderingHint( hintKey ); } public RenderingHints getRenderingHints() { log.println( "getRenderingHints():" ); return g2D.getRenderingHints(); } public Stroke getStroke() { log.println( "getStroke():" ); return g2D.getStroke(); } public AffineTransform getTransform() { log.println( "getTransform():" ); return g2D.getTransform(); } public boolean hit(Rectangle rect, Shape s, boolean onStroke) { String l = "hit(Rectangle, Shape, onStroke):" + "\n rect = " + rect + "\n s = " + s + "\n onStroke = " + onStroke; log.println( l ); return g2D.hit( rect, s, onStroke ); } public void rotate(double theta) { String l = "rotate(theta):" + "\n theta = " + theta; log.println( l ); g2D.rotate( theta ); } public void rotate(double theta, double x, double y) { String l = "rotate(double,double,double):" + "\n theta = " + theta + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.rotate( theta, x, y ); } public void scale(double sx, double sy) { String l = "scale(double,double):" + "\n sx = " + sx + "\n sy"; log.println( l ); g2D.scale( sx, sy ); } public void setBackground(Color color) { String l = "setBackground(Color):" + "\n color = " + color; log.println( l ); g2D.setBackground( color ); } public void setComposite(Composite comp) { String l = "setComposite(Composite):" + "\n comp = " + comp; log.println( l ); g2D.setComposite( comp ); } public void setPaint( Paint paint ) { String l = "setPaint(Paint):" + "\n paint = " + paint; log.println( l ); g2D.setPaint( paint ); } public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue) { String l = "setRenderingHint(RenderingHints.Key, Object):" + "\n hintKey = " + hintKey + "\n hintValue = " + hintValue; log.println( l ); g2D.setRenderingHint( hintKey, hintValue ); } public void setRenderingHints(Map<?,?> hints) { String l = "setRenderingHints(Map):" + "\n hints = " + hints; log.println( l ); g2D.setRenderingHints( hints ); } public void setStroke(Stroke s) { String l; if (s instanceof BasicStroke) { BasicStroke bs = (BasicStroke)s; l = "setStroke(Stoke):" + "\n s = BasicStroke(" + "\n dash[]: "+Arrays.toString(bs.getDashArray()) + "\n dashPhase: "+bs.getDashPhase() + "\n endCap: "+bs.getEndCap() + "\n lineJoin: "+bs.getLineJoin() + "\n width: "+bs.getLineWidth() + "\n miterLimit: "+bs.getMiterLimit() + "\n )"; } else { l = "setStroke(Stoke):" + "\n s = " + s; } log.println( l ); g2D.setStroke( s ); } public void setTransform(AffineTransform Tx) { String l = "setTransform():" + "\n Tx = " + Tx; log.println( l ); g2D.setTransform( Tx ); } public void shear(double shx, double shy) { String l = "shear(shx, dhy):" + "\n shx = " + shx + "\n shy = " + shy; log.println( l ); g2D.shear( shx, shy ); } public void transform(AffineTransform Tx) { String l = "transform(AffineTransform):" + "\n Tx = " + Tx; log.println( l ); g2D.transform( Tx ); } public void translate(double tx, double ty) { String l = "translate(double, double):" + "\n tx = " + tx + "\n ty = " + ty; log.println( l ); g2D.translate( tx, ty ); } public void clearRect(int x, int y, int width, int height) { String l = "clearRect(int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); g2D.clearRect( x, y, width, height ); } public void clipRect(int x, int y, int width, int height) { String l = "clipRect(int, int, int, int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "height = " + height; log.println( l ); g2D.clipRect( x, y, width, height ); } public void copyArea(int x, int y, int width, int height, int dx, int dy) { String l = "copyArea(int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); g2D.copyArea( x, y, width, height, dx, dy ); } public Graphics create() { log.println( "create():" ); return g2D.create(); } public Graphics create(int x, int y, int width, int height) { String l = "create(int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); return g2D.create( x, y, width, height ); } public void dispose() { log.println( "dispose():" ); g2D.dispose(); } public void draw3DRect(int x, int y, int width, int height, boolean raised) { String l = "draw3DRect(int,int,int,int,boolean):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height + "\n raised = " + raised; log.println( l ); g2D.draw3DRect( x, y, width, height, raised ); } public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { String l = "drawArc(int,int,int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height + "\n startAngle = " + startAngle + "\n arcAngle = " + arcAngle; log.println( l ); g2D.drawArc( x, y, width, height, startAngle, arcAngle ); } public void drawBytes(byte data[], int offset, int length, int x, int y) { String l = "drawBytes(byte[],int,int,int,int):" + "\n data = " + Arrays.toString(data) + "\n offset = " + offset + "\n length = " + length + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.drawBytes( data, offset, length, x, y ); } public void drawChars(char data[], int offset, int length, int x, int y) { String l = "drawChars(data,int,int,int,int):" + "\n data = " + Arrays.toString(data) + "\n offset = " + offset + "\n length = " + length + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.drawChars( data, offset, length, x, y ); } public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) { String l = "drawImage(Image,int,int,int,int,int,int,int,int,ImageObserver):" + "\n img = " + img + "\n dx1 = " + dx1 + "\n dy1 = " + dy1 + "\n dx2 = " + dx2 + "\n dy2 = " + dy2 + "\n sx1 = " + sx1 + "\n sy1 = " + sy1 + "\n sx2 = " + sx2 + "\n sy2 = " + sy2 + "\n observer = " + observer; log.println( l ); return g2D.drawImage( img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer ); } public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) { String l = "drawImage(Image,int,int,int,int,int,int,int,int,Color,ImageObserver):" + "\n img = " + img + "\n dx1 = " + dx1 + "\n dy1 = " + dy1 + "\n dx2 = " + dx2 + "\n dy2 = " + dy2 + "\n sx1 = " + sx1 + "\n sy1 = " + sy1 + "\n sx2 = " + sx2 + "\n sy2 = " + sy2 + "\n bgcolor = " + bgcolor + "\n observer = " + observer; log.println( l ); return g2D.drawImage( img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgcolor, observer ); } public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) { String l = "drawImage(Image,int,int,Color,ImageObserver):" + "\n img = " + img + "\n x = " + x + "\n y = " + y + "\n bgcolor = " + bgcolor + "\n observer = " + observer; log.println( l ); return g2D.drawImage( img, x, y, bgcolor, observer ); } public boolean drawImage(Image img, int x, int y, ImageObserver observer) { String l = "drawImage(Image,int,int,observer):" + "\n img = " + img + "\n x = " + x + "\n y = " + y + "\n observer = " + observer; log.println( l ); return g2D.drawImage( img, x, y, observer ); } public boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) { String l = "drawImage(Image,int,int,int,int,Color,ImageObserver):" + "\n img = " + img + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height + "\n bgcolor = " + bgcolor + "\n observer = " + observer; log.println( l ); return g2D.drawImage( img, x, y, width, height, bgcolor, observer ); } public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) { String l = "drawImage(Image,int,int,width,height,observer):" + "\n img = " + img + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height + "\n observer = " + observer; log.println( l ); return g2D.drawImage( img, x, y, width, height, observer ); } public void drawLine(int x1, int y1, int x2, int y2) { String l = "drawLine(int,int,int,int):" + "\n x1 = " + x1 + "\n y1 = " + y1 + "\n x2 = " + x2 + "\n y2 = " + y2; log.println( l ); g2D.drawLine( x1, y1, x2, y2 ); } public void drawOval(int x, int y, int width, int height) { String l = "drawOval(int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); g2D.drawOval( x, y, width, height ); } public void drawPolygon(Polygon p) { String l = "drawPolygon(Polygon):" + "\n p = " + p; log.println( l ); g2D.drawPolygon( p ); } public void drawPolygon(int xPoints[], int yPoints[], int nPoints) { String l = "drawPolygon(int[],int[],int):" + "\n xPoints = " + Arrays.toString(xPoints) + "\n yPoints = " + Arrays.toString(yPoints) + "\n nPoints = " + nPoints; log.println( l ); g2D.drawPolygon( xPoints, yPoints, nPoints ); } public void drawPolyline(int xPoints[], int yPoints[], int nPoints) { String l = "drawPolyline(int[],int[],int):" + "\n xPoints = " + Arrays.toString(xPoints) + "\n yPoints = " + Arrays.toString(yPoints) + "\n nPoints = " + nPoints; log.println( l ); g2D.drawPolyline( xPoints, yPoints, nPoints ); } public void drawRect(int x, int y, int width, int height) { String l = "drawRect(int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); g2D.drawRect( x, y, width, height ); } public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { String l = "drawRoundRect(int,int,int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height + "\n arcWidth = " + arcWidth + "\n arcHeight = " + arcHeight; log.println( l ); g2D.drawRoundRect( x, y, width, height, arcWidth, arcHeight ); } public void drawString(AttributedCharacterIterator iterator, int x, int y) { String l = "drawString(AttributedCharacterIterator,int,int):" + "\n iterator = " + iterator + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.drawString( iterator, x, y ); } public void drawString(String str, int x, int y) { String l = "drawString(str,int,int):" + "\n str = " + str + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.drawString( str, x, y ); } public void fill3DRect(int x, int y, int width, int height, boolean raised) { String l = "fill3DRect(int,int,int,int,boolean):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height + "\n raised = " + raised; log.println( l ); g2D.fill3DRect( x, y, width, height, raised ); } public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { String l = "fillArc(int,int,int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height + "\n startAngle = " + startAngle + "\n arcAngle = " + arcAngle; log.println( l ); g2D.fillArc( x, y, width, height, startAngle, arcAngle ); } public void fillOval(int x, int y, int width, int height) { String l = "fillOval(int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); g2D.fillOval( x, y, width, height ); } public void fillPolygon(Polygon p) { String l = "fillPolygon(Polygon):" + "\n p = " + p; log.println( l ); g2D.fillPolygon( p ); } public void fillPolygon(int xPoints[], int yPoints[], int nPoints) { String l = "fillPolygon(int[],int[],int):" + "\n xPoints = " + Arrays.toString(xPoints) + "\n yPoints = " + Arrays.toString(yPoints) + "\n nPoints = " + nPoints; log.println( l ); g2D.fillPolygon( xPoints, yPoints, nPoints ); } public void fillRect(int x, int y, int width, int height) { String l = "fillRect(int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); g2D.fillRect( x, y, width, height ); } public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { String l = "fillRoundRect(int,int,int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); g2D.fillRoundRect( x, y, width, height, arcWidth, arcHeight ); } // FIXME: should be protected // FindBugs, category MALICIOUS_CODE, FI_PUBLIC_SHOULD_BE_PROTECTED // A class's finalize() method should have protected access, not public @Internal @Override public final void finalize() { log.println( "finalize():" ); g2D.finalize(); // NOSOLAR super.finalize(); } public Shape getClip() { log.println( "getClip():" ); return g2D.getClip(); } public Rectangle getClipBounds() { log.println( "getClipBounds():" ); return g2D.getClipBounds(); } public Rectangle getClipBounds(Rectangle r) { String l = "getClipBounds(Rectangle):" + "\n r = " + r; log.println( l ); return g2D.getClipBounds( r ); } public Color getColor() { log.println( "getColor():" ); return g2D.getColor(); } public Font getFont() { log.println( "getFont():" ); return g2D.getFont(); } public FontMetrics getFontMetrics() { log.println( "getFontMetrics():" ); return g2D.getFontMetrics(); } public FontMetrics getFontMetrics(Font f) { log.println( "getFontMetrics():" ); return g2D.getFontMetrics( f ); } public boolean hitClip(int x, int y, int width, int height) { String l = "hitClip(int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); return g2D.hitClip( x, y, width, height ); } public void setClip(Shape clip) { String l = "setClip(Shape):" + "\n clip = " + clip; log.println( l ); g2D.setClip( clip ); } public void setClip(int x, int y, int width, int height) { String l = "setClip(int,int,int,int):" + "\n x = " + x + "\n y = " + y + "\n width = " + width + "\n height = " + height; log.println( l ); g2D.setClip( x, y, width, height ); } public void setColor(Color c) { String l = "setColor():" + "\n c = " + c; log.println( l ); g2D.setColor( c ); } public void setFont(Font font) { String l = "setFont(Font):" + "\n font = " + font; log.println( l ); g2D.setFont( font ); } public void setPaintMode() { log.println( "setPaintMode():" ); g2D.setPaintMode(); } public void setXORMode(Color c1) { String l = "setXORMode(Color):" + "\n c1 = " + c1; log.println( l ); g2D.setXORMode( c1 ); } public String toString() { log.println( "toString():" ); return g2D.toString(); } public void translate(int x, int y) { String l = "translate(int,int):" + "\n x = " + x + "\n y = " + y; log.println( l ); g2D.translate( x, y ); } }
package jstamp.ssca2; /* ============================================================================= * * alg_radix_smp.java * * ============================================================================= * * For the license of ssca2, please see ssca2/COPYRIGHT * * ------------------------------------------------------------------------ * * Unless otherwise noted, the following license applies to STAMP files: * * Copyright (c) 2007, Stanford University * 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 Stanford University 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 STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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. * * ============================================================================= */ public class Alg_Radix_Smp { public int[] global_myHisto; public int[] global_psHisto; public int[] global_lTemp; public int[] global_lTemp2; public Alg_Radix_Smp() { global_myHisto = null; global_psHisto = null; global_lTemp = null; global_lTemp2 = null; } public static int BITS(int x, int k, int j) { return ((x>>k) & ~(~0<<j)); } /* ============================================================================= * all_countsort_node * * R (range) must be a multiple of NODES * q (elems/proc) must be a multiple of NODES * ============================================================================= */ /* public void all_countsort_node ( int q, int[] lKey, int[] lSorted, int R, int bitOff, int m) { int[] myHisto = null; int[] psHisto = null; if (myId == 0) { myHisto = new int[numThread*R]; global_myHisto = myHisto; psHisto = new int[numThread*R]; global_psHisto = psHisto; } Barrier.enterBarrier(); myHisto = global_myHisto; psHisto = global_psHisto; int index = myId * R; for (int k = index; k < index+R; k++) { myHisto[k] = 0; } LocalStartStop lss = new LocalStartStop(); CreatePartition.createPartition(0, q, myId, numThread, lss); for (int k = lss.i_start; k < lss.i_stop; k++) { myHisto[(myId * R) + BITS(lKey[k],bitOff,m)]++; } Barrier.enterBarrier(); CreatePartition.createPartition(0, R, myId, numThread, lss); int last; for (int k = lss.i_start; k < lss.i_stop; k++) { last = psHisto[k] = myHisto[k]; for (int j = 1; j < numThread; j++) { int temp = psHisto[(j*R) + k] = last + myHisto[(j*R) + k]; last = temp; } } Barrier.enterBarrier(); int offset = 0; for (int k = 0; k < R; k++) { myHisto[(myId * R) + k] = (psHisto[(myId * R) + k] - myHisto[(myId * R) + k]) + offset; offset += psHisto[((numThread - 1) * R) + k]; } Barrier.enterBarrier(); CreatePartition.createPartition(0, q, myId, numThread, lss); for (int k = lss.i_start; k < lss.i_stop; k++) { int j = BITS(lKey[k],bitOff,m); lSorted[myHisto[(myId * R) + j]] = lKey[k]; myHisto[(myId * R) + j]++; } Barrier.enterBarrier(); if (myId == 0) { psHisto = null; myHisto = null; } } */ /* ============================================================================= * all_countsort_node_aux_seq * * R (range) must be a multiple of NODES * q (elems/proc) must be a multiple of NODES * ============================================================================= */ public void all_countsort_node_aux_seq (int q, int[] lKey, int[] lSorted, int[] auxKey, int[] auxSorted, int R, int bitOff, int m) { int[] myHisto = new int[ R]; int[] psHisto = new int[ R]; for (int k = 0; k < R; k++) { myHisto[k] = 0; } for (int k = 0; k < q; k++) { myHisto[BITS(lKey[k],bitOff,m)]++; } int last; for (int k = 0; k < R; k++) { last = psHisto[k] = myHisto[k]; } int offset = 0; for (int k = 0; k < R; k++) { myHisto[k] = (psHisto[k] - myHisto[k]) + offset; offset += psHisto[k]; } for (int k = 0; k < q; k++) { int j = BITS(lKey[k], bitOff, m); lSorted[myHisto[j]] = lKey[k]; auxSorted[myHisto[j]] = auxKey[k]; myHisto[j]++; // //lSorted[mhp[j]] = lKey[k]; //auxSorted[mhp[j]] = auxKey[k]; //mhp[j]++; } } /* ============================================================================= * all_countsort_node_aux * * R (range) must be a multiple of NODES * q (elems/proc) must be a multiple of NODES * ============================================================================= */ public void all_countsort_node_aux (int myId, int numThread, int q, int[] lKey, int[] lSorted, int[] auxKey, int[] auxSorted, int R, int bitOff, int m, Alg_Radix_Smp rdxsort) { int[] myHisto = null; int[] psHisto = null; if (myId == 0) { myHisto = new int[numThread * R]; rdxsort.global_myHisto = myHisto; psHisto = new int[numThread * R]; rdxsort.global_psHisto = psHisto; } Barrier.enterBarrier(); myHisto = rdxsort.global_myHisto; psHisto = rdxsort.global_psHisto; for (int k = 0; k < R; k++) { myHisto[((myId*R) + k)] = 0; } LocalStartStop lss = new LocalStartStop(); CreatePartition.createPartition(0, q, myId, numThread, lss); for (int k = lss.i_start; k < lss.i_stop; k++) { myHisto[(myId*R) + BITS(lKey[k],bitOff,m)]++; } Barrier.enterBarrier(); CreatePartition.createPartition(0, R, myId, numThread, lss); int last; for (int k = lss.i_start; k < lss.i_stop; k++) { last = psHisto[k] = myHisto[k]; for (int j = 1; j < numThread; j++) { int temp = psHisto[(j*R + k)] = last + myHisto[ (j*R + k)]; last = temp; } } Barrier.enterBarrier(); int offset = 0; for (int k = 0; k < R; k++) { myHisto[(myId*R)+k] = (psHisto[(myId*R) + k] - myHisto[(myId*R) +k]) + offset; offset += psHisto[((numThread -1) * R) + k]; } Barrier.enterBarrier(); CreatePartition.createPartition(0, q, myId, numThread, lss); for (int k = lss.i_start; k < lss.i_stop; k++) { int j = BITS(lKey[k], bitOff, m); lSorted[myHisto[(myId*R) +j]] = lKey[k]; auxSorted[myHisto[(myId*R) +j]] = auxKey[k]; myHisto[(myId*R) +j]++; } Barrier.enterBarrier(); if (myId == 0) { psHisto = null; myHisto = null; } } /* ============================================================================= * all_radixsort_node_s3 * * q (elems/proc) must be a multiple of NODES * ============================================================================= */ /* public void all_radixsort_node_s3 (int q, int[] lKeys, int[] lSorted) { int[] lTemp = null; if (myId == 0) { lTemp = new int[ q]; global_lTemp = lTemp; } Barrier.enterBarrier(); lTemp = global_lTemp; all_countsort_node(q, lKeys, lSorted, (1<<11), 0, 11); all_countsort_node(q, lSorted, lTemp, (1<<11), 11, 11); all_countsort_node(q, lTemp, lSorted, (1<<10), 22, 10); Barrier.enterBarrier(); if (myId == 0) { lTemp = null; } } */ /* ============================================================================= * all_radixsort_node_s2 * * q (elems/proc) must be a multiple of NODES * ============================================================================= */ /* public void all_radixsort_node_s2 (int q, int[] lKeys, int[] lSorted) { int[] lTemp = null; if (myId == 0) { lTemp = new int[ q]; global_lTemp = lTemp; } Barrier.enterBarrier(); lTemp = global_lTemp; all_countsort_node(q, lKeys, lTemp, (1<<16), 0, 16); all_countsort_node(q, lTemp, lSorted, (1<<16), 16, 16); Barrier.enterBarrier(); if (myId == 0) { lTemp = null; } } */ /* ============================================================================= * all_radixsort_node_aux_s3_seq * * q (elems/proc) must be a multiple of NODES * ============================================================================= */ public void all_radixsort_node_aux_s3_seq (int q, int[] lKeys, int[] lSorted, int[] auxKey, int[] auxSorted) { int[] lTemp = new int[q]; int[] lTemp2 = new int[q]; all_countsort_node_aux_seq(q, lKeys, lSorted, auxKey, auxSorted, (1<<11), 0, 11); all_countsort_node_aux_seq(q, lSorted, lTemp, auxSorted, lTemp2, (1<<11), 11, 11); all_countsort_node_aux_seq(q, lTemp, lSorted, lTemp2, auxSorted, (1<<10), 22, 10); } /* ============================================================================= * all_radixsort_node_aux_s3 * * q (elems/proc) must be a multiple of NODES * ============================================================================= */ public static void all_radixsort_node_aux_s3 (int myId, int numThread, int q, int[] lKeys, int[] lSorted, int[] auxKey, int[] auxSorted, Alg_Radix_Smp rdxsort) { int[] lTemp = null; int[] lTemp2 = null; if (myId == 0) { lTemp = new int[ q]; rdxsort.global_lTemp = lTemp; lTemp2 = new int[ q]; rdxsort.global_lTemp2 = lTemp2; } Barrier.enterBarrier(); lTemp = rdxsort.global_lTemp; lTemp2 = rdxsort.global_lTemp2; rdxsort.all_countsort_node_aux(myId, numThread, q, lKeys, lSorted, auxKey, auxSorted, (1<<11), 0, 11, rdxsort); rdxsort.all_countsort_node_aux(myId, numThread, q, lSorted, lTemp, auxSorted, lTemp2, (1<<11), 11, 11, rdxsort); rdxsort.all_countsort_node_aux(myId, numThread, q, lTemp, lSorted, lTemp2, auxSorted, (1<<10), 22, 10, rdxsort); Barrier.enterBarrier(); } } /* ============================================================================= * * End of alg_radix_smp.java * * ============================================================================= */
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.jackrabbit.oak.plugins.index.lucene.directory; import static com.google.common.collect.Sets.newHashSet; import static org.apache.commons.io.FileUtils.ONE_GB; import static org.apache.commons.io.FileUtils.ONE_MB; import static org.apache.jackrabbit.JcrConstants.JCR_DATA; import static org.apache.jackrabbit.oak.InitialContent.INITIAL_CONTENT; import static org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants.INDEX_DATA_CHILD_NAME; import static org.apache.jackrabbit.oak.plugins.index.lucene.directory.OakDirectory.PROP_BLOB_SIZE; import static org.apache.jackrabbit.oak.plugins.index.lucene.directory.OakDirectory.PROP_UNIQUE_KEY; import static org.apache.jackrabbit.oak.plugins.index.lucene.directory.OakDirectory.PROP_UNSAFE_FOR_ACTIVE_DELETION; import static org.apache.jackrabbit.oak.plugins.index.lucene.directory.OakDirectory.UNIQUE_KEY_SIZE; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.collect.Sets; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.NullInputStream; import org.apache.jackrabbit.oak.api.Blob; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.plugins.index.lucene.IndexDefinition; import org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants; import org.apache.jackrabbit.oak.plugins.memory.ArrayBasedBlob; import org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState; import org.apache.jackrabbit.oak.plugins.memory.PropertyStates; import org.apache.jackrabbit.oak.segment.SegmentNodeStore; import org.apache.jackrabbit.oak.segment.SegmentNodeStoreBuilders; import org.apache.jackrabbit.oak.segment.SegmentTestConstants; import org.apache.jackrabbit.oak.segment.file.FileStore; import org.apache.jackrabbit.oak.segment.file.FileStoreBuilder; import org.apache.jackrabbit.oak.spi.blob.GarbageCollectableBlobStore; import org.apache.jackrabbit.oak.spi.blob.MemoryBlobStore; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.ReadOnlyBuilder; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.InputStreamDataInput; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; abstract public class OakDirectoryTestBase { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(new File("target")); private Random rnd = new Random(); private NodeState root = INITIAL_CONTENT; protected NodeBuilder builder = root.builder(); int fileSize = IndexDefinition.DEFAULT_BLOB_SIZE * 2 + rnd.nextInt(1000); @Test public void writes_DefaultSetup() throws Exception{ Directory dir = createDir(builder, false, "/foo"); assertWrites(dir, IndexDefinition.DEFAULT_BLOB_SIZE); } @Test public void testCompatibility() throws Exception{ builder.setProperty(LuceneIndexConstants.BLOB_SIZE, OakBufferedIndexFile.DEFAULT_BLOB_SIZE); Directory dir = createDir(builder, false, "/foo"); byte[] data = assertWrites(dir, OakBufferedIndexFile.DEFAULT_BLOB_SIZE); NodeBuilder testNode = builder.child(INDEX_DATA_CHILD_NAME).child("test"); //Remove the size property to simulate old behaviour testNode.removeProperty(PROP_BLOB_SIZE); //Read should still work even if the size property is removed IndexInput i = dir.openInput("test", IOContext.DEFAULT); assertEquals(fileSize, i.length()); byte[] result = new byte[fileSize]; i.readBytes(result, 0, result.length); assertTrue(Arrays.equals(data, result)); } @Test //OAK-2388 public void testOverflow() throws Exception{ Directory dir = createDir(builder, false, "/foo"); NodeBuilder file = builder.child(INDEX_DATA_CHILD_NAME).child("test.txt"); int blobSize = 32768; int dataSize = 90844; file.setProperty(OakDirectory.PROP_BLOB_SIZE, blobSize); List<? super Blob> blobs = new ArrayList<Blob>(dataSize); for (int i = 0; i < dataSize; i++) { blobs.add(new ArrayBasedBlob(new byte[0])); } file.setProperty(PropertyStates.createProperty("jcr:data", blobs, Type.BINARIES)); IndexInput input = dir.openInput("test.txt", IOContext.DEFAULT); assertEquals((long) blobSize * (dataSize - 1), input.length()); } @Test public void saveListing() throws Exception{ builder.setProperty(LuceneIndexConstants.SAVE_DIR_LISTING, true); Directory dir = createDir(builder, false, "/foo"); Set<String> fileNames = newHashSet(); for (int i = 0; i < 10; i++) { String fileName = "foo" + i; createFile(dir, fileName); fileNames.add(fileName); } dir.close(); dir = createDir(builder, true, "/foo"); assertEquals(fileNames, newHashSet(dir.listAll())); } @Test public void skipSaveListingIfUnchanged() throws Exception{ builder.setProperty(LuceneIndexConstants.SAVE_DIR_LISTING, true); Directory dir = createDir(builder, false, "/foo"); Set<String> fileNames = newHashSet(); for (int i = 0; i < 10; i++) { String fileName = "foo" + i; createFile(dir, fileName); fileNames.add(fileName); } dir.close(); dir = createDir(new ReadOnlyBuilder(builder.getNodeState()), false, "/foo"); Set<String> files = newHashSet(dir.listAll()); dir.close(); assertEquals(fileNames, files); } // OAK-6562 @Test public void createOutputReInitsFile() throws Exception { builder.setProperty(LuceneIndexConstants.SAVE_DIR_LISTING, true); Directory dir = createDir(builder, false, "/foo"); final String fileName = "foo"; dir.createOutput(fileName, IOContext.DEFAULT); String firstUniqueKey = builder.getChildNode(INDEX_DATA_CHILD_NAME) .getChildNode(fileName).getString(PROP_UNIQUE_KEY); dir.createOutput(fileName, IOContext.DEFAULT); String secondUniqueKey = builder.getChildNode(INDEX_DATA_CHILD_NAME) .getChildNode(fileName).getString(PROP_UNIQUE_KEY); assertFalse("Unique key must change on re-incarnating output with same name", firstUniqueKey.equals(secondUniqueKey)); } byte[] assertWrites(Directory dir, int blobSize) throws IOException { byte[] data = randomBytes(fileSize); IndexOutput o = dir.createOutput("test", IOContext.DEFAULT); o.writeBytes(data, data.length); o.close(); assertTrue(dir.fileExists("test")); assertEquals(fileSize, dir.fileLength("test")); IndexInput i = dir.openInput("test", IOContext.DEFAULT); assertEquals(fileSize, i.length()); byte[] result = new byte[fileSize]; i.readBytes(result, 0, result.length); assertTrue(Arrays.equals(data, result)); NodeBuilder testNode = builder.child(INDEX_DATA_CHILD_NAME).child("test"); assertEquals(blobSize, testNode.getProperty(PROP_BLOB_SIZE).getValue(Type.LONG).longValue()); assertBlobSizeInWrite(testNode.getProperty(JCR_DATA), blobSize, fileSize); return data; } abstract void assertBlobSizeInWrite(PropertyState jcrData, int blobSize, int fileSize); private int createFile(Directory dir, String fileName) throws IOException { int size = rnd.nextInt(1000) + 1; byte[] data = randomBytes(size); IndexOutput o = dir.createOutput(fileName, IOContext.DEFAULT); o.writeBytes(data, data.length); o.close(); return size; } protected OakDirectory createDir(NodeBuilder builder, boolean readOnly, String indexPath){ return getOakDirectoryBuilder(builder, indexPath).setReadOnly(readOnly).build(); } byte[] randomBytes(int size) { byte[] data = new byte[size]; rnd.nextBytes(data); return data; } @Test public void testCloseOnOriginalIndexInput() throws Exception { Directory dir = createDir(builder, false, "/foo"); NodeBuilder file = builder.child(INDEX_DATA_CHILD_NAME).child("test.txt"); int dataSize = 1024; List<? super Blob> blobs = new ArrayList<Blob>(dataSize); for (int i = 0; i < dataSize; i++) { blobs.add(new ArrayBasedBlob(new byte[0])); } file.setProperty(PropertyStates.createProperty("jcr:data", blobs, Type.BINARIES)); IndexInput input = dir.openInput("test.txt", IOContext.DEFAULT); input.close(); assertClosed(input); } @Test public void testCloseOnClonedIndexInputs() throws Exception { Directory dir = createDir(builder, false, "/foo"); NodeBuilder file = builder.child(INDEX_DATA_CHILD_NAME).child("test.txt"); int dataSize = 1024; List<? super Blob> blobs = new ArrayList<Blob>(dataSize); for (int i = 0; i < dataSize; i++) { blobs.add(new ArrayBasedBlob(new byte[0])); } file.setProperty(PropertyStates.createProperty("jcr:data", blobs, Type.BINARIES)); IndexInput input = dir.openInput("test.txt", IOContext.DEFAULT); IndexInput clone1 = input.clone(); IndexInput clone2 = input.clone(); input.close(); assertClosed(input); assertClosed(clone1); assertClosed(clone2); } private void assertClosed(IndexInput input) throws IOException { try { input.length(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.seek(0); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.getFilePointer(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readInt(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readShort(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readLong(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readByte(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readString(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readStringSet(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readStringStringMap(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readVInt(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readVLong(); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readBytes(null, 0, 0); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } try { input.readBytes(null, 0, 0, false); fail("cannot use IndexInput once closed"); } catch (AlreadyClosedException e) { // expected exception } } @Test public void largeFile() throws Exception{ FileStore store = FileStoreBuilder.fileStoreBuilder(tempFolder.getRoot()) .withMemoryMapping(false) .withBlobStore(getBlackHoleBlobStore()) .build(); SegmentNodeStore nodeStore = SegmentNodeStoreBuilders.builder(store).build(); IndexDefinition defn = new IndexDefinition(INITIAL_CONTENT, EmptyNodeState.EMPTY_NODE, "/foo"); Directory directory = getOakDirectoryBuilder(nodeStore.getRoot().builder(), defn).setReadOnly(false).build(); long expectedSize = ONE_GB * 2 + ONE_MB; String fileName = "test"; writeFile(directory, fileName, expectedSize); assertEquals(expectedSize, directory.fileLength(fileName)); IndexInput input = directory.openInput(fileName, IOContext.DEFAULT); readInputToEnd(expectedSize, input); store.close(); } @Test public void dirNameInExceptionMessage() throws Exception{ String indexPath = "/foo/bar"; Directory dir = createDir(builder, false, indexPath); try { dir.openInput("foo.txt", IOContext.DEFAULT); fail(); } catch (IOException e){ assertThat(e.getMessage(), containsString(indexPath)); } int fileSize = createFile(dir, "test.txt"); IndexInput in = dir.openInput("test.txt", IOContext.DEFAULT); try { in.seek(fileSize + 1); fail(); } catch (IOException e){ assertThat(e.getMessage(), containsString(indexPath)); } IndexInput in2 = dir.openInput("test.txt", IOContext.DEFAULT); try { byte[] data = new byte[fileSize + 1]; in2.readBytes(data, 0, fileSize + 1); fail(); } catch (IOException e){ assertThat(e.getMessage(), containsString(indexPath)); } } @Test public void dirNameInException_Writes() throws Exception{ FailOnDemandBlobStore blobStore = new FailOnDemandBlobStore(); FileStore store = FileStoreBuilder.fileStoreBuilder(tempFolder.getRoot()) .withMemoryMapping(false) .withBlobStore(blobStore) .build(); SegmentNodeStore nodeStore = SegmentNodeStoreBuilders.builder(store).build(); String indexPath = "/foo/bar"; int minFileSize = SegmentTestConstants.MEDIUM_LIMIT; int blobSize = minFileSize + 1000; builder = nodeStore.getRoot().builder(); builder.setProperty(LuceneIndexConstants.BLOB_SIZE, blobSize); Directory dir = createDir(builder, false, indexPath); blobStore.startFailing(); IndexOutput o = dir.createOutput("test1.txt", IOContext.DEFAULT); try{ o.writeBytes(randomBytes(blobSize + 10), blobSize + 10); fail(); } catch (IOException e){ assertThat(e.getMessage(), containsString(indexPath)); assertThat(e.getMessage(), containsString("test1.txt")); } store.close(); } @Test public void readOnlyDirectory() throws Exception{ Directory dir = getOakDirectoryBuilder(new ReadOnlyBuilder(builder.getNodeState()),"/foo") .setReadOnly(true).build(); assertEquals(0, dir.listAll().length); } @Test public void testDirty() throws Exception{ OakDirectory dir = createDir(builder, false, "/foo"); assertFalse(dir.isDirty()); createFile(dir, "a"); assertTrue(dir.isDirty()); dir.close(); dir = createDir(builder, false, "/foo"); assertFalse(dir.isDirty()); dir.openInput("a", IOContext.DEFAULT); assertFalse(dir.isDirty()); dir.deleteFile("a"); assertTrue(dir.isDirty()); dir.close(); } // OAK-6503 @Test public void dontMarkNonBlobStoreBlobsAsDeleted() throws Exception{ final String deletedBlobId = "blobIdentifier"; final String blobIdToString = "NeverEver-Ever-Ever-ShouldThisBeMarkedAsDeleted"; final int fileSize = 1; final AtomicBoolean identifiableBlob = new AtomicBoolean(false); IndexDefinition def = new IndexDefinition(root, builder.getNodeState(), "/foo"); BlobFactory factory = new BlobFactory() { @Override public Blob createBlob(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); byte[] data = out.toByteArray(); return new ArrayBasedBlob(data) { @Override public String getContentIdentity() { return identifiableBlob.get()?deletedBlobId:null; } @Override public String toString() { return blobIdToString; } }; } }; OakDirectory dir = getOakDirectoryBuilder(builder, def).setReadOnly(false) .with(factory). with( new ActiveDeletedBlobCollectorFactory.BlobDeletionCallback() { @Override public void deleted(String blobId, Iterable<String> ids) { assertEquals("Only blobs with content identity must be reported as deleted", deletedBlobId, blobId); } @Override public void commitProgress(IndexProgress indexProgress) { } @Override public boolean isMarkingForActiveDeletionUnsafe() { return false; } }) .build(); writeFile(dir, "file1", fileSize); writeFile(dir, "file2", fileSize); dir.deleteFile("file1"); identifiableBlob.set(true); dir.deleteFile("file2"); dir.close(); } // OAK-6950 @Test public void blobsCreatedWhenActiveDeletionIsUnsafe() throws Exception { final int fileSize = 1; IndexDefinition def = new IndexDefinition(root, builder.getNodeState(), "/foo"); BlobFactory factory = in -> { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); byte[] data = out.toByteArray(); return new ArrayBasedBlob(data); }; final AtomicBoolean markingForceActiveDeletionUnsafe = new AtomicBoolean(); OakDirectory dir = getOakDirectoryBuilder(builder, def).setReadOnly(false) .with(factory). with( new ActiveDeletedBlobCollectorFactory.BlobDeletionCallback() { @Override public void deleted(String blobId, Iterable<String> ids) { } @Override public void commitProgress(IndexProgress indexProgress) { } @Override public boolean isMarkingForActiveDeletionUnsafe() { return markingForceActiveDeletionUnsafe.get(); } }) .build(); // file1 created before marking was flagged as unsafe writeFile(dir, "file1", fileSize); markingForceActiveDeletionUnsafe.set(true); // file2 created after marking was flagged as unsafe writeFile(dir, "file2", fileSize); dir.close(); NodeBuilder dataBuilder = builder.getChildNode(INDEX_DATA_CHILD_NAME); assertNull("file1 must not get flagged to be unsafe to be actively deleted", dataBuilder.getChildNode("file1").getProperty(PROP_UNSAFE_FOR_ACTIVE_DELETION)); assertTrue("file2 must get flagged to be unsafe to be actively deleted", dataBuilder.getChildNode("file2").getProperty(PROP_UNSAFE_FOR_ACTIVE_DELETION).getValue(Type.BOOLEAN)); } // OAK-6950 @Test public void dontReportFilesMarkedUnsafeForActiveDeletion() throws Exception { AtomicInteger blobIdSuffix = new AtomicInteger(); IndexDefinition def = new IndexDefinition(root, builder.getNodeState(), "/foo"); BlobFactory factory = in -> { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); byte[] data = out.toByteArray(); return new ArrayBasedBlob(data) { @Override public String getContentIdentity() { return Long.toString(length() - UNIQUE_KEY_SIZE) + "-id-" + blobIdSuffix.get(); } }; }; final AtomicBoolean markingForceActiveDeletionUnsafe = new AtomicBoolean(); final Set<String> deletedBlobs = Sets.newHashSet(); OakDirectory dir = getOakDirectoryBuilder(builder, def).setReadOnly(false) .with(factory). with( new ActiveDeletedBlobCollectorFactory.BlobDeletionCallback() { @Override public void deleted(String blobId, Iterable<String> ids) { deletedBlobs.add(blobId); } @Override public void commitProgress(IndexProgress indexProgress) { } @Override public boolean isMarkingForActiveDeletionUnsafe() { return markingForceActiveDeletionUnsafe.get(); } }) .build(); // file1 created before marking was flagged as unsafe blobIdSuffix.set(1); writeFile(dir, "file1", fileSize); markingForceActiveDeletionUnsafe.set(true); // file2 created after marking was flagged as unsafe blobIdSuffix.set(1); writeFile(dir, "file2", fileSize); dir.deleteFile("file1"); dir.deleteFile("file2"); dir.close(); deletedBlobs.forEach(deletedBlob -> { assertTrue("Deleted blob id " + deletedBlob + " must belong to file1", deletedBlob.endsWith("-id-1")); }); } @Test public void blobFactory() throws Exception { final AtomicInteger numBlobs = new AtomicInteger(); final int fileSize = 1024; IndexDefinition def = new IndexDefinition(root, builder.getNodeState(), "/foo"); BlobFactory factory = new BlobFactory() { @Override public Blob createBlob(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); byte[] data = out.toByteArray(); assertEquals(fileSize + UNIQUE_KEY_SIZE, data.length); numBlobs.incrementAndGet(); return new ArrayBasedBlob(data); } }; OakDirectory dir = getOakDirectoryBuilder(builder, def).setReadOnly(false).with(factory).build(); numBlobs.set(0); writeFile(dir, "file", fileSize); assertEquals(1, numBlobs.get()); dir.close(); } @Test public void fileLength() throws Exception { final int fileSize = 1024; final String fileName = "file"; OakDirectory dir = createDir(builder, false, "/foo"); writeFile(dir, fileName, fileSize); assertEquals(fileSize, dir.fileLength(fileName)); try { dir.fileLength("unknown"); fail("must throw FileNotFoundException"); } catch (FileNotFoundException expected) { // expected } dir.close(); } static void readInputToEnd(long expectedSize, IndexInput input) throws IOException { int COPY_BUFFER_SIZE = 16384; byte[] copyBuffer = new byte[(int) ONE_MB]; long left = expectedSize; while (left > 0) { final int toCopy; if (left > COPY_BUFFER_SIZE) { toCopy = COPY_BUFFER_SIZE; } else { toCopy = (int) left; } input.readBytes(copyBuffer, 0, toCopy); left -= toCopy; } } static void writeFile(Directory directory, String fileName, long size) throws Exception{ IndexOutput o = directory.createOutput(fileName, IOContext.DEFAULT); o.copyBytes(new InputStreamDataInput(new NullInputStream(size)), size); o.close(); } OakDirectoryBuilder getOakDirectoryBuilder(NodeBuilder builder, String indexPath) { return getOakDirectoryBuilder(builder, new IndexDefinition(root, builder.getNodeState(), indexPath)); } abstract OakDirectoryBuilder getOakDirectoryBuilder(NodeBuilder builder, IndexDefinition indexDefinition); abstract MemoryBlobStore getBlackHoleBlobStore(); static class FailOnDemandBlobStore extends MemoryBlobStore { private boolean fail; @Override public String writeBlob(InputStream in) throws IOException { if (fail) { throw new IOException("Failing on demand"); } return super.writeBlob(in); } public void startFailing(){ fail = true; } public void reset(){ fail = false; } } static class OakDirectoryBuilder { private final NodeBuilder builder; private final IndexDefinition defn; private final boolean streamingEnabled; public OakDirectoryBuilder(NodeBuilder builder, IndexDefinition defn, boolean streamingEnabled) { this.builder = builder; this.defn = defn; this.streamingEnabled = streamingEnabled; } private boolean readOnly = false; public OakDirectoryBuilder setReadOnly(boolean readOnly) { this.readOnly = readOnly; return this; } private GarbageCollectableBlobStore blobStore = null; private OakDirectoryBuilder with(GarbageCollectableBlobStore blobStore) { this.blobStore = blobStore; return this; } private BlobFactory blobFactory = null; public OakDirectoryBuilder with(BlobFactory blobFactory) { this.blobFactory = blobFactory; return this; } private ActiveDeletedBlobCollectorFactory.BlobDeletionCallback blobDeletionCallback = ActiveDeletedBlobCollectorFactory.BlobDeletionCallback.NOOP; public OakDirectoryBuilder with(ActiveDeletedBlobCollectorFactory.BlobDeletionCallback blobDeletionCallback) { this.blobDeletionCallback = blobDeletionCallback; return this; } public OakDirectory build() { if (blobFactory == null) { blobFactory = blobStore != null ? BlobFactory.getBlobStoreBlobFactory(blobStore) : BlobFactory.getNodeBuilderBlobFactory(builder); } return new OakDirectory(builder, INDEX_DATA_CHILD_NAME, defn, readOnly, blobFactory, blobDeletionCallback, streamingEnabled); } } }
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.storagegateway.model; import java.io.Serializable; /** * */ public class ListVolumesResult implements Serializable, Cloneable { private String gatewayARN; private String marker; private com.amazonaws.internal.SdkInternalList<VolumeInfo> volumeInfos; /** * @param gatewayARN */ public void setGatewayARN(String gatewayARN) { this.gatewayARN = gatewayARN; } /** * @return */ public String getGatewayARN() { return this.gatewayARN; } /** * @param gatewayARN * @return Returns a reference to this object so that method calls can be * chained together. */ public ListVolumesResult withGatewayARN(String gatewayARN) { setGatewayARN(gatewayARN); return this; } /** * @param marker */ public void setMarker(String marker) { this.marker = marker; } /** * @return */ public String getMarker() { return this.marker; } /** * @param marker * @return Returns a reference to this object so that method calls can be * chained together. */ public ListVolumesResult withMarker(String marker) { setMarker(marker); return this; } /** * @return */ public java.util.List<VolumeInfo> getVolumeInfos() { if (volumeInfos == null) { volumeInfos = new com.amazonaws.internal.SdkInternalList<VolumeInfo>(); } return volumeInfos; } /** * @param volumeInfos */ public void setVolumeInfos(java.util.Collection<VolumeInfo> volumeInfos) { if (volumeInfos == null) { this.volumeInfos = null; return; } this.volumeInfos = new com.amazonaws.internal.SdkInternalList<VolumeInfo>( volumeInfos); } /** * <p> * <b>NOTE:</b> This method appends the values to the existing list (if * any). Use {@link #setVolumeInfos(java.util.Collection)} or * {@link #withVolumeInfos(java.util.Collection)} if you want to override * the existing values. * </p> * * @param volumeInfos * @return Returns a reference to this object so that method calls can be * chained together. */ public ListVolumesResult withVolumeInfos(VolumeInfo... volumeInfos) { if (this.volumeInfos == null) { setVolumeInfos(new com.amazonaws.internal.SdkInternalList<VolumeInfo>( volumeInfos.length)); } for (VolumeInfo ele : volumeInfos) { this.volumeInfos.add(ele); } return this; } /** * @param volumeInfos * @return Returns a reference to this object so that method calls can be * chained together. */ public ListVolumesResult withVolumeInfos( java.util.Collection<VolumeInfo> volumeInfos) { setVolumeInfos(volumeInfos); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getGatewayARN() != null) sb.append("GatewayARN: " + getGatewayARN() + ","); if (getMarker() != null) sb.append("Marker: " + getMarker() + ","); if (getVolumeInfos() != null) sb.append("VolumeInfos: " + getVolumeInfos()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListVolumesResult == false) return false; ListVolumesResult other = (ListVolumesResult) obj; if (other.getGatewayARN() == null ^ this.getGatewayARN() == null) return false; if (other.getGatewayARN() != null && other.getGatewayARN().equals(this.getGatewayARN()) == false) return false; if (other.getMarker() == null ^ this.getMarker() == null) return false; if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false) return false; if (other.getVolumeInfos() == null ^ this.getVolumeInfos() == null) return false; if (other.getVolumeInfos() != null && other.getVolumeInfos().equals(this.getVolumeInfos()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getGatewayARN() == null) ? 0 : getGatewayARN().hashCode()); hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode()); hashCode = prime * hashCode + ((getVolumeInfos() == null) ? 0 : getVolumeInfos().hashCode()); return hashCode; } @Override public ListVolumesResult clone() { try { return (ListVolumesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * 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 org.broad.igv.lists; import org.apache.log4j.Logger; import org.broad.igv.DirectoryManager; import org.broad.igv.Globals; import org.broad.igv.track.TrackProperties; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.FileUtils; import org.broad.igv.util.ParsingUtils; import java.io.*; import java.net.URLEncoder; import java.util.*; /** * @author jrobinso * @date Sep 26, 2010 */ public class GeneListManager { private static Logger log = Logger.getLogger(GeneListManager.class); public static final List<String> DEFAULT_GENE_LISTS = Arrays.asList( /*"biocarta_cancer_cp.gmt",*/ "examples.gmt", "reactome_cp.gmt", "kegg_cancer_cp.gmt"); public static final String USER_GROUP = "My lists"; private static final HashSet<String> fileTypes = new HashSet(Arrays.asList("bed", "gmt", "grp")); private LinkedHashSet<String> groups = new LinkedHashSet(); private HashMap<String, File> importedFiles = new HashMap(); private LinkedHashMap<String, GeneList> geneLists = new LinkedHashMap(); static GeneListManager theInstance; public static GeneListManager getInstance() { if (theInstance == null) { theInstance = new GeneListManager(); } return theInstance; } private GeneListManager() { loadDefaultLists(); loadUserLists(); } public GeneList getGeneList(String listID) { return geneLists.get(listID); } public LinkedHashMap<String, GeneList> getGeneLists() { return geneLists; } // Gene lists -- these don't belong here obviously public void addGeneList(GeneList genes) { geneLists.put(genes.getName(), genes); groups.add(genes.getGroup()); } private void loadDefaultLists() { for (String geneListFile : DEFAULT_GENE_LISTS) { InputStream is = GeneListManager.class.getResourceAsStream(geneListFile); if (is == null) { log.info("Could not find gene list resource: " + geneListFile); return; } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(is)); new BufferedReader(new InputStreamReader(is)); List<GeneList> lists = loadGMTFile(reader); for (GeneList gl : lists) { gl.setEditable(false); addGeneList(gl); } } catch (IOException e) { log.error("Error loading default gene lists", e); MessageUtils.showMessage("<html>Error encountered loading gene lists (" + e.toString() + ")" + "<br/>See log for more details"); } finally { try { reader.close(); } catch (IOException e) { } } } } private void loadUserLists() { File dir = DirectoryManager.getGeneListDirectory(); if (dir.exists()) { for (File f : dir.listFiles()) { try { if (fileTypes.contains(getFileType(f.getPath()))) { importFile(f); } } catch (IOException e) { log.error("Error loading user gene lists: ", e); MessageUtils.showMessage("<html>Error encountered loading user gene lists (" + e.toString() + ")" + "<br/>See log for more details"); } } } // Add empty group if there are no lists if (!groups.contains(USER_GROUP)) { groups.add(USER_GROUP); } } private String getFileType(String path) { String tmp = path.toLowerCase(); if (tmp.endsWith(".gz")) { tmp = tmp.substring(0, tmp.length() - 3); } int idx = path.lastIndexOf("."); return idx < 0 ? path : path.substring(idx + 1); } public List<GeneList> importFile(File f) throws IOException { String path = f.getPath(); String name = f.getName(); File dir = DirectoryManager.getGeneListDirectory(); if (!dir.equals(f.getParentFile())) { File copy = new File(dir, f.getName()); FileUtils.copyFile(f, copy); } List<GeneList> loadedLists = loadFile(path); if (loadedLists.size() > 0) { importedFiles.put(name, f); } return loadedLists; } private List<GeneList> loadFile(String path) throws IOException { String type = getFileType(path); if (type.equals("bed")) { return loadBEDFile(path); } else if (type.equals("gmt")) { return loadGMTFile(path); } else if (type.equals("grp")) { return loadGRPFile(path); } else { throw new RuntimeException("Unrecognized file extension: " + path); } } private List<GeneList> loadBEDFile(String path) throws IOException { String name = (new File(path)).getName(); BufferedReader reader = null; try { reader = ParsingUtils.openBufferedReader(path); try { List<String> loci = new ArrayList<String>(1000); String nextLine; while ((nextLine = reader.readLine()) != null) { if (nextLine.startsWith("#") || nextLine.startsWith("browser")) continue; if (nextLine.startsWith("track")) { TrackProperties tp = new TrackProperties(); ParsingUtils.parseTrackLine(nextLine, tp); String tmp = tp.getName(); if (tmp != null) name = tmp; continue; } String[] tokens = Globals.whitespacePattern.split(nextLine); if (tokens.length > 2) { loci.add(tokens[0] + ":" + tokens[1] + "-" + tokens[2]); } } GeneList geneList = new GeneList(name, loci); geneList.setGroup(USER_GROUP); geneList.setEditable(false); addGeneList(geneList); return Arrays.asList(geneList); } finally { if (reader != null) reader.close(); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } public List<GeneList> loadGMTFile(String path) throws IOException { BufferedReader reader = null; try { reader = ParsingUtils.openBufferedReader(path); return loadGMTFile(reader); } finally { if (reader != null) reader.close(); } } private List<GeneList> loadGMTFile(BufferedReader reader) throws IOException { String group = USER_GROUP; String nextLine; List<GeneList> lists = new ArrayList(); while ((nextLine = reader.readLine()) != null) { if (nextLine.startsWith("#")) { if (nextLine.startsWith("#group") || nextLine.startsWith("#name")) { String[] tokens = nextLine.split("="); if (tokens.length > 1) { group = tokens[1]; } } } else { String[] tokens = nextLine.split("\t"); if (tokens.length > 2) { String name = tokens[0]; String description = tokens[1].replaceFirst(">", ""); List<String> genes = new ArrayList(); for (int i = 2; i < tokens.length; i++) { genes.add(tokens[i]); } lists.add(new GeneList(name, description, group, genes)); } } } for (GeneList gl : lists) { gl.setEditable(false); addGeneList(gl); } return lists; } List<GeneList> loadGRPFile(String path) throws IOException { String name = (new File(path)).getName(); String group = USER_GROUP; String description = null; // BufferedReader reader = null; try { List<String> genes = new ArrayList(); reader = ParsingUtils.openBufferedReader(path); String nextLine; while ((nextLine = reader.readLine()) != null) { if (nextLine.startsWith("#")) { if (nextLine.startsWith("#name")) { String[] tokens = nextLine.split("="); if (tokens.length > 1) { name = tokens[1]; } } else if (nextLine.startsWith("#description")) { String[] tokens = nextLine.split("="); if (tokens.length > 1) { description = tokens[1]; } } } else { String[] tokens = nextLine.split("\\s+"); for (String s : tokens) { genes.add(s); } } } if (genes.size() > 0) { GeneList geneList = new GeneList(name, description, group, genes); geneList.setEditable(false); addGeneList(geneList); return Arrays.asList(geneList); } else { return Collections.EMPTY_LIST; } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } /** * #name=Example gene lists * Proneural dev genes Proneural dev genes SOX1 SOX2 SOX3 SOX21 DCX DLL3 ASCL1 TCF4 * * @param group * @param outputFile */ void exportGMT(String group, File outputFile) throws IOException { PrintWriter pw = null; try { pw = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); List<GeneList> lists = getListsForGroup(group); if (lists.isEmpty()) { MessageUtils.showMessage("Nothing to export."); return; } pw.println("#name=" + group); for (GeneList gl : lists) { pw.print(gl.getName()); for (String gene : gl.getLoci()) { pw.print("\t"); pw.print(gene); } pw.println(); } } finally { if (pw != null) pw.close(); } } // TODO -- this is really ineffecient, redesign private List<GeneList> getListsForGroup(String group) { List<GeneList> list = new ArrayList<GeneList>(); for (GeneList gl : geneLists.values()) { if (gl.getGroup().equals(group)) { list.add(gl); } } return list; } public void saveGeneList(GeneList geneList) { File file = null; PrintWriter pw = null; try { final String listName = geneList.getName(); String description = geneList.getDescription(); List<String> genes = geneList.getLoci(); if (listName != null && genes != null) { file = new File(DirectoryManager.getGeneListDirectory(), getLegalFilename(listName) + ".grp"); pw = new PrintWriter(new BufferedWriter(new FileWriter(file))); pw.println("#name=" + listName); if (description != null) pw.println("#description=" + description); for (String s : genes) { pw.println(s); } pw.close(); importedFiles.put(listName, file); } } catch (IOException e) { if (file != null) { MessageUtils.showMessage("Error writing gene list file: " + file.getAbsolutePath() + " " + e.getMessage()); } log.error("Error saving gene list", e); } finally { if (pw != null) { pw.close(); } } } /** * Return a legal filename derived from the input string. * todo Move this to a utility class * * @param s * @return */ private static String getLegalFilename(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { return s; } } /** * Test to see of group was imported by the user Needed to determine if group can be removed. */ public boolean isImported(String groupName) { return importedFiles.containsKey(groupName); } public LinkedHashSet<String> getGroups() { return groups; } public void deleteGroup(String selectedGroup) { File f = importedFiles.get(selectedGroup); if (f.exists()) { f.delete(); } groups.remove(selectedGroup); importedFiles.remove(selectedGroup); Collection<GeneList> tmp = new ArrayList(geneLists.values()); for (GeneList gl : tmp) { if (gl.getGroup().equals(selectedGroup)) { geneLists.remove(gl.getName()); } } } /** * Return true if a group was also removed. * * @param listName */ public boolean deleteList(String listName) { File f = importedFiles.get(listName); if (f != null && f.exists()) { f.delete(); } importedFiles.remove(listName); if (geneLists.containsKey(listName)) { String group = geneLists.get(listName).getGroup(); geneLists.remove(listName); // If the group is empty remove it as well, except for user group if (!group.equals(USER_GROUP)) { for (GeneList gl : geneLists.values()) { if (gl.getGroup().equals(group)) { return false; } } groups.remove(group); return true; } } return false; } }
/* 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.activiti5.engine.impl; import java.util.List; import java.util.Set; import org.activiti.engine.impl.variable.VariableTypes; import org.activiti5.engine.ActivitiIllegalArgumentException; import org.activiti5.engine.history.HistoricVariableInstance; import org.activiti5.engine.history.HistoricVariableInstanceQuery; import org.activiti5.engine.impl.context.Context; import org.activiti5.engine.impl.interceptor.CommandContext; import org.activiti5.engine.impl.interceptor.CommandExecutor; import org.activiti5.engine.impl.persistence.entity.HistoricVariableInstanceEntity; import org.activiti5.engine.impl.variable.CacheableVariable; import org.activiti5.engine.impl.variable.JPAEntityListVariableType; import org.activiti5.engine.impl.variable.JPAEntityVariableType; /** * @author Christian Lipphardt (camunda) */ public class HistoricVariableInstanceQueryImpl extends AbstractQuery<HistoricVariableInstanceQuery, HistoricVariableInstance> implements HistoricVariableInstanceQuery { private static final long serialVersionUID = 1L; protected String id; protected String taskId; protected Set<String> taskIds; protected String executionId; protected Set<String> executionIds; protected String processInstanceId; protected String activityInstanceId; protected String variableName; protected String variableNameLike; protected boolean excludeTaskRelated = false; protected boolean excludeVariableInitialization = false; protected QueryVariableValue queryVariableValue; public HistoricVariableInstanceQueryImpl() { } public HistoricVariableInstanceQueryImpl(CommandContext commandContext) { super(commandContext); } public HistoricVariableInstanceQueryImpl(CommandExecutor commandExecutor) { super(commandExecutor); } public HistoricVariableInstanceQuery id(String id) { this.id = id; return this; } public HistoricVariableInstanceQueryImpl processInstanceId(String processInstanceId) { if (processInstanceId == null) { throw new ActivitiIllegalArgumentException("processInstanceId is null"); } this.processInstanceId = processInstanceId; return this; } public HistoricVariableInstanceQueryImpl executionId(String executionId) { if (executionId == null) { throw new ActivitiIllegalArgumentException("Execution id is null"); } this.executionId = executionId; return this; } public HistoricVariableInstanceQueryImpl executionIds(Set<String> executionIds) { if (executionIds == null) { throw new ActivitiIllegalArgumentException("executionIds is null"); } if (executionIds.isEmpty()){ throw new ActivitiIllegalArgumentException("Set of executionIds is empty"); } this.executionIds = executionIds; return this; } public HistoricVariableInstanceQuery activityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; return this; } public HistoricVariableInstanceQuery taskId(String taskId) { if (taskId == null) { throw new ActivitiIllegalArgumentException("taskId is null"); } if(excludeTaskRelated) { throw new ActivitiIllegalArgumentException("Cannot use taskId together with excludeTaskVariables"); } this.taskId = taskId; return this; } public HistoricVariableInstanceQueryImpl taskIds(Set<String> taskIds) { if (taskIds == null) { throw new ActivitiIllegalArgumentException("taskIds is null"); } if (taskIds.isEmpty()){ throw new ActivitiIllegalArgumentException("Set of taskIds is empty"); } if (excludeTaskRelated) { throw new ActivitiIllegalArgumentException("Cannot use taskIds together with excludeTaskVariables"); } this.taskIds = taskIds; return this; } @Override public HistoricVariableInstanceQuery excludeTaskVariables() { if (taskId != null) { throw new ActivitiIllegalArgumentException("Cannot use taskId together with excludeTaskVariables"); } if (taskIds != null) { throw new ActivitiIllegalArgumentException("Cannot use taskIds together with excludeTaskVariables"); } excludeTaskRelated = true; return this; } public HistoricVariableInstanceQuery excludeVariableInitialization() { excludeVariableInitialization = true; return this; } public HistoricVariableInstanceQuery variableName(String variableName) { if (variableName == null) { throw new ActivitiIllegalArgumentException("variableName is null"); } this.variableName = variableName; return this; } public HistoricVariableInstanceQuery variableValueEquals(String variableName, Object variableValue) { if (variableName == null) { throw new ActivitiIllegalArgumentException("variableName is null"); } if (variableValue == null) { throw new ActivitiIllegalArgumentException("variableValue is null"); } this.variableName = variableName; queryVariableValue = new QueryVariableValue(variableName, variableValue, QueryOperator.EQUALS, true); return this; } public HistoricVariableInstanceQuery variableValueNotEquals(String variableName, Object variableValue) { if (variableName == null) { throw new ActivitiIllegalArgumentException("variableName is null"); } if (variableValue == null) { throw new ActivitiIllegalArgumentException("variableValue is null"); } this.variableName = variableName; queryVariableValue = new QueryVariableValue(variableName, variableValue, QueryOperator.NOT_EQUALS, true); return this; } public HistoricVariableInstanceQuery variableValueLike(String variableName, String variableValue) { if (variableName == null) { throw new ActivitiIllegalArgumentException("variableName is null"); } if (variableValue == null) { throw new ActivitiIllegalArgumentException("variableValue is null"); } this.variableName = variableName; queryVariableValue = new QueryVariableValue(variableName, variableValue, QueryOperator.LIKE, true); return this; } public HistoricVariableInstanceQuery variableValueLikeIgnoreCase(String variableName, String variableValue) { if (variableName == null) { throw new ActivitiIllegalArgumentException("variableName is null"); } if (variableValue == null) { throw new ActivitiIllegalArgumentException("variableValue is null"); } this.variableName = variableName; queryVariableValue = new QueryVariableValue(variableName, variableValue.toLowerCase(), QueryOperator.LIKE_IGNORE_CASE, true); return this; } public HistoricVariableInstanceQuery variableNameLike(String variableNameLike) { if (variableNameLike == null) { throw new ActivitiIllegalArgumentException("variableNameLike is null"); } this.variableNameLike = variableNameLike; return this; } protected void ensureVariablesInitialized() { if (this.queryVariableValue != null) { VariableTypes variableTypes = Context.getProcessEngineConfiguration().getVariableTypes(); queryVariableValue.initialize(variableTypes); } } public long executeCount(CommandContext commandContext) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getHistoricVariableInstanceEntityManager() .findHistoricVariableInstanceCountByQueryCriteria(this); } public List<HistoricVariableInstance> executeList(CommandContext commandContext, Page page) { checkQueryOk(); ensureVariablesInitialized(); List<HistoricVariableInstance> historicVariableInstances = commandContext .getHistoricVariableInstanceEntityManager() .findHistoricVariableInstancesByQueryCriteria(this, page); if (excludeVariableInitialization == false) { for (HistoricVariableInstance historicVariableInstance: historicVariableInstances) { if (historicVariableInstance instanceof HistoricVariableInstanceEntity) { HistoricVariableInstanceEntity variableEntity = (HistoricVariableInstanceEntity) historicVariableInstance; if(variableEntity != null && variableEntity.getVariableType() != null) { variableEntity.getValue(); // make sure JPA entities are cached for later retrieval if (JPAEntityVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName()) || JPAEntityListVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName())) { ((CacheableVariable) variableEntity.getVariableType()).setForceCacheable(true); } } } } } return historicVariableInstances; } // order by ///////////////////////////////////////////////////////////////// public HistoricVariableInstanceQuery orderByProcessInstanceId() { orderBy(HistoricVariableInstanceQueryProperty.PROCESS_INSTANCE_ID); return this; } public HistoricVariableInstanceQuery orderByVariableName() { orderBy(HistoricVariableInstanceQueryProperty.VARIABLE_NAME); return this; } // getters and setters ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getTaskId() { return taskId; } public String getActivityInstanceId() { return activityInstanceId; } public boolean getExcludeTaskRelated() { return excludeTaskRelated; } public String getVariableName() { return variableName; } public String getVariableNameLike() { return variableNameLike; } public QueryVariableValue getQueryVariableValue() { return queryVariableValue; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.util.collection.unsafe.sort; import java.util.Comparator; import java.util.LinkedList; import org.apache.avro.reflect.Nullable; import org.apache.spark.TaskContext; import org.apache.spark.memory.MemoryConsumer; import org.apache.spark.memory.SparkOutOfMemoryError; import org.apache.spark.memory.TaskMemoryManager; import org.apache.spark.unsafe.UnsafeAlignedOffset; import org.apache.spark.unsafe.array.LongArray; import org.apache.spark.unsafe.memory.MemoryBlock; import org.apache.spark.util.collection.Sorter; /** * Sorts records using an AlphaSort-style key-prefix sort. This sort stores pointers to records * alongside a user-defined prefix of the record's sorting key. When the underlying sort algorithm * compares records, it will first compare the stored key prefixes; if the prefixes are not equal, * then we do not need to traverse the record pointers to compare the actual records. Avoiding these * random memory accesses improves cache hit rates. */ public final class UnsafeInMemorySorter { private static final class SortComparator implements Comparator<RecordPointerAndKeyPrefix> { private final RecordComparator recordComparator; private final PrefixComparator prefixComparator; private final TaskMemoryManager memoryManager; SortComparator( RecordComparator recordComparator, PrefixComparator prefixComparator, TaskMemoryManager memoryManager) { this.recordComparator = recordComparator; this.prefixComparator = prefixComparator; this.memoryManager = memoryManager; } @Override public int compare(RecordPointerAndKeyPrefix r1, RecordPointerAndKeyPrefix r2) { final int prefixComparisonResult = prefixComparator.compare(r1.keyPrefix, r2.keyPrefix); int uaoSize = UnsafeAlignedOffset.getUaoSize(); if (prefixComparisonResult == 0) { final Object baseObject1 = memoryManager.getPage(r1.recordPointer); final long baseOffset1 = memoryManager.getOffsetInPage(r1.recordPointer) + uaoSize; final int baseLength1 = UnsafeAlignedOffset.getSize(baseObject1, baseOffset1 - uaoSize); final Object baseObject2 = memoryManager.getPage(r2.recordPointer); final long baseOffset2 = memoryManager.getOffsetInPage(r2.recordPointer) + uaoSize; final int baseLength2 = UnsafeAlignedOffset.getSize(baseObject2, baseOffset2 - uaoSize); return recordComparator.compare(baseObject1, baseOffset1, baseLength1, baseObject2, baseOffset2, baseLength2); } else { return prefixComparisonResult; } } } private final MemoryConsumer consumer; private final TaskMemoryManager memoryManager; @Nullable private final Comparator<RecordPointerAndKeyPrefix> sortComparator; /** * If non-null, specifies the radix sort parameters and that radix sort will be used. */ @Nullable private final PrefixComparators.RadixSortSupport radixSortSupport; /** * Within this buffer, position {@code 2 * i} holds a pointer to the record at * index {@code i}, while position {@code 2 * i + 1} in the array holds an 8-byte key prefix. * * Only part of the array will be used to store the pointers, the rest part is preserved as * temporary buffer for sorting. */ private LongArray array; /** * The position in the sort buffer where new records can be inserted. */ private int pos = 0; /** * If sorting with radix sort, specifies the starting position in the sort buffer where records * with non-null prefixes are kept. Positions [0..nullBoundaryPos) will contain null-prefixed * records, and positions [nullBoundaryPos..pos) non-null prefixed records. This lets us avoid * radix sorting over null values. */ private int nullBoundaryPos = 0; /* * How many records could be inserted, because part of the array should be left for sorting. */ private int usableCapacity = 0; private long initialSize; private long totalSortTimeNanos = 0L; public UnsafeInMemorySorter( final MemoryConsumer consumer, final TaskMemoryManager memoryManager, final RecordComparator recordComparator, final PrefixComparator prefixComparator, int initialSize, boolean canUseRadixSort) { this(consumer, memoryManager, recordComparator, prefixComparator, consumer.allocateArray(initialSize * 2L), canUseRadixSort); } public UnsafeInMemorySorter( final MemoryConsumer consumer, final TaskMemoryManager memoryManager, final RecordComparator recordComparator, final PrefixComparator prefixComparator, LongArray array, boolean canUseRadixSort) { this.consumer = consumer; this.memoryManager = memoryManager; this.initialSize = array.size(); if (recordComparator != null) { this.sortComparator = new SortComparator(recordComparator, prefixComparator, memoryManager); if (canUseRadixSort && prefixComparator instanceof PrefixComparators.RadixSortSupport) { this.radixSortSupport = (PrefixComparators.RadixSortSupport)prefixComparator; } else { this.radixSortSupport = null; } } else { this.sortComparator = null; this.radixSortSupport = null; } this.array = array; this.usableCapacity = getUsableCapacity(); } private int getUsableCapacity() { // Radix sort requires same amount of used memory as buffer, Tim sort requires // half of the used memory as buffer. return (int) (array.size() / (radixSortSupport != null ? 2 : 1.5)); } /** * Free the memory used by pointer array. */ public void free() { if (consumer != null) { if (array != null) { consumer.freeArray(array); } array = null; } } public void reset() { if (consumer != null) { consumer.freeArray(array); // the call to consumer.allocateArray may trigger a spill which in turn access this instance // and eventually re-enter this method and try to free the array again. by setting the array // to null and its length to 0 we effectively make the spill code-path a no-op. setting the // array to null also indicates that it has already been de-allocated which prevents a double // de-allocation in free(). array = null; usableCapacity = 0; pos = 0; nullBoundaryPos = 0; array = consumer.allocateArray(initialSize); usableCapacity = getUsableCapacity(); } pos = 0; nullBoundaryPos = 0; } /** * @return the number of records that have been inserted into this sorter. */ public int numRecords() { return pos / 2; } /** * @return the total amount of time spent sorting data (in-memory only). */ public long getSortTimeNanos() { return totalSortTimeNanos; } public long getMemoryUsage() { return array.size() * 8; } public boolean hasSpaceForAnotherRecord() { return pos + 1 < usableCapacity; } public void expandPointerArray(LongArray newArray) { if (newArray.size() < array.size()) { throw new SparkOutOfMemoryError("Not enough memory to grow pointer array"); } MemoryBlock.copyMemory(array.memoryBlock(), newArray.memoryBlock(), pos * 8L); consumer.freeArray(array); array = newArray; usableCapacity = getUsableCapacity(); } /** * Inserts a record to be sorted. Assumes that the record pointer points to a record length * stored as a 4-byte integer, followed by the record's bytes. * * @param recordPointer pointer to a record in a data page, encoded by {@link TaskMemoryManager}. * @param keyPrefix a user-defined key prefix */ public void insertRecord(long recordPointer, long keyPrefix, boolean prefixIsNull) { if (!hasSpaceForAnotherRecord()) { throw new IllegalStateException("There is no space for new record"); } if (prefixIsNull && radixSortSupport != null) { // Swap forward a non-null record to make room for this one at the beginning of the array. array.set(pos, array.get(nullBoundaryPos)); pos++; array.set(pos, array.get(nullBoundaryPos + 1)); pos++; // Place this record in the vacated position. array.set(nullBoundaryPos, recordPointer); nullBoundaryPos++; array.set(nullBoundaryPos, keyPrefix); nullBoundaryPos++; } else { array.set(pos, recordPointer); pos++; array.set(pos, keyPrefix); pos++; } } public final class SortedIterator extends UnsafeSorterIterator implements Cloneable { private final int numRecords; private int position; private int offset; private Object baseObject; private long baseOffset; private long keyPrefix; private int recordLength; private long currentPageNumber; private final TaskContext taskContext = TaskContext.get(); private SortedIterator(int numRecords, int offset) { this.numRecords = numRecords; this.position = 0; this.offset = offset; } public SortedIterator clone() { SortedIterator iter = new SortedIterator(numRecords, offset); iter.position = position; iter.baseObject = baseObject; iter.baseOffset = baseOffset; iter.keyPrefix = keyPrefix; iter.recordLength = recordLength; iter.currentPageNumber = currentPageNumber; return iter; } @Override public int getNumRecords() { return numRecords; } @Override public boolean hasNext() { return position / 2 < numRecords; } @Override public void loadNext() { // Kill the task in case it has been marked as killed. This logic is from // InterruptibleIterator, but we inline it here instead of wrapping the iterator in order // to avoid performance overhead. This check is added here in `loadNext()` instead of in // `hasNext()` because it's technically possible for the caller to be relying on // `getNumRecords()` instead of `hasNext()` to know when to stop. if (taskContext != null) { taskContext.killTaskIfInterrupted(); } // This pointer points to a 4-byte record length, followed by the record's bytes final long recordPointer = array.get(offset + position); currentPageNumber = TaskMemoryManager.decodePageNumber(recordPointer); int uaoSize = UnsafeAlignedOffset.getUaoSize(); baseObject = memoryManager.getPage(recordPointer); // Skip over record length baseOffset = memoryManager.getOffsetInPage(recordPointer) + uaoSize; recordLength = UnsafeAlignedOffset.getSize(baseObject, baseOffset - uaoSize); keyPrefix = array.get(offset + position + 1); position += 2; } @Override public Object getBaseObject() { return baseObject; } @Override public long getBaseOffset() { return baseOffset; } public long getCurrentPageNumber() { return currentPageNumber; } @Override public int getRecordLength() { return recordLength; } @Override public long getKeyPrefix() { return keyPrefix; } } /** * Return an iterator over record pointers in sorted order. For efficiency, all calls to * {@code next()} will return the same mutable object. */ public UnsafeSorterIterator getSortedIterator() { int offset = 0; long start = System.nanoTime(); if (sortComparator != null) { if (this.radixSortSupport != null) { offset = RadixSort.sortKeyPrefixArray( array, nullBoundaryPos, (pos - nullBoundaryPos) / 2L, 0, 7, radixSortSupport.sortDescending(), radixSortSupport.sortSigned()); } else { MemoryBlock unused = array.memoryBlock().subBlock(pos * 8L, (array.size() - pos) * 8L); LongArray buffer = new LongArray(unused); Sorter<RecordPointerAndKeyPrefix, LongArray> sorter = new Sorter<>(new UnsafeSortDataFormat(buffer)); sorter.sort(array, 0, pos / 2, sortComparator); } } totalSortTimeNanos += System.nanoTime() - start; if (nullBoundaryPos > 0) { assert radixSortSupport != null : "Nulls are only stored separately with radix sort"; LinkedList<UnsafeSorterIterator> queue = new LinkedList<>(); // The null order is either LAST or FIRST, regardless of sorting direction (ASC|DESC) if (radixSortSupport.nullsFirst()) { queue.add(new SortedIterator(nullBoundaryPos / 2, 0)); queue.add(new SortedIterator((pos - nullBoundaryPos) / 2, offset)); } else { queue.add(new SortedIterator((pos - nullBoundaryPos) / 2, offset)); queue.add(new SortedIterator(nullBoundaryPos / 2, 0)); } return new UnsafeExternalSorter.ChainedIterator(queue); } else { return new SortedIterator(pos / 2, offset); } } }
package ht.edu.fds.mbds.android.bibliotheque.views; import ht.edu.fds.mbds.android.bibliotheque.Etudiant; import ht.edu.fds.mbds.android.bibliotheque.views.util.JsfUtil; import ht.edu.fds.mbds.android.bibliotheque.views.util.PaginationHelper; import ht.edu.fds.mbds.android.bibliotheque.bean.EtudiantFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @ManagedBean(name = "etudiantController") @SessionScoped public class EtudiantController implements Serializable { private Etudiant current; private DataModel items = null; @EJB private ht.edu.fds.mbds.android.bibliotheque.bean.EtudiantFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public EtudiantController() { } public Etudiant getSelected() { if (current == null) { current = new Etudiant(); selectedItemIndex = -1; } return current; } private EtudiantFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Etudiant) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Etudiant(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EtudiantCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Etudiant) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EtudiantUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Etudiant) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EtudiantDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = Etudiant.class) public static class EtudiantControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } EtudiantController controller = (EtudiantController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "etudiantController"); return controller.ejbFacade.find(getKey(value)); } java.lang.Long getKey(String value) { java.lang.Long key; key = Long.valueOf(value); return key; } String getStringKey(java.lang.Long value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Etudiant) { Etudiant o = (Etudiant) object; return getStringKey(o.getId()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Etudiant.class.getName()); } } } }
/* * 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.hyracks.storage.am.lsm.rtree.impls; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory; import org.apache.hyracks.api.dataflow.value.ILinearizeComparatorFactory; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.api.io.IIOManager; import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference; import org.apache.hyracks.storage.am.bloomfilter.impls.BloomCalculations; import org.apache.hyracks.storage.am.bloomfilter.impls.BloomFilter; import org.apache.hyracks.storage.am.bloomfilter.impls.BloomFilterFactory; import org.apache.hyracks.storage.am.bloomfilter.impls.BloomFilterSpecification; import org.apache.hyracks.storage.am.btree.impls.BTree; import org.apache.hyracks.storage.am.btree.impls.BTree.BTreeBulkLoader; import org.apache.hyracks.storage.am.common.api.IIndexBulkLoader; import org.apache.hyracks.storage.am.common.api.IIndexCursor; import org.apache.hyracks.storage.am.common.api.IIndexOperationContext; import org.apache.hyracks.storage.am.common.api.IModificationOperationCallback; import org.apache.hyracks.storage.am.common.api.ISearchOperationCallback; import org.apache.hyracks.storage.am.common.api.ISearchPredicate; import org.apache.hyracks.storage.am.common.api.ITreeIndexCursor; import org.apache.hyracks.storage.am.common.api.ITreeIndexFrameFactory; import org.apache.hyracks.storage.am.common.api.ITwoPCIndexBulkLoader; import org.apache.hyracks.storage.am.common.api.IndexException; import org.apache.hyracks.storage.am.common.api.TreeIndexException; import org.apache.hyracks.storage.am.common.impls.NoOpOperationCallback; import org.apache.hyracks.storage.am.common.ophelpers.IndexOperation; import org.apache.hyracks.storage.am.lsm.common.api.ILSMDiskComponent; import org.apache.hyracks.storage.am.lsm.common.api.ILSMComponent; import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperation; import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallback; import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationScheduler; import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexAccessor; import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexFileManager; import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexOperationContext; import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicy; import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTracker; import org.apache.hyracks.storage.am.lsm.common.api.ITwoPCIndex; import org.apache.hyracks.storage.am.lsm.common.api.LSMOperationType; import org.apache.hyracks.storage.am.lsm.common.impls.BlockingIOOperationCallbackWrapper; import org.apache.hyracks.storage.am.lsm.common.impls.ExternalIndexHarness; import org.apache.hyracks.storage.am.lsm.common.impls.LSMComponentFileReferences; import org.apache.hyracks.storage.am.lsm.common.impls.TreeIndexFactory; import org.apache.hyracks.storage.am.rtree.impls.RTree; import org.apache.hyracks.storage.am.rtree.impls.SearchPredicate; import org.apache.hyracks.storage.common.file.IFileMapProvider; /** * This is an lsm r-tree that does not have memory component and is modified * only by bulk loading and addition of disk components as of this point, it is * intended for use with external dataset indexes only. * * @author alamouda */ public class ExternalRTree extends LSMRTree implements ITwoPCIndex { // A second disk component list that will be used when a transaction is // committed and will be seen by subsequent accessors private final List<ILSMDiskComponent> secondDiskComponents; // A pointer that points to the current most recent list (either // diskComponents = 0, or secondDiskComponents = 1). It starts with -1 to // indicate first time activation private int version = -1; private final int fieldCount; public ExternalRTree(IIOManager ioManager, ITreeIndexFrameFactory rtreeInteriorFrameFactory, ITreeIndexFrameFactory rtreeLeafFrameFactory, ITreeIndexFrameFactory btreeInteriorFrameFactory, ITreeIndexFrameFactory btreeLeafFrameFactory, ILSMIndexFileManager fileNameManager, TreeIndexFactory<RTree> diskRTreeFactory, TreeIndexFactory<BTree> diskBTreeFactory, BloomFilterFactory bloomFilterFactory, double bloomFilterFalsePositiveRate, IFileMapProvider diskFileMapProvider, int fieldCount, IBinaryComparatorFactory[] rtreeCmpFactories, IBinaryComparatorFactory[] btreeCmpFactories, ILinearizeComparatorFactory linearizer, int[] comparatorFields, IBinaryComparatorFactory[] linearizerArray, ILSMMergePolicy mergePolicy, ILSMOperationTracker opTracker, ILSMIOOperationScheduler ioScheduler, ILSMIOOperationCallback ioOpCallback, int[] buddyBTreeFields, int version, boolean durable, boolean isPointMBR) { super(ioManager, rtreeInteriorFrameFactory, rtreeLeafFrameFactory, btreeInteriorFrameFactory, btreeLeafFrameFactory, fileNameManager, diskRTreeFactory, diskBTreeFactory, bloomFilterFactory, bloomFilterFalsePositiveRate, diskFileMapProvider, rtreeCmpFactories, btreeCmpFactories, linearizer, comparatorFields, linearizerArray, mergePolicy, opTracker, ioScheduler, ioOpCallback, buddyBTreeFields, durable, isPointMBR); this.secondDiskComponents = new LinkedList<>(); this.version = version; this.fieldCount = fieldCount; } // The subsume merged components is overridden to account for: // 1. the number of readers of components // 2. maintaining two versions of the index @Override public void subsumeMergedComponents(ILSMDiskComponent newComponent, List<ILSMComponent> mergedComponents) throws HyracksDataException { // determine which list is the new one List<ILSMDiskComponent> newerList; List<ILSMDiskComponent> olderList; if (version == 0) { newerList = diskComponents; olderList = secondDiskComponents; } else { newerList = secondDiskComponents; olderList = diskComponents; } // check if merge will affect the older list if (olderList.containsAll(mergedComponents)) { int swapIndex = olderList.indexOf(mergedComponents.get(0)); olderList.removeAll(mergedComponents); olderList.add(swapIndex, newComponent); } // The new list will always have all the merged components int swapIndex = newerList.indexOf(mergedComponents.get(0)); newerList.removeAll(mergedComponents); newerList.add(swapIndex, newComponent); } // This method is used by the merge policy when it needs to check if a merge // is needed. // It only needs to return the newer list @Override public List<ILSMDiskComponent> getImmutableComponents() { if (version == 0) { return diskComponents; } else { return secondDiskComponents; } } // This function should only be used when a transaction fail. it doesn't // take any parameters since there can only be // a single transaction and hence a single transaction component on disk public void deleteTransactionComponent() throws HyracksDataException { fileManager.deleteTransactionFiles(); } // This function in an instance of this index is only used after a bulk load // is successful // it will therefore add the component to the first list and enter it. @Override public void addDiskComponent(ILSMDiskComponent c) throws HyracksDataException { if (version == 0) { diskComponents.add(0, c); } else if (version == 1) { secondDiskComponents.add(0, c); } } // This function is used when a new component is to be committed. @Override public void commitTransactionDiskComponent(ILSMDiskComponent newComponent) throws HyracksDataException { // determine which list is the new one and flip the pointer List<ILSMDiskComponent> newerList; List<ILSMDiskComponent> olderList; if (version == 0) { newerList = diskComponents; olderList = secondDiskComponents; version = 1; } else { newerList = secondDiskComponents; olderList = diskComponents; version = 0; } // Remove components from list olderList.clear(); // Add components olderList.addAll(newerList); if (newComponent != null) { // Add it to the list olderList.add(0, newComponent); } } @Override public synchronized void activate() throws HyracksDataException { if (isActivated) { throw new HyracksDataException("Failed to activate the index since it is already activated."); } if (diskComponents.size() == 0 && secondDiskComponents.size() == 0) { //First time activation List<LSMComponentFileReferences> validFileReferences; try { validFileReferences = fileManager.cleanupAndGetValidFiles(); } catch (IndexException e) { throw new HyracksDataException(e); } for (LSMComponentFileReferences lsmComonentFileReference : validFileReferences) { LSMRTreeDiskComponent component; try { component = createDiskComponent(componentFactory, lsmComonentFileReference.getInsertIndexFileReference(), lsmComonentFileReference.getDeleteIndexFileReference(), lsmComonentFileReference.getBloomFilterFileReference(), false); } catch (IndexException e) { throw new HyracksDataException(e); } diskComponents.add(component); secondDiskComponents.add(component); } ((ExternalIndexHarness) lsmHarness).indexFirstTimeActivated(); } else { // This index has been opened before or is brand new with no components // components. It should also maintain the version pointer for (ILSMComponent c : diskComponents) { LSMRTreeDiskComponent component = (LSMRTreeDiskComponent) c; RTree rtree = component.getRTree(); BTree btree = component.getBTree(); BloomFilter bloomFilter = component.getBloomFilter(); rtree.activate(); btree.activate(); bloomFilter.activate(); } for (ILSMComponent c : secondDiskComponents) { // Only activate non shared components if (!diskComponents.contains(c)) { LSMRTreeDiskComponent component = (LSMRTreeDiskComponent) c; RTree rtree = component.getRTree(); BTree btree = component.getBTree(); BloomFilter bloomFilter = component.getBloomFilter(); rtree.activate(); btree.activate(); bloomFilter.activate(); } } } isActivated = true; } @Override public synchronized void create() throws HyracksDataException { super.create(); secondDiskComponents.clear(); } // we override this method because this index uses a different opcontext @Override public void search(ILSMIndexOperationContext ictx, IIndexCursor cursor, ISearchPredicate pred) throws HyracksDataException, IndexException { ExternalRTreeOpContext ctx = (ExternalRTreeOpContext) ictx; List<ILSMComponent> operationalComponents = ictx.getComponentHolder(); ctx.initialState.setOperationalComponents(operationalComponents); cursor.open(ctx.initialState, pred); } // The only reason for overriding the merge method is the way to determine // the need to keep deleted tuples // This can be done in a better way by creating a method boolean // keepDeletedTuples(mergedComponents); @Override public ILSMDiskComponent merge(ILSMIOOperation operation) throws HyracksDataException, IndexException { LSMRTreeMergeOperation mergeOp = (LSMRTreeMergeOperation) operation; ITreeIndexCursor cursor = mergeOp.getCursor(); ISearchPredicate rtreeSearchPred = new SearchPredicate(null, null); ILSMIndexOperationContext opCtx = ((LSMRTreeSortedCursor) cursor).getOpCtx(); opCtx.getComponentHolder().addAll(mergeOp.getMergingComponents()); search(opCtx, cursor, rtreeSearchPred); LSMRTreeDiskComponent mergedComponent = createDiskComponent(componentFactory, mergeOp.getRTreeMergeTarget(), mergeOp.getBTreeMergeTarget(), mergeOp.getBloomFilterMergeTarget(), true); // In case we must keep the deleted-keys BTrees, then they must be // merged *before* merging the r-trees so that // lsmHarness.endSearch() is called once when the r-trees have been // merged. if (mergeOp.isKeepDeletedTuples()) { // Keep the deleted tuples since the oldest disk component is not // included in the merge operation LSMRTreeDeletedKeysBTreeMergeCursor btreeCursor = new LSMRTreeDeletedKeysBTreeMergeCursor(opCtx); search(opCtx, btreeCursor, rtreeSearchPred); BTree btree = mergedComponent.getBTree(); IIndexBulkLoader btreeBulkLoader = btree.createBulkLoader(1.0f, true, 0L, false); long numElements = 0L; for (int i = 0; i < mergeOp.getMergingComponents().size(); ++i) { numElements += ((LSMRTreeDiskComponent) mergeOp.getMergingComponents().get(i)).getBloomFilter() .getNumElements(); } int maxBucketsPerElement = BloomCalculations.maxBucketsPerElement(numElements); BloomFilterSpecification bloomFilterSpec = BloomCalculations.computeBloomSpec(maxBucketsPerElement, bloomFilterFalsePositiveRate); IIndexBulkLoader builder = mergedComponent.getBloomFilter().createBuilder(numElements, bloomFilterSpec.getNumHashes(), bloomFilterSpec.getNumBucketsPerElements()); try { while (btreeCursor.hasNext()) { btreeCursor.next(); ITupleReference tuple = btreeCursor.getTuple(); btreeBulkLoader.add(tuple); builder.add(tuple); } } finally { btreeCursor.close(); builder.end(); } btreeBulkLoader.end(); } IIndexBulkLoader bulkLoader = mergedComponent.getRTree().createBulkLoader(1.0f, false, 0L, false); try { while (cursor.hasNext()) { cursor.next(); ITupleReference frameTuple = cursor.getTuple(); bulkLoader.add(frameTuple); } } finally { cursor.close(); } bulkLoader.end(); return mergedComponent; } @Override public void deactivate(boolean flushOnExit) throws HyracksDataException { if (!isActivated) { throw new HyracksDataException("Failed to deactivate the index since it is already deactivated."); } if (flushOnExit) { BlockingIOOperationCallbackWrapper cb = new BlockingIOOperationCallbackWrapper(ioOpCallback); cb.afterFinalize(LSMOperationType.FLUSH, null); } for (ILSMComponent c : diskComponents) { LSMRTreeDiskComponent component = (LSMRTreeDiskComponent) c; RTree rtree = component.getRTree(); BTree btree = component.getBTree(); BloomFilter bloomFilter = component.getBloomFilter(); rtree.deactivateCloseHandle(); btree.deactivateCloseHandle(); bloomFilter.deactivate(); } for (ILSMComponent c : secondDiskComponents) { // Only deactivate non shared components if (!diskComponents.contains(c)) { LSMRTreeDiskComponent component = (LSMRTreeDiskComponent) c; RTree rtree = component.getRTree(); BTree btree = component.getBTree(); BloomFilter bloomFilter = component.getBloomFilter(); rtree.deactivateCloseHandle(); btree.deactivateCloseHandle(); bloomFilter.deactivate(); } } isActivated = false; } // The clear method is not used anywhere in AsterixDB! we override it anyway // to exit components first and clear the two lists @Override public void clear() throws HyracksDataException { if (!isActivated) { throw new HyracksDataException("Failed to clear the index since it is not activated."); } ((ExternalIndexHarness) lsmHarness).indexClear(); for (ILSMComponent c : diskComponents) { LSMRTreeDiskComponent component = (LSMRTreeDiskComponent) c; component.getRTree().deactivate(); component.getBloomFilter().deactivate(); component.getBTree().deactivate(); component.getRTree().destroy(); component.getBloomFilter().destroy(); component.getBTree().destroy(); // Remove from second list to avoid destroying twice secondDiskComponents.remove(c); } for (ILSMComponent c : secondDiskComponents) { LSMRTreeDiskComponent component = (LSMRTreeDiskComponent) c; component.getRTree().deactivate(); component.getBloomFilter().deactivate(); component.getBTree().deactivate(); component.getRTree().destroy(); component.getBloomFilter().destroy(); component.getBTree().destroy(); } diskComponents.clear(); secondDiskComponents.clear(); version = -1; } @Override public void destroy() throws HyracksDataException { if (isActivated) { throw new HyracksDataException("Failed to destroy the index since it is activated."); } for (ILSMComponent c : diskComponents) { LSMRTreeDiskComponent component = (LSMRTreeDiskComponent) c; component.getRTree().destroy(); component.getBTree().destroy(); component.getBloomFilter().destroy(); // Remove from second list to avoid destroying twice secondDiskComponents.remove(c); } for (ILSMComponent c : secondDiskComponents) { LSMRTreeDiskComponent component = (LSMRTreeDiskComponent) c; component.getRTree().destroy(); component.getBTree().destroy(); component.getBloomFilter().destroy(); } diskComponents.clear(); secondDiskComponents.clear(); fileManager.deleteDirs(); version = -1; } // Not supported @Override public void modify(IIndexOperationContext ictx, ITupleReference tuple) throws HyracksDataException, IndexException { throw new UnsupportedOperationException("tuple modify not supported in LSM-Disk-Only-RTree"); } // Not supported @Override public void scheduleFlush(ILSMIndexOperationContext ctx, ILSMIOOperationCallback callback) throws HyracksDataException { throw new UnsupportedOperationException("flush not supported in LSM-Disk-Only-RTree"); } // Not supported @Override public ILSMDiskComponent flush(ILSMIOOperation operation) throws HyracksDataException, IndexException { throw new UnsupportedOperationException("flush not supported in LSM-Disk-Only-RTree"); } // Only support search and merge operations @Override public void getOperationalComponents(ILSMIndexOperationContext ctx) { List<ILSMComponent> operationalComponents = ctx.getComponentHolder(); List<ILSMDiskComponent> immutableComponents; // Identify current list in case of a merge if (version == 0) { immutableComponents = diskComponents; } else { immutableComponents = secondDiskComponents; } ExternalRTreeOpContext opCtx = (ExternalRTreeOpContext) ctx; operationalComponents.clear(); switch (ctx.getOperation()) { case SEARCH: if (opCtx.getTargetIndexVersion() == 0) { operationalComponents.addAll(diskComponents); } else { operationalComponents.addAll(secondDiskComponents); } break; case MERGE: operationalComponents.addAll(ctx.getComponentsToBeMerged()); break; case FULL_MERGE: operationalComponents.addAll(immutableComponents); break; case REPLICATE: operationalComponents.addAll(ctx.getComponentsToBeReplicated()); break; case FLUSH: // Do nothing. this is left here even though the index never // performs flushes because a flush is triggered by // dataset lifecycle manager when closing an index. Having no // components is a no operation break; default: throw new UnsupportedOperationException("Operation " + ctx.getOperation() + " not supported."); } } // For initial load @Override public IIndexBulkLoader createBulkLoader(float fillLevel, boolean verifyInput, long numElementsHint, boolean checkIfEmptyIndex) throws TreeIndexException { try { return new LSMTwoPCRTreeBulkLoader(fillLevel, verifyInput, 0, checkIfEmptyIndex, false); } catch (HyracksDataException e) { throw new TreeIndexException(e); } } // For transaction bulk load <- could consolidate with the above method -> @Override public IIndexBulkLoader createTransactionBulkLoader(float fillLevel, boolean verifyInput, long numElementsHint, boolean checkIfEmptyIndex) throws TreeIndexException { try { return new LSMTwoPCRTreeBulkLoader(fillLevel, verifyInput, numElementsHint, checkIfEmptyIndex, true); } catch (HyracksDataException e) { throw new TreeIndexException(e); } } // The bulk loader used for both initial loading and transaction // modifications public class LSMTwoPCRTreeBulkLoader implements IIndexBulkLoader, ITwoPCIndexBulkLoader { private final ILSMDiskComponent component; private final IIndexBulkLoader rtreeBulkLoader; private final BTreeBulkLoader btreeBulkLoader; private final IIndexBulkLoader builder; private boolean cleanedUpArtifacts = false; private boolean isEmptyComponent = true; private boolean endedBloomFilterLoad = false; private final boolean isTransaction; public LSMTwoPCRTreeBulkLoader(float fillFactor, boolean verifyInput, long numElementsHint, boolean checkIfEmptyIndex, boolean isTransaction) throws TreeIndexException, HyracksDataException { this.isTransaction = isTransaction; // Create the appropriate target if (isTransaction) { try { component = createTransactionTarget(); } catch (HyracksDataException | IndexException e) { throw new TreeIndexException(e); } } else { if (checkIfEmptyIndex && !isEmptyIndex()) { throw new TreeIndexException("Cannot load an index that is not empty"); } try { component = createBulkLoadTarget(); } catch (HyracksDataException | IndexException e) { throw new TreeIndexException(e); } } // Create the three loaders rtreeBulkLoader = ((LSMRTreeDiskComponent) component).getRTree().createBulkLoader(fillFactor, verifyInput, numElementsHint, false); btreeBulkLoader = (BTreeBulkLoader) ((LSMRTreeDiskComponent) component).getBTree() .createBulkLoader(fillFactor, verifyInput, numElementsHint, false); int maxBucketsPerElement = BloomCalculations.maxBucketsPerElement(numElementsHint); BloomFilterSpecification bloomFilterSpec = BloomCalculations.computeBloomSpec(maxBucketsPerElement, bloomFilterFalsePositiveRate); builder = ((LSMRTreeDiskComponent) component).getBloomFilter().createBuilder(numElementsHint, bloomFilterSpec.getNumHashes(), bloomFilterSpec.getNumBucketsPerElements()); } @Override public void add(ITupleReference tuple) throws IndexException, HyracksDataException { try { rtreeBulkLoader.add(tuple); } catch (IndexException | HyracksDataException | RuntimeException e) { cleanupArtifacts(); throw e; } if (isEmptyComponent) { isEmptyComponent = false; } } // This is made public in case of a failure, it is better to delete all // created artifacts. public void cleanupArtifacts() throws HyracksDataException { if (!cleanedUpArtifacts) { cleanedUpArtifacts = true; try { ((LSMRTreeDiskComponent) component).getRTree().deactivate(); } catch (Exception e) { } ((LSMRTreeDiskComponent) component).getRTree().destroy(); try { ((LSMRTreeDiskComponent) component).getBTree().deactivate(); } catch (Exception e) { } ((LSMRTreeDiskComponent) component).getBTree().destroy(); try { ((LSMRTreeDiskComponent) component).getBloomFilter().deactivate(); } catch (Exception e) { } ((LSMRTreeDiskComponent) component).getBloomFilter().destroy(); } } @Override public void end() throws HyracksDataException, IndexException { if (!cleanedUpArtifacts) { if (!endedBloomFilterLoad) { builder.end(); endedBloomFilterLoad = true; } rtreeBulkLoader.end(); btreeBulkLoader.end(); if (isEmptyComponent) { cleanupArtifacts(); } else if (isTransaction) { // Since this is a transaction component, validate and // deactivate. it could later be added or deleted markAsValid(component); RTree rtree = ((LSMRTreeDiskComponent) component).getRTree(); BTree btree = ((LSMRTreeDiskComponent) component).getBTree(); BloomFilter bloomFilter = ((LSMRTreeDiskComponent) component).getBloomFilter(); rtree.deactivate(); btree.deactivate(); bloomFilter.deactivate(); } else { lsmHarness.addBulkLoadedComponent(component); } } } @Override public void delete(ITupleReference tuple) throws IndexException, HyracksDataException { try { btreeBulkLoader.add(tuple); builder.add(tuple); } catch (IndexException | HyracksDataException | RuntimeException e) { cleanupArtifacts(); throw e; } if (isEmptyComponent) { isEmptyComponent = false; } } @Override public void abort() { try { cleanupArtifacts(); } catch (Exception e) { } } // This method is used to create a target for a bulk modify operation. This // component must then eventually be either committed or deleted private ILSMDiskComponent createTransactionTarget() throws HyracksDataException, IndexException { LSMComponentFileReferences componentFileRefs; try { componentFileRefs = fileManager.getNewTransactionFileReference(); } catch (IOException e) { throw new HyracksDataException("Failed to create transaction components", e); } return createDiskComponent(componentFactory, componentFileRefs.getInsertIndexFileReference(), componentFileRefs.getDeleteIndexFileReference(), componentFileRefs.getBloomFilterFileReference(), true); } } @Override public String toString() { return "LSMTwoPCRTree [" + fileManager.getBaseDir() + "]"; } // The only change the the schedule merge is the method used to create the // opCtx. first line <- in schedule merge, we-> @Override public void scheduleMerge(ILSMIndexOperationContext ctx, ILSMIOOperationCallback callback) throws HyracksDataException, IndexException { ILSMIndexOperationContext rctx = createOpContext(NoOpOperationCallback.INSTANCE, -1); rctx.setOperation(IndexOperation.MERGE); List<ILSMComponent> mergingComponents = ctx.getComponentHolder(); ITreeIndexCursor cursor = new LSMRTreeSortedCursor(rctx, linearizer, buddyBTreeFields); LSMComponentFileReferences relMergeFileRefs = getMergeTargetFileName(mergingComponents); ILSMIndexAccessor accessor = new LSMRTreeAccessor(lsmHarness, rctx); // create the merge operation. LSMRTreeMergeOperation mergeOp = new LSMRTreeMergeOperation(accessor, mergingComponents, cursor, relMergeFileRefs.getInsertIndexFileReference(), relMergeFileRefs.getDeleteIndexFileReference(), relMergeFileRefs.getBloomFilterFileReference(), callback, fileManager.getBaseDir()); // set the keepDeletedTuples flag boolean keepDeleteTuples = false; if (version == 0) { keepDeleteTuples = mergeOp.getMergingComponents() .get(mergeOp.getMergingComponents().size() - 1) != diskComponents.get(diskComponents.size() - 1); } else { keepDeleteTuples = mergeOp.getMergingComponents() .get(mergeOp.getMergingComponents().size() - 1) != secondDiskComponents .get(secondDiskComponents.size() - 1); } mergeOp.setKeepDeletedTuples(keepDeleteTuples); ioScheduler.scheduleOperation(mergeOp); } @Override public ILSMIndexAccessor createAccessor(ISearchOperationCallback searchCallback, int targetIndexVersion) throws HyracksDataException { return new LSMRTreeAccessor(lsmHarness, createOpContext(searchCallback, targetIndexVersion)); } // This method creates the appropriate opContext for the targeted version public ExternalRTreeOpContext createOpContext(ISearchOperationCallback searchCallback, int targetVersion) { return new ExternalRTreeOpContext(rtreeCmpFactories, btreeCmpFactories, searchCallback, targetVersion, lsmHarness, comparatorFields, linearizerArray, rtreeLeafFrameFactory, rtreeInteriorFrameFactory, btreeLeafFrameFactory); } // The accessor for disk only indexes don't use modification callback and // always carry the target index version with them @Override public ILSMIndexAccessor createAccessor(IModificationOperationCallback modificationCallback, ISearchOperationCallback searchCallback) { return new LSMRTreeAccessor(lsmHarness, createOpContext(searchCallback, version)); } @Override public int getCurrentVersion() { return version; } @Override public List<ILSMDiskComponent> getFirstComponentList() { return diskComponents; } @Override public List<ILSMDiskComponent> getSecondComponentList() { return secondDiskComponents; } @Override public void commitTransaction() throws TreeIndexException, HyracksDataException, IndexException { LSMComponentFileReferences componentFileRefrences = fileManager.getTransactionFileReferenceForCommit(); LSMRTreeDiskComponent component = null; if (componentFileRefrences != null) { component = createDiskComponent(componentFactory, componentFileRefrences.getInsertIndexFileReference(), componentFileRefrences.getDeleteIndexFileReference(), componentFileRefrences.getBloomFilterFileReference(), false); } ((ExternalIndexHarness) lsmHarness).addTransactionComponents(component); } @Override public void abortTransaction() throws TreeIndexException { try { fileManager.deleteTransactionFiles(); } catch (HyracksDataException e) { throw new TreeIndexException(e); } } @Override public void recoverTransaction() throws TreeIndexException { try { fileManager.recoverTransaction(); } catch (HyracksDataException e) { throw new TreeIndexException(e); } } @Override public boolean hasMemoryComponents() { return false; } @Override public int getFieldCount() { return fieldCount; } }
/* * 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.termvectors; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.*; import org.apache.lucene.index.memory.MemoryIndex; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.termvector.TermVectorRequest; import org.elasticsearch.action.termvector.TermVectorResponse; import org.elasticsearch.cluster.action.index.MappingUpdatedAction; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.get.GetField; import org.elasticsearch.index.get.GetResult; import org.elasticsearch.index.mapper.*; import org.elasticsearch.index.mapper.core.StringFieldMapper; import org.elasticsearch.index.mapper.internal.UidFieldMapper; import org.elasticsearch.index.service.IndexService; import org.elasticsearch.index.settings.IndexSettings; import org.elasticsearch.index.shard.AbstractIndexShardComponent; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.service.IndexShard; import java.io.IOException; import java.util.*; import static org.elasticsearch.index.mapper.SourceToParse.source; /** */ public class ShardTermVectorService extends AbstractIndexShardComponent { private IndexShard indexShard; private final MappingUpdatedAction mappingUpdatedAction; @Inject public ShardTermVectorService(ShardId shardId, @IndexSettings Settings indexSettings, MappingUpdatedAction mappingUpdatedAction) { super(shardId, indexSettings); this.mappingUpdatedAction = mappingUpdatedAction; } // sadly, to overcome cyclic dep, we need to do this and inject it ourselves... public ShardTermVectorService setIndexShard(IndexShard indexShard) { this.indexShard = indexShard; return this; } public TermVectorResponse getTermVector(TermVectorRequest request, String concreteIndex) { final Engine.Searcher searcher = indexShard.acquireSearcher("term_vector"); IndexReader topLevelReader = searcher.reader(); final TermVectorResponse termVectorResponse = new TermVectorResponse(concreteIndex, request.type(), request.id()); final Term uidTerm = new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(request.type(), request.id())); Engine.GetResult get = indexShard.get(new Engine.Get(request.realtime(), uidTerm)); boolean docFromTranslog = get.source() != null; /* fetched from translog is treated as an artificial document */ if (docFromTranslog) { request.doc(get.source().source, false); termVectorResponse.setDocVersion(get.version()); } /* handle potential wildcards in fields */ if (request.selectedFields() != null) { handleFieldWildcards(request); } try { Fields topLevelFields = MultiFields.getFields(topLevelReader); Versions.DocIdAndVersion docIdAndVersion = get.docIdAndVersion(); /* from an artificial document */ if (request.doc() != null) { Fields termVectorsByField = generateTermVectorsFromDoc(request, !docFromTranslog); // if no document indexed in shard, take the queried document itself for stats if (topLevelFields == null) { topLevelFields = termVectorsByField; } termVectorResponse.setFields(termVectorsByField, request.selectedFields(), request.getFlags(), topLevelFields); termVectorResponse.setExists(true); termVectorResponse.setArtificial(!docFromTranslog); } /* or from an existing document */ else if (docIdAndVersion != null) { // fields with stored term vectors Fields termVectorsByField = docIdAndVersion.context.reader().getTermVectors(docIdAndVersion.docId); Set<String> selectedFields = request.selectedFields(); // generate tvs for fields where analyzer is overridden if (selectedFields == null && request.perFieldAnalyzer() != null) { selectedFields = getFieldsToGenerate(request.perFieldAnalyzer(), termVectorsByField); } // fields without term vectors if (selectedFields != null) { termVectorsByField = addGeneratedTermVectors(get, termVectorsByField, request, selectedFields); } termVectorResponse.setFields(termVectorsByField, request.selectedFields(), request.getFlags(), topLevelFields); termVectorResponse.setDocVersion(docIdAndVersion.version); termVectorResponse.setExists(true); } else { termVectorResponse.setExists(false); } } catch (Throwable ex) { throw new ElasticsearchException("failed to execute term vector request", ex); } finally { searcher.close(); get.release(); } return termVectorResponse; } private void handleFieldWildcards(TermVectorRequest request) { Set<String> fieldNames = new HashSet<>(); for (String pattern : request.selectedFields()) { fieldNames.addAll(indexShard.mapperService().simpleMatchToIndexNames(pattern)); } request.selectedFields(fieldNames.toArray(Strings.EMPTY_ARRAY)); } private boolean isValidField(FieldMapper field) { // must be a string if (!(field instanceof StringFieldMapper)) { return false; } // and must be indexed if (!field.fieldType().indexed()) { return false; } return true; } private Fields addGeneratedTermVectors(Engine.GetResult get, Fields termVectorsByField, TermVectorRequest request, Set<String> selectedFields) throws IOException { /* only keep valid fields */ Set<String> validFields = new HashSet<>(); for (String field : selectedFields) { FieldMapper fieldMapper = indexShard.mapperService().smartNameFieldMapper(field); if (!isValidField(fieldMapper)) { continue; } // already retrieved, only if the analyzer hasn't been overridden at the field if (fieldMapper.fieldType().storeTermVectors() && (request.perFieldAnalyzer() == null || !request.perFieldAnalyzer().containsKey(field))) { continue; } validFields.add(field); } if (validFields.isEmpty()) { return termVectorsByField; } /* generate term vectors from fetched document fields */ GetResult getResult = indexShard.getService().get( get, request.id(), request.type(), validFields.toArray(Strings.EMPTY_ARRAY), null, false); Fields generatedTermVectors = generateTermVectors(getResult.getFields().values(), request.offsets(), request.perFieldAnalyzer()); /* merge with existing Fields */ if (termVectorsByField == null) { return generatedTermVectors; } else { return mergeFields(termVectorsByField, generatedTermVectors); } } private Analyzer getAnalyzerAtField(String field, @Nullable Map<String, String> perFieldAnalyzer) { MapperService mapperService = indexShard.mapperService(); Analyzer analyzer; if (perFieldAnalyzer != null && perFieldAnalyzer.containsKey(field)) { analyzer = mapperService.analysisService().analyzer(perFieldAnalyzer.get(field).toString()); } else { analyzer = mapperService.smartNameFieldMapper(field).indexAnalyzer(); } if (analyzer == null) { analyzer = mapperService.analysisService().defaultIndexAnalyzer(); } return analyzer; } private Set<String> getFieldsToGenerate(Map<String, String> perAnalyzerField, Fields fieldsObject) { Set<String> selectedFields = new HashSet<>(); for (String fieldName : fieldsObject) { if (perAnalyzerField.containsKey(fieldName)) { selectedFields.add(fieldName); } } return selectedFields; } private Fields generateTermVectors(Collection<GetField> getFields, boolean withOffsets, @Nullable Map<String, String> perFieldAnalyzer) throws IOException { /* store document in memory index */ MemoryIndex index = new MemoryIndex(withOffsets); for (GetField getField : getFields) { String field = getField.getName(); Analyzer analyzer = getAnalyzerAtField(field, perFieldAnalyzer); for (Object text : getField.getValues()) { index.addField(field, text.toString(), analyzer); } } /* and read vectors from it */ return MultiFields.getFields(index.createSearcher().getIndexReader()); } private Fields generateTermVectorsFromDoc(TermVectorRequest request, boolean doAllFields) throws IOException { // parse the document, at the moment we do update the mapping, just like percolate ParsedDocument parsedDocument = parseDocument(indexShard.shardId().getIndex(), request.type(), request.doc()); // select the right fields and generate term vectors ParseContext.Document doc = parsedDocument.rootDoc(); Collection<String> seenFields = new HashSet<>(); Collection<GetField> getFields = new HashSet<>(); for (IndexableField field : doc.getFields()) { FieldMapper fieldMapper = indexShard.mapperService().smartNameFieldMapper(field.name()); if (seenFields.contains(field.name())) { continue; } else { seenFields.add(field.name()); } if (!isValidField(fieldMapper)) { continue; } if (request.selectedFields() == null && !doAllFields && !fieldMapper.fieldType().storeTermVectors()) { continue; } if (request.selectedFields() != null && !request.selectedFields().contains(field.name())) { continue; } String[] values = doc.getValues(field.name()); getFields.add(new GetField(field.name(), Arrays.asList((Object[]) values))); } return generateTermVectors(getFields, request.offsets(), request.perFieldAnalyzer()); } private ParsedDocument parseDocument(String index, String type, BytesReference doc) { MapperService mapperService = indexShard.mapperService(); IndexService indexService = indexShard.indexService(); // TODO: make parsing not dynamically create fields not in the original mapping Tuple<DocumentMapper, Boolean> docMapper = mapperService.documentMapperWithAutoCreate(type); ParsedDocument parsedDocument = docMapper.v1().parse(source(doc).type(type).flyweight(true)).setMappingsModified(docMapper); if (parsedDocument.mappingsModified()) { mappingUpdatedAction.updateMappingOnMaster(index, docMapper.v1(), indexService.indexUUID()); } return parsedDocument; } private Fields mergeFields(Fields fields1, Fields fields2) throws IOException { ParallelFields parallelFields = new ParallelFields(); for (String fieldName : fields2) { Terms terms = fields2.terms(fieldName); if (terms != null) { parallelFields.addField(fieldName, terms); } } for (String fieldName : fields1) { if (parallelFields.fields.containsKey(fieldName)) { continue; } Terms terms = fields1.terms(fieldName); if (terms != null) { parallelFields.addField(fieldName, terms); } } return parallelFields; } // Poached from Lucene ParallelAtomicReader private static final class ParallelFields extends Fields { final Map<String,Terms> fields = new TreeMap<>(); ParallelFields() { } void addField(String fieldName, Terms terms) { fields.put(fieldName, terms); } @Override public Iterator<String> iterator() { return Collections.unmodifiableSet(fields.keySet()).iterator(); } @Override public Terms terms(String field) { return fields.get(field); } @Override public int size() { return fields.size(); } } }
package jadx.core.xmlgen; import jadx.core.codegen.CodeWriter; import jadx.core.xmlgen.entry.EntryConfig; import jadx.core.xmlgen.entry.RawNamedValue; import jadx.core.xmlgen.entry.RawValue; import jadx.core.xmlgen.entry.ResourceEntry; import jadx.core.xmlgen.entry.ValuesParser; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResTableParser extends CommonBinaryParser { private static final Logger LOG = LoggerFactory.getLogger(ResTableParser.class); private static final class PackageChunk { private final int id; private final String name; private final String[] typeStrings; private final String[] keyStrings; private PackageChunk(int id, String name, String[] typeStrings, String[] keyStrings) { this.id = id; this.name = name; this.typeStrings = typeStrings; this.keyStrings = keyStrings; } public int getId() { return id; } public String getName() { return name; } public String[] getTypeStrings() { return typeStrings; } public String[] getKeyStrings() { return keyStrings; } } private String[] strings; private final ResourceStorage resStorage = new ResourceStorage(); public void decode(InputStream inputStream) throws IOException { is = new ParserStream(inputStream); decodeTableChunk(); resStorage.finish(); } public CodeWriter decodeToCodeWriter(InputStream inputStream) throws IOException { decode(inputStream); CodeWriter writer = new CodeWriter(); writer.add("app package: ").add(resStorage.getAppPackage()); writer.startLine(); ValuesParser vp = new ValuesParser(strings, resStorage.getResourcesNames()); for (ResourceEntry ri : resStorage.getResources()) { writer.startLine(ri + ": " + vp.getValueString(ri)); } writer.finish(); return writer; } public ResourceStorage getResStorage() { return resStorage; } void decodeTableChunk() throws IOException { is.checkInt16(RES_TABLE_TYPE, "Not a table chunk"); is.checkInt16(0x000c, "Unexpected table header size"); /*int size = */ is.readInt32(); int pkgCount = is.readInt32(); strings = parseStringPool(); for (int i = 0; i < pkgCount; i++) { parsePackage(); } } private PackageChunk parsePackage() throws IOException { long start = is.getPos(); is.checkInt16(RES_TABLE_PACKAGE_TYPE, "Not a table chunk"); int headerSize = is.readInt16(); if (headerSize != 0x011c && headerSize != 0x0120) { die("Unexpected package header size"); } long size = is.readUInt32(); long endPos = start + size; int id = is.readInt32(); String name = is.readString16Fixed(128); long typeStringsOffset = start + is.readInt32(); /* int lastPublicType = */ is.readInt32(); long keyStringsOffset = start + is.readInt32(); /* int lastPublicKey = */ is.readInt32(); if (headerSize == 0x0120) { /* int typeIdOffset = */ is.readInt32(); } String[] typeStrings = null; if (typeStringsOffset != 0) { is.skipToPos(typeStringsOffset, "Expected typeStrings string pool"); typeStrings = parseStringPool(); } String[] keyStrings = null; if (keyStringsOffset != 0) { is.skipToPos(keyStringsOffset, "Expected keyStrings string pool"); keyStrings = parseStringPool(); } PackageChunk pkg = new PackageChunk(id, name, typeStrings, keyStrings); if (id == 0x7F) { resStorage.setAppPackage(name); } while (is.getPos() < endPos) { long chunkStart = is.getPos(); int type = is.readInt16(); if (type == RES_NULL_TYPE) { continue; } if (type == RES_TABLE_TYPE_SPEC_TYPE) { parseTypeSpecChunk(); } else if (type == RES_TABLE_TYPE_TYPE) { parseTypeChunk(chunkStart, pkg); } } return pkg; } private void parseTypeSpecChunk() throws IOException { is.checkInt16(0x0010, "Unexpected type spec header size"); /*int size = */ is.readInt32(); int id = is.readInt8(); is.skip(3); int entryCount = is.readInt32(); for (int i = 0; i < entryCount; i++) { int entryFlag = is.readInt32(); } } private void parseTypeChunk(long start, PackageChunk pkg) throws IOException { /*int headerSize = */ is.readInt16(); /*int size = */ is.readInt32(); int id = is.readInt8(); is.checkInt8(0, "type chunk, res0"); is.checkInt16(0, "type chunk, res1"); int entryCount = is.readInt32(); long entriesStart = start + is.readInt32(); EntryConfig config = parseConfig(); int[] entryIndexes = new int[entryCount]; for (int i = 0; i < entryCount; i++) { entryIndexes[i] = is.readInt32(); } is.checkPos(entriesStart, "Expected entry start"); for (int i = 0; i < entryCount; i++) { if (entryIndexes[i] != NO_ENTRY) { parseEntry(pkg, id, i, config); } } } private void parseEntry(PackageChunk pkg, int typeId, int entryId, EntryConfig config) throws IOException { /* int size = */ is.readInt16(); int flags = is.readInt16(); int key = is.readInt32(); int resRef = pkg.getId() << 24 | typeId << 16 | entryId; String typeName = pkg.getTypeStrings()[typeId - 1]; String keyName = pkg.getKeyStrings()[key]; ResourceEntry ri = new ResourceEntry(resRef, pkg.getName(), typeName, keyName); ri.setConfig(config); if ((flags & FLAG_COMPLEX) == 0) { ri.setSimpleValue(parseValue()); } else { int parentRef = is.readInt32(); ri.setParentRef(parentRef); int count = is.readInt32(); List<RawNamedValue> values = new ArrayList<RawNamedValue>(count); for (int i = 0; i < count; i++) { values.add(parseValueMap()); } ri.setNamedValues(values); } resStorage.add(ri); } private RawNamedValue parseValueMap() throws IOException { int nameRef = is.readInt32(); return new RawNamedValue(nameRef, parseValue()); } private RawValue parseValue() throws IOException { is.checkInt16(8, "value size"); is.checkInt8(0, "value res0 not 0"); int dataType = is.readInt8(); int data = is.readInt32(); return new RawValue(dataType, data); } private EntryConfig parseConfig() throws IOException { long start = is.getPos(); int size = is.readInt32(); EntryConfig config = new EntryConfig(); is.readInt16(); //mcc is.readInt16(); //mnc config.setLanguage(parseLocale()); config.setCountry(parseLocale()); int orientation = is.readInt8(); int touchscreen = is.readInt8(); int density = is.readInt16(); /* is.readInt8(); // keyboard is.readInt8(); // navigation is.readInt8(); // inputFlags is.readInt8(); // inputPad0 is.readInt16(); // screenWidth is.readInt16(); // screenHeight is.readInt16(); // sdkVersion is.readInt16(); // minorVersion is.readInt8(); // screenLayout is.readInt8(); // uiMode is.readInt16(); // smallestScreenWidthDp is.readInt16(); // screenWidthDp is.readInt16(); // screenHeightDp */ is.skipToPos(start + size, "Skip config parsing"); return config; } private String parseLocale() throws IOException { int b1 = is.readInt8(); int b2 = is.readInt8(); String str = null; if (b1 != 0 && b2 != 0) { if ((b1 & 0x80) == 0) { str = new String(new char[]{(char) b1, (char) b2}); } else { LOG.warn("TODO: parse locale: 0x{}{}", Integer.toHexString(b1), Integer.toHexString(b2)); } } return str; } }
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.transport.common.routing; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.helix.model.ExternalView; import org.apache.helix.model.InstanceConfig; import org.testng.Assert; import org.testng.annotations.Test; import com.linkedin.pinot.common.response.ServerInstance; import com.linkedin.pinot.common.utils.SegmentNameBuilder; import com.linkedin.pinot.routing.HelixExternalViewBasedRouting; import com.linkedin.pinot.routing.RoutingTableLookupRequest; import com.linkedin.pinot.routing.builder.KafkaHighLevelConsumerBasedRoutingTableBuilder; import com.linkedin.pinot.routing.builder.RandomRoutingTableBuilder; import com.linkedin.pinot.routing.builder.RoutingTableBuilder; import com.linkedin.pinot.transport.common.SegmentIdSet; public class RoutingTableTest { @Test public void testHelixExternalViewBasedRoutingTable() { RoutingTableBuilder routingStrategy = new RandomRoutingTableBuilder(100); HelixExternalViewBasedRouting routingTable = new HelixExternalViewBasedRouting(routingStrategy, null, null, null); ExternalView externalView = new ExternalView("testResource0_OFFLINE"); externalView.setState("segment0", "dataServer_instance_0", "ONLINE"); externalView.setState("segment0", "dataServer_instance_1", "ONLINE"); externalView.setState("segment1", "dataServer_instance_1", "ONLINE"); externalView.setState("segment1", "dataServer_instance_2", "ONLINE"); externalView.setState("segment2", "dataServer_instance_2", "ONLINE"); externalView.setState("segment2", "dataServer_instance_0", "ONLINE"); routingTable.markDataResourceOnline("testResource0_OFFLINE", externalView, new ArrayList<InstanceConfig>()); ExternalView externalView1 = new ExternalView("testResource1_OFFLINE"); externalView1.setState("segment10", "dataServer_instance_0", "ONLINE"); externalView1.setState("segment11", "dataServer_instance_1", "ONLINE"); externalView1.setState("segment12", "dataServer_instance_2", "ONLINE"); routingTable.markDataResourceOnline("testResource1_OFFLINE", externalView1, new ArrayList<InstanceConfig>()); ExternalView externalView2 = new ExternalView("testResource2_OFFLINE"); externalView2.setState("segment20", "dataServer_instance_0", "ONLINE"); externalView2.setState("segment21", "dataServer_instance_0", "ONLINE"); externalView2.setState("segment22", "dataServer_instance_0", "ONLINE"); externalView2.setState("segment20", "dataServer_instance_1", "ONLINE"); externalView2.setState("segment21", "dataServer_instance_1", "ONLINE"); externalView2.setState("segment22", "dataServer_instance_1", "ONLINE"); externalView2.setState("segment20", "dataServer_instance_2", "ONLINE"); externalView2.setState("segment21", "dataServer_instance_2", "ONLINE"); externalView2.setState("segment22", "dataServer_instance_2", "ONLINE"); routingTable.markDataResourceOnline("testResource2_OFFLINE", externalView2, new ArrayList<InstanceConfig>()); for (int numRun = 0; numRun < 100; ++numRun) { assertResourceRequest(routingTable, "testResource0_OFFLINE", "[segment0, segment1, segment2]", 3); } for (int numRun = 0; numRun < 100; ++numRun) { assertResourceRequest(routingTable, "testResource1_OFFLINE", "[segment10, segment11, segment12]", 3); } for (int numRun = 0; numRun < 100; ++numRun) { assertResourceRequest(routingTable, "testResource2_OFFLINE", "[segment20, segment21, segment22]", 3); } } private void assertResourceRequest(HelixExternalViewBasedRouting routingTable, String resource, String expectedSegmentList, int expectedNumSegment) { RoutingTableLookupRequest request = new RoutingTableLookupRequest(resource); Map<ServerInstance, SegmentIdSet> serversMap = routingTable.findServers(request); List<String> selectedSegments = new ArrayList<String>(); for (ServerInstance serverInstance : serversMap.keySet()) { System.out.println(serverInstance); SegmentIdSet segmentIdSet = serversMap.get(serverInstance); System.out.println(segmentIdSet.toString()); selectedSegments.addAll(segmentIdSet.getSegmentsNameList()); } String[] selectedSegmentArray = selectedSegments.toArray(new String[0]); Arrays.sort(selectedSegmentArray); Assert.assertEquals(selectedSegments.size(), expectedNumSegment); Assert.assertEquals(Arrays.toString(selectedSegmentArray), expectedSegmentList); System.out.println("********************************"); } @Test public void testKafkaHighLevelConsumerBasedRoutingTable() { RoutingTableBuilder routingStrategy = new KafkaHighLevelConsumerBasedRoutingTableBuilder(); HelixExternalViewBasedRouting routingTable = new HelixExternalViewBasedRouting(null, routingStrategy, null, null); ExternalView externalView = new ExternalView("testResource0_REALTIME"); externalView.setState(SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "0", "0", "0"), "dataServer_instance_0", "ONLINE"); externalView.setState(SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "0", "1", "1"), "dataServer_instance_1", "ONLINE"); externalView.setState(SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "1", "0", "2"), "dataServer_instance_2", "ONLINE"); externalView.setState(SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "1", "1", "3"), "dataServer_instance_3", "ONLINE"); externalView.setState(SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "2", "0", "4"), "dataServer_instance_4", "ONLINE"); externalView.setState(SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "2", "1", "5"), "dataServer_instance_5", "ONLINE"); routingTable.markDataResourceOnline("testResource0_REALTIME", externalView, new ArrayList<InstanceConfig>()); ExternalView externalView1 = new ExternalView("testResource1_REALTIME"); externalView1.setState(SegmentNameBuilder.Realtime.build("testResource1_REALTIME", "instance", "0", "0", "10"), "dataServer_instance_10", "ONLINE"); externalView1.setState(SegmentNameBuilder.Realtime.build("testResource1_REALTIME", "instance", "0", "1", "11"), "dataServer_instance_11", "ONLINE"); externalView1.setState(SegmentNameBuilder.Realtime.build("testResource1_REALTIME", "instance", "0", "2", "12"), "dataServer_instance_12", "ONLINE"); routingTable.markDataResourceOnline("testResource1_REALTIME", externalView1, new ArrayList<InstanceConfig>()); ExternalView externalView2 = new ExternalView("testResource2_REALTIME"); externalView2.setState(SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "0", "0", "20"), "dataServer_instance_20", "ONLINE"); externalView2.setState(SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "0", "1", "21"), "dataServer_instance_21", "ONLINE"); externalView2.setState(SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "0", "2", "22"), "dataServer_instance_22", "ONLINE"); externalView2.setState(SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "1", "0", "23"), "dataServer_instance_23", "ONLINE"); externalView2.setState(SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "1", "1", "24"), "dataServer_instance_24", "ONLINE"); externalView2.setState(SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "1", "2", "25"), "dataServer_instance_25", "ONLINE"); externalView2.setState(SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "2", "0", "26"), "dataServer_instance_26", "ONLINE"); externalView2.setState(SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "2", "1", "27"), "dataServer_instance_27", "ONLINE"); externalView2.setState(SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "2", "2", "28"), "dataServer_instance_28", "ONLINE"); routingTable.markDataResourceOnline("testResource2_REALTIME", externalView2, new ArrayList<InstanceConfig>()); for (int numRun = 0; numRun < 100; ++numRun) { assertResourceRequest( routingTable, "testResource0_REALTIME", new String[] { "[" + SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "0", "0", "0") + ", " + SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "0", "1", "1") + "]", "[" + SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "1", "0", "2") + ", " + SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "1", "1", "3") + "]", "[" + SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "2", "0", "4") + ", " + SegmentNameBuilder.Realtime.build("testResource0_REALTIME", "instance", "2", "1", "5") + "]" }, 2); } for (int numRun = 0; numRun < 100; ++numRun) { assertResourceRequest(routingTable, "testResource1_REALTIME", new String[] { "[" + SegmentNameBuilder.Realtime.build("testResource1_REALTIME", "instance", "0", "0", "10") + ", " + SegmentNameBuilder.Realtime.build("testResource1_REALTIME", "instance", "0", "1", "11") + ", " + SegmentNameBuilder.Realtime.build("testResource1_REALTIME", "instance", "0", "2", "12") + "]" }, 3); } for (int numRun = 0; numRun < 100; ++numRun) { assertResourceRequest(routingTable, "testResource2_REALTIME", new String[] { "[" + SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "0", "0", "20") + ", " + SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "0", "1", "21") + ", " + SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "0", "2", "22") + "]", "[" + SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "1", "0", "23") + ", " + SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "1", "1", "24") + ", " + SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "1", "2", "25") + "]", "[" + SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "2", "0", "26") + ", " + SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "2", "1", "27") + ", " + SegmentNameBuilder.Realtime.build("testResource2_REALTIME", "instance", "2", "2", "28") + "]" }, 3); } } private void assertResourceRequest(HelixExternalViewBasedRouting routingTable, String resource, String[] expectedSegmentLists, int expectedNumSegment) { RoutingTableLookupRequest request = new RoutingTableLookupRequest(resource); Map<ServerInstance, SegmentIdSet> serversMap = routingTable.findServers(request); List<String> selectedSegments = new ArrayList<String>(); for (ServerInstance serverInstance : serversMap.keySet()) { System.out.println(serverInstance); SegmentIdSet segmentIdSet = serversMap.get(serverInstance); System.out.println(segmentIdSet.toString()); selectedSegments.addAll(segmentIdSet.getSegmentsNameList()); } String[] selectedSegmentArray = selectedSegments.toArray(new String[0]); Arrays.sort(selectedSegmentArray); Assert.assertEquals(selectedSegments.size(), expectedNumSegment); boolean matchedExpectedLists = false; for (String expectedSegmentList : expectedSegmentLists) { if (expectedSegmentList.equals(Arrays.toString(selectedSegmentArray))) { matchedExpectedLists = true; } } Assert.assertTrue(matchedExpectedLists); System.out.println("********************************"); } }
/** * Copyright 2015 David Karnok and 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 hu.akarnokd.rxjava2flow.internal.operators; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.concurrent.Flow.*; import org.junit.Test; import hu.akarnokd.rxjava2flow.*; import hu.akarnokd.rxjava2flow.subjects.PublishSubject; import hu.akarnokd.rxjava2flow.subscribers.TestSubscriber; public class OperatorTakeUntilTest { @Test public void testTakeUntil() { Subscription sSource = mock(Subscription.class); Subscription sOther = mock(Subscription.class); TestObservable source = new TestObservable(sSource); TestObservable other = new TestObservable(sOther); Subscriber<String> result = TestHelper.mockSubscriber(); Observable<String> stringObservable = Observable.create(source) .takeUntil(Observable.create(other)); stringObservable.subscribe(result); source.sendOnNext("one"); source.sendOnNext("two"); other.sendOnNext("three"); source.sendOnNext("four"); source.sendOnCompleted(); other.sendOnCompleted(); verify(result, times(1)).onNext("one"); verify(result, times(1)).onNext("two"); verify(result, times(0)).onNext("three"); verify(result, times(0)).onNext("four"); verify(sSource, times(1)).cancel(); verify(sOther, times(1)).cancel(); } @Test public void testTakeUntilSourceCompleted() { Subscription sSource = mock(Subscription.class); Subscription sOther = mock(Subscription.class); TestObservable source = new TestObservable(sSource); TestObservable other = new TestObservable(sOther); Subscriber<String> result = TestHelper.mockSubscriber(); Observable<String> stringObservable = Observable.create(source).takeUntil(Observable.create(other)); stringObservable.subscribe(result); source.sendOnNext("one"); source.sendOnNext("two"); source.sendOnCompleted(); verify(result, times(1)).onNext("one"); verify(result, times(1)).onNext("two"); verify(sSource, times(1)).cancel(); verify(sOther, times(1)).cancel(); } @Test public void testTakeUntilSourceError() { Subscription sSource = mock(Subscription.class); Subscription sOther = mock(Subscription.class); TestObservable source = new TestObservable(sSource); TestObservable other = new TestObservable(sOther); Throwable error = new Throwable(); Subscriber<String> result = TestHelper.mockSubscriber(); Observable<String> stringObservable = Observable.create(source).takeUntil(Observable.create(other)); stringObservable.subscribe(result); source.sendOnNext("one"); source.sendOnNext("two"); source.sendOnError(error); source.sendOnNext("three"); verify(result, times(1)).onNext("one"); verify(result, times(1)).onNext("two"); verify(result, times(0)).onNext("three"); verify(result, times(1)).onError(error); verify(sSource, times(1)).cancel(); verify(sOther, times(1)).cancel(); } @Test public void testTakeUntilOtherError() { Subscription sSource = mock(Subscription.class); Subscription sOther = mock(Subscription.class); TestObservable source = new TestObservable(sSource); TestObservable other = new TestObservable(sOther); Throwable error = new Throwable(); Subscriber<String> result = TestHelper.mockSubscriber(); Observable<String> stringObservable = Observable.create(source).takeUntil(Observable.create(other)); stringObservable.subscribe(result); source.sendOnNext("one"); source.sendOnNext("two"); other.sendOnError(error); source.sendOnNext("three"); verify(result, times(1)).onNext("one"); verify(result, times(1)).onNext("two"); verify(result, times(0)).onNext("three"); verify(result, times(1)).onError(error); verify(result, times(0)).onComplete(); verify(sSource, times(1)).cancel(); verify(sOther, times(1)).cancel(); } /** * If the 'other' onCompletes then we unsubscribe from the source and onComplete */ @Test public void testTakeUntilOtherCompleted() { Subscription sSource = mock(Subscription.class); Subscription sOther = mock(Subscription.class); TestObservable source = new TestObservable(sSource); TestObservable other = new TestObservable(sOther); Subscriber<String> result = TestHelper.mockSubscriber(); Observable<String> stringObservable = Observable.create(source).takeUntil(Observable.create(other)); stringObservable.subscribe(result); source.sendOnNext("one"); source.sendOnNext("two"); other.sendOnCompleted(); source.sendOnNext("three"); verify(result, times(1)).onNext("one"); verify(result, times(1)).onNext("two"); verify(result, times(0)).onNext("three"); verify(result, times(1)).onComplete(); verify(sSource, times(1)).cancel(); verify(sOther, times(1)).cancel(); // unsubscribed since SafeSubscriber unsubscribes after onComplete } private static class TestObservable implements Publisher<String> { Subscriber<? super String> observer; Subscription s; public TestObservable(Subscription s) { this.s = s; } /* used to simulate subscription */ public void sendOnCompleted() { observer.onComplete(); } /* used to simulate subscription */ public void sendOnNext(String value) { observer.onNext(value); } /* used to simulate subscription */ public void sendOnError(Throwable e) { observer.onError(e); } @Override public void subscribe(Subscriber<? super String> observer) { this.observer = observer; observer.onSubscribe(s); } } @Test public void testUntilFires() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> until = PublishSubject.create(); TestSubscriber<Integer> ts = new TestSubscriber<>(); source.takeUntil(until).unsafeSubscribe(ts); assertTrue(source.hasSubscribers()); assertTrue(until.hasSubscribers()); source.onNext(1); ts.assertValue(1); until.onNext(1); ts.assertValue(1); ts.assertNoErrors(); ts.assertTerminated(); assertFalse("Source still has observers", source.hasSubscribers()); assertFalse("Until still has observers", until.hasSubscribers()); assertFalse("TestSubscriber is unsubscribed", ts.isCancelled()); } @Test public void testMainCompletes() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> until = PublishSubject.create(); TestSubscriber<Integer> ts = new TestSubscriber<>(); source.takeUntil(until).unsafeSubscribe(ts); assertTrue(source.hasSubscribers()); assertTrue(until.hasSubscribers()); source.onNext(1); source.onComplete(); ts.assertValue(1); ts.assertNoErrors(); ts.assertTerminated(); assertFalse("Source still has observers", source.hasSubscribers()); assertFalse("Until still has observers", until.hasSubscribers()); assertFalse("TestSubscriber is unsubscribed", ts.isCancelled()); } @Test public void testDownstreamUnsubscribes() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> until = PublishSubject.create(); TestSubscriber<Integer> ts = new TestSubscriber<>(); source.takeUntil(until).take(1).unsafeSubscribe(ts); assertTrue(source.hasSubscribers()); assertTrue(until.hasSubscribers()); source.onNext(1); ts.assertValue(1); ts.assertNoErrors(); ts.assertTerminated(); assertFalse("Source still has observers", source.hasSubscribers()); assertFalse("Until still has observers", until.hasSubscribers()); assertFalse("TestSubscriber is unsubscribed", ts.isCancelled()); } public void testBackpressure() { PublishSubject<Integer> until = PublishSubject.create(); TestSubscriber<Integer> ts = new TestSubscriber<>((Long)null); Observable.range(1, 10).takeUntil(until).unsafeSubscribe(ts); assertTrue(until.hasSubscribers()); ts.request(1); ts.assertValue(1); ts.assertNoErrors(); ts.assertNotComplete(); assertFalse("Until still has observers", until.hasSubscribers()); assertFalse("TestSubscriber is unsubscribed", ts.isCancelled()); } }
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.googlejavaformat.java; import static com.google.common.base.MoreObjects.firstNonNull; import com.google.common.base.MoreObjects; import com.google.common.base.Splitter; import com.google.common.base.Verify; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Range; import com.google.googlejavaformat.Input; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.core.dom.CompilationUnit; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.NavigableMap; /** * {@code JavaInput} extends {@link Input} to represent a Java input document. */ public final class JavaInput extends Input { /** * A {@code JavaInput} is a sequence of {@link Tok}s that cover the Java input. A {@link Tok} is * either a token (if {@code isToken()}), or a non-token, which is a comment (if * {@code isComment()}) or a newline (if {@code isNewline()}) or a maximal sequence of other * whitespace characters (if {@code isSpaces()}). Each {@link Tok} contains a sequence of * characters, an index (sequential starting at {@code 0} for tokens and comments, else * {@code -1}), and an Eclipse-compatible ({@code 0}-origin) position in the input. The * concatenation of the texts of all the {@link Tok}s equals the input. Each Input ends with a * token EOF {@link Tok}, with empty text. * * <p>A {@code /*} comment possibly contains newlines; a {@code //} comment does not contain the * terminating newline character, but is followed by a newline {@link Tok}. */ static final class Tok implements Input.Tok { private final int index; private final String originalText; private final String text; private final int position; private final int columnI; private final boolean isToken; /** * The {@code Tok} constructor. * @param index its index * @param originalText its original text, before removing Unicode escapes * @param text its text after removing Unicode escapes * @param position its {@code 0}-origin position in the input * @param columnI its {@code 0}-origin column number in the input * @param isToken whether the {@code Tok} is a token */ Tok(int index, String originalText, String text, int position, int columnI, boolean isToken) { this.index = index; this.originalText = originalText; this.text = text; this.position = position; this.columnI = columnI; this.isToken = isToken; } @Override public int getIndex() { return index; } @Override public String getText() { return text; } @Override public String getOriginalText() { return originalText; } @Override public int getPosition() { return position; } @Override public int getColumn() { return columnI; } boolean isToken() { return isToken; } @Override public boolean isNewline() { return "\n".equals(text); } @Override public boolean isSlashSlashComment() { return text.startsWith("//"); } @Override public boolean isSlashStarComment() { return text.startsWith("/*"); } @Override public boolean isComment() { return isSlashSlashComment() || isSlashStarComment(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("index", index) .add("text", text) .add("position", position) .add("columnI", columnI) .add("isToken", isToken) .toString(); } } /** * A {@link Token} contains a token {@link Tok} and its associated non-tokens; each non-token * {@link Tok} belongs to one {@link Token}. Each {@link Token} has an immutable list of its * non-tokens that appear before it, and another list of its non-tokens that appear after it. The * concatenation of the texts of all the {@link Token}s' {@link Tok}s, each preceded by the texts * of its {@code toksBefore} and followed by the texts of its {@code toksAfter}, equals the input. */ static final class Token implements Input.Token { private final Tok tok; private final ImmutableList<Tok> toksBefore; private final ImmutableList<Tok> toksAfter; /** * Token constructor. * @param toksBefore the earlier non-token {link Tok}s assigned to this {@code Token} * @param tok this token {@link Tok} * @param toksAfter the later non-token {link Tok}s assigned to this {@code Token} */ Token(List<Tok> toksBefore, Tok tok, List<Tok> toksAfter) { this.toksBefore = ImmutableList.copyOf(toksBefore); this.tok = tok; this.toksAfter = ImmutableList.copyOf(toksAfter); } /** * Get the token's {@link Tok}. * @return the token's {@link Tok} */ @Override public Tok getTok() { return tok; } /** * Get the earlier {@link Tok}s assigned to this {@code Token}. * @return the earlier {@link Tok}s assigned to this {@code Token} */ @Override public ImmutableList<? extends Input.Tok> getToksBefore() { return toksBefore; } /** * Get the later {@link Tok}s assigned to this {@code Token}. * @return the later {@link Tok}s assigned to this {@code Token} */ @Override public ImmutableList<? extends Input.Tok> getToksAfter() { return toksAfter; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("tok", tok) .add("toksBefore", toksBefore) .add("toksAfter", toksAfter) .toString(); } } private static final Splitter NEWLINE_SPLITTER = Splitter.on('\n'); private final String filename; private final String text; // The input. private int kN; // The number of numbered toks (tokens or comments), excluding the EOF. private Map<Integer, Range<Integer>> kToI = null; // Map from token indices to line numbers. /* * The following lists record the sequential indices of the {@code Tok}s on each input line. (Only * tokens and comments have sequential indices.) Tokens and {@code //} comments lie on just one * line; {@code /*} comments can lie on multiple lines. These data structures (along with * equivalent ones for the formatted output) let us compute correspondences between the input and * output. */ private final ImmutableMap<Integer, Integer> positionToColumnMap; // Map Tok position to column. private final ImmutableList<Token> tokens; // The Tokens for this input. private final ImmutableSortedMap<Integer, Token> positionTokenMap; // Map position to Token. /** Map from Tok index to the associated Token. */ private final Token[] kToToken; /** * Input constructor. * @param text the input text * @throws FormatterException if the input cannot be parsed */ public JavaInput(String filename, String text) throws FormatterException { this.filename = filename; this.text = text; char[] chars = text.toCharArray(); List<String> lines = NEWLINE_SPLITTER.splitToList(text); setLines(ImmutableList.copyOf(lines)); ImmutableList<Tok> toks = buildToks(text, chars); positionToColumnMap = makePositionToColumnMap(toks); tokens = buildTokens(toks); ImmutableSortedMap.Builder<Integer, Token> locationTokenMap = ImmutableSortedMap.naturalOrder(); for (Token token : tokens) { locationTokenMap.put(JavaOutput.startTok(token).getPosition(), token); } positionTokenMap = locationTokenMap.build(); // adjust kN for EOF kToToken = new Token[kN + 1]; for (Token token : tokens) { for (Input.Tok tok : token.getToksBefore()) { if (tok.getIndex() < 0) { continue; } kToToken[tok.getIndex()] = token; } kToToken[token.getTok().getIndex()] = token; for (Input.Tok tok : token.getToksAfter()) { if (tok.getIndex() < 0) { continue; } kToToken[tok.getIndex()] = token; } } } private static ImmutableMap<Integer, Integer> makePositionToColumnMap(List<Tok> toks) { ImmutableMap.Builder<Integer, Integer> builder = ImmutableMap.builder(); for (Tok tok : toks) { builder.put(tok.getPosition(), tok.getColumn()); } return builder.build(); } /** * Get the input text. * @return the input text */ @Override public String getText() { return text; } @Override public ImmutableMap<Integer, Integer> getPositionToColumnMap() { return positionToColumnMap; } /** Lex the input and build the list of toks. */ private ImmutableList<Tok> buildToks(String text, char... chars) throws FormatterException { try { kN = 0; IScanner scanner = ToolFactory.createScanner(true, true, true, "1.8"); scanner.setSource(chars); List<Tok> toks = new ArrayList<>(); int charI = 0; int columnI = 0; while (scanner.getCurrentTokenEndPosition() < chars.length - 1 && scanner.getNextToken() != ITerminalSymbols.TokenNameEOF) { int charI0 = scanner.getCurrentTokenStartPosition(); // Get string, possibly with Unicode escapes. String originalTokText = text.substring(charI0, scanner.getCurrentTokenEndPosition() + 1); String tokText = new String(scanner.getCurrentTokenSource()); // Unicode escapes removed. char tokText0 = tokText.charAt(0); // The token's first character. final boolean isToken; // Is this tok a token? final boolean isNumbered; // Is this tok numbered? (tokens and comments) boolean extraNewline = false; // Extra newline at end? List<String> strings = new ArrayList<>(); if (Character.isWhitespace(tokText0)) { isToken = false; isNumbered = false; boolean first = true; for (String spaces : NEWLINE_SPLITTER.split(originalTokText)) { if (!first) { strings.add("\n"); } if (!spaces.isEmpty()) { strings.add(spaces); } first = false; } } else if (tokText.startsWith("'") || tokText.startsWith("\"")) { isToken = true; isNumbered = true; strings.add(originalTokText); } else if (tokText.startsWith("//") || tokText.startsWith("/*")) { // For compatibility with an earlier lexer, the newline after a // comment is its own tok. if (tokText.startsWith("//") && originalTokText.endsWith("\n")) { originalTokText = originalTokText.substring(0, originalTokText.length() - 1); tokText = tokText.substring(0, tokText.length() - 1); extraNewline = true; } isToken = false; isNumbered = true; strings.add(originalTokText); } else if (Character.isJavaIdentifierStart(tokText0) || Character.isDigit(tokText0) || tokText0 == '.' && tokText.length() > 1 && Character.isDigit(tokText.charAt(1))) { // Identifier, keyword, or numeric literal (a dot may begin a number, as in .2D). isToken = true; isNumbered = true; strings.add(tokText); } else { // Other tokens ("+" or "++" or ">>" are broken into one-character toks, because ">>" // cannot be lexed without syntactic knowledge. This implementation fails if the token // contains Unicode escapes. isToken = true; isNumbered = true; for (char c : tokText.toCharArray()) { strings.add(String.valueOf(c)); } } if (strings.size() == 1) { toks.add( new Tok(isNumbered ? kN++ : -1, originalTokText, tokText, charI, columnI, isToken)); for (char c : originalTokText.toCharArray()) { if (c == '\n') { columnI = 0; } else { ++columnI; } ++charI; } } else { if (strings.size() != 1 && !tokText.equals(originalTokText)) { throw new FormatterException( "Unicode escapes not allowed in whitespace or multi-character operators"); } for (String str : strings) { toks.add(new Tok(isNumbered ? kN++ : -1, str, str, charI, columnI, isToken)); for (char c : str.toCharArray()) { if (c == '\n') { columnI = 0; } else { ++columnI; } ++charI; } } } if (extraNewline) { toks.add(new Tok(-1, "\n", "\n", charI, columnI, false)); columnI = 0; ++charI; } } toks.add(new Tok(kN++, "", "", charI, columnI, true)); // EOF tok. --kN; // Don't count EOF tok. computeRanges(toks); return ImmutableList.copyOf(toks); } catch (InvalidInputException e) { throw new FormatterException(e.getMessage()); } } private static ImmutableList<Token> buildTokens(List<Tok> toks) { ImmutableList.Builder<Token> tokens = ImmutableList.builder(); int k = 0; int kN = toks.size(); while (k < kN) { // Remaining non-tokens before the token go here. ImmutableList.Builder<Tok> toksBefore = ImmutableList.builder(); while (!toks.get(k).isToken()) { toksBefore.add(toks.get(k++)); } Tok tok = toks.get(k++); // Non-tokens starting on the same line go here too. ImmutableList.Builder<Tok> toksAfter = ImmutableList.builder(); while (k < kN && !"\n".equals(toks.get(k).getText()) && !toks.get(k).isToken()) { // Don't attach inline comments to leading '('s, e.g. for `f(/*flag1=*/true). // // Attaching inline comments to the right token is hard, and this barely // scratches the surface. But it's enough to do a better job with parameter // name comments. // // TODO(cushon): find a better strategy. if (("(".equals(tok.getText())) && toks.get(k).isSlashStarComment()) { break; } Tok nonTokenAfter = toks.get(k++); toksAfter.add(nonTokenAfter); if (nonTokenAfter.getText().contains("\n")) { break; } } tokens.add(new Token(toksBefore.build(), tok, toksAfter.build())); } return tokens.build(); } /** * Returns the lowest line number the {@link Token} or one of its {@code tokBefore}s lies on in * the {@code JavaInput}. * @param token the {@link Token} * @return the {@code 0}-based line number */ int getLineNumberLo(Token token) { int k = -1; for (Tok tok : token.toksBefore) { k = tok.getIndex(); if (k >= 0) { break; } } if (k < 0) { k = token.tok.getIndex(); } if (kToI == null) { kToI = makeKToIJ(this, kN); } return kToI.get(k).lowerEndpoint(); } /** * Returns the highest line number the {@link Token} or one of its {@code tokAfter}s lies on in * the {@code JavaInput}. * @param token the {@link Token} * @return the {@code 0}-based line number */ int getLineNumberHi(Token token) { int k = -1; for (Tok tok : token.toksAfter.reverse()) { k = tok.getIndex(); if (k >= 0) { break; } } if (k < 0) { k = token.tok.getIndex(); } if (kToI == null) { kToI = makeKToIJ(this, kN); } return kToI.get(k).upperEndpoint() - 1; } /** * Convert from an offset and length flag pair to a token range. * @param offset the {@code 0}-based offset in characters * @param length the length in characters * @return the {@code 0}-based {@link Range} of tokens * @throws FormatterException */ Range<Integer> characterRangeToTokenRange(int offset, int length) throws FormatterException { int requiredLength = offset + length; if (requiredLength > text.length()) { throw new FormatterException( String.format( "invalid length %d, offset + length (%d) is outside the file", requiredLength, requiredLength)); } if (length <= 0) { return Formatter.EMPTY_RANGE; } NavigableMap<Integer, JavaInput.Token> map = getPositionTokenMap(); Map.Entry<Integer, JavaInput.Token> tokenEntryLo = firstNonNull(map.floorEntry(offset), map.firstEntry()); Map.Entry<Integer, JavaInput.Token> tokenEntryHi = firstNonNull(map.ceilingEntry(offset + length - 1), map.lastEntry()); return Range.closedOpen( tokenEntryLo.getValue().getTok().getIndex(), tokenEntryHi.getValue().getTok().getIndex() + 1); } Range<Integer> lineRangeToTokenRange(Range<Integer> lineRange) { Range<Integer> lines = Range.closedOpen(0, getLineCount()); if (!lines.isConnected(lineRange)) { return EMPTY_RANGE; } lineRange = lines.intersection(lineRange); int startLine = Math.max(0, lineRange.lowerEndpoint()); int start = getRange0s(startLine).lowerEndpoint(); while (start < 0 && lines.contains(startLine)) { startLine++; start = getRange0s(startLine).lowerEndpoint(); } int endLine = Math.min(lineRange.upperEndpoint() - 1, getLineCount() - 1); int end = getRange1s(endLine).upperEndpoint(); while (end < 0 && lines.contains(endLine)) { endLine--; end = getRange1s(endLine).upperEndpoint(); } Verify.verify(start >= 0); if (end <= start) { // If the file starts with blank lines, a request to format the first line // wont include any tokens, and 'end' will end up being -1. That issue can't // happen at the end of the file because there's an explicit EOF token. return EMPTY_RANGE; } Verify.verify(end >= 0); return Range.closedOpen(start, end); } /** * Get the number of toks. * @return the number of toks, including the EOF tok */ int getkN() { return kN; } /** * Get the Token by index. * @param k the token index */ Token getToken(int k) { return kToToken[k]; } /** * Get the input tokens. * @return the input tokens */ @Override public ImmutableList<? extends Input.Token> getTokens() { return tokens; } /** * Get the navigable map from position to {@link Token}. Used to look for tokens following a given * one, and to implement the --offset and --length flags to reformat a character range in the * input file. * @return the navigable map from position to {@link Token} */ @Override public NavigableMap<Integer, Token> getPositionTokenMap() { return positionTokenMap; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("tokens", tokens) .add("super", super.toString()) .toString(); } @Override public String filename() { return filename; } private CompilationUnit unit; @Override public int getLineNumber(int inputPosition) { Verify.verifyNotNull(unit, "Expected compilation unit to be set."); return unit.getLineNumber(inputPosition); } // TODO(cushon): refactor JavaInput so the CompilationUnit can be passed into // the constructor. public void setCompilationUnit(CompilationUnit unit) { this.unit = unit; } }
package com.googlecode.pythonforandroid; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.widget.Button; import com.googlecode.android_scripting.AsyncTaskListener; import com.googlecode.android_scripting.FileUtils; import com.googlecode.android_scripting.InterpreterInstaller; import com.googlecode.android_scripting.InterpreterUninstaller; import com.googlecode.android_scripting.activity.Main; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; import com.googlecode.android_scripting.interpreter.InterpreterUtils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * Python Installer. Incorporates module installer. * * The module installer reads a zip file previously downloaded into "download", and unpacks it. If * the module contains shared libraries (*.so) then the module is unpacked into data, other installs * in extras. * * Typically, these will be /data/data/com.googlecode.pythonforandroid/files/python/lib/python2.6 * and /sdcard/com.googlecode.pythonforandroid/extras respectively. * * @author Damon * @author Robbie Matthews (rjmatthews62@gmail.com) * @author Manuel Narango */ // TODO:(Robbie) The whole Import Module is more of a proof of concept than a fully realised // process. Needs some means of checking that these are properly formatted zip files, and probably a // means of uninstalling as well. Import handling could well be a separate activity, too. public class PythonMain extends Main { Button mButtonModules; File mDownloads; private Dialog mDialog; protected String mModule; private CharSequence[] mList; private ProgressDialog mProgress; private boolean mPromptResult; final Handler mModuleHandler = new Handler() { @Override public void handleMessage(Message message) { Bundle bundle = message.getData(); boolean running = bundle.getBoolean("running"); if (running) { if (bundle.containsKey("max")) { mProgress.setProgress(0); mProgress.setMax(bundle.getInt("max")); } else if (bundle.containsKey("pos")) { mProgress.setProgress(bundle.getInt("pos")); } else if (bundle.containsKey("message")) { mProgress.setMessage(bundle.getString("message")); } else { mProgress.incrementProgressBy(1); } } else { mProgress.dismiss(); String info = message.getData().getString("info"); if (info != null) { showMessage("Import Module", info); } } } }; private Button mButtonBrowse; private File mFrom; private File mSoPath; private File mPythonPath; @Override protected InterpreterDescriptor getDescriptor() { return new PythonDescriptor(); } @Override protected InterpreterInstaller getInterpreterInstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { return new PythonInstaller(descriptor, context, listener); } @Override protected InterpreterUninstaller getInterpreterUninstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { return new PythonUninstaller(descriptor, context, listener); } @Override protected void initializeViews() { super.initializeViews(); mDownloads = FileUtils.getExternalDownload(); if (!mDownloads.exists()) { for (File file : new File(Environment.getExternalStorageDirectory().getAbsolutePath()) .listFiles()) { if (file.isDirectory()) { if (file.getName().toLowerCase().startsWith("download")) { mDownloads = file; break; } } } } MarginLayoutParams marginParams = new MarginLayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); final float scale = getResources().getDisplayMetrics().density; int marginPixels = (int) (MARGIN_DIP * scale + 0.5f); marginParams.setMargins(marginPixels, marginPixels, marginPixels, marginPixels); mButtonModules = new Button(this); mButtonModules.setLayoutParams(marginParams); mButtonModules.setText("Import Modules"); mLayout.addView(mButtonModules); mButtonModules.setOnClickListener(new OnClickListener() { public void onClick(View v) { doImportModule(); } }); mButtonBrowse = new Button(this); mButtonBrowse.setLayoutParams(marginParams); mButtonBrowse.setText("Browse Modules"); mLayout.addView(mButtonBrowse); mButtonBrowse.setOnClickListener(new OnClickListener() { public void onClick(View v) { doBrowseModule(); } }); } protected void doBrowseModule() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.mithril.com.au/android/modules")); startActivity(intent); } public void doImportModule() { AlertDialog.Builder builder = new AlertDialog.Builder(this); DialogInterface.OnClickListener buttonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDialog.dismiss(); if (which == DialogInterface.BUTTON_NEUTRAL) { showMessage("Import Module", "This will take a previously downloaded (and appropriately formatted) " + "python external module zip file.\nSee sl4a wiki for more defails.\n" + "Looking for files in \n" + mDownloads); } } }; List<String> flist = new Vector<String>(); for (File f : mDownloads.listFiles()) { if (f.getName().endsWith(".zip")) { flist.add(f.getName()); } } builder.setTitle("Import Module"); mList = flist.toArray(new CharSequence[flist.size()]); builder.setItems(mList, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mModule = (String) mList[which]; performImport(mModule); mDialog.dismiss(); } }); builder.setNegativeButton("Cancel", buttonListener); builder.setNeutralButton("Help", buttonListener); mModule = null; mDialog = builder.show(); if (mModule != null) { } } protected void performImport(String module) { mFrom = new File(mDownloads, mModule); mSoPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/lib/python2.6"); mPythonPath = new File(mDescriptor.getEnvironmentVariables(this).get("PYTHONPATH")); prompt("Install module " + module, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == AlertDialog.BUTTON_POSITIVE) { extract("Extracting " + mModule, mFrom, mPythonPath, mSoPath); } } }); } protected void extract(String caption, File from, File pypath, File sopath) { mProgress = showProgress(caption); Thread t = new RunExtract(caption, from, pypath, sopath, mModuleHandler); t.start(); } protected ProgressDialog showProgress(String caption) { ProgressDialog b = new ProgressDialog(this); b.setTitle(caption); b.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); b.show(); return b; } protected void showMessage(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(title); builder.setMessage(message); builder.setNeutralButton("OK", null); builder.show(); } protected boolean prompt(String message, DialogInterface.OnClickListener btnlisten) { mPromptResult = false; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Python Installer"); builder.setMessage(message); builder.setNegativeButton("Cancel", btnlisten); builder.setPositiveButton("OK", btnlisten); builder.show(); return mPromptResult; } class RunExtract extends Thread { String caption; File from; File sopath; File pypath; Handler mHandler; RunExtract(String caption, File from, File pypath, File sopath, Handler h) { this.caption = caption; this.from = from; this.pypath = pypath; this.sopath = sopath; mHandler = h; } @Override public void run() { byte[] buf = new byte[4096]; boolean useshared; boolean hasSo = false; List<ZipEntry> list = new ArrayList<ZipEntry>(); try { ZipFile zipfile = new ZipFile(from); int cnt = 0; sendmsg(true, "max", zipfile.size()); Enumeration<? extends ZipEntry> entries = zipfile.entries(); while (entries.hasMoreElements()) { ZipEntry ex = entries.nextElement(); if (ex.getName().endsWith(".so")) { hasSo = true; } list.add(ex); } for (ZipEntry entry : list) { cnt += 1; if (entry.isDirectory()) { continue; } useshared = hasSo; File destinationPath = useshared ? sopath : pypath; File destinationFile = new File(destinationPath, entry.getName()); FileUtils.makeDirectories(destinationFile.getParentFile(), 0755); sendmsg(true, "pos", cnt); OutputStream output = new BufferedOutputStream(new FileOutputStream(destinationFile)); InputStream input = zipfile.getInputStream(entry); int len; while ((len = input.read(buf)) > 0) { output.write(buf, 0, len); } input.close(); output.flush(); output.close(); destinationFile.setLastModified(entry.getTime()); FileUtils.chmod(destinationFile, entry.getName().endsWith(".so") ? 0755 : 0644); } sendmsg(false, "Success"); } catch (Exception entry) { sendmsg(false, "Error" + entry); } } private void sendmsg(boolean running, String info) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); if (info != null) { bundle.putString("info", info); } message.setData(bundle); mHandler.sendMessage(message); } private void sendmsg(boolean running, String key, int value) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); bundle.putInt(key, value); message.setData(bundle); mHandler.sendMessage(message); } } }
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.jsp; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderEnumerator; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.impl.source.jsp.jspJava.JspClass; import com.intellij.psi.jsp.BaseJspFile; import com.intellij.psi.jsp.JspFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.Consumer; import com.intellij.util.IncorrectOperationException; import com.intellij.util.Processor; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; /** * @author peter */ public abstract class JspSpiUtil { private static final Logger LOG = Logger.getInstance(JspSpiUtil.class); @NonNls private static final String JAR_EXTENSION = "jar"; @Nullable private static JspSpiUtil getJspSpiUtil() { return ApplicationManager.getApplication().getService(JspSpiUtil.class); } public static int escapeCharsInJspContext(JspFile file, int offset, String toEscape) throws IncorrectOperationException { final JspSpiUtil util = getJspSpiUtil(); return util != null ? util._escapeCharsInJspContext(file, offset, toEscape) : 0; } protected abstract int _escapeCharsInJspContext(JspFile file, int offset, String toEscape) throws IncorrectOperationException; public static void visitAllIncludedFilesRecursively(BaseJspFile jspFile, Processor<? super BaseJspFile> visitor) { final JspSpiUtil util = getJspSpiUtil(); if (util != null) { util._visitAllIncludedFilesRecursively(jspFile, visitor); } } protected abstract void _visitAllIncludedFilesRecursively(BaseJspFile jspFile, Processor<? super BaseJspFile> visitor); @Nullable public static PsiElement resolveMethodPropertyReference(@NotNull PsiReference reference, @Nullable PsiClass resolvedClass, boolean readable) { final JspSpiUtil util = getJspSpiUtil(); return util == null ? null : util._resolveMethodPropertyReference(reference, resolvedClass, readable); } @Nullable protected abstract PsiElement _resolveMethodPropertyReference(@NotNull PsiReference reference, @Nullable PsiClass resolvedClass, boolean readable); public static Object @NotNull [] getMethodPropertyReferenceVariants(@NotNull PsiReference reference, @Nullable PsiClass resolvedClass, boolean readable) { final JspSpiUtil util = getJspSpiUtil(); return util == null ? ArrayUtilRt.EMPTY_OBJECT_ARRAY : util._getMethodPropertyReferenceVariants(reference, resolvedClass, readable); } protected abstract Object[] _getMethodPropertyReferenceVariants(@NotNull PsiReference reference, @Nullable PsiClass resolvedClass, boolean readable); public static boolean isIncludedOrIncludesSomething(@NotNull JspFile file) { return isIncludingAnything(file) || isIncluded(file); } public static boolean isIncluded(@NotNull JspFile jspFile) { final JspSpiUtil util = getJspSpiUtil(); return util != null && util._isIncluded(jspFile); } public abstract boolean _isIncluded(@NotNull final JspFile jspFile); public static boolean isIncludingAnything(@NotNull JspFile jspFile) { final JspSpiUtil util = getJspSpiUtil(); return util != null && util._isIncludingAnything(jspFile); } protected abstract boolean _isIncludingAnything(@NotNull final JspFile jspFile); public static PsiFile[] getIncludedFiles(@NotNull JspFile jspFile) { final JspSpiUtil util = getJspSpiUtil(); return util == null ? PsiFile.EMPTY_ARRAY : util._getIncludedFiles(jspFile); } public static PsiFile[] getIncludingFiles(@NotNull JspFile jspFile) { final JspSpiUtil util = getJspSpiUtil(); return util == null ? PsiFile.EMPTY_ARRAY : util._getIncludingFiles(jspFile); } protected abstract PsiFile[] _getIncludingFiles(@NotNull PsiFile file); protected abstract PsiFile @NotNull [] _getIncludedFiles(@NotNull final JspFile jspFile); public static boolean isJavaContext(PsiElement position) { if(PsiTreeUtil.getContextOfType(position, JspClass.class, false) != null) return true; return false; } public static boolean isJarFile(@Nullable VirtualFile file) { if (file != null){ final String ext = file.getExtension(); if(ext != null && ext.equalsIgnoreCase(JAR_EXTENSION)) { return true; } } return false; } public static List<URL> buildUrls(@Nullable final VirtualFile virtualFile, @Nullable final Module module) { return buildUrls(virtualFile, module, true); } public static List<URL> buildUrls(@Nullable final VirtualFile virtualFile, @Nullable final Module module, boolean includeModuleOutput) { final List<URL> urls = new ArrayList<>(); processClassPathItems(virtualFile, module, file -> addUrl(urls, file), includeModuleOutput); return urls; } public static List<Path> buildFiles(@Nullable VirtualFile virtualFile, @Nullable Module module, boolean includeModuleOutput) { List<Path> result = new ArrayList<>(); processClassPathItems(virtualFile, module, file -> { if (file != null && file.isValid()) { Path path = file.getFileSystem().getNioPath(file); if (path != null) { result.add(path); } } }, includeModuleOutput); return result; } public static void processClassPathItems(final VirtualFile virtualFile, final Module module, final Consumer<? super VirtualFile> consumer) { processClassPathItems(virtualFile, module, consumer, true); } public static void processClassPathItems(final VirtualFile virtualFile, final Module module, final Consumer<? super VirtualFile> consumer, boolean includeModuleOutput) { if (isJarFile(virtualFile)){ consumer.consume(virtualFile); } if (module != null) { OrderEnumerator enumerator = ModuleRootManager.getInstance(module).orderEntries().recursively(); if (!includeModuleOutput) { enumerator = enumerator.withoutModuleSourceEntries(); } for (VirtualFile root : enumerator.getClassesRoots()) { final VirtualFile file; if (root.getFileSystem().getProtocol().equals(JarFileSystem.PROTOCOL)) { file = JarFileSystem.getInstance().getVirtualFileForJar(root); } else { file = root; } consumer.consume(file); } } } private static void addUrl(List<? super URL> urls, VirtualFile file) { if (file == null || !file.isValid()) return; final URL url = getUrl(file); if (url != null) { urls.add(url); } } @SuppressWarnings({"HardCodedStringLiteral"}) @Nullable private static URL getUrl(VirtualFile file) { if (file.getFileSystem() instanceof JarFileSystem && file.getParent() != null) return null; String path = file.getPath(); if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { path = path.substring(0, path.length() - 2); } String url; if (SystemInfo.isWindows) { url = "file:/" + path; } else { url = "file://" + path; } if (file.isDirectory() && !(file.getFileSystem() instanceof JarFileSystem)) url += "/"; try { return new URL(url); } catch (MalformedURLException e) { LOG.error(e); return null; } } }
package com.vm.gameplay.service; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.content.Intent; import android.util.Log; import com.vm.gameplay.FindGameActivity; public class BluetoothGameService { private static final String TAG = "BluetoothGameService"; private static final boolean D = true; private static final String NAME_SECURE = "BluetoothGameSecure"; private static final String NAME_INSECURE = "BluetoothGameInsecure"; // Unique UUID for this application private static final UUID MY_UUID_SECURE = UUID .fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); private static final UUID MY_UUID_INSECURE = UUID .fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); // Member fields private final BluetoothAdapter mAdapter; private AcceptThread mSecureAcceptThread; private AcceptThread mInsecureAcceptThread; private ConnectThread mConnectThread; private ConnectedThread mConnectedThread; private int mState; private Context mContext; public static final int STATE_NONE = 0; // we're doing nothing public static final int STATE_LISTEN = 1; // now listening for incoming // connections public static final int STATE_CONNECTING = 2; // now initiating an outgoing // connection public static final int STATE_CONNECTED = 3; // now connected to a remote // device public static BluetoothGameService instance; public static BluetoothGameService getInstance(Context context) { if (instance == null) { instance = new BluetoothGameService(context); } return instance; } private BluetoothGameService(Context context) { mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; mContext = context; } private synchronized void setState(int state) { if (D) Log.d(TAG, "setState() " + mState + " -> " + state); mState = state; Intent intent = new Intent(); intent.setAction(FindGameActivity.STR_MESSAGE_STATE_CHANGE); intent.putExtra("state", state); mContext.sendBroadcast(intent); } public synchronized int getState() { return mState; } public synchronized void start() { if (D) Log.d(TAG, "start"); // Cancel any thread attempting to make a connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } setState(STATE_LISTEN); // Start the thread to listen on a BluetoothServerSocket if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); } mSecureAcceptThread = new AcceptThread(true); mSecureAcceptThread.start(); if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); } mInsecureAcceptThread = new AcceptThread(false); mInsecureAcceptThread.start(); } public synchronized void connect(BluetoothDevice device, boolean secure) { if (D) Log.d(TAG, "connect to: " + device); // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } // Start the thread to connect with the given device mConnectThread = new ConnectThread(device, secure); mConnectThread.start(); setState(STATE_CONNECTING); } /** * Start the ConnectedThread to begin managing a Bluetooth connection * * @param socket * The BluetoothSocket on which the connection was made * @param device * The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) { if (D) Log.d(TAG, "connected, Socket Type:" + socketType); // Cancel the thread that completed the connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } // Cancel the accept thread because we only want to connect to one // device if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket, socketType); mConnectedThread.start(); Intent intent = new Intent(); intent.setAction(FindGameActivity.STR_MESSAGE_DEVICE_NAME); intent.putExtra(FindGameActivity.DEVICE_NAME, device.getName()); mContext.sendBroadcast(intent); setState(STATE_CONNECTED); } /** * Stop all threads */ public synchronized void stop() { if (D) Log.d(TAG, "stop"); if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } setState(STATE_NONE); } /** * Write to the ConnectedThread in an unsynchronized manner * * @param out * The bytes to write * @see ConnectedThread#write(byte[]) */ public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (mState != STATE_CONNECTED) return; r = mConnectedThread; } // Perform the write unsynchronized r.write(out); } /** * Indicate that the connection attempt failed and notify the UI Activity. */ private void connectionFailed() { // Start the service over to restart listening mode BluetoothGameService.this.start(); } /** * Indicate that the connection was lost and notify the UI Activity. */ private void connectionLost() { // Start the service over to restart listening mode BluetoothGameService.this.start(); } /** * This thread runs while listening for incoming connections. It behaves * like a server-side client. It runs until a connection is accepted (or * until cancelled). */ private class AcceptThread extends Thread { // The local server socket private final BluetoothServerSocket mmServerSocket; private String mSocketType; public AcceptThread(boolean secure) { BluetoothServerSocket tmp = null; mSocketType = secure ? "Secure" : "Insecure"; // Create a new listening server socket try { if (secure) { tmp = mAdapter.listenUsingRfcommWithServiceRecord( NAME_SECURE, MY_UUID_SECURE); } else { tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord( NAME_INSECURE, MY_UUID_INSECURE); } } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e); } mmServerSocket = tmp; } public void run() { if (D) Log.d(TAG, "Socket Type: " + mSocketType + "BEGIN mAcceptThread" + this); setName("AcceptThread" + mSocketType); BluetoothSocket socket = null; // Listen to the server socket if we're not connected while (mState != STATE_CONNECTED) { try { // This is a blocking call and will only return on a // successful connection or an exception socket = mmServerSocket.accept(); } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e); break; } // If a connection was accepted if (socket != null) { synchronized (BluetoothGameService.this) { switch (mState) { case STATE_LISTEN: case STATE_CONNECTING: // Situation normal. Start the connected thread. connected(socket, socket.getRemoteDevice(), mSocketType); break; case STATE_NONE: case STATE_CONNECTED: // Either not ready or already connected. Terminate // new socket. try { socket.close(); } catch (IOException e) { Log.e(TAG, "Could not close unwanted socket", e); } break; } } } } if (D) Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType); } public void cancel() { if (D) Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this); try { mmServerSocket.close(); } catch (IOException e) { Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e); } } } /** * This thread runs while attempting to make an outgoing connection with a * device. It runs straight through; the connection either succeeds or * fails. */ private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; private String mSocketType; public ConnectThread(BluetoothDevice device, boolean secure) { mmDevice = device; BluetoothSocket tmp = null; mSocketType = secure ? "Secure" : "Insecure"; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try { if (secure) { tmp = device .createRfcommSocketToServiceRecord(MY_UUID_SECURE); } else { tmp = device .createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE); } } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e); } mmSocket = tmp; } public void run() { Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType); setName("ConnectThread" + mSocketType); // Always cancel discovery because it will slow down a connection mAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception mmSocket.connect(); } catch (IOException e) { Log.e(TAG, "unable to connect() " + mSocketType + " socket during connection failure", e); // Close the socket try { mmSocket.close(); } catch (IOException e2) { Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e2); } connectionFailed(); return; } // Reset the ConnectThread because we're done synchronized (BluetoothGameService.this) { mConnectThread = null; } // Start the connected thread connected(mmSocket, mmDevice, mSocketType); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e); } } } /** * This thread runs during a connection with a remote device. It handles all * incoming and outgoing transmissions. */ private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket, String socketType) { Log.d(TAG, "create ConnectedThread: " + socketType); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI Activity // mHandler.obtainMessage( // BluetoothGameSetupActivity.MESSAGE_READ, bytes, -1, // buffer).sendToTarget(); Intent intent = new Intent(); intent.setAction(FindGameActivity.STR_MESSAGE_READ); intent.putExtra("data", buffer); intent.putExtra("length", bytes); mContext.sendBroadcast(intent); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); // Start the service over to restart listening mode BluetoothGameService.this.start(); break; } } } /** * Write to the connected OutStream. * * @param buffer * The bytes to write */ public void write(byte[] buffer) { try { mmOutStream.write(buffer); // Share the sent message back to the UI Activity // mHandler.obtainMessage( // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1, // buffer).sendToTarget(); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } }
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.project; import com.google.common.collect.Lists; import com.google.gerrit.common.Nullable; import com.google.gerrit.common.data.LabelType; import com.google.gerrit.common.data.LabelTypes; import com.google.gerrit.common.data.PermissionRange; import com.google.gerrit.common.data.RefConfigSection; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.PatchSetApproval; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.notedb.ChangeNotes; import com.google.gerrit.server.query.change.ChangeData; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import java.io.IOException; import java.util.Collection; import java.util.List; /** Access control management for a user accessing a single change. */ public class ChangeControl { public static class GenericFactory { private final ProjectControl.GenericFactory projectControl; private final Provider<ReviewDb> db; @Inject GenericFactory(ProjectControl.GenericFactory p, Provider<ReviewDb> d) { projectControl = p; db = d; } public ChangeControl controlFor(Change.Id changeId, CurrentUser user) throws NoSuchChangeException, OrmException { Change change = db.get().changes().get(changeId); if (change == null) { throw new NoSuchChangeException(changeId); } return controlFor(change, user); } public ChangeControl controlFor(Change change, CurrentUser user) throws NoSuchChangeException { final Project.NameKey projectKey = change.getProject(); try { return projectControl.controlFor(projectKey, user).controlFor(change); } catch (NoSuchProjectException e) { throw new NoSuchChangeException(change.getId(), e); } catch (IOException e) { // TODO: propagate this exception throw new NoSuchChangeException(change.getId(), e); } } public ChangeControl validateFor(Change.Id changeId, CurrentUser user) throws NoSuchChangeException, OrmException { Change change = db.get().changes().get(changeId); if (change == null) { throw new NoSuchChangeException(changeId); } return validateFor(change, user); } public ChangeControl validateFor(Change change, CurrentUser user) throws NoSuchChangeException, OrmException { ChangeControl c = controlFor(change, user); if (!c.isVisible(db.get())) { throw new NoSuchChangeException(c.getChange().getId()); } return c; } } public interface AssistedFactory { ChangeControl create(RefControl refControl, Change change); ChangeControl create(RefControl refControl, ChangeNotes notes); } private final ChangeData.Factory changeDataFactory; private final RefControl refControl; private final ChangeNotes notes; @AssistedInject ChangeControl( ChangeData.Factory changeDataFactory, ChangeNotes.Factory notesFactory, @Assisted RefControl refControl, @Assisted Change change) { this(changeDataFactory, refControl, notesFactory.create(change)); } @AssistedInject ChangeControl( ChangeData.Factory changeDataFactory, @Assisted RefControl refControl, @Assisted ChangeNotes notes) { this.changeDataFactory = changeDataFactory; this.refControl = refControl; this.notes = notes; } public ChangeControl forUser(final CurrentUser who) { if (getCurrentUser().equals(who)) { return this; } return new ChangeControl(changeDataFactory, getRefControl().forUser(who), notes); } public RefControl getRefControl() { return refControl; } public CurrentUser getCurrentUser() { return getRefControl().getCurrentUser(); } public ProjectControl getProjectControl() { return getRefControl().getProjectControl(); } public Project getProject() { return getProjectControl().getProject(); } public Change getChange() { return notes.getChange(); } public ChangeNotes getNotes() { return notes; } /** Can this user see this change? */ public boolean isVisible(ReviewDb db) throws OrmException { if (getChange().getStatus() == Change.Status.DRAFT && !isDraftVisible(db, null)) { return false; } return isRefVisible(); } /** Can the user see this change? Does not account for draft status */ public boolean isRefVisible() { return getRefControl().isVisible(); } /** Can this user see the given patchset? */ public boolean isPatchVisible(PatchSet ps, ReviewDb db) throws OrmException { if (ps != null && ps.isDraft() && !isDraftVisible(db, null)) { return false; } return isVisible(db); } /** Can this user abandon this change? */ public boolean canAbandon() { return isOwner() // owner (aka creator) of the change can abandon || getRefControl().isOwner() // branch owner can abandon || getProjectControl().isOwner() // project owner can abandon || getCurrentUser().getCapabilities().canAdministrateServer() // site administers are god || getRefControl().canAbandon() // user can abandon a specific ref ; } /** Can this user publish this draft change or any draft patch set of this change? */ public boolean canPublish(final ReviewDb db) throws OrmException { return (isOwner() || getRefControl().canPublishDrafts()) && isVisible(db); } /** Can this user delete this draft change or any draft patch set of this change? */ public boolean canDeleteDraft(final ReviewDb db) throws OrmException { return (isOwner() || getRefControl().canDeleteDrafts()) && isVisible(db); } /** Can this user rebase this change? */ public boolean canRebase() { return isOwner() || getRefControl().canSubmit() || getRefControl().canRebase(); } /** Can this user restore this change? */ public boolean canRestore() { return canAbandon() // Anyone who can abandon the change can restore it back && getRefControl().canUpload(); // as long as you can upload too } /** All available label types for this change. */ public LabelTypes getLabelTypes() { String destBranch = getChange().getDest().get(); List<LabelType> all = getProjectControl().getLabelTypes().getLabelTypes(); List<LabelType> r = Lists.newArrayListWithCapacity(all.size()); for (LabelType l : all) { List<String> refs = l.getRefPatterns(); if (refs == null) { r.add(l); } else { for (String refPattern : refs) { if (RefConfigSection.isValid(refPattern) && match(destBranch, refPattern)) { r.add(l); break; } } } } return new LabelTypes(r); } /** All value ranges of any allowed label permission. */ public List<PermissionRange> getLabelRanges() { return getRefControl().getLabelRanges(isOwner()); } /** The range of permitted values associated with a label permission. */ public PermissionRange getRange(String permission) { return getRefControl().getRange(permission, isOwner()); } /** Can this user add a patch set to this change? */ public boolean canAddPatchSet() { return getRefControl().canUpload(); } /** Is this user the owner of the change? */ public boolean isOwner() { if (getCurrentUser().isIdentifiedUser()) { final IdentifiedUser i = (IdentifiedUser) getCurrentUser(); return i.getAccountId().equals(getChange().getOwner()); } return false; } /** Is this user a reviewer for the change? */ public boolean isReviewer(ReviewDb db) throws OrmException { return isReviewer(db, null); } /** Is this user a reviewer for the change? */ public boolean isReviewer(ReviewDb db, @Nullable ChangeData cd) throws OrmException { if (getCurrentUser().isIdentifiedUser()) { Collection<Account.Id> results = changeData(db, cd).reviewers().values(); IdentifiedUser user = (IdentifiedUser) getCurrentUser(); return results.contains(user.getAccountId()); } return false; } /** @return true if the user is allowed to remove this reviewer. */ public boolean canRemoveReviewer(PatchSetApproval approval) { return canRemoveReviewer(approval.getAccountId(), approval.getValue()); } public boolean canRemoveReviewer(Account.Id reviewer, int value) { if (getChange().getStatus().isOpen()) { // A user can always remove themselves. // if (getCurrentUser().isIdentifiedUser()) { final IdentifiedUser i = (IdentifiedUser) getCurrentUser(); if (i.getAccountId().equals(reviewer)) { return true; // can remove self } } // The change owner may remove any zero or positive score. // if (isOwner() && 0 <= value) { return true; } // Users with the remove reviewer permission, the branch owner, project // owner and site admin can remove anyone if (getRefControl().canRemoveReviewer() // has removal permissions || getRefControl().isOwner() // branch owner || getProjectControl().isOwner() // project owner || getCurrentUser().getCapabilities().canAdministrateServer()) { return true; } } return false; } /** Can this user edit the topic name? */ public boolean canEditTopicName() { if (getChange().getStatus().isOpen()) { return isOwner() // owner (aka creator) of the change can edit topic || getRefControl().isOwner() // branch owner can edit topic || getProjectControl().isOwner() // project owner can edit topic || getCurrentUser().getCapabilities().canAdministrateServer() // site administers are god || getRefControl().canEditTopicName() // user can edit topic on a specific ref ; } else { return getRefControl().canForceEditTopicName(); } } /** Can this user edit the hashtag name? */ public boolean canEditHashtags() { return isOwner() // owner (aka creator) of the change can edit hashtags || getRefControl().isOwner() // branch owner can edit hashtags || getProjectControl().isOwner() // project owner can edit hashtags || getCurrentUser().getCapabilities().canAdministrateServer() // site administers are god || getRefControl().canEditHashtags(); // user can edit hashtag on a specific ref } public boolean canSubmit() { return getRefControl().canSubmit(); } public boolean canSubmitAs() { return getRefControl().canSubmitAs(); } private boolean match(String destBranch, String refPattern) { return RefPatternMatcher.getMatcher(refPattern).match(destBranch, getCurrentUser().getUserName()); } private ChangeData changeData(ReviewDb db, @Nullable ChangeData cd) { return cd != null ? cd : changeDataFactory.create(db, this); } public boolean isDraftVisible(ReviewDb db, ChangeData cd) throws OrmException { return isOwner() || isReviewer(db, cd) || getRefControl().canViewDrafts() || getCurrentUser().isInternalUser(); } }
/* * 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.ode.bpel.compiler.wsdl; import org.apache.ode.bpel.compiler.bom.PartnerLinkType; import org.apache.ode.bpel.compiler.bom.Property; import org.apache.ode.bpel.compiler.bom.PropertyAlias; import org.apache.ode.utils.stl.CollectionsX; import org.apache.ode.utils.stl.MemberOfFunction; import org.w3c.dom.Element; import javax.wsdl.Binding; import javax.wsdl.BindingFault; import javax.wsdl.BindingInput; import javax.wsdl.BindingOperation; import javax.wsdl.BindingOutput; import javax.wsdl.Definition; import javax.wsdl.Fault; import javax.wsdl.Import; import javax.wsdl.Input; import javax.wsdl.Message; import javax.wsdl.Operation; import javax.wsdl.Output; import javax.wsdl.Part; import javax.wsdl.Port; import javax.wsdl.PortType; import javax.wsdl.Service; import javax.wsdl.Types; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.ExtensionRegistry; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Implementation of the {@link Definition4BPEL} wrapper. */ class Definition4BPELImpl implements Definition4BPEL { private static final long serialVersionUID = 1L; Definition _def; private String _bpwsNS; private String _plnkNS; private String _propNS; Definition4BPELImpl(Definition wsdlDef, String bpwsNS, String plnkNS, String propNS) { _def = wsdlDef; _bpwsNS = bpwsNS; _plnkNS = plnkNS; _propNS = propNS; } /** * Get a list of the defined {@link PartnerLinkType}s. * * @return {@link List} of {@link PartnerLinkType} objects */ public List<PartnerLinkType> getPartnerLinkTypes() { return getElementsForType(new QName(_plnkNS, "partnerLinkType"), PartnerLinkType.class); } /** * Get a list of the defined {@link PartnerLinkType}s. * * @return {@link List} of {@link PartnerLinkType} objects */ public List<Property> getProperties() { return getElementsForType(new QName(_propNS, "property"), Property.class); } /** * Get a list of the defined {@link PropertyAlias}es. * * @return {@link List} of {@link PropertyAlias} objects */ public List<PropertyAlias> getPropertyAliases() { return getElementsForType(new QName(_propNS, "propertyAlias"), PropertyAlias.class); } public Property getProperty(final QName name) { return CollectionsX.find_if(getProperties(), new MemberOfFunction<Property>() { public boolean isMember(Property o) { return o.getName().equals(name); } }); } public PartnerLinkType getPartnerLinkType(final QName partnerLinkTypeName) { return CollectionsX.find_if(getPartnerLinkTypes(), new MemberOfFunction<PartnerLinkType>() { public boolean isMember(PartnerLinkType o) { return o.getName().equals(partnerLinkTypeName); } }); } public PropertyAlias getPropertyAlias(final QName propertyName, final QName messageType) { return CollectionsX.find_if(getPropertyAliases(), new MemberOfFunction<PropertyAlias>() { public boolean isMember(PropertyAlias o) { return o.getPropertyName().equals(propertyName) && o.getMessageType().equals(messageType); } }); } /** * Get a list of the schema types defined in-line. * * @return {@link List} of {@link XMLSchemaType} objects */ @SuppressWarnings("unchecked") public List <XMLSchemaType> getSchemas() { return (List<XMLSchemaType>)getTypes().getExtensibilityElements(); } public void addBinding(Binding binding) { _def.addBinding(binding); } public void addExtensibilityElement(ExtensibilityElement extensibilityElement) { _def.addExtensibilityElement(extensibilityElement); } public void addImport(Import anImport) { _def.addImport(anImport); } public void addMessage(Message message) { _def.addMessage(message); } public void addNamespace(String s, String s1) { _def.addNamespace(s,s1); } public void addPortType(PortType portType) { _def.addPortType(portType); } public void addService(Service service) { _def.addService(service); } public Binding createBinding() { return _def.createBinding(); } public BindingFault createBindingFault() { return _def.createBindingFault(); } public BindingInput createBindingInput() { return _def.createBindingInput(); } public BindingOperation createBindingOperation() { return _def.createBindingOperation(); } public BindingOutput createBindingOutput() { return _def.createBindingOutput(); } public Fault createFault() { return _def.createFault(); } public Import createImport() { return _def.createImport(); } public Input createInput() { return _def.createInput(); } public Message createMessage() { return _def.createMessage(); } public Operation createOperation() { return _def.createOperation(); } public Output createOutput() { return _def.createOutput(); } public Part createPart() { return _def.createPart(); } public Port createPort() { return _def.createPort(); } public PortType createPortType() { return _def.createPortType(); } public Service createService() { return _def.createService(); } public Types createTypes() { return _def.createTypes(); } public Binding getBinding(QName qName) { return _def.getBinding(qName); } public Map getBindings() { return _def.getBindings(); } public String getDocumentBaseURI() { return _def.getDocumentBaseURI(); } public Element getDocumentationElement() { return _def.getDocumentationElement(); } public List getExtensibilityElements() { return _def.getExtensibilityElements(); } public ExtensionRegistry getExtensionRegistry() { return _def.getExtensionRegistry(); } public Map getImports() { return _def.getImports(); } public List getImports(String s) { return _def.getImports(s); } public Message getMessage(QName qName) { return _def.getMessage(qName); } public Map getMessages() { return _def.getMessages(); } public String getNamespace(String s) { return _def.getNamespace(s); } public Map getNamespaces() { return _def.getNamespaces(); } public PortType getPortType(QName qName) { return _def.getPortType(qName); } public Map getPortTypes() { return _def.getPortTypes(); } public String getPrefix(String s) { return _def.getPrefix(s); } public QName getQName() { return _def.getQName(); } public Service getService(QName qName) { return _def.getService(qName); } public Map getServices() { return _def.getServices(); } public String getTargetNamespace() { return _def.getTargetNamespace(); } public Types getTypes() { return _def.getTypes(); } public Binding removeBinding(QName qName) { return _def.removeBinding(qName); } public Message removeMessage(QName qName) { return _def.removeMessage(qName); } public PortType removePortType(QName qName) { return _def.removePortType(qName); } public Service removeService(QName qName) { return _def.removeService(qName); } public void setDocumentBaseURI(String s) { _def.setDocumentBaseURI(s); } public void setDocumentationElement(Element element) { _def.setDocumentationElement(element); } public void setExtensionRegistry(ExtensionRegistry extensionRegistry) { _def.setExtensionRegistry(extensionRegistry); } public void setQName(QName qName) { _def.setQName(qName); } public void setTargetNamespace(String s) { _def.setTargetNamespace(s); } public void setTypes(Types types) { _def.setTypes(types); } public Definition getDefinition() { return _def; } public Map getAllServices() { return _def.getAllServices(); } public Map getAllBindings() { return _def.getAllBindings(); } public Map getAllPortTypes() { return _def.getAllPortTypes(); } public Import removeImport(Import anImport) { return _def.removeImport(anImport); } public String removeNamespace(String string) { return _def.removeNamespace(string); } public Object getExtensionAttribute(QName qName) { return _def.getExtensionAttribute(qName); } public Map getExtensionAttributes() { return _def.getExtensionAttributes(); } public List getNativeAttributeNames() { return _def.getNativeAttributeNames(); } public void setExtensionAttribute(QName qName, Object object) { _def.setExtensionAttribute(qName, object); } public ExtensibilityElement removeExtensibilityElement(ExtensibilityElement e) { return _def.removeExtensibilityElement(e); } /** * Get all the extensibility elements of a certain name (element name that is). * @param type type of extensibility element * @return list of extensibility elements of the given type */ @SuppressWarnings("unchecked") private <T extends ExtensibilityElement> List<T> getElementsForType(final QName type, Class<T> cls) { List<T> ret = new ArrayList<T>(); CollectionsX.filter(ret, getExtensibilityElements(), new MemberOfFunction() { public boolean isMember(Object o) { return ((ExtensibilityElement)o).getElementType().equals(type); } }); return ret; } }
/* * Copyright 2011 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.net.URL; import java.net.UnknownHostException; import java.security.ProtectionDomain; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.Scanner; import org.apache.log4j.PropertyConfigurator; import org.eclipse.jetty.security.ConstraintMapping; import org.eclipse.jetty.security.ConstraintSecurityHandler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.session.HashSessionManager; import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS; import org.eclipse.jgit.util.FileUtils; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.gitblit.authority.GitblitAuthority; import com.gitblit.authority.NewCertificateConfig; import com.gitblit.servlet.GitblitContext; import com.gitblit.utils.StringUtils; import com.gitblit.utils.TimeUtils; import com.gitblit.utils.X509Utils; import com.gitblit.utils.X509Utils.X509Log; import com.gitblit.utils.X509Utils.X509Metadata; import com.unboundid.ldap.listener.InMemoryDirectoryServer; import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; import com.unboundid.ldap.listener.InMemoryListenerConfig; import com.unboundid.ldif.LDIFReader; /** * GitBlitServer is the embedded Jetty server for Gitblit GO. This class starts * and stops an instance of Jetty that is configured from a combination of the * gitblit.properties file and command line parameters. JCommander is used to * simplify command line parameter processing. This class also automatically * generates a self-signed certificate for localhost, if the keystore does not * already exist. * * @author James Moger * */ public class GitBlitServer { private static Logger logger; public static void main(String... args) { GitBlitServer server = new GitBlitServer(); // filter out the baseFolder parameter List<String> filtered = new ArrayList<String>(); String folder = "data"; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.equals("--baseFolder")) { if (i + 1 == args.length) { System.out.println("Invalid --baseFolder parameter!"); System.exit(-1); } else if (!".".equals(args[i + 1])) { folder = args[i + 1]; } i = i + 1; } else { filtered.add(arg); } } Params.baseFolder = folder; Params params = new Params(); CmdLineParser parser = new CmdLineParser(params); try { parser.parseArgument(filtered); if (params.help) { server.usage(parser, null); } } catch (CmdLineException t) { server.usage(parser, t); } if (params.stop) { server.stop(params); } else { server.start(params); } } /** * Display the command line usage of Gitblit GO. * * @param parser * @param t */ protected final void usage(CmdLineParser parser, CmdLineException t) { System.out.println(Constants.BORDER); System.out.println(Constants.getGitBlitVersion()); System.out.println(Constants.BORDER); System.out.println(); if (t != null) { System.out.println(t.getMessage()); System.out.println(); } if (parser != null) { parser.printUsage(System.out); System.out .println("\nExample:\n java -server -Xmx1024M -jar gitblit.jar --repositoriesFolder c:\\git --httpPort 80 --httpsPort 443"); } System.exit(0); } protected File getBaseFolder(Params params) { String path = System.getProperty("GITBLIT_HOME", Params.baseFolder); if (!StringUtils.isEmpty(System.getenv("GITBLIT_HOME"))) { path = System.getenv("GITBLIT_HOME"); } return new File(path).getAbsoluteFile(); } /** * Stop Gitblt GO. */ public void stop(Params params) { try { Socket s = new Socket(InetAddress.getByName("127.0.0.1"), params.shutdownPort); OutputStream out = s.getOutputStream(); System.out.println("Sending Shutdown Request to " + Constants.NAME); out.write("\r\n".getBytes()); out.flush(); s.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Start Gitblit GO. */ protected final void start(Params params) { final File baseFolder = getBaseFolder(params); FileSettings settings = params.FILESETTINGS; if (!StringUtils.isEmpty(params.settingsfile)) { if (new File(params.settingsfile).exists()) { settings = new FileSettings(params.settingsfile); } } if (params.dailyLogFile) { // Configure log4j for daily log file generation InputStream is = null; try { is = getClass().getResourceAsStream("/log4j.properties"); Properties loggingProperties = new Properties(); loggingProperties.load(is); loggingProperties.put("log4j.appender.R.File", new File(baseFolder, "logs/gitblit.log").getAbsolutePath()); loggingProperties.put("log4j.rootCategory", "INFO, R"); if (settings.getBoolean(Keys.web.debugMode, false)) { loggingProperties.put("log4j.logger.com.gitblit", "DEBUG"); } PropertyConfigurator.configure(loggingProperties); } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } logger = LoggerFactory.getLogger(GitBlitServer.class); logger.info("\n" + Constants.getASCIIArt()); System.setProperty("java.awt.headless", "true"); String osname = System.getProperty("os.name"); String osversion = System.getProperty("os.version"); logger.info("Running on " + osname + " (" + osversion + ")"); QueuedThreadPool threadPool = new QueuedThreadPool(); int maxThreads = settings.getInteger(Keys.server.threadPoolSize, 50); if (maxThreads > 0) { threadPool.setMaxThreads(maxThreads); } Server server = new Server(threadPool); server.setStopAtShutdown(true); // conditionally configure the https connector if (params.securePort > 0) { File certificatesConf = new File(baseFolder, X509Utils.CA_CONFIG); File serverKeyStore = new File(baseFolder, X509Utils.SERVER_KEY_STORE); File serverTrustStore = new File(baseFolder, X509Utils.SERVER_TRUST_STORE); File caRevocationList = new File(baseFolder, X509Utils.CA_REVOCATION_LIST); // generate CA & web certificates, create certificate stores X509Metadata metadata = new X509Metadata("localhost", params.storePassword); // set default certificate values from config file if (certificatesConf.exists()) { FileBasedConfig config = new FileBasedConfig(certificatesConf, FS.detect()); try { config.load(); } catch (Exception e) { logger.error("Error parsing " + certificatesConf, e); } NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config); certificateConfig.update(metadata); } metadata.notAfter = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR); X509Utils.prepareX509Infrastructure(metadata, baseFolder, new X509Log() { @Override public void log(String message) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(new File(baseFolder, X509Utils.CERTS + File.separator + "log.txt"), true)); writer.write(MessageFormat.format("{0,date,yyyy-MM-dd HH:mm}: {1}", new Date(), message)); writer.newLine(); writer.flush(); } catch (Exception e) { LoggerFactory.getLogger(GitblitAuthority.class).error("Failed to append log entry!", e); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } }); if (serverKeyStore.exists()) { /* * HTTPS */ logger.info("Setting up HTTPS transport on port " + params.securePort); GitblitSslContextFactory factory = new GitblitSslContextFactory(params.alias, serverKeyStore, serverTrustStore, params.storePassword, caRevocationList); if (params.requireClientCertificates) { factory.setNeedClientAuth(true); } else { factory.setWantClientAuth(true); } ServerConnector connector = new ServerConnector(server, factory); connector.setSoLingerTime(-1); connector.setIdleTimeout(30000); connector.setPort(params.securePort); String bindInterface = settings.getString(Keys.server.httpsBindInterface, null); if (!StringUtils.isEmpty(bindInterface)) { logger.warn(MessageFormat.format( "Binding HTTPS transport on port {0,number,0} to {1}", params.securePort, bindInterface)); connector.setHost(bindInterface); } if (params.securePort < 1024 && !isWindows()) { logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!"); } server.addConnector(connector); } else { logger.warn("Failed to find or load Keystore?"); logger.warn("HTTPS transport DISABLED."); } } // conditionally configure the http transport if (params.port > 0) { /* * HTTP */ logger.info("Setting up HTTP transport on port " + params.port); HttpConfiguration httpConfig = new HttpConfiguration(); if (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) { httpConfig.setSecureScheme("https"); httpConfig.setSecurePort(params.securePort); } httpConfig.setSendServerVersion(false); httpConfig.setSendDateHeader(false); ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); connector.setSoLingerTime(-1); connector.setIdleTimeout(30000); connector.setPort(params.port); String bindInterface = settings.getString(Keys.server.httpBindInterface, null); if (!StringUtils.isEmpty(bindInterface)) { logger.warn(MessageFormat.format("Binding HTTP transport on port {0,number,0} to {1}", params.port, bindInterface)); connector.setHost(bindInterface); } if (params.port < 1024 && !isWindows()) { logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!"); } server.addConnector(connector); } // tempDir is where the embedded Gitblit web application is expanded and // where Jetty creates any necessary temporary files File tempDir = com.gitblit.utils.FileUtils.resolveParameter(Constants.baseFolder$, baseFolder, params.temp); if (tempDir.exists()) { try { FileUtils.delete(tempDir, FileUtils.RECURSIVE | FileUtils.RETRY); } catch (IOException x) { logger.warn("Failed to delete temp dir " + tempDir.getAbsolutePath(), x); } } if (!tempDir.mkdirs()) { logger.warn("Failed to create temp dir " + tempDir.getAbsolutePath()); } // Get the execution path of this class // We use this to set the WAR path. ProtectionDomain protectionDomain = GitBlitServer.class.getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); // Root WebApp Context WebAppContext rootContext = new WebAppContext(); rootContext.setContextPath(settings.getString(Keys.server.contextPath, "/")); rootContext.setServer(server); rootContext.setWar(location.toExternalForm()); rootContext.setTempDirectory(tempDir); // Set cookies HttpOnly so they are not accessible to JavaScript engines HashSessionManager sessionManager = new HashSessionManager(); sessionManager.setHttpOnly(true); // Use secure cookies if only serving https sessionManager.setSecureRequestOnly(params.port <= 0 && params.securePort > 0); rootContext.getSessionHandler().setSessionManager(sessionManager); // Ensure there is a defined User Service String realmUsers = params.userService; if (StringUtils.isEmpty(realmUsers)) { logger.error(MessageFormat.format("PLEASE SPECIFY {0}!!", Keys.realm.userService)); return; } // Override settings from the command-line settings.overrideSetting(Keys.realm.userService, params.userService); settings.overrideSetting(Keys.git.repositoriesFolder, params.repositoriesFolder); settings.overrideSetting(Keys.git.daemonPort, params.gitPort); settings.overrideSetting(Keys.git.sshPort, params.sshPort); // Start up an in-memory LDAP server, if configured try { if (!StringUtils.isEmpty(params.ldapLdifFile)) { File ldifFile = new File(params.ldapLdifFile); if (ldifFile != null && ldifFile.exists()) { URI ldapUrl = new URI(settings.getRequiredString(Keys.realm.ldap.server)); String firstLine = new Scanner(ldifFile).nextLine(); String rootDN = firstLine.substring(4); String bindUserName = settings.getString(Keys.realm.ldap.username, ""); String bindPassword = settings.getString(Keys.realm.ldap.password, ""); // Get the port int port = ldapUrl.getPort(); if (port == -1) port = 389; InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(rootDN); config.addAdditionalBindCredentials(bindUserName, bindPassword); config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", port)); config.setSchema(null); InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config); ds.importFromLDIF(true, new LDIFReader(ldifFile)); ds.startListening(); logger.info("LDAP Server started at ldap://localhost:" + port); } } } catch (Exception e) { // Completely optional, just show a warning logger.warn("Unable to start LDAP server", e); } // Set the server's contexts server.setHandler(rootContext); // redirect HTTP requests to HTTPS if (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) { logger.info(String.format("Configuring automatic http(%1$s) -> https(%2$s) redirects", params.port, params.securePort)); // Create the internal mechanisms to handle secure connections and redirects Constraint constraint = new Constraint(); constraint.setDataConstraint(Constraint.DC_CONFIDENTIAL); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); ConstraintSecurityHandler sh = new ConstraintSecurityHandler(); sh.setConstraintMappings(new ConstraintMapping[] { cm }); // Configure this context to use the Security Handler defined before rootContext.setHandler(sh); } // Setup the Gitblit context GitblitContext gitblit = newGitblit(settings, baseFolder); rootContext.addEventListener(gitblit); try { // start the shutdown monitor if (params.shutdownPort > 0) { Thread shutdownMonitor = new ShutdownMonitorThread(server, params); shutdownMonitor.start(); } // start Jetty server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(100); } } protected GitblitContext newGitblit(IStoredSettings settings, File baseFolder) { return new GitblitContext(settings, baseFolder); } /** * Tests to see if the operating system is Windows. * * @return true if this is a windows machine */ private boolean isWindows() { return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1; } /** * The ShutdownMonitorThread opens a socket on a specified port and waits * for an incoming connection. When that connection is accepted a shutdown * message is issued to the running Jetty server. * * @author James Moger * */ private static class ShutdownMonitorThread extends Thread { private final ServerSocket socket; private final Server server; private final Logger logger = LoggerFactory.getLogger(ShutdownMonitorThread.class); public ShutdownMonitorThread(Server server, Params params) { this.server = server; setDaemon(true); setName(Constants.NAME + " Shutdown Monitor"); ServerSocket skt = null; try { skt = new ServerSocket(params.shutdownPort, 1, InetAddress.getByName("127.0.0.1")); } catch (Exception e) { logger.warn("Could not open shutdown monitor on port " + params.shutdownPort, e); } socket = skt; } @Override public void run() { // Only run if the socket was able to be created (not already in use, failed to bind, etc.) if (null != socket) { logger.info("Shutdown Monitor listening on port " + socket.getLocalPort()); Socket accept; try { accept = socket.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader( accept.getInputStream())); reader.readLine(); logger.info(Constants.BORDER); logger.info("Stopping " + Constants.NAME); logger.info(Constants.BORDER); server.stop(); server.setStopAtShutdown(false); accept.close(); socket.close(); } catch (Exception e) { logger.warn("Failed to shutdown Jetty", e); } } } } /** * Parameters class for GitBlitServer. */ public static class Params { public static String baseFolder; private final FileSettings FILESETTINGS = new FileSettings(new File(baseFolder, Constants.PROPERTIES_FILE).getAbsolutePath()); /* * Server parameters */ @Option(name = "--help", aliases = { "-h"}, usage = "Show this help") public Boolean help = false; @Option(name = "--stop", usage = "Stop Server") public Boolean stop = false; @Option(name = "--tempFolder", usage = "Folder for server to extract built-in webapp", metaVar="PATH") public String temp = FILESETTINGS.getString(Keys.server.tempFolder, "temp"); @Option(name = "--dailyLogFile", usage = "Log to a rolling daily log file INSTEAD of stdout.") public Boolean dailyLogFile = false; /* * GIT Servlet Parameters */ @Option(name = "--repositoriesFolder", usage = "Git Repositories Folder", metaVar="PATH") public String repositoriesFolder = FILESETTINGS.getString(Keys.git.repositoriesFolder, "git"); /* * Authentication Parameters */ @Option(name = "--userService", usage = "Authentication and Authorization Service (filename or fully qualified classname)") public String userService = FILESETTINGS.getString(Keys.realm.userService, "users.conf"); /* * JETTY Parameters */ @Option(name = "--httpPort", usage = "HTTP port for to serve. (port <= 0 will disable this connector)", metaVar="PORT") public Integer port = FILESETTINGS.getInteger(Keys.server.httpPort, 0); @Option(name = "--httpsPort", usage = "HTTPS port to serve. (port <= 0 will disable this connector)", metaVar="PORT") public Integer securePort = FILESETTINGS.getInteger(Keys.server.httpsPort, 8443); @Option(name = "--gitPort", usage = "Git Daemon port to serve. (port <= 0 will disable this connector)", metaVar="PORT") public Integer gitPort = FILESETTINGS.getInteger(Keys.git.daemonPort, 9418); @Option(name = "--sshPort", usage = "Git SSH port to serve. (port <= 0 will disable this connector)", metaVar = "PORT") public Integer sshPort = FILESETTINGS.getInteger(Keys.git.sshPort, 29418); @Option(name = "--alias", usage = "Alias of SSL certificate in keystore for serving https.", metaVar="ALIAS") public String alias = FILESETTINGS.getString(Keys.server.certificateAlias, ""); @Option(name = "--storePassword", usage = "Password for SSL (https) keystore.", metaVar="PASSWORD") public String storePassword = FILESETTINGS.getString(Keys.server.storePassword, ""); @Option(name = "--shutdownPort", usage = "Port for Shutdown Monitor to listen on. (port <= 0 will disable this monitor)", metaVar="PORT") public Integer shutdownPort = FILESETTINGS.getInteger(Keys.server.shutdownPort, 8081); @Option(name = "--requireClientCertificates", usage = "Require client X509 certificates for https connections.") public Boolean requireClientCertificates = FILESETTINGS.getBoolean(Keys.server.requireClientCertificates, false); /* * Setting overrides */ @Option(name = "--settings", usage = "Path to alternative settings", metaVar="FILE") public String settingsfile; @Option(name = "--ldapLdifFile", usage = "Path to LDIF file. This will cause an in-memory LDAP server to be started according to gitblit settings", metaVar="FILE") public String ldapLdifFile; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.security; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.hadoop.hive.ql.hooks.ReadEntity; import org.apache.hadoop.hive.ql.hooks.WriteEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.metastore.IHMSHandler; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.ql.metadata.AuthorizationException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.security.authorization.HiveMetastoreAuthorizationProvider; import org.apache.hadoop.hive.ql.security.authorization.Privilege; import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException; import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePolicyProvider; /** * Dummy implementation for use by unit tests. Tracks the context of calls made to * its authorize functions in {@link AuthCallContext} */ public class DummyHiveMetastoreAuthorizationProvider implements HiveMetastoreAuthorizationProvider { protected HiveAuthenticationProvider authenticator; public enum AuthCallContextType { USER, DB, TABLE, PARTITION, TABLE_AND_PARTITION, AUTHORIZATION }; class AuthCallContext { public AuthCallContextType type; public List<Object> authObjects; public Privilege[] readRequiredPriv; public Privilege[] writeRequiredPriv; AuthCallContext(AuthCallContextType typeOfCall, Privilege[] readRequiredPriv, Privilege[] writeRequiredPriv) { this.type = typeOfCall; this.authObjects = new ArrayList<Object>(); this.readRequiredPriv = readRequiredPriv; this.writeRequiredPriv = writeRequiredPriv; } AuthCallContext(AuthCallContextType typeOfCall, Object authObject, Privilege[] readRequiredPriv, Privilege[] writeRequiredPriv) { this(typeOfCall,readRequiredPriv,writeRequiredPriv); this.authObjects.add(authObject); } AuthCallContext(AuthCallContextType typeOfCall, List<? extends Object> authObjects, Privilege[] readRequiredPriv, Privilege[] writeRequiredPriv) { this(typeOfCall,readRequiredPriv,writeRequiredPriv); this.authObjects.addAll(authObjects); } } public static final List<AuthCallContext> authCalls = new ArrayList<AuthCallContext>(); private Configuration conf; public static final Logger LOG = LoggerFactory.getLogger( DummyHiveMetastoreAuthorizationProvider.class);; @Override public Configuration getConf() { return this.conf; } @Override public void setConf(Configuration conf) { this.conf = conf; try { init(conf); } catch (HiveException e) { throw new RuntimeException(e); } } @Override public HiveAuthenticationProvider getAuthenticator() { return authenticator; } @Override public void setAuthenticator(HiveAuthenticationProvider authenticator) { this.authenticator = authenticator; } @Override public void init(Configuration conf) throws HiveException { debugLog("DHMAP.init"); } @Override public void authorizeDbLevelOperations(Privilege[] readRequiredPriv, Privilege[] writeRequiredPriv, Collection<ReadEntity> inputs, Collection<WriteEntity> outputs) throws HiveException, AuthorizationException { debugLog("DHMAP.authorize " + "read:" + debugPrivPrint(readRequiredPriv) + " , write:" + debugPrivPrint(writeRequiredPriv) ); authCalls.add(new AuthCallContext(AuthCallContextType.USER, readRequiredPriv, writeRequiredPriv)); } @Override public void authorize(Database db, Privilege[] readRequiredPriv, Privilege[] writeRequiredPriv) throws HiveException, AuthorizationException { debugLog("DHMAP.authorizedb " + "db:" + db.getName() + " , read:" + debugPrivPrint(readRequiredPriv) + " , write:" + debugPrivPrint(writeRequiredPriv) ); authCalls.add(new AuthCallContext(AuthCallContextType.DB, db, readRequiredPriv, writeRequiredPriv)); } @Override public void authorize(Table table, Privilege[] readRequiredPriv, Privilege[] writeRequiredPriv) throws HiveException, AuthorizationException { debugLog("DHMAP.authorizetbl " + "tbl:" + table.getCompleteName() + " , read:" + debugPrivPrint(readRequiredPriv) + " , write:" + debugPrivPrint(writeRequiredPriv) ); authCalls.add(new AuthCallContext(AuthCallContextType.TABLE, table, readRequiredPriv, writeRequiredPriv)); } @Override public void authorize(Partition part, Privilege[] readRequiredPriv, Privilege[] writeRequiredPriv) throws HiveException, AuthorizationException { debugLog("DHMAP.authorizepart " + "tbl:" + part.getTable().getCompleteName() + " , part: " + part.getName() + " , read:" + debugPrivPrint(readRequiredPriv) + " , write:" + debugPrivPrint(writeRequiredPriv) ); authCalls.add(new AuthCallContext(AuthCallContextType.PARTITION, part, readRequiredPriv, writeRequiredPriv)); } @Override public void authorize(Table table, Partition part, List<String> columns, Privilege[] readRequiredPriv, Privilege[] writeRequiredPriv) throws HiveException, AuthorizationException { debugLog("DHMAP.authorizecols " + "tbl:" + table.getCompleteName() + " , part: " + part.getName() + " . cols: " + columns.toString() + " , read:" + debugPrivPrint(readRequiredPriv) + " , write:" + debugPrivPrint(writeRequiredPriv) ); List<Object> authObjects = new ArrayList<Object>(); authObjects.add(table); authObjects.add(part); authCalls.add(new AuthCallContext(AuthCallContextType.TABLE_AND_PARTITION, authObjects, readRequiredPriv, writeRequiredPriv)); } private void debugLog(String s) { LOG.debug(s); } private String debugPrivPrint(Privilege[] privileges) { StringBuilder sb = new StringBuilder(); sb.append("Privileges{"); if (privileges != null){ for (Privilege p : privileges){ sb.append(p.toString()); } }else{ sb.append("null"); } sb.append("}"); return sb.toString(); } @Override public void setMetaStoreHandler(IHMSHandler handler) { debugLog("DHMAP.setMetaStoreHandler"); } @Override public void authorizeAuthorizationApiInvocation() throws HiveException, AuthorizationException { debugLog("DHMAP.authorizeauthapi"); authCalls.add(new AuthCallContext(AuthCallContextType.AUTHORIZATION, null, null)); } @Override public HivePolicyProvider getHivePolicyProvider() throws HiveAuthzPluginException { return null; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.SocketTimeoutException; import java.net.URI; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FsServerDefaults; import org.apache.hadoop.fs.FileChecksum; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocatedFileStatus; import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum; import org.apache.hadoop.fs.Options.ChecksumOpt; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.fs.StorageType; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys; import org.apache.hadoop.hdfs.net.Peer; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.apache.hadoop.hdfs.protocol.HdfsConstants.RollingUpgradeAction; import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.server.datanode.DataNode; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeSpi; import org.apache.hadoop.hdfs.web.WebHdfsConstants; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.util.DataChecksum; import org.apache.hadoop.util.Time; import org.apache.log4j.Level; import org.junit.Assert; import org.junit.Test; import org.mockito.InOrder; public class TestDistributedFileSystem { private static final Random RAN = new Random(); static { GenericTestUtils.setLogLevel(DFSClient.LOG, Level.ALL); } private boolean dualPortTesting = false; private boolean noXmlDefaults = false; private HdfsConfiguration getTestConfiguration() { HdfsConfiguration conf; if (noXmlDefaults) { conf = new HdfsConfiguration(false); String namenodeDir = new File(MiniDFSCluster.getBaseDirectory(), "name"). getAbsolutePath(); conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, namenodeDir); conf.set(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY, namenodeDir); } else { conf = new HdfsConfiguration(); } if (dualPortTesting) { conf.set(DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY, "localhost:0"); } conf.setLong(DFSConfigKeys.DFS_NAMENODE_MIN_BLOCK_SIZE_KEY, 0); return conf; } @Test public void testEmptyDelegationToken() throws IOException { Configuration conf = getTestConfiguration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); FileSystem fileSys = cluster.getFileSystem(); fileSys.getDelegationToken(""); } finally { if (cluster != null) { cluster.shutdown(); } } } @Test public void testFileSystemCloseAll() throws Exception { Configuration conf = getTestConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0). build(); URI address = FileSystem.getDefaultUri(conf); try { FileSystem.closeAll(); conf = getTestConfiguration(); FileSystem.setDefaultUri(conf, address); FileSystem.get(conf); FileSystem.get(conf); FileSystem.closeAll(); } finally { if (cluster != null) {cluster.shutdown();} } } /** * Tests DFSClient.close throws no ConcurrentModificationException if * multiple files are open. * Also tests that any cached sockets are closed. (HDFS-3359) */ @Test public void testDFSClose() throws Exception { Configuration conf = getTestConfiguration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); DistributedFileSystem fileSys = cluster.getFileSystem(); // create two files, leaving them open fileSys.create(new Path("/test/dfsclose/file-0")); fileSys.create(new Path("/test/dfsclose/file-1")); // create another file, close it, and read it, so // the client gets a socket in its SocketCache Path p = new Path("/non-empty-file"); DFSTestUtil.createFile(fileSys, p, 1L, (short)1, 0L); DFSTestUtil.readFile(fileSys, p); fileSys.close(); DFSClient dfsClient = fileSys.getClient(); verifyOpsUsingClosedClient(dfsClient); } finally { if (cluster != null) {cluster.shutdown();} } } private void verifyOpsUsingClosedClient(DFSClient dfsClient) { Path p = new Path("/non-empty-file"); try { dfsClient.getBlockSize(p.getName()); fail("getBlockSize using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.getServerDefaults(); fail("getServerDefaults using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.reportBadBlocks(new LocatedBlock[0]); fail("reportBadBlocks using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.getBlockLocations(p.getName(), 0, 1); fail("getBlockLocations using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.createSymlink("target", "link", true); fail("createSymlink using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.getLinkTarget(p.getName()); fail("getLinkTarget using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.setReplication(p.getName(), (short) 3); fail("setReplication using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.setStoragePolicy(p.getName(), HdfsConstants.ONESSD_STORAGE_POLICY_NAME); fail("setStoragePolicy using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.getStoragePolicies(); fail("getStoragePolicies using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.setSafeMode(SafeModeAction.SAFEMODE_LEAVE); fail("setSafeMode using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.refreshNodes(); fail("refreshNodes using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.metaSave(p.getName()); fail("metaSave using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.setBalancerBandwidth(1000L); fail("setBalancerBandwidth using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.finalizeUpgrade(); fail("finalizeUpgrade using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.rollingUpgrade(RollingUpgradeAction.QUERY); fail("rollingUpgrade using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.getInotifyEventStream(); fail("getInotifyEventStream using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.getInotifyEventStream(100L); fail("getInotifyEventStream using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.saveNamespace(1000L, 200L); fail("saveNamespace using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.rollEdits(); fail("rollEdits using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.restoreFailedStorage(""); fail("restoreFailedStorage using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.getContentSummary(p.getName()); fail("getContentSummary using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.setQuota(p.getName(), 1000L, 500L); fail("setQuota using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } try { dfsClient.setQuotaByStorageType(p.getName(), StorageType.DISK, 500L); fail("setQuotaByStorageType using a closed filesystem!"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains("Filesystem closed", ioe); } } @Test public void testDFSCloseOrdering() throws Exception { DistributedFileSystem fs = new MyDistributedFileSystem(); Path path = new Path("/a"); fs.deleteOnExit(path); fs.close(); InOrder inOrder = inOrder(fs.dfs); inOrder.verify(fs.dfs).closeOutputStreams(eq(false)); inOrder.verify(fs.dfs).delete(eq(path.toString()), eq(true)); inOrder.verify(fs.dfs).close(); } private static class MyDistributedFileSystem extends DistributedFileSystem { MyDistributedFileSystem() { statistics = new FileSystem.Statistics("myhdfs"); // can't mock finals dfs = mock(DFSClient.class); } @Override public boolean exists(Path p) { return true; // trick out deleteOnExit } // Symlink resolution doesn't work with a mock, since it doesn't // have a valid Configuration to resolve paths to the right FileSystem. // Just call the DFSClient directly to register the delete @Override public boolean delete(Path f, final boolean recursive) throws IOException { return dfs.delete(f.toUri().getPath(), recursive); } } @Test public void testDFSSeekExceptions() throws IOException { Configuration conf = getTestConfiguration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); FileSystem fileSys = cluster.getFileSystem(); String file = "/test/fileclosethenseek/file-0"; Path path = new Path(file); // create file FSDataOutputStream output = fileSys.create(path); output.writeBytes("Some test data to write longer than 10 bytes"); output.close(); FSDataInputStream input = fileSys.open(path); input.seek(10); boolean threw = false; try { input.seek(100); } catch (IOException e) { // success threw = true; } assertTrue("Failed to throw IOE when seeking past end", threw); input.close(); threw = false; try { input.seek(1); } catch (IOException e) { //success threw = true; } assertTrue("Failed to throw IOE when seeking after close", threw); fileSys.close(); } finally { if (cluster != null) {cluster.shutdown();} } } @Test public void testDFSClient() throws Exception { Configuration conf = getTestConfiguration(); final long grace = 1000L; MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); final String filepathstring = "/test/LeaseChecker/foo"; final Path[] filepaths = new Path[4]; for(int i = 0; i < filepaths.length; i++) { filepaths[i] = new Path(filepathstring + i); } final long millis = Time.now(); { final DistributedFileSystem dfs = cluster.getFileSystem(); Method setMethod = dfs.dfs.getLeaseRenewer().getClass() .getDeclaredMethod("setGraceSleepPeriod", long.class); setMethod.setAccessible(true); setMethod.invoke(dfs.dfs.getLeaseRenewer(), grace); Method checkMethod = dfs.dfs.getLeaseRenewer().getClass() .getDeclaredMethod("isRunning"); checkMethod.setAccessible(true); assertFalse((boolean) checkMethod.invoke(dfs.dfs.getLeaseRenewer())); { //create a file final FSDataOutputStream out = dfs.create(filepaths[0]); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //write something out.writeLong(millis); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //close out.close(); Thread.sleep(grace/4*3); //within grace period assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); for(int i = 0; i < 3; i++) { if ((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())) { Thread.sleep(grace/2); } } //passed grace period assertFalse((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); } { //create file1 final FSDataOutputStream out1 = dfs.create(filepaths[1]); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //create file2 final FSDataOutputStream out2 = dfs.create(filepaths[2]); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //write something to file1 out1.writeLong(millis); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //close file1 out1.close(); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //write something to file2 out2.writeLong(millis); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //close file2 out2.close(); Thread.sleep(grace/4*3); //within grace period assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); } { //create file3 final FSDataOutputStream out3 = dfs.create(filepaths[3]); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); Thread.sleep(grace/4*3); //passed previous grace period, should still running assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //write something to file3 out3.writeLong(millis); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //close file3 out3.close(); assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); Thread.sleep(grace/4*3); //within grace period assertTrue((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); for(int i = 0; i < 3; i++) { if ((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())) { Thread.sleep(grace/2); } } //passed grace period assertFalse((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); } dfs.close(); } { // Check to see if opening a non-existent file triggers a FNF FileSystem fs = cluster.getFileSystem(); Path dir = new Path("/wrwelkj"); assertFalse("File should not exist for test.", fs.exists(dir)); try { FSDataInputStream in = fs.open(dir); try { in.close(); fs.close(); } finally { assertTrue("Did not get a FileNotFoundException for non-existing" + " file.", false); } } catch (FileNotFoundException fnf) { // This is the proper exception to catch; move on. } } { final DistributedFileSystem dfs = cluster.getFileSystem(); Method checkMethod = dfs.dfs.getLeaseRenewer().getClass() .getDeclaredMethod("isRunning"); checkMethod.setAccessible(true); assertFalse((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); //open and check the file FSDataInputStream in = dfs.open(filepaths[0]); assertFalse((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); assertEquals(millis, in.readLong()); assertFalse((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); in.close(); assertFalse((boolean)checkMethod.invoke(dfs.dfs.getLeaseRenewer())); dfs.close(); } { // test accessing DFS with ip address. should work with any hostname // alias or ip address that points to the interface that NameNode // is listening on. In this case, it is localhost. String uri = "hdfs://127.0.0.1:" + cluster.getNameNodePort() + "/test/ipAddress/file"; Path path = new Path(uri); FileSystem fs = FileSystem.get(path.toUri(), conf); FSDataOutputStream out = fs.create(path); byte[] buf = new byte[1024]; out.write(buf); out.close(); FSDataInputStream in = fs.open(path); in.readFully(buf); in.close(); fs.close(); } } finally { if (cluster != null) {cluster.shutdown();} } } @Test public void testStatistics() throws Exception { int lsLimit = 2; final Configuration conf = getTestConfiguration(); conf.setInt(DFSConfigKeys.DFS_LIST_LIMIT, lsLimit); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); try { final FileSystem fs = cluster.getFileSystem(); Path dir = new Path("/test"); Path file = new Path(dir, "file"); int readOps = DFSTestUtil.getStatistics(fs).getReadOps(); int writeOps = DFSTestUtil.getStatistics(fs).getWriteOps(); int largeReadOps = DFSTestUtil.getStatistics(fs).getLargeReadOps(); fs.mkdirs(dir); checkStatistics(fs, readOps, ++writeOps, largeReadOps); FSDataOutputStream out = fs.create(file, (short)1); out.close(); checkStatistics(fs, readOps, ++writeOps, largeReadOps); FileStatus status = fs.getFileStatus(file); checkStatistics(fs, ++readOps, writeOps, largeReadOps); fs.getFileBlockLocations(file, 0, 0); checkStatistics(fs, ++readOps, writeOps, largeReadOps); fs.getFileBlockLocations(status, 0, 0); checkStatistics(fs, ++readOps, writeOps, largeReadOps); FSDataInputStream in = fs.open(file); in.close(); checkStatistics(fs, ++readOps, writeOps, largeReadOps); fs.setReplication(file, (short)2); checkStatistics(fs, readOps, ++writeOps, largeReadOps); Path file1 = new Path(dir, "file1"); fs.rename(file, file1); checkStatistics(fs, readOps, ++writeOps, largeReadOps); fs.getContentSummary(file1); checkStatistics(fs, ++readOps, writeOps, largeReadOps); // Iterative ls test for (int i = 0; i < 10; i++) { Path p = new Path(dir, Integer.toString(i)); fs.mkdirs(p); FileStatus[] list = fs.listStatus(dir); if (list.length > lsLimit) { // if large directory, then count readOps and largeReadOps by // number times listStatus iterates int iterations = (int)Math.ceil((double)list.length/lsLimit); largeReadOps += iterations; readOps += iterations; } else { // Single iteration in listStatus - no large read operation done readOps++; } // writeOps incremented by 1 for mkdirs // readOps and largeReadOps incremented by 1 or more checkStatistics(fs, readOps, ++writeOps, largeReadOps); } fs.getStatus(file1); checkStatistics(fs, ++readOps, writeOps, largeReadOps); fs.getFileChecksum(file1); checkStatistics(fs, ++readOps, writeOps, largeReadOps); fs.setPermission(file1, new FsPermission((short)0777)); checkStatistics(fs, readOps, ++writeOps, largeReadOps); fs.setTimes(file1, 0L, 0L); checkStatistics(fs, readOps, ++writeOps, largeReadOps); UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); fs.setOwner(file1, ugi.getUserName(), ugi.getGroupNames()[0]); checkStatistics(fs, readOps, ++writeOps, largeReadOps); fs.delete(dir, true); checkStatistics(fs, readOps, ++writeOps, largeReadOps); } finally { if (cluster != null) cluster.shutdown(); } } /** Checks statistics. -1 indicates do not check for the operations */ private void checkStatistics(FileSystem fs, int readOps, int writeOps, int largeReadOps) { assertEquals(readOps, DFSTestUtil.getStatistics(fs).getReadOps()); assertEquals(writeOps, DFSTestUtil.getStatistics(fs).getWriteOps()); assertEquals(largeReadOps, DFSTestUtil.getStatistics(fs).getLargeReadOps()); } @Test public void testFileChecksum() throws Exception { final long seed = RAN.nextLong(); System.out.println("seed=" + seed); RAN.setSeed(seed); final Configuration conf = getTestConfiguration(); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(2).build(); final FileSystem hdfs = cluster.getFileSystem(); final String nnAddr = conf.get(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY); final UserGroupInformation current = UserGroupInformation.getCurrentUser(); final UserGroupInformation ugi = UserGroupInformation.createUserForTesting( current.getShortUserName() + "x", new String[]{"user"}); try { hdfs.getFileChecksum(new Path( "/test/TestNonExistingFile")); fail("Expecting FileNotFoundException"); } catch (FileNotFoundException e) { assertTrue("Not throwing the intended exception message", e.getMessage() .contains("File does not exist: /test/TestNonExistingFile")); } try { Path path = new Path("/test/TestExistingDir/"); hdfs.mkdirs(path); hdfs.getFileChecksum(path); fail("Expecting FileNotFoundException"); } catch (FileNotFoundException e) { assertTrue("Not throwing the intended exception message", e.getMessage() .contains("Path is not a file: /test/TestExistingDir")); } //webhdfs final String webhdfsuri = WebHdfsConstants.WEBHDFS_SCHEME + "://" + nnAddr; System.out.println("webhdfsuri=" + webhdfsuri); final FileSystem webhdfs = ugi.doAs( new PrivilegedExceptionAction<FileSystem>() { @Override public FileSystem run() throws Exception { return new Path(webhdfsuri).getFileSystem(conf); } }); final Path dir = new Path("/filechecksum"); final int block_size = 1024; final int buffer_size = conf.getInt( CommonConfigurationKeys.IO_FILE_BUFFER_SIZE_KEY, 4096); conf.setInt(HdfsClientConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, 512); //try different number of blocks for(int n = 0; n < 5; n++) { //generate random data final byte[] data = new byte[RAN.nextInt(block_size/2-1)+n*block_size+1]; RAN.nextBytes(data); System.out.println("data.length=" + data.length); //write data to a file final Path foo = new Path(dir, "foo" + n); { final FSDataOutputStream out = hdfs.create(foo, false, buffer_size, (short)2, block_size); out.write(data); out.close(); } //compute checksum final FileChecksum hdfsfoocs = hdfs.getFileChecksum(foo); System.out.println("hdfsfoocs=" + hdfsfoocs); //webhdfs final FileChecksum webhdfsfoocs = webhdfs.getFileChecksum(foo); System.out.println("webhdfsfoocs=" + webhdfsfoocs); final Path webhdfsqualified = new Path(webhdfsuri + dir, "foo" + n); final FileChecksum webhdfs_qfoocs = webhdfs.getFileChecksum(webhdfsqualified); System.out.println("webhdfs_qfoocs=" + webhdfs_qfoocs); //create a zero byte file final Path zeroByteFile = new Path(dir, "zeroByteFile" + n); { final FSDataOutputStream out = hdfs.create(zeroByteFile, false, buffer_size, (short)2, block_size); out.close(); } // verify the magic val for zero byte files { final FileChecksum zeroChecksum = hdfs.getFileChecksum(zeroByteFile); assertEquals(zeroChecksum.toString(), "MD5-of-0MD5-of-0CRC32:70bc8f4b72a86921468bf8e8441dce51"); } //write another file final Path bar = new Path(dir, "bar" + n); { final FSDataOutputStream out = hdfs.create(bar, false, buffer_size, (short)2, block_size); out.write(data); out.close(); } { //verify checksum final FileChecksum barcs = hdfs.getFileChecksum(bar); final int barhashcode = barcs.hashCode(); assertEquals(hdfsfoocs.hashCode(), barhashcode); assertEquals(hdfsfoocs, barcs); //webhdfs assertEquals(webhdfsfoocs.hashCode(), barhashcode); assertEquals(webhdfsfoocs, barcs); assertEquals(webhdfs_qfoocs.hashCode(), barhashcode); assertEquals(webhdfs_qfoocs, barcs); } hdfs.setPermission(dir, new FsPermission((short)0)); { //test permission error on webhdfs try { webhdfs.getFileChecksum(webhdfsqualified); fail(); } catch(IOException ioe) { FileSystem.LOG.info("GOOD: getting an exception", ioe); } } hdfs.setPermission(dir, new FsPermission((short)0777)); } cluster.shutdown(); } @Test public void testAllWithDualPort() throws Exception { dualPortTesting = true; try { testFileSystemCloseAll(); testDFSClose(); testDFSClient(); testFileChecksum(); } finally { dualPortTesting = false; } } @Test public void testAllWithNoXmlDefaults() throws Exception { // Do all the tests with a configuration that ignores the defaults in // the XML files. noXmlDefaults = true; try { testFileSystemCloseAll(); testDFSClose(); testDFSClient(); testFileChecksum(); } finally { noXmlDefaults = false; } } @Test(timeout=120000) public void testLocatedFileStatusStorageIdsTypes() throws Exception { final Configuration conf = getTestConfiguration(); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(3).build(); try { final DistributedFileSystem fs = cluster.getFileSystem(); final Path testFile = new Path("/testListLocatedStatus"); final int blockSize = 4096; final int numBlocks = 10; // Create a test file final int repl = 2; DFSTestUtil.createFile(fs, testFile, blockSize, numBlocks * blockSize, blockSize, (short) repl, 0xADDED); // Get the listing RemoteIterator<LocatedFileStatus> it = fs.listLocatedStatus(testFile); assertTrue("Expected file to be present", it.hasNext()); LocatedFileStatus stat = it.next(); BlockLocation[] locs = stat.getBlockLocations(); assertEquals("Unexpected number of locations", numBlocks, locs.length); Set<String> dnStorageIds = new HashSet<>(); for (DataNode d : cluster.getDataNodes()) { try (FsDatasetSpi.FsVolumeReferences volumes = d.getFSDataset() .getFsVolumeReferences()) { for (FsVolumeSpi vol : volumes) { dnStorageIds.add(vol.getStorageID()); } } } for (BlockLocation loc : locs) { String[] ids = loc.getStorageIds(); // Run it through a set to deduplicate, since there should be no dupes Set<String> storageIds = new HashSet<>(); Collections.addAll(storageIds, ids); assertEquals("Unexpected num storage ids", repl, storageIds.size()); // Make sure these are all valid storage IDs assertTrue("Unknown storage IDs found!", dnStorageIds.containsAll (storageIds)); // Check storage types are the default, since we didn't set any StorageType[] types = loc.getStorageTypes(); assertEquals("Unexpected num storage types", repl, types.length); for (StorageType t: types) { assertEquals("Unexpected storage type", StorageType.DEFAULT, t); } } } finally { if (cluster != null) { cluster.shutdown(); } } } @Test public void testCreateWithCustomChecksum() throws Exception { Configuration conf = getTestConfiguration(); MiniDFSCluster cluster = null; Path testBasePath = new Path("/test/csum"); // create args Path path1 = new Path(testBasePath, "file_wtih_crc1"); Path path2 = new Path(testBasePath, "file_with_crc2"); ChecksumOpt opt1 = new ChecksumOpt(DataChecksum.Type.CRC32C, 512); ChecksumOpt opt2 = new ChecksumOpt(DataChecksum.Type.CRC32, 512); // common args FsPermission perm = FsPermission.getDefault().applyUMask( FsPermission.getUMask(conf)); EnumSet<CreateFlag> flags = EnumSet.of(CreateFlag.OVERWRITE, CreateFlag.CREATE); short repl = 1; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); FileSystem dfs = cluster.getFileSystem(); dfs.mkdirs(testBasePath); // create two files with different checksum types FSDataOutputStream out1 = dfs.create(path1, perm, flags, 4096, repl, 131072L, null, opt1); FSDataOutputStream out2 = dfs.create(path2, perm, flags, 4096, repl, 131072L, null, opt2); for (int i = 0; i < 1024; i++) { out1.write(i); out2.write(i); } out1.close(); out2.close(); // the two checksums must be different. MD5MD5CRC32FileChecksum sum1 = (MD5MD5CRC32FileChecksum)dfs.getFileChecksum(path1); MD5MD5CRC32FileChecksum sum2 = (MD5MD5CRC32FileChecksum)dfs.getFileChecksum(path2); assertFalse(sum1.equals(sum2)); // check the individual params assertEquals(DataChecksum.Type.CRC32C, sum1.getCrcType()); assertEquals(DataChecksum.Type.CRC32, sum2.getCrcType()); } finally { if (cluster != null) { cluster.getFileSystem().delete(testBasePath, true); cluster.shutdown(); } } } @Test(timeout=60000) public void testFileCloseStatus() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); DistributedFileSystem fs = cluster.getFileSystem(); try { // create a new file. Path file = new Path("/simpleFlush.dat"); FSDataOutputStream output = fs.create(file); // write to file output.writeBytes("Some test data"); output.flush(); assertFalse("File status should be open", fs.isFileClosed(file)); output.close(); assertTrue("File status should be closed", fs.isFileClosed(file)); } finally { cluster.shutdown(); } } @Test(timeout=60000) public void testListFiles() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); try { DistributedFileSystem fs = cluster.getFileSystem(); final Path relative = new Path("relative"); fs.create(new Path(relative, "foo")).close(); final List<LocatedFileStatus> retVal = new ArrayList<>(); final RemoteIterator<LocatedFileStatus> iter = fs.listFiles(relative, true); while (iter.hasNext()) { retVal.add(iter.next()); } System.out.println("retVal = " + retVal); } finally { cluster.shutdown(); } } @Test(timeout=10000) public void testDFSClientPeerReadTimeout() throws IOException { final int timeout = 1000; final Configuration conf = new HdfsConfiguration(); conf.setInt(HdfsClientConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY, timeout); // only need cluster to create a dfs client to get a peer final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); try { cluster.waitActive(); DistributedFileSystem dfs = cluster.getFileSystem(); // use a dummy socket to ensure the read timesout ServerSocket socket = new ServerSocket(0); Peer peer = dfs.getClient().newConnectedPeer( (InetSocketAddress) socket.getLocalSocketAddress(), null, null); long start = Time.now(); try { peer.getInputStream().read(); Assert.fail("read should timeout"); } catch (SocketTimeoutException ste) { long delta = Time.now() - start; Assert.assertTrue("read timedout too soon", delta >= timeout*0.9); Assert.assertTrue("read timedout too late", delta <= timeout*1.1); } catch (Throwable t) { Assert.fail("wrong exception:"+t); } } finally { cluster.shutdown(); } } @Test(timeout=60000) public void testGetServerDefaults() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); try { cluster.waitActive(); DistributedFileSystem dfs = cluster.getFileSystem(); FsServerDefaults fsServerDefaults = dfs.getServerDefaults(); Assert.assertNotNull(fsServerDefaults); } finally { cluster.shutdown(); } } @Test(timeout=10000) public void testDFSClientPeerWriteTimeout() throws IOException { final int timeout = 1000; final Configuration conf = new HdfsConfiguration(); conf.setInt(HdfsClientConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY, timeout); // only need cluster to create a dfs client to get a peer final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); try { cluster.waitActive(); DistributedFileSystem dfs = cluster.getFileSystem(); // Write 10 MB to a dummy socket to ensure the write times out ServerSocket socket = new ServerSocket(0); Peer peer = dfs.getClient().newConnectedPeer( (InetSocketAddress) socket.getLocalSocketAddress(), null, null); long start = Time.now(); try { byte[] buf = new byte[10 * 1024 * 1024]; peer.getOutputStream().write(buf); long delta = Time.now() - start; Assert.fail("write finish in " + delta + " ms" + "but should timedout"); } catch (SocketTimeoutException ste) { long delta = Time.now() - start; Assert.assertTrue("write timedout too soon in " + delta + " ms", delta >= timeout * 0.9); Assert.assertTrue("write timedout too late in " + delta + " ms", delta <= timeout * 1.2); } catch (Throwable t) { Assert.fail("wrong exception:" + t); } } finally { cluster.shutdown(); } } }
package sqldump.etl; import sqldump.etl.esql.ESQL; import sqldump.log.Log; import sqldump.log.PingPong; import java.io.*; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Creates a query from a .sql file, stored on disk */ public class Query { /** * Connection, used for creating the query */ private Connection connection; /** * Logobject for accessing the console */ private Log log; /*** * default constructor * @param con Connection object to database * @param log logobject, access console */ public Query(Connection con, Log log) { this.connection = con; this.log = log; } /** * Gets a resultset by executing the SQL in the specified file * @param sqlFile the file to be executed * @return a ResultSet holding the results from the execution */ public Boolean getDataFromSQLFile(String sqlFile, String outFile) { try { FileReader fr = new FileReader(sqlFile); BufferedReader br = new BufferedReader(fr); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } br.close(); // Removing semi-colon from end of query (if any) // Oracle driver will throw exception if it find ; in end String query = sb.toString().trim(); if(query.endsWith(";")) { query = query.substring(0, query.length() - 1); } return executeQuery(query, outFile); } catch (FileNotFoundException e) { log.error("failed to load file. error: "); e.printStackTrace(); } catch (IOException e) { log.error("failed closing file. error: "); e.printStackTrace(); } return false; } /** * Replaces any ESQL found in query and generates subqueries. This process is repeated * rekursively for all generated subqueries (by calling this function again for every subquery) until * no ESQL is left in the query. * * @param query The query where the ESQL is replaced. This query is exploded to 1 or more subqueries * @return A List of Strings, holding all subqueries */ private List<String> explodeNextESQL(String query) { List<String> explodedQueries = new ArrayList<String>(); query = query.replace("-- $ESQL_","$ESQL_"); query = query.replace("--$ESQL_","$ESQL_"); // replace next $ESQL_ // 1. find instance of $ESQL_ and isolate as string // 2. call the ESQL engine to replace string by result(s) // 3. generate subqueries, by replacing the instance by all results // 1. isolation // locate ESQL Pattern p = Pattern.compile("(\\$ESQL_.*?\\(.*?\\))"); Matcher m = p.matcher(query); String esql = ""; if (m.find()) { // only work first block, leave up rest to // recursion esql = m.group(1); log.info("esql detected: " + esql); } else { log.info("no esql detected, returning..."); explodedQueries.add(query); return explodedQueries; } // 2. call engine List<String> esqlResults = ESQL.applyESQLFunction(esql, log); // 3. generate query for(Integer i = 0; i < esqlResults.size(); ++i) { String subquery = query.replace(esql, esqlResults.get(i)); if(ESQL.containsESQL(subquery)) { explodedQueries.addAll(explodeNextESQL(subquery)); } else { explodedQueries.add(subquery); } } return explodedQueries; } /** * takes on query * - searches for the first instance of an ESQL formula * - evaluates that * - Calls itself again if there is another instance * @param query * @return */ private List<String> explodeFirstESQL(String query) { List<String> returnQueries = new ArrayList<String>(); // locate ESQL Pattern p = Pattern.compile(".*\\-\\-\\s*\\$\\((.*)\\).*"); Matcher m = p.matcher(query); if (m.find()) { if(m.groupCount() == 0) { returnQueries.add(query); } if (m.groupCount() > 0) { String[] blocks = m.group(1).split(",\\s+"); List<String> blockPermutations = new ArrayList<String>(); for(Integer j = 0; j < blocks.length; j++) { String blockValue = blocks[j]; log.info("working block " + blockValue); List<String> tmp = ESQL.applyESQLFunction(blockValue, log); for(Integer blocknum = 0; blocknum < blocks.length; blocknum++) { if (blocknum != j) { } } } if( m.groupCount() > 1) { } } } else { returnQueries.add(query); } return returnQueries; } /** * Generates subqueries * @param query the query as string * @return list with all subqueries */ private List<String> setESQL(String query) { List<String> queries = new ArrayList<String>(); queries = explodeNextESQL(query); List<String> finalInserts = new ArrayList<String>(); log.info("generated " + queries.size() + " sub-queries from evaluating ESQL."); return queries; } /** * Executes the query * @param query The query as string (NOT a file, but the content) * @return a ResultSet holding the results from the execution */ private Boolean executeQuery(String query, String filename) { // generate final queries List<String> queries = setESQL(query); Statement s = null; try { s = this.connection.createStatement(); s.setFetchSize(10000); // leads to major performance improvements } catch (SQLException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); // stack trace as a string log.error("executing query failed. message: " + sw.toString()); log.error("failed to create query. Message:"); e.printStackTrace(); return false; } for(Integer i = 0; i < queries.size(); ++i) { PingPong ping = log.info("executing subquery (" + (i+1) + "/" + queries.size() + "): \n" + queries.get(i) ); ResultSet rsSub = null; try { rsSub = s.executeQuery( queries.get(i) ); Dump.toFile(rsSub, filename, !(i == 0), log); } catch (SQLException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); // stack trace as a string log.error("executing query failed. message: " + sw.toString()); return false; } log.finished(ping); } return true; } }
/* * The MIT License (MIT) * * Copyright (c) 2020 Ziver Koc * * 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 zutil.net.ssdp; import zutil.log.LogUtil; import zutil.net.http.HttpHeader; import zutil.net.http.HttpHeaderParser; import zutil.net.http.HttpPrintStream; import zutil.net.threaded.ThreadedUDPNetwork; import zutil.net.threaded.ThreadedUDPNetworkThread; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.util.HashMap; import java.util.LinkedList; import java.util.logging.Level; import java.util.logging.Logger; import static zutil.net.ssdp.SSDPServer.SSDP_MULTICAST_ADDR; import static zutil.net.ssdp.SSDPServer.SSDP_PORT; /** * An SSDP client class that will request * service information. * * @author Ziver */ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{ private static final Logger logger = LogUtil.getLogger(); public static final String USER_AGENT = "Zutil SSDP Client"; /** Mapping of search targets and list of associated services **/ private HashMap<String, LinkedList<StandardSSDPInfo>> services_st; /** Map of all unique services received **/ private HashMap<String, StandardSSDPInfo> services_usn; private SSDPServiceListener listener; /** * Creates new instance of this class. An UDP * listening socket at the SSDP port. */ public SSDPClient() throws IOException{ super(SSDP_MULTICAST_ADDR, SSDP_PORT); super.setThread(this); services_st = new HashMap<>(); services_usn = new HashMap<>(); } /** * Sends an request for an service * * @param searchTarget is the SearchTarget of the service * * ***** REQUEST: * M-SEARCH * HTTP/1.1 * Host: 239.255.255.250:reservedSSDPport * Man: "ssdp:discover" * ST: ge:fridge * MX: 3 * */ public void requestService(String searchTarget) { requestService(searchTarget, null); } public void requestService(String searchTarget, HashMap<String,String> headers) { try { // Generate an SSDP discover message ByteArrayOutputStream buffer = new ByteArrayOutputStream(); HttpPrintStream http = new HttpPrintStream(buffer, HttpPrintStream.HttpMessageType.REQUEST); http.setRequestType("M-SEARCH"); http.setRequestURL("*"); http.setHeader("Host", SSDP_MULTICAST_ADDR + ":" + SSDP_PORT); http.setHeader("ST", searchTarget); http.setHeader("Man", "\"ssdp:discover\""); http.setHeader("MX", "3"); http.setHeader("USER-AGENT", USER_AGENT); if (headers != null) { for (String key : headers.keySet()) { http.setHeader(key, headers.get(key)); } } logger.log(Level.FINEST, "Sending Multicast: " + http); http.flush(); byte[] data = buffer.toByteArray(); //System.out.println(new String(data) + "****************"); DatagramPacket packet = new DatagramPacket( data, data.length, InetAddress.getByName(SSDP_MULTICAST_ADDR), SSDP_PORT); super.send(packet); http.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Set a listener that will be notified when new services are detected */ public void setListener(SSDPServiceListener listener) { this.listener = listener; } /** * Returns a list of received services by * the given search target. * * @param searchTarget is the search target * @return a list of received services */ public LinkedList<StandardSSDPInfo> getServices(String searchTarget) { if (services_st.get(searchTarget) == null) return new LinkedList<>(); return services_st.get(searchTarget); } /** * Returns the amount of services in the search target * * @param searchTarget is the search target * @return the amount of services cached */ public int getServicesCount(String searchTarget) { if (services_st.containsKey(searchTarget)) { return services_st.get(searchTarget).size(); } return 0; } /** * Returns a service with the given USN. * * @param usn is the unique identifier for a service * @return an service, null if there is no such service */ public StandardSSDPInfo getService(String usn) { return services_usn.get(usn); } /** * Clears all the received information of the services */ public void clearServices() { services_usn.clear(); services_st.clear(); } /** * Clears all services matching the search target */ public void clearServices(String st) { if (services_st.get(st) != null) { for (StandardSSDPInfo service : services_st.get(st)) { services_usn.remove(service.getUSN()); } } } /** * Waits for responses * * ***** RESPONSE; * HTTP/1.1 200 OK * Ext: * Cache-Control: no-cache="Ext", max-age = 5000 * ST: ge:fridge * USN: uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 * Location: http://localhost:80 */ public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) { try { String msg = new String(packet.getData(), packet.getOffset(), packet.getLength()); HttpHeaderParser headerParser = new HttpHeaderParser(msg); HttpHeader header = headerParser.read(); String usn = header.getHeader("USN"); String st = header.getHeader("ST"); StandardSSDPInfo service = null; // Get existing service if (services_usn.containsKey(usn)) { service = services_usn.get(usn); } // Remove service if ("NOTIFY".equals(header.getRequestType()) && "ssdp:byebye".equalsIgnoreCase(header.getHeader("NTS"))) { logger.log(Level.FINER, "Received NOTIFY:byebye (from: " + packet.getAddress() + "): " + header); if (service != null) { services_usn.remove(usn); if (services_st.containsKey(st)) services_st.get(st).remove(service); if (listener != null) listener.serviceLost(service); } } // Existing or new service update else if (header.isResponse() || "NOTIFY".equals(header.getRequestType())) { logger.log(Level.FINER, "Received service update (from: " + packet.getAddress() + "): " + header); boolean newService = false; // Add new service if (service == null) { newService = true; service = new StandardSSDPInfo(); services_usn.put(usn, service); if (!services_st.containsKey(st)) services_st.put(st, new LinkedList<>()); services_st.get(header.getHeader("ST")).add(service); } service.setLocation(header.getHeader("LOCATION")); service.setST(st); service.setUSN(usn); service.setInetAddress(packet.getAddress()); if (header.getHeader("Cache-Control") != null) { service.setExpirationTime( System.currentTimeMillis() + 1000 * getCacheTime(header.getHeader("Cache-Control"))); } service.readHeaders(header); if (listener != null && newService) listener.serviceDiscovered(service); } else { logger.log(Level.FINEST, "Ignored (from: " + packet.getAddress() + "): " + header); } } catch (IOException e) { logger.log(Level.SEVERE, null, e); } } private long getCacheTime(String cache_control) { long ret = 0; HashMap<String,String> tmpMap = new HashMap<>(); HttpHeaderParser.parseHeaderValues(tmpMap, cache_control, ","); if (tmpMap.containsKey("max-age")) ret = Long.parseLong(tmpMap.get("max-age")); return ret; } public interface SSDPServiceListener{ /** * Is called when a new service is discovered. Will only be called once per service. */ void serviceDiscovered(StandardSSDPInfo service); /** * Is called when a service goes down and is not available anymore. */ void serviceLost(StandardSSDPInfo service); } }
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// import gnu.trove.map.TDoubleDoubleMap; import gnu.trove.function.TDoubleFunction; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.iterator.*; import gnu.trove.iterator.hash.*; import gnu.trove.impl.hash.*; import gnu.trove.impl.HashFunctions; import gnu.trove.*; import java.io.*; import java.util.*; /** * An open addressed Map implementation for double keys and double values. * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $ */ public class TDoubleDoubleHashMap extends TDoubleDoubleHash implements TDoubleDoubleMap, Externalizable { static final long serialVersionUID = 1L; /** the values of the map */ protected transient double[] _values; /** * Creates a new <code>TDoubleDoubleHashMap</code> instance with the default * capacity and load factor. */ public TDoubleDoubleHashMap() { super(); } /** * Creates a new <code>TDoubleDoubleHashMap</code> instance with a prime * capacity equal to or greater than <tt>initialCapacity</tt> and * with the default load factor. * * @param initialCapacity an <code>int</code> value */ public TDoubleDoubleHashMap( int initialCapacity ) { super( initialCapacity ); } /** * Creates a new <code>TDoubleDoubleHashMap</code> instance with a prime * capacity equal to or greater than <tt>initialCapacity</tt> and * with the specified load factor. * * @param initialCapacity an <code>int</code> value * @param loadFactor a <code>float</code> value */ public TDoubleDoubleHashMap( int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor ); } /** * Creates a new <code>TDoubleDoubleHashMap</code> instance with a prime * capacity equal to or greater than <tt>initialCapacity</tt> and * with the specified load factor. * * @param initialCapacity an <code>int</code> value * @param loadFactor a <code>float</code> value * @param noEntryKey a <code>double</code> value that represents * <tt>null</tt> for the Key set. * @param noEntryValue a <code>double</code> value that represents * <tt>null</tt> for the Value set. */ public TDoubleDoubleHashMap( int initialCapacity, float loadFactor, double noEntryKey, double noEntryValue ) { super( initialCapacity, loadFactor, noEntryKey, noEntryValue ); } /** * Creates a new <code>TDoubleDoubleHashMap</code> instance containing * all of the entries in the map passed in. * * @param keys a <tt>double</tt> array containing the keys for the matching values. * @param values a <tt>double</tt> array containing the values. */ public TDoubleDoubleHashMap( double[] keys, double[] values ) { super( Math.max( keys.length, values.length ) ); int size = Math.min( keys.length, values.length ); for ( int i = 0; i < size; i++ ) { this.put( keys[i], values[i] ); } } /** * Creates a new <code>TDoubleDoubleHashMap</code> instance containing * all of the entries in the map passed in. * * @param map a <tt>TDoubleDoubleMap</tt> that will be duplicated. */ public TDoubleDoubleHashMap( TDoubleDoubleMap map ) { super( map.size() ); if ( map instanceof TDoubleDoubleHashMap ) { TDoubleDoubleHashMap hashmap = ( TDoubleDoubleHashMap ) map; this._loadFactor = hashmap._loadFactor; this.no_entry_key = hashmap.no_entry_key; this.no_entry_value = hashmap.no_entry_value; //noinspection RedundantCast if ( this.no_entry_key != ( double ) 0 ) { Arrays.fill( _set, this.no_entry_key ); } //noinspection RedundantCast if ( this.no_entry_value != ( double ) 0 ) { Arrays.fill( _values, this.no_entry_value ); } setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); } putAll( map ); } /** * initializes the hashtable to a prime capacity which is at least * <tt>initialCapacity + 1</tt>. * * @param initialCapacity an <code>int</code> value * @return the actual capacity chosen */ protected int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _values = new double[capacity]; return capacity; } /** * rehashes the map to the new capacity. * * @param newCapacity an <code>int</code> value */ /** {@inheritDoc} */ protected void rehash( int newCapacity ) { int oldCapacity = _set.length; double oldKeys[] = _set; double oldVals[] = _values; byte oldStates[] = _states; _set = new double[newCapacity]; _values = new double[newCapacity]; _states = new byte[newCapacity]; for ( int i = oldCapacity; i-- > 0; ) { if( oldStates[i] == FULL ) { double o = oldKeys[i]; int index = insertKey( o ); _values[index] = oldVals[i]; } } } /** {@inheritDoc} */ public double put( double key, double value ) { int index = insertKey( key ); return doPut( key, value, index ); } /** {@inheritDoc} */ public double putIfAbsent( double key, double value ) { int index = insertKey( key ); if (index < 0) return _values[-index - 1]; return doPut( key, value, index ); } private double doPut( double key, double value, int index ) { double previous = no_entry_value; boolean isNewMapping = true; if ( index < 0 ) { index = -index -1; previous = _values[index]; isNewMapping = false; } _values[index] = value; if (isNewMapping) { postInsertHook( consumeFreeSlot ); } return previous; } /** {@inheritDoc} */ public void putAll( Map<? extends Double, ? extends Double> map ) { ensureCapacity( map.size() ); // could optimize this for cases when map instanceof THashMap for ( Map.Entry<? extends Double, ? extends Double> entry : map.entrySet() ) { this.put( entry.getKey().doubleValue(), entry.getValue().doubleValue() ); } } /** {@inheritDoc} */ public void putAll( TDoubleDoubleMap map ) { ensureCapacity( map.size() ); TDoubleDoubleIterator iter = map.iterator(); while ( iter.hasNext() ) { iter.advance(); this.put( iter.key(), iter.value() ); } } /** {@inheritDoc} */ public double get( double key ) { int index = index( key ); return index < 0 ? no_entry_value : _values[index]; } /** {@inheritDoc} */ public void clear() { super.clear(); Arrays.fill( _set, 0, _set.length, no_entry_key ); Arrays.fill( _values, 0, _values.length, no_entry_value ); Arrays.fill( _states, 0, _states.length, FREE ); } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public double remove( double key ) { double prev = no_entry_value; int index = index( key ); if ( index >= 0 ) { prev = _values[index]; removeAt( index ); // clear key,state; adjust size } return prev; } /** {@inheritDoc} */ protected void removeAt( int index ) { _values[index] = no_entry_value; super.removeAt( index ); // clear key, state; adjust size } /** {@inheritDoc} */ public TDoubleSet keySet() { return new TKeyView(); } /** {@inheritDoc} */ public double[] keys() { double[] keys = new double[size()]; if ( keys.length == 0 ) { return keys; // nothing to copy } double[] k = _set; byte[] states = _states; for ( int i = k.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { keys[j++] = k[i]; } } return keys; } /** {@inheritDoc} */ public double[] keys( double[] array ) { int size = size(); if ( size == 0 ) { return array; // nothing to copy } if ( array.length < size ) { array = new double[size]; } double[] keys = _set; byte[] states = _states; for ( int i = keys.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { array[j++] = keys[i]; } } return array; } /** {@inheritDoc} */ public TDoubleCollection valueCollection() { return new TValueView(); } /** {@inheritDoc} */ public double[] values() { double[] vals = new double[size()]; if ( vals.length == 0 ) { return vals; // nothing to copy } double[] v = _values; byte[] states = _states; for ( int i = v.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { vals[j++] = v[i]; } } return vals; } /** {@inheritDoc} */ public double[] values( double[] array ) { int size = size(); if ( size == 0 ) { return array; // nothing to copy } if ( array.length < size ) { array = new double[size]; } double[] v = _values; byte[] states = _states; for ( int i = v.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { array[j++] = v[i]; } } return array; } /** {@inheritDoc} */ public boolean containsValue( double val ) { byte[] states = _states; double[] vals = _values; for ( int i = vals.length; i-- > 0; ) { if ( states[i] == FULL && val == vals[i] ) { return true; } } return false; } /** {@inheritDoc} */ public boolean containsKey( double key ) { return contains( key ); } /** {@inheritDoc} */ public TDoubleDoubleIterator iterator() { return new TDoubleDoubleHashIterator( this ); } /** {@inheritDoc} */ public boolean forEachKey( TDoubleProcedure procedure ) { return forEach( procedure ); } /** {@inheritDoc} */ public boolean forEachValue( TDoubleProcedure procedure ) { byte[] states = _states; double[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( values[i] ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean forEachEntry( TDoubleDoubleProcedure procedure ) { byte[] states = _states; double[] keys = _set; double[] values = _values; for ( int i = keys.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) { return false; } } return true; } /** {@inheritDoc} */ public void transformValues( TDoubleFunction function ) { byte[] states = _states; double[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL ) { values[i] = function.execute( values[i] ); } } } /** {@inheritDoc} */ public boolean retainEntries( TDoubleDoubleProcedure procedure ) { boolean modified = false; byte[] states = _states; double[] keys = _set; double[] values = _values; // Temporarily disable compaction. This is a fix for bug #1738760 tempDisableAutoCompaction(); try { for ( int i = keys.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) { removeAt( i ); modified = true; } } } finally { reenableAutoCompaction( true ); } return modified; } /** {@inheritDoc} */ public boolean increment( double key ) { return adjustValue( key, ( double ) 1 ); } /** {@inheritDoc} */ public boolean adjustValue( double key, double amount ) { int index = index( key ); if (index < 0) { return false; } else { _values[index] += amount; return true; } } /** {@inheritDoc} */ public double adjustOrPutValue( double key, double adjust_amount, double put_amount ) { int index = insertKey( key ); final boolean isNewMapping; final double newValue; if ( index < 0 ) { index = -index -1; newValue = ( _values[index] += adjust_amount ); isNewMapping = false; } else { newValue = ( _values[index] = put_amount ); isNewMapping = true; } byte previousState = _states[index]; if ( isNewMapping ) { postInsertHook(consumeFreeSlot); } return newValue; } /** a view onto the keys of the map. */ protected class TKeyView implements TDoubleSet { /** {@inheritDoc} */ public TDoubleIterator iterator() { return new TDoubleDoubleKeyHashIterator( TDoubleDoubleHashMap.this ); } /** {@inheritDoc} */ public double getNoEntryValue() { return no_entry_key; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public boolean contains( double entry ) { return TDoubleDoubleHashMap.this.contains( entry ); } /** {@inheritDoc} */ public double[] toArray() { return TDoubleDoubleHashMap.this.keys(); } /** {@inheritDoc} */ public double[] toArray( double[] dest ) { return TDoubleDoubleHashMap.this.keys( dest ); } /** * Unsupported when operating upon a Key Set view of a TDoubleDoubleMap * <p/> * {@inheritDoc} */ public boolean add( double entry ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean remove( double entry ) { return no_entry_value != TDoubleDoubleHashMap.this.remove( entry ); } /** {@inheritDoc} */ public boolean containsAll( Collection<?> collection ) { for ( Object element : collection ) { if ( element instanceof Double ) { double ele = ( ( Double ) element ).doubleValue(); if ( ! TDoubleDoubleHashMap.this.containsKey( ele ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( TDoubleCollection collection ) { TDoubleIterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! TDoubleDoubleHashMap.this.containsKey( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( double[] array ) { for ( double element : array ) { if ( ! TDoubleDoubleHashMap.this.contains( element ) ) { return false; } } return true; } /** * Unsupported when operating upon a Key Set view of a TDoubleDoubleMap * <p/> * {@inheritDoc} */ public boolean addAll( Collection<? extends Double> collection ) { throw new UnsupportedOperationException(); } /** * Unsupported when operating upon a Key Set view of a TDoubleDoubleMap * <p/> * {@inheritDoc} */ public boolean addAll( TDoubleCollection collection ) { throw new UnsupportedOperationException(); } /** * Unsupported when operating upon a Key Set view of a TDoubleDoubleMap * <p/> * {@inheritDoc} */ public boolean addAll( double[] array ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection<?> collection ) { boolean modified = false; TDoubleIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( Double.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( TDoubleCollection collection ) { if ( this == collection ) { return false; } boolean modified = false; TDoubleIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( double[] array ) { boolean changed = false; Arrays.sort( array ); double[] set = _set; byte[] states = _states; for ( int i = set.length; i-- > 0; ) { if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection<?> collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof Double ) { double c = ( ( Double ) element ).doubleValue(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( TDoubleCollection collection ) { if ( this == collection ) { clear(); return true; } boolean changed = false; TDoubleIterator iter = collection.iterator(); while ( iter.hasNext() ) { double element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( double[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { TDoubleDoubleHashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( TDoubleProcedure procedure ) { return TDoubleDoubleHashMap.this.forEachKey( procedure ); } @Override public boolean equals( Object other ) { if (! (other instanceof TDoubleSet)) { return false; } final TDoubleSet that = ( TDoubleSet ) other; if ( that.size() != this.size() ) { return false; } for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { if ( ! that.contains( _set[i] ) ) { return false; } } } return true; } @Override public int hashCode() { int hashcode = 0; for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { hashcode += HashFunctions.hash( _set[i] ); } } return hashcode; } @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachKey( new TDoubleProcedure() { private boolean first = true; public boolean execute( double key ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( key ); return true; } } ); buf.append( "}" ); return buf.toString(); } } /** a view onto the values of the map. */ protected class TValueView implements TDoubleCollection { /** {@inheritDoc} */ public TDoubleIterator iterator() { return new TDoubleDoubleValueHashIterator( TDoubleDoubleHashMap.this ); } /** {@inheritDoc} */ public double getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public boolean contains( double entry ) { return TDoubleDoubleHashMap.this.containsValue( entry ); } /** {@inheritDoc} */ public double[] toArray() { return TDoubleDoubleHashMap.this.values(); } /** {@inheritDoc} */ public double[] toArray( double[] dest ) { return TDoubleDoubleHashMap.this.values( dest ); } public boolean add( double entry ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean remove( double entry ) { double[] values = _values; double[] set = _set; for ( int i = values.length; i-- > 0; ) { if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) { removeAt( i ); return true; } } return false; } /** {@inheritDoc} */ public boolean containsAll( Collection<?> collection ) { for ( Object element : collection ) { if ( element instanceof Double ) { double ele = ( ( Double ) element ).doubleValue(); if ( ! TDoubleDoubleHashMap.this.containsValue( ele ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( TDoubleCollection collection ) { TDoubleIterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! TDoubleDoubleHashMap.this.containsValue( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( double[] array ) { for ( double element : array ) { if ( ! TDoubleDoubleHashMap.this.containsValue( element ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean addAll( Collection<? extends Double> collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( TDoubleCollection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( double[] array ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection<?> collection ) { boolean modified = false; TDoubleIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( Double.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( TDoubleCollection collection ) { if ( this == collection ) { return false; } boolean modified = false; TDoubleIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( double[] array ) { boolean changed = false; Arrays.sort( array ); double[] values = _values; byte[] states = _states; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection<?> collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof Double ) { double c = ( ( Double ) element ).doubleValue(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( TDoubleCollection collection ) { if ( this == collection ) { clear(); return true; } boolean changed = false; TDoubleIterator iter = collection.iterator(); while ( iter.hasNext() ) { double element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( double[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { TDoubleDoubleHashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( TDoubleProcedure procedure ) { return TDoubleDoubleHashMap.this.forEachValue( procedure ); } /** {@inheritDoc} */ @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachValue( new TDoubleProcedure() { private boolean first = true; public boolean execute( double value ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( value ); return true; } } ); buf.append( "}" ); return buf.toString(); } } class TDoubleDoubleKeyHashIterator extends THashPrimitiveIterator implements TDoubleIterator { /** * Creates an iterator over the specified map * * @param hash the <tt>TPrimitiveHash</tt> we will be iterating over. */ TDoubleDoubleKeyHashIterator( TPrimitiveHash hash ) { super( hash ); } /** {@inheritDoc} */ public double next() { moveToNextIndex(); return _set[_index]; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.tempDisableAutoCompaction(); TDoubleDoubleHashMap.this.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } } class TDoubleDoubleValueHashIterator extends THashPrimitiveIterator implements TDoubleIterator { /** * Creates an iterator over the specified map * * @param hash the <tt>TPrimitiveHash</tt> we will be iterating over. */ TDoubleDoubleValueHashIterator( TPrimitiveHash hash ) { super( hash ); } /** {@inheritDoc} */ public double next() { moveToNextIndex(); return _values[_index]; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.tempDisableAutoCompaction(); TDoubleDoubleHashMap.this.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } } class TDoubleDoubleHashIterator extends THashPrimitiveIterator implements TDoubleDoubleIterator { /** * Creates an iterator over the specified map * * @param map the <tt>TDoubleDoubleHashMap</tt> we will be iterating over. */ TDoubleDoubleHashIterator( TDoubleDoubleHashMap map ) { super( map ); } /** {@inheritDoc} */ public void advance() { moveToNextIndex(); } /** {@inheritDoc} */ public double key() { return _set[_index]; } /** {@inheritDoc} */ public double value() { return _values[_index]; } /** {@inheritDoc} */ public double setValue( double val ) { double old = value(); _values[_index] = val; return old; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.tempDisableAutoCompaction(); TDoubleDoubleHashMap.this.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } } /** {@inheritDoc} */ @Override public boolean equals( Object other ) { if ( ! ( other instanceof TDoubleDoubleMap ) ) { return false; } TDoubleDoubleMap that = ( TDoubleDoubleMap ) other; if ( that.size() != this.size() ) { return false; } double[] values = _values; byte[] states = _states; double this_no_entry_value = getNoEntryValue(); double that_no_entry_value = that.getNoEntryValue(); for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL ) { double key = _set[i]; double that_value = that.get( key ); double this_value = values[i]; if ( ( this_value != that_value ) && ( this_value != this_no_entry_value ) && ( that_value != that_no_entry_value ) ) { return false; } } } return true; } /** {@inheritDoc} */ @Override public int hashCode() { int hashcode = 0; byte[] states = _states; for ( int i = _values.length; i-- > 0; ) { if ( states[i] == FULL ) { hashcode += HashFunctions.hash( _set[i] ) ^ HashFunctions.hash( _values[i] ); } } return hashcode; } /** {@inheritDoc} */ @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachEntry( new TDoubleDoubleProcedure() { private boolean first = true; public boolean execute( double key, double value ) { if ( first ) first = false; else buf.append( ", " ); buf.append(key); buf.append("="); buf.append(value); return true; } }); buf.append( "}" ); return buf.toString(); } /** {@inheritDoc} */ public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte( 0 ); // SUPER super.writeExternal( out ); // NUMBER OF ENTRIES out.writeInt( _size ); // ENTRIES for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { out.writeDouble( _set[i] ); out.writeDouble( _values[i] ); } } } /** {@inheritDoc} */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SUPER super.readExternal( in ); // NUMBER OF ENTRIES int size = in.readInt(); setUp( size ); // ENTRIES while (size-- > 0) { double key = in.readDouble(); double val = in.readDouble(); put(key, val); } } } // TDoubleDoubleHashMap
// ================================================================================================= // ADOBE SYSTEMS INCORPORATED // Copyright 2006 Adobe Systems Incorporated // All Rights Reserved // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms // of the Adobe license agreement accompanying it. // ================================================================================================= package com.adobe.xmp.impl; import com.adobe.xmp.XMPConst; /** * Utility functions for the XMPToolkit implementation. * * @since 06.06.2006 */ public class Utils implements XMPConst { /** segments of a UUID */ public static final int UUID_SEGMENT_COUNT = 4; /** length of a UUID */ public static final int UUID_LENGTH = 32 + UUID_SEGMENT_COUNT; /** table of XML name start chars (<= 0xFF) */ private static boolean[] xmlNameStartChars; /** table of XML name chars (<= 0xFF) */ private static boolean[] xmlNameChars; /** init char tables */ static { initCharTables(); } /** * Private constructor */ private Utils() { // EMPTY } /** * Normalize an xml:lang value so that comparisons are effectively case * insensitive as required by RFC 3066 (which superceeds RFC 1766). The * normalization rules: * <ul> * <li> The primary subtag is lower case, the suggested practice of ISO 639. * <li> All 2 letter secondary subtags are upper case, the suggested * practice of ISO 3166. * <li> All other subtags are lower case. * </ul> * * @param value * raw value * @return Returns the normalized value. */ public static String normalizeLangValue(String value) { // don't normalize x-default if (XMPConst.X_DEFAULT.equals(value)) { return value; } int subTag = 1; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < value.length(); i++) { switch (value.charAt(i)) { case '-': case '_': // move to next subtag and convert underscore to hyphen buffer.append('-'); subTag++; break; case ' ': // remove spaces break; default: // convert second subtag to uppercase, all other to lowercase if (subTag != 2) { buffer.append(Character.toLowerCase(value.charAt(i))); } else { buffer.append(Character.toUpperCase(value.charAt(i))); } } } return buffer.toString(); } /** * Split the name and value parts for field and qualifier selectors: * <ul> * <li>[qualName="value"] - An element in an array of structs, chosen by a * field value. * <li>[?qualName="value"] - An element in an array, chosen by a qualifier * value. * </ul> * The value portion is a string quoted by ''' or '"'. The value may contain * any character including a doubled quoting character. The value may be * empty. <em>Note:</em> It is assumed that the expression is formal * correct * * @param selector * the selector * @return Returns an array where the first entry contains the name and the * second the value. */ static String[] splitNameAndValue(String selector) { // get the name int eq = selector.indexOf('='); int pos = 1; if (selector.charAt(pos) == '?') { pos++; } String name = selector.substring(pos, eq); // get the value pos = eq + 1; char quote = selector.charAt(pos); pos++; int end = selector.length() - 2; // quote and ] StringBuffer value = new StringBuffer(end - eq); while (pos < end) { value.append(selector.charAt(pos)); pos++; if (selector.charAt(pos) == quote) { // skip one quote in value pos++; } } return new String[] { name, value.toString() }; } /** * * @param schema * a schema namespace * @param prop * an XMP Property * @return Returns true if the property is defined as &quot;Internal * Property&quot;, see XMP Specification. */ static boolean isInternalProperty(String schema, String prop) { boolean isInternal = false; if (NS_DC.equals(schema)) { if ("dc:format".equals(prop) || "dc:language".equals(prop)) { isInternal = true; } } else if (NS_XMP.equals(schema)) { if ("xmp:BaseURL".equals(prop) || "xmp:CreatorTool".equals(prop) || "xmp:Format".equals(prop) || "xmp:Locale".equals(prop) || "xmp:MetadataDate".equals(prop) || "xmp:ModifyDate".equals(prop)) { isInternal = true; } } else if (NS_PDF.equals(schema)) { if ("pdf:BaseURL".equals(prop) || "pdf:Creator".equals(prop) || "pdf:ModDate".equals(prop) || "pdf:PDFVersion".equals(prop) || "pdf:Producer".equals(prop)) { isInternal = true; } } else if (NS_TIFF.equals(schema)) { isInternal = true; if ("tiff:ImageDescription".equals(prop) || "tiff:Artist".equals(prop) || "tiff:Copyright".equals(prop)) { isInternal = false; } } else if (NS_EXIF.equals(schema)) { isInternal = true; if ("exif:UserComment".equals(prop)) { isInternal = false; } } else if (NS_EXIF_AUX.equals(schema)) { isInternal = true; } else if (NS_PHOTOSHOP.equals(schema)) { if ("photoshop:ICCProfile".equals(prop)) { isInternal = true; } } else if (NS_CAMERARAW.equals(schema)) { if ("crs:Version".equals(prop) || "crs:RawFileName".equals(prop) || "crs:ToneCurveName".equals(prop)) { isInternal = true; } } else if (NS_ADOBESTOCKPHOTO.equals(schema)) { isInternal = true; } else if (NS_XMP_MM.equals(schema)) { isInternal = true; } else if (TYPE_TEXT.equals(schema)) { isInternal = true; } else if (TYPE_PAGEDFILE.equals(schema)) { isInternal = true; } else if (TYPE_GRAPHICS.equals(schema)) { isInternal = true; } else if (TYPE_IMAGE.equals(schema)) { isInternal = true; } else if (TYPE_FONT.equals(schema)) { isInternal = true; } return isInternal; } /** * Check some requirements for an UUID: * <ul> * <li>Length of the UUID is 32</li> * <li>The Delimiter count is 4 and all the 4 delimiter are on their right * position (8,13,18,23)</li> * </ul> * * * @param uuid uuid to test * @return true - this is a well formed UUID, false - UUID has not the expected format */ static boolean checkUUIDFormat(String uuid) { boolean result = true; int delimCnt = 0; int delimPos = 0; if (uuid == null) { return false; } for (delimPos = 0; delimPos < uuid.length(); delimPos++) { if (uuid.charAt(delimPos) == '-') { delimCnt++; result = result && (delimPos == 8 || delimPos == 13 || delimPos == 18 || delimPos == 23); } } return result && UUID_SEGMENT_COUNT == delimCnt && UUID_LENGTH == delimPos; } /** * Simple check for valid XMLNames. Within ASCII range<br> * ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6]<br> * are accepted, above all characters (which is not entirely * correct according to the XML Spec. * * @param name an XML Name * @return Return <code>true</code> if the name is correct. */ public static boolean isXMLName(String name) { if (name.length() > 0 && !isNameStartChar(name.charAt(0))) { return false; } for (int i = 1; i < name.length(); i++) { if (!isNameChar(name.charAt(i))) { return false; } } return true; } /** * Checks if the value is a legal "unqualified" XML name, as * defined in the XML Namespaces proposed recommendation. * These are XML names, except that they must not contain a colon. * @param name the value to check * @return Returns true if the name is a valid "unqualified" XML name. */ public static boolean isXMLNameNS(String name) { if (name.length() > 0 && (!isNameStartChar(name.charAt(0)) || name.charAt(0) == ':')) { return false; } for (int i = 1; i < name.length(); i++) { if (!isNameChar(name.charAt(i)) || name.charAt(i) == ':') { return false; } } return true; } /** * @param c a char * @return Returns true if the char is an ASCII control char. */ static boolean isControlChar(char c) { return (c <= 0x1F || c == 0x7F) && c != 0x09 && c != 0x0A && c != 0x0D; } /** * Serializes the node value in XML encoding. Its used for tag bodies and * attributes.<br> * <em>Note:</em> The attribute is always limited by quotes, * thats why <code>&amp;apos;</code> is never serialized.<br> * <em>Note:</em> Control chars are written unescaped, but if the user uses others than tab, LF * and CR the resulting XML will become invalid. * @param value a string * @param forAttribute flag if string is attribute value (need to additional escape quotes) * @param escapeWhitespaces Decides if LF, CR and TAB are escaped. * @return Returns the value ready for XML output. */ public static String escapeXML(String value, boolean forAttribute, boolean escapeWhitespaces) { // quick check if character are contained that need special treatment boolean needsEscaping = false; for (int i = 0; i < value.length (); i++) { char c = value.charAt (i); if ( c == '<' || c == '>' || c == '&' || // XML chars (escapeWhitespaces && (c == '\t' || c == '\n' || c == '\r')) || (forAttribute && c == '"')) { needsEscaping = true; break; } } if (!needsEscaping) { // fast path return value; } else { // slow path with escaping StringBuffer buffer = new StringBuffer(value.length() * 4 / 3); for (int i = 0; i < value.length (); i++) { char c = value.charAt (i); if (!(escapeWhitespaces && (c == '\t' || c == '\n' || c == '\r'))) { switch (c) { // we do what "Canonical XML" expects // AUDIT: &apos; not serialized as only outer qoutes are used case '<': buffer.append("&lt;"); continue; case '>': buffer.append("&gt;"); continue; case '&': buffer.append("&amp;"); continue; case '"': buffer.append(forAttribute ? "&quot;" : "\""); continue; default: buffer.append(c); continue; } } else { // write control chars escaped, // if there are others than tab, LF and CR the xml will become invalid. buffer.append("&#x"); buffer.append(Integer.toHexString(c).toUpperCase()); buffer.append(';'); } } return buffer.toString(); } } /** * Replaces the ASCII control chars with a space. * * @param value * a node value * @return Returns the cleaned up value */ static String removeControlChars(String value) { StringBuffer buffer = new StringBuffer(value); for (int i = 0; i < buffer.length(); i++) { if (isControlChar(buffer.charAt(i))) { buffer.setCharAt(i, ' '); } } return buffer.toString(); } /** * Simple check if a character is a valid XML start name char. * Within ASCII range<br> * ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6]<br> * are accepted, above all characters (which is not entirely * correct according to the XML Spec) * * @param ch a character * @return Returns true if the character is a valid first char of an XML name. */ private static boolean isNameStartChar(char ch) { return ch > 0xFF || xmlNameStartChars[ch]; } /** * Simple check if a character is a valid XML name char * (every char except the first one). * Within ASCII range<br> * ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6]<br> * are accepted, above all characters (which is not entirely * correct according to the XML Spec) * * @param ch a character * @return Returns true if the character is a valid char of an XML name. */ private static boolean isNameChar(char ch) { return ch > 0xFF || xmlNameChars[ch]; } /** * Initializes the char tables for later use. */ private static void initCharTables() { xmlNameChars = new boolean[0x0100]; xmlNameStartChars = new boolean[0x0100]; for (char ch = 0; ch < xmlNameChars.length; ch++) { xmlNameStartChars[ch] = ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ch == ':' || ch == '_' || (0xC0 <= ch && ch <= 0xD6) || (0xD8 <= ch && ch <= 0xF6); xmlNameChars[ch] = ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == ':' || ch == '_' || ch == '-' || ch == '.' || ch == 0xB7 || (0xC0 <= ch && ch <= 0xD6) || (0xD8 <= ch && ch <= 0xF6); } } }
/* # 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 storage; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import objs.CodeDistr; import objs.File; import objs.Review; public class DBStoring { public static void insertCode (String appid, String revid, String title, String review, String codeclass, String refcode, String rawcode) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:mobbs", "mobbs", "mobbs"); Statement s = c.createStatement(); s.execute("insert into Codes (appid, revid, title, review, codeclass, refinedcode, rawcode) values('" + appid + "', '" + revid + "', '" + title + "', '" + review + "', '" + codeclass + "', '" + refcode + "', '" + rawcode + "')"); c.close(); } catch(Exception e) { e.printStackTrace(); } } public static void updateReview(String appid, String revid, String device) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:mobbs", "mobbs", "mobbs"); Statement s = c.createStatement(); s.execute("UPDATE Codes SET device='" + device + "' WHERE appid='" + appid + "' AND revid='" + revid + "'"); c.close(); } catch(Exception e) { e.printStackTrace(); } } public static void insertRev (String appid, String title, String device, String version, String date) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:mobbs", "mobbs", "mobbs"); Statement s = c.createStatement(); s.execute("insert into Revs (appid, title, device, version, date) values('" + appid + "', '" + title + "', '" + device + "', '" + version + "', '" + date + "')"); c.close(); } catch(Exception e) { e.printStackTrace(); } } public static ArrayList<File> getFiles() { ArrayList<File> files = new ArrayList<File>(); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:mobbs", "mobbs", "mobbs"); Statement s = c.createStatement(); ResultSet r = s.executeQuery("SELECT * from Files"); while (r.next()) files.add(new File(r.getString("fileid"), r.getInt("status"))); c.close(); } catch(Exception e) { e.printStackTrace(); } return files; } public static void setFileStatus(String filename, int status) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:mobbs", "mobbs", "mobbs"); Statement s = c.createStatement(); s.executeUpdate("UPDATE Files SET status='" + status + "' WHERE fileid='" + filename + "'"); c.close(); } catch(Exception e) { e.printStackTrace(); } } public static int getFileStatus(String filename) { int status = -2; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:mobbs", "mobbs", "mobbs"); Statement s = c.createStatement(); ResultSet r = s.executeQuery("SELECT status FROM Files WHERE fileid='" + filename + "'"); while (r.next()) status = r.getInt("status"); c.close(); } catch(Exception e) { e.printStackTrace(); } return status; } public static void initialLoadFilestoDB() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:mobbs", "mobbs", "mobbs"); Statement s = c.createStatement(); FileInputStream fstream = new FileInputStream("apps.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { s.execute("INSERT into Files (fileid, status) VALUES('" + strLine + "', '" + 0 + "')"); } in.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } } public static void getAllReview() { ArrayList<String> files = new ArrayList<String>(); ArrayList<Review> revs = new ArrayList<Review>(); try { FileInputStream fstream = new FileInputStream("conf/apps.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) files.add(strLine); //Close the input stream in.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } for (String fileName : files) { try { FileInputStream fstream = new FileInputStream("output/f_" + fileName + ".txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { Review r = new Review(); r.setAppid(fileName); r.setDate(strLine.split("&&&")[0]); r.setRate(strLine.split("&&&")[1]); r.setDevice(strLine.split("&&&")[2]); r.setVersion(strLine.split("&&&")[3]); r.setTitle(strLine.split("&&&")[4]); if (strLine.split("&&&").length == 6) r.setText(strLine.split("&&&")[5]); else r.setText(""); revs.add(r); } in.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.toString()); } } try { FileWriter fstream = new FileWriter("conf/revs.txt"); BufferedWriter out = new BufferedWriter(fstream); for (Review r : revs) { System.out.println(r.getDevice()); out.write(r.getAppid() + " " + r.getTitle() + " "+ r.getDevice() + " " + r.getVersion() + " " + r.getDate()); out.newLine(); } out.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } } public static void main(String[] args) { ArrayList<String> files = new ArrayList<String>(); try { FileInputStream fstream = new FileInputStream("conf/apps.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) files.add(strLine); //Close the input stream in.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } for (String fileName : files) { System.out.println(fileName); try { FileInputStream fstream = new FileInputStream("output/f_" + fileName + ".txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int index = 0; //Read File Line By Line while ((strLine = br.readLine()) != null) { Review r = new Review(); r.setAppid(fileName); r.setDate(strLine.split("&&&")[0]); r.setRate(strLine.split("&&&")[1]); r.setDevice(strLine.split("&&&")[2].replace("'", " ")); r.setVersion(strLine.split("&&&")[3]); r.setTitle(strLine.split("&&&")[4]); if (strLine.split("&&&").length == 6) r.setText(strLine.split("&&&")[5]); else r.setText(""); DBStoring.updateReview(fileName, Integer.toString(index), r.getDevice()); index++; } in.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.toString()); } } } }
package com.miguelgaeta.bootstrap.mg_recycler; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.Setter; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by Miguel Gaeta on 5/2/15. */ public class MGRecyclerDataList<T> { private MGRecyclerData<List<T>> data; private Subscription updateSubscription; @Setter private MGRecyclerData.DataUpdated<List<T>> updated; /** * Convenience class that represents an arbitrary object * list that drives an adapter. * * When new data is provided to this object, the associated * adapter (which should be drive by the list) will * be updated by this helper class which will compute * the minimal notify changed needed. * * A key generator is provided so that a unique * key can be generated for each object in the list. There * should not be any duplicate keys in a given data list. */ public static <T> MGRecyclerDataList<T> create(@NonNull final MGRecyclerAdapter adapter, final List<T> initialData, final Func1<T, String> keyGenerator) { final MGRecyclerDataList<T> dataList = new MGRecyclerDataList<>(); dataList.data = MGRecyclerData.create(initialData, new MGRecyclerData.DataUpdated<List<T>>() { @Override public void updated(final List<T> oldData, final List<T> newData) { if (newData == null ? oldData != null : !newData.equals(oldData)) { // On changes, perform diffing on a computation thread. Observable<AdapterUpdateData> worker = Observable.create(new Observable.OnSubscribe<AdapterUpdateData>() { @Override public void call(final Subscriber<? super AdapterUpdateData> subscriber) { final LinkedHashMap<String, Integer> oldDataIndexes = dataList.generateIndexMap(oldData, keyGenerator); final LinkedHashMap<String, Integer> newDataIndexes = dataList.generateIndexMap(newData, keyGenerator); final List<Integer> indicesChanged = dataList.changeItems(oldDataIndexes, newDataIndexes, oldData, newData); final List<AdapterUpdateData.DataRange> indicesRangeRemoved = dataList.removeItems(oldData, newDataIndexes, keyGenerator); final List<AdapterUpdateData.DataRange> indicesRangeInserted = dataList.insertItems(newData, oldDataIndexes, keyGenerator); subscriber.onNext(AdapterUpdateData.create(indicesChanged, indicesRangeRemoved, indicesRangeInserted)); subscriber.onCompleted(); } }); dataList.unsubscribeFromUpdates(); // Run callbacks and adapter update events on the main thread. dataList.updateSubscription = worker.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<AdapterUpdateData>() { @Override public void call(AdapterUpdateData adapterUpdateData) { // Set new data. dataList.data.set(newData); // Trigger adapter updates. adapterUpdateData.update(adapter); if (dataList.updated != null) { dataList.updated.updated(oldData, newData); } } }); } } }); return dataList; } public void unsubscribeFromUpdates() { if (updateSubscription != null) { updateSubscription.unsubscribe(); updateSubscription = null; } } /** * Triggers a lazy update of the backed * data object. After performing * a diff it may or may not commit the new data. */ public void set(List<T> data) { this.data.update(data); } /** * Grab the current data list. */ public List<T> get() { return data.get(); } /** * Figure out which items were changed in the list. Potentially * someday this function can do a more comprehensive * analysis and do actual item moves instead of just * notifying that the item at index has changed. */ private List<Integer> changeItems(LinkedHashMap<String, Integer> oldDataIndexes, LinkedHashMap<String, Integer> newDataIndexes, List<T> oldData, List<T> newData) { final List<String> keys = new ArrayList<>(oldDataIndexes.keySet()); final List<Integer> changed = new ArrayList<>(); for (int i = 0; i < oldDataIndexes.size(); i++) { String key = keys.get(i); if (newDataIndexes.containsKey(key)) { int oldIndex = oldDataIndexes.get(key); int newIndex = newDataIndexes.get(key); T oldDataItem = oldData.get(oldIndex); T newDataItem = newData.get(newIndex); if (oldDataItem == null ? newDataItem != null : !oldDataItem.equals(newDataItem)) { changed.add(oldIndex); } } } return changed; } /** * Figure out which items were inserted * into the list. */ private List<AdapterUpdateData.DataRange> insertItems(List<T> newData, LinkedHashMap<String, Integer> oldDataIndexes, Func1<T, String> keyGenerator) { List<AdapterUpdateData.DataRange> inserted = new ArrayList<>(); int count = 0; int startIndex = 0; for (int i = 0; i < newData.size(); i++) { if (!oldDataIndexes.containsKey(keyGenerator.call(newData.get(i)))) { if (count == 0) { startIndex = i; } count++; } else if (count > 0) { inserted.add(AdapterUpdateData.DataRange.create(startIndex, count)); count = 0; } } if (count > 0) { inserted.add(AdapterUpdateData.DataRange.create(startIndex, count)); } return inserted; } /** * Figure out which items were removed * from the list of data. */ private List<AdapterUpdateData.DataRange> removeItems(List<T> oldData, LinkedHashMap<String, Integer> newDataIndexes, Func1<T, String> keyGenerator) { List<AdapterUpdateData.DataRange> removed = new ArrayList<>(); int count = 0; int startIndex = 0; int startIndexOffset = 0; for (int i = 0; i < oldData.size(); i++) { if (!newDataIndexes.containsKey(keyGenerator.call(oldData.get(i)))) { if (count == 0) { startIndex = i + startIndexOffset; } count++; } else if (count > 0) { removed.add(AdapterUpdateData.DataRange.create(startIndex, count)); startIndexOffset -= count; count = 0; } } if (count > 0) { removed.add(AdapterUpdateData.DataRange.create(startIndex, count)); } return removed; } /** * Given a list of data and a key generator function. Create * a linked hash map of keys to associated index positions. */ private LinkedHashMap<String, Integer> generateIndexMap(@NonNull List<T> data, Func1<T, String> keyGenerator) { LinkedHashMap<String, Integer> indexMap = new LinkedHashMap<>(); for (int index = 0; index < data.size(); index++) { indexMap.put(keyGenerator.call(data.get(index)), index); } return indexMap; } @AllArgsConstructor(staticName = "create") private static class AdapterUpdateData { @NonNull final List<Integer> indicesChanged; @NonNull final List<DataRange> indicesRangeRemoved; @NonNull final List<DataRange> indicesRangeInserted; public void update(RecyclerView.Adapter adapter) { for (int index : indicesChanged) { adapter.notifyItemChanged(index); } for (DataRange indexWithCount : indicesRangeRemoved) { adapter.notifyItemRangeRemoved(indexWithCount.index, indexWithCount.count); } for (DataRange indexWithCount : indicesRangeInserted) { adapter.notifyItemRangeInserted(indexWithCount.index, indexWithCount.count); } } @AllArgsConstructor(staticName = "create") private static class DataRange { final int index; final int count; } } }
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.support; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanInstantiationException; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.BeanFactory; import org.springframework.cglib.core.SpringNamingPolicy; import org.springframework.cglib.proxy.Callback; import org.springframework.cglib.proxy.CallbackFilter; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.Factory; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import org.springframework.cglib.proxy.NoOp; /** * Default object instantiation strategy for use in BeanFactories. * * <p>Uses CGLIB to generate subclasses dynamically if methods need to be * overridden by the container to implement <em>Method Injection</em>. * * @author Rod Johnson * @author Juergen Hoeller * @author Sam Brannen * @since 1.1 */ public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy { /** * Index in the CGLIB callback array for passthrough behavior, * in which case the subclass won't override the original class. */ private static final int PASSTHROUGH = 0; /** * Index in the CGLIB callback array for a method that should * be overridden to provide <em>method lookup</em>. */ private static final int LOOKUP_OVERRIDE = 1; /** * Index in the CGLIB callback array for a method that should * be overridden using generic <em>method replacer</em> functionality. */ private static final int METHOD_REPLACER = 2; @Override protected Object instantiateWithMethodInjection(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { return instantiateWithMethodInjection(beanDefinition, beanName, owner, null, null); } @Override protected Object instantiateWithMethodInjection(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Constructor<?> ctor, Object[] args) { // Must generate CGLIB subclass. return new CglibSubclassCreator(beanDefinition, owner).instantiate(ctor, args); } /** * An inner class created for historical reasons to avoid external CGLIB dependency * in Spring versions earlier than 3.2. */ private static class CglibSubclassCreator { private static final Class<?>[] CALLBACK_TYPES = new Class<?>[] { NoOp.class, LookupOverrideMethodInterceptor.class, ReplaceOverrideMethodInterceptor.class }; private final RootBeanDefinition beanDefinition; private final BeanFactory owner; CglibSubclassCreator(RootBeanDefinition beanDefinition, BeanFactory owner) { this.beanDefinition = beanDefinition; this.owner = owner; } /** * Create a new instance of a dynamically generated subclass implementing the * required lookups. * @param ctor constructor to use. If this is {@code null}, use the * no-arg constructor (no parameterization, or Setter Injection) * @param args arguments to use for the constructor. * Ignored if the {@code ctor} parameter is {@code null}. * @return new instance of the dynamically generated subclass */ Object instantiate(Constructor<?> ctor, Object[] args) { Class<?> subclass = createEnhancedSubclass(this.beanDefinition); Object instance; if (ctor == null) { instance = BeanUtils.instantiate(subclass); } else { try { Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes()); instance = enhancedSubclassConstructor.newInstance(args); } catch (Exception e) { throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), String.format( "Failed to invoke construcor for CGLIB enhanced subclass [%s]", subclass.getName()), e); } } // SPR-10785: set callbacks directly on the instance instead of in the // enhanced class (via the Enhancer) in order to avoid memory leaks. Factory factory = (Factory) instance; factory.setCallbacks(new Callback[] { NoOp.INSTANCE,// new LookupOverrideMethodInterceptor(beanDefinition, owner),// new ReplaceOverrideMethodInterceptor(beanDefinition, owner) }); return instance; } /** * Create an enhanced subclass of the bean class for the provided bean * definition, using CGLIB. */ private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(beanDefinition.getBeanClass()); enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE); enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition)); enhancer.setCallbackTypes(CALLBACK_TYPES); return enhancer.createClass(); } } /** * Class providing hashCode and equals methods required by CGLIB to * ensure that CGLIB doesn't generate a distinct class per bean. * Identity is based on class and bean definition. */ private static class CglibIdentitySupport { private final RootBeanDefinition beanDefinition; CglibIdentitySupport(RootBeanDefinition beanDefinition) { this.beanDefinition = beanDefinition; } RootBeanDefinition getBeanDefinition() { return this.beanDefinition; } @Override public boolean equals(Object other) { return other.getClass().equals(this.getClass()) && ((CglibIdentitySupport) other).getBeanDefinition().equals(this.getBeanDefinition()); } @Override public int hashCode() { return this.beanDefinition.hashCode(); } } /** * CGLIB callback for filtering method interception behavior. */ private static class MethodOverrideCallbackFilter extends CglibIdentitySupport implements CallbackFilter { private static final Log logger = LogFactory.getLog(MethodOverrideCallbackFilter.class); MethodOverrideCallbackFilter(RootBeanDefinition beanDefinition) { super(beanDefinition); } @Override public int accept(Method method) { MethodOverride methodOverride = getBeanDefinition().getMethodOverrides().getOverride(method); if (logger.isTraceEnabled()) { logger.trace("Override for '" + method.getName() + "' is [" + methodOverride + "]"); } if (methodOverride == null) { return PASSTHROUGH; } else if (methodOverride instanceof LookupOverride) { return LOOKUP_OVERRIDE; } else if (methodOverride instanceof ReplaceOverride) { return METHOD_REPLACER; } throw new UnsupportedOperationException("Unexpected MethodOverride subclass: " + methodOverride.getClass().getName()); } } /** * CGLIB MethodInterceptor to override methods, replacing them with an * implementation that returns a bean looked up in the container. */ private static class LookupOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor { private final BeanFactory owner; LookupOverrideMethodInterceptor(RootBeanDefinition beanDefinition, BeanFactory owner) { super(beanDefinition); this.owner = owner; } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable { // Cast is safe, as CallbackFilter filters are used selectively. LookupOverride lo = (LookupOverride) getBeanDefinition().getMethodOverrides().getOverride(method); return this.owner.getBean(lo.getBeanName()); } } /** * CGLIB MethodInterceptor to override methods, replacing them with a call * to a generic MethodReplacer. */ private static class ReplaceOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor { private final BeanFactory owner; ReplaceOverrideMethodInterceptor(RootBeanDefinition beanDefinition, BeanFactory owner) { super(beanDefinition); this.owner = owner; } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable { ReplaceOverride ro = (ReplaceOverride) getBeanDefinition().getMethodOverrides().getOverride(method); // TODO could cache if a singleton for minor performance optimization MethodReplacer mr = owner.getBean(ro.getMethodReplacerBeanName(), MethodReplacer.class); return mr.reimplement(obj, method, args); } } }
package com.rey.material.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.Typeface; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.AnimationUtils; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import com.rey.material.R; import com.rey.material.util.ColorUtil; import com.rey.material.util.ThemeUtil; import com.rey.material.util.TypefaceUtil; import com.rey.material.util.ViewUtil; /** * Created by Rey on 12/19/2014. */ public class TimePicker extends View{ private int mBackgroundColor; private int mSelectionColor; private int mSelectionRadius; private int mTickSize; private Typeface mTypeface; private int mTextSize; private int mTextColor; private int mTextHighlightColor; private boolean m24Hour = true; private int mAnimDuration; private Interpolator mInInterpolator; private Interpolator mOutInterpolator; private long mStartTime; private float mAnimProgress; private boolean mRunning; private Paint mPaint; private PointF mCenterPoint; private float mOuterRadius; private float mInnerRadius; private float mSecondInnerRadius; private float[] mLocations = new float[72]; private Rect mRect; private static final String[] TICKS = new String[]{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "00", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "00" }; private int mMode = MODE_HOUR; public static final int MODE_HOUR = 0; public static final int MODE_MINUTE = 1; private int mHour = 0; private int mMinute = 0; private boolean mEdited = false; public interface OnTimeChangedListener{ public void onModeChanged(int mode); public void onHourChanged(int oldValue, int newValue); public void onMinuteChanged(int oldValue, int newValue); } private OnTimeChangedListener mOnTimeChangedListener; public TimePicker(Context context) { super(context); init(context, null, 0, 0); } public TimePicker(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0, 0); } public TimePicker(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, 0); } public TimePicker(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, defStyleRes); } private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){ mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mRect = new Rect(); applyStyle(context, attrs, defStyleAttr, defStyleRes); } public void applyStyle(int styleId){ applyStyle(getContext(), null, 0, styleId); } private void applyStyle(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){ TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TimePicker, defStyleAttr, defStyleRes); mBackgroundColor = a.getColor(R.styleable.TimePicker_tp_backgroundColor, ColorUtil.getColor(ThemeUtil.colorPrimary(context, 0xFF000000), 0.25f)); mSelectionColor = a.getColor(R.styleable.TimePicker_tp_selectionColor, ThemeUtil.colorPrimary(context, 0xFF000000)); mSelectionRadius = a.getDimensionPixelOffset(R.styleable.TimePicker_tp_selectionRadius, ThemeUtil.dpToPx(context, 8)); mTickSize = a.getDimensionPixelSize(R.styleable.TimePicker_tp_tickSize, ThemeUtil.dpToPx(context, 1)); mTextSize = a.getDimensionPixelSize(R.styleable.TimePicker_tp_textSize, context.getResources().getDimensionPixelOffset(R.dimen.abc_text_size_caption_material)); mTextColor = a.getColor(R.styleable.TimePicker_tp_textColor, 0xFF000000); mTextHighlightColor = a.getColor(R.styleable.TimePicker_tp_textHighlightColor, 0xFFFFFFFF); mAnimDuration = a.getInteger(R.styleable.TimePicker_tp_animDuration, context.getResources().getInteger(android.R.integer.config_mediumAnimTime)); int resId = a.getResourceId(R.styleable.TimePicker_tp_inInterpolator, 0); mInInterpolator = resId == 0 ? new DecelerateInterpolator() : AnimationUtils.loadInterpolator(context, resId); resId = a.getResourceId(R.styleable.TimePicker_tp_outInterpolator, 0); mOutInterpolator = resId == 0 ? new DecelerateInterpolator() : AnimationUtils.loadInterpolator(context, resId); setMode(a.getInteger(R.styleable.TimePicker_tp_mode, mMode), false); set24Hour(a.getBoolean(R.styleable.TimePicker_tp_24Hour, m24Hour)); setHour(a.getInteger(R.styleable.TimePicker_tp_hour, mHour)); setMinute(a.getInteger(R.styleable.TimePicker_tp_minute, mMinute)); String familyName = a.getString(R.styleable.TimePicker_tp_fontFamily); int style = a.getInteger(R.styleable.TimePicker_tp_textStyle, Typeface.NORMAL); mTypeface = TypefaceUtil.load(context, familyName, style); a.recycle(); } public int getBackgroundColor(){ return mBackgroundColor; } public int getSelectionColor(){ return mSelectionColor; } public Typeface getTypeface(){ return mTypeface; } public int getTextSize(){ return mTextSize; } public int getTextColor(){ return mTextColor; } public int getTextHighlightColor(){ return mTextHighlightColor; } public int getAnimDuration(){ return mAnimDuration; } public Interpolator getInInterpolator(){ return mInInterpolator; } public Interpolator getOutInterpolator(){ return mOutInterpolator; } public int getMode(){ return mMode; } public int getHour(){ return mHour; } public int getMinute(){ return mMinute; } public boolean is24Hour(){ return m24Hour; } public void setMode(int mode, boolean animation){ if(mMode != mode){ mMode = mode; if(mOnTimeChangedListener != null) mOnTimeChangedListener.onModeChanged(mMode); if(animation) startAnimation(); else invalidate(); } } public void setHour(int hour){ if(m24Hour) hour = Math.max(hour, 0) % 24; else hour = Math.max(hour, 0) % 12; if(mHour != hour){ int old = mHour; mHour = hour; if(mOnTimeChangedListener != null) mOnTimeChangedListener.onHourChanged(old, mHour); if(mMode == MODE_HOUR) invalidate(); } } public void setMinute(int minute){ minute = Math.min(Math.max(minute, 0), 59); if(mMinute != minute){ int old = mMinute; mMinute = minute; if(mOnTimeChangedListener != null) mOnTimeChangedListener.onMinuteChanged(old, mMinute); if(mMode == MODE_MINUTE) invalidate(); } } public void setOnTimeChangedListener(OnTimeChangedListener listener){ mOnTimeChangedListener = listener; } public void set24Hour(boolean b){ if(m24Hour != b){ m24Hour = b; if(!m24Hour && mHour > 11) setHour(mHour - 12); calculateTextLocation(); } } private float getAngle(int value, int mode){ switch (mode){ case MODE_HOUR: return (float)(-Math.PI / 2 + Math.PI / 6 * value); case MODE_MINUTE: return (float)(-Math.PI / 2 + Math.PI / 30 * value); default: return 0f; } } private int getSelectedTick(int value, int mode){ switch (mode){ case MODE_HOUR: return value == 0 ? (m24Hour ? 23 : 11) : value - 1; case MODE_MINUTE: if(value % 5 == 0) return (value == 0) ? 35 : (value / 5 + 23); default: return -1; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = (widthMode == MeasureSpec.UNSPECIFIED) ? mSelectionRadius * 12 : MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = (heightMode == MeasureSpec.UNSPECIFIED) ? mSelectionRadius * 12 : MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); int size = Math.min(widthSize, heightSize); int width = (widthMode == MeasureSpec.EXACTLY) ? widthSize : size; int height = (heightMode == MeasureSpec.EXACTLY) ? heightSize : size; setMeasuredDimension(width + getPaddingLeft() + getPaddingRight(), height + getPaddingTop() + getPaddingBottom()); } private void calculateTextLocation(){ if(mCenterPoint == null) return; double step = Math.PI / 6; double angle = -Math.PI / 3; float x, y; mPaint.setTextSize(mTextSize); mPaint.setTypeface(mTypeface); mPaint.setTextAlign(Paint.Align.CENTER); if(m24Hour){ for(int i = 0; i < 12; i++){ mPaint.getTextBounds(TICKS[i], 0, TICKS[i].length(), mRect); if(i == 0) mSecondInnerRadius = mInnerRadius - mSelectionRadius - mRect.height(); x = mCenterPoint.x + (float)Math.cos(angle) * mSecondInnerRadius; y = mCenterPoint.y + (float)Math.sin(angle) * mSecondInnerRadius; mLocations[i * 2] = x; mLocations[i * 2 + 1] = y + mRect.height() / 2f; angle += step; } for(int i = 12; i < TICKS.length; i++){ x = mCenterPoint.x + (float)Math.cos(angle) * mInnerRadius; y = mCenterPoint.y + (float)Math.sin(angle) * mInnerRadius; mPaint.getTextBounds(TICKS[i], 0, TICKS[i].length(), mRect); mLocations[i * 2] = x; mLocations[i * 2 + 1] = y + mRect.height() / 2f; angle += step; } } else{ for(int i = 0; i < 12; i++){ x = mCenterPoint.x + (float)Math.cos(angle) * mInnerRadius; y = mCenterPoint.y + (float)Math.sin(angle) * mInnerRadius; mPaint.getTextBounds(TICKS[i], 0, TICKS[i].length(), mRect); mLocations[i * 2] = x; mLocations[i * 2 + 1] = y + mRect.height() / 2f; angle += step; } for(int i = 24; i < TICKS.length; i++){ x = mCenterPoint.x + (float)Math.cos(angle) * mInnerRadius; y = mCenterPoint.y + (float)Math.sin(angle) * mInnerRadius; mPaint.getTextBounds(TICKS[i], 0, TICKS[i].length(), mRect); mLocations[i * 2] = x; mLocations[i * 2 + 1] = y + mRect.height() / 2f; angle += step; } } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { int left = getPaddingLeft(); int top = getPaddingTop(); int size = Math.min(w - getPaddingLeft() - getPaddingRight(), h - getPaddingTop() - getPaddingBottom()); if(mCenterPoint == null) mCenterPoint = new PointF(); mOuterRadius = size / 2f; mCenterPoint.set(left + mOuterRadius, top + mOuterRadius); mInnerRadius = mOuterRadius - mSelectionRadius - ThemeUtil.dpToPx(getContext(), 4); calculateTextLocation(); } private int getPointedValue(float x, float y, boolean isDown){ float radius = (float) Math.sqrt(Math.pow(x - mCenterPoint.x, 2) + Math.pow(y - mCenterPoint.y, 2)); if(isDown) { if(mMode == MODE_HOUR && m24Hour){ if (radius > mInnerRadius + mSelectionRadius || radius < mSecondInnerRadius - mSelectionRadius) return -1; } else if (radius > mInnerRadius + mSelectionRadius || radius < mInnerRadius - mSelectionRadius) return -1; } float angle = (float)Math.atan2(y - mCenterPoint.y, x - mCenterPoint.x); if(angle < 0) angle += Math.PI * 2; if(mMode == MODE_HOUR){ if(m24Hour){ if(radius > mSecondInnerRadius + mSelectionRadius / 2){ int value = (int) Math.round(angle * 6 / Math.PI) + 15; if(value == 24) return 0; else if(value > 24) return value - 12; else return value; } else{ int value = (int) Math.round(angle * 6 / Math.PI) + 3; return value > 12 ? value - 12 : value; } } else { int value = (int) Math.round(angle * 6 / Math.PI) + 3; return value > 11 ? value - 12 : value; } } else if(mMode == MODE_MINUTE){ int value = (int)Math.round(angle * 30 / Math.PI) + 15; return value > 59 ? value - 60 : value; } return -1; } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: int value = getPointedValue(event.getX(), event.getY(), true); if(value < 0) return false; else if(mMode == MODE_HOUR) setHour(value); else if(mMode == MODE_MINUTE) setMinute(value); mEdited = true; return true; case MotionEvent.ACTION_MOVE: value = getPointedValue(event.getX(), event.getY(), false); if(value < 0) return true; else if(mMode == MODE_HOUR) setHour(value); else if(mMode == MODE_MINUTE) setMinute(value); mEdited = true; return true; case MotionEvent.ACTION_UP: if(mEdited && mMode == MODE_HOUR){ setMode(MODE_MINUTE, true); mEdited = false; return true; } break; case MotionEvent.ACTION_CANCEL: mEdited = false; break; } return false; } @Override public void draw(Canvas canvas) { super.draw(canvas); mPaint.setColor(mBackgroundColor); mPaint.setStyle(Paint.Style.FILL); canvas.drawCircle(mCenterPoint.x, mCenterPoint.y, mOuterRadius, mPaint); if(!mRunning){ float angle; int selectedTick; int start; int length; float radius; if(mMode == MODE_HOUR){ angle = getAngle(mHour, MODE_HOUR); selectedTick = getSelectedTick(mHour, MODE_HOUR); start = 0; length = m24Hour ? 24 : 12; radius = m24Hour && selectedTick < 12 ? mSecondInnerRadius : mInnerRadius; } else{ angle = getAngle(mMinute, MODE_MINUTE); selectedTick = getSelectedTick(mMinute, MODE_MINUTE); start = 24; length = 12; radius = mInnerRadius; } mPaint.setColor(mSelectionColor); float x = mCenterPoint.x + (float)Math.cos(angle) * radius; float y = mCenterPoint.y + (float)Math.sin(angle) * radius; canvas.drawCircle(x, y, mSelectionRadius, mPaint); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(mTickSize); x -= (float)Math.cos(angle) * mSelectionRadius; y -= (float)Math.sin(angle) * mSelectionRadius; canvas.drawLine(mCenterPoint.x, mCenterPoint.y, x, y, mPaint); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(mTextColor); canvas.drawCircle(mCenterPoint.x, mCenterPoint.y, mTickSize * 2, mPaint); mPaint.setTextSize(mTextSize); mPaint.setTypeface(mTypeface); mPaint.setTextAlign(Paint.Align.CENTER); int index; for(int i = 0; i < length; i++) { index = start + i; mPaint.setColor(index == selectedTick ? mTextHighlightColor : mTextColor); canvas.drawText(TICKS[index], mLocations[index * 2], mLocations[index * 2 + 1], mPaint); } } else{ float maxOffset = mOuterRadius - mInnerRadius + mTextSize / 2; int textOutColor = ColorUtil.getColor(mTextColor, 1f - mAnimProgress); int textHighlightOutColor= ColorUtil.getColor(mTextHighlightColor, 1f - mAnimProgress); int textInColor = ColorUtil.getColor(mTextColor, mAnimProgress); int textHighlightInColor= ColorUtil.getColor(mTextHighlightColor, mAnimProgress); float outOffset; float inOffset; float outAngle; float inAngle; int outStart; int inStart; int outLength; int inLength; int outSelectedTick; int inSelectedTick; float outRadius; float inRadius; if(mMode == MODE_MINUTE){ outAngle = getAngle(mHour, MODE_HOUR); inAngle = getAngle(mMinute, MODE_MINUTE); outOffset = mOutInterpolator.getInterpolation(mAnimProgress) * maxOffset; inOffset = (1f - mInInterpolator.getInterpolation(mAnimProgress)) * -maxOffset; outSelectedTick = getSelectedTick(mHour, MODE_HOUR); inSelectedTick = getSelectedTick(mMinute, MODE_MINUTE); outStart = 0; outLength = m24Hour ? 24 : 12; outRadius = m24Hour && outSelectedTick < 12 ? mSecondInnerRadius : mInnerRadius; inStart = 24; inLength = 12; inRadius = mInnerRadius; } else{ outAngle = getAngle(mMinute, MODE_MINUTE); inAngle = getAngle(mHour, MODE_HOUR); outOffset = mOutInterpolator.getInterpolation(mAnimProgress) * -maxOffset; inOffset = (1f - mInInterpolator.getInterpolation(mAnimProgress)) * maxOffset; outSelectedTick = getSelectedTick(mMinute, MODE_MINUTE); inSelectedTick = getSelectedTick(mHour, MODE_HOUR); outStart = 24; outLength = 12; outRadius = mInnerRadius; inStart = 0; inLength = m24Hour ? 24 : 12; inRadius = m24Hour && inSelectedTick < 12 ? mSecondInnerRadius : mInnerRadius; } mPaint.setColor(ColorUtil.getColor(mSelectionColor, 1f - mAnimProgress)); float x = mCenterPoint.x + (float)Math.cos(outAngle) * (outRadius + outOffset); float y = mCenterPoint.y + (float)Math.sin(outAngle) * (outRadius + outOffset); canvas.drawCircle(x, y, mSelectionRadius, mPaint); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(mTickSize); x -= (float)Math.cos(outAngle) * mSelectionRadius; y -= (float)Math.sin(outAngle) * mSelectionRadius; canvas.drawLine(mCenterPoint.x, mCenterPoint.y, x, y, mPaint); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(ColorUtil.getColor(mSelectionColor, mAnimProgress)); x = mCenterPoint.x + (float)Math.cos(inAngle) * (inRadius + inOffset); y = mCenterPoint.y + (float)Math.sin(inAngle) * (inRadius + inOffset); canvas.drawCircle(x, y, mSelectionRadius, mPaint); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(mTickSize); x -= (float)Math.cos(inAngle) * mSelectionRadius; y -= (float)Math.sin(inAngle) * mSelectionRadius; canvas.drawLine(mCenterPoint.x, mCenterPoint.y, x, y, mPaint); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(mTextColor); canvas.drawCircle(mCenterPoint.x, mCenterPoint.y, mTickSize * 2, mPaint); mPaint.setTextSize(mTextSize); mPaint.setTypeface(mTypeface); mPaint.setTextAlign(Paint.Align.CENTER); double step = Math.PI / 6; double angle = -Math.PI / 3; int index; for(int i = 0; i < outLength; i++){ index = i + outStart; x = mLocations[index * 2] + (float)Math.cos(angle) * outOffset; y = mLocations[index * 2 + 1] + (float)Math.sin(angle) * outOffset; mPaint.setColor(index == outSelectedTick ? textHighlightOutColor : textOutColor); canvas.drawText(TICKS[index], x, y, mPaint); angle += step; } for(int i = 0; i < inLength; i++){ index = i + inStart; x = mLocations[index * 2] + (float)Math.cos(angle) * inOffset; y = mLocations[index * 2 + 1] + (float)Math.sin(angle) * inOffset; mPaint.setColor(index == inSelectedTick ? textHighlightInColor : textInColor); canvas.drawText(TICKS[index], x, y, mPaint); angle += step; } } } private void resetAnimation(){ mStartTime = SystemClock.uptimeMillis(); mAnimProgress = 0f; } private void startAnimation() { if(getHandler() != null){ resetAnimation(); mRunning = true; getHandler().postAtTime(mUpdater, SystemClock.uptimeMillis() + ViewUtil.FRAME_DURATION); } invalidate(); } private void stopAnimation() { mRunning = false; getHandler().removeCallbacks(mUpdater); invalidate(); } private final Runnable mUpdater = new Runnable() { @Override public void run() { update(); } }; private void update(){ long curTime = SystemClock.uptimeMillis(); mAnimProgress = Math.min(1f, (float)(curTime - mStartTime) / mAnimDuration); if(mAnimProgress == 1f) stopAnimation(); if(mRunning) getHandler().postAtTime(mUpdater, SystemClock.uptimeMillis() + ViewUtil.FRAME_DURATION); invalidate(); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.mode = mMode; ss.hour = mHour; ss.minute = mMinute; ss.is24Hour = m24Hour; return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); set24Hour(ss.is24Hour); setMode(ss.mode, false); setHour(ss.hour); setMinute(ss.minute); } static class SavedState extends BaseSavedState { int mode; int hour; int minute; boolean is24Hour; /** * Constructor called from {@link Switch#onSaveInstanceState()} */ SavedState(Parcelable superState) { super(superState); } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); mode = in.readInt(); hour = in.readInt(); minute = in.readInt(); is24Hour = in.readInt() == 1; } @Override public void writeToParcel(@NonNull Parcel out, int flags) { super.writeToParcel(out, flags); out.writeValue(mode); out.writeValue(hour); out.writeValue(minute); out.writeValue(is24Hour ? 1 : 0); } @Override public String toString() { return "TimePicker.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " mode=" + mode + " hour=" + hour + " minute=" + minute + "24hour=" + is24Hour + "}"; } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
/** * 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.openejb.cli; import org.apache.xbean.finder.ResourceFinder; import org.apache.openejb.loader.SystemInstance; import org.apache.openejb.util.OpenEjbVersion; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.ParseException; import java.util.ArrayList; import java.util.Locale; import java.util.Properties; import java.util.Enumeration; import java.util.Map; import java.util.List; import java.io.IOException; import java.io.File; import java.io.FileInputStream; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.net.URL; /** * Entry point for ALL things OpenEJB. This will use the new service * architecture explained here: * * @link http://docs.codehaus.org/display/OPENEJB/Executables * * @version $Rev$ $Date$ */ public class MainImpl implements Main { private static final String BASE_PATH = "META-INF/org.apache.openejb.cli/"; private static final String MAIN_CLASS_PROPERTY_NAME = "main.class"; private static ResourceFinder finder = null; private static String locale = ""; private static String descriptionBase = "description"; private static String descriptionI18n; public void main(String[] args) { args = processSystemProperties(args); finder = new ResourceFinder(BASE_PATH); locale = Locale.getDefault().getLanguage(); descriptionI18n = descriptionBase + "." + locale; CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(null, "version", false, ""); options.addOption("h", "help", false, ""); CommandLine line = null; String commandName = null; try { // parse the arguments up until the first // command, then let the rest fall into // the arguments array. line = parser.parse(options, args, true); // Get and remove the commandName (first arg) List<String> list = line.getArgList(); if (list.size() > 0){ commandName = list.get(0); list.remove(0); } // The rest of the args will be passed to the command args = line.getArgs(); } catch (ParseException exp) { exp.printStackTrace(); System.exit(-1); } if (line.hasOption("version")) { OpenEjbVersion.get().print(System.out); System.exit(0); } else if (line.hasOption("help") || commandName == null || commandName.equals("help")) { help(); System.exit(0); } Properties props = null; try { props = finder.findProperties(commandName); } catch (IOException e1) { System.out.println("Unavailable command: " + commandName); help(false); System.exit(1); } if (props == null) { System.out.println("Unavailable command: " + commandName); help(false); System.exit(1); } // Shift the command name itself off the args list String mainClass = props.getProperty(MAIN_CLASS_PROPERTY_NAME); if (mainClass == null) { throw new NullPointerException("Command " + commandName + " did not specify a " + MAIN_CLASS_PROPERTY_NAME + " property"); } Class<?> clazz = null; try { clazz = Thread.currentThread().getContextClassLoader().loadClass(mainClass); } catch (ClassNotFoundException cnfe) { throw new IllegalStateException("Main class of command " + commandName + " does not exist: " + mainClass, cnfe); } Method mainMethod = null; try { mainMethod = clazz.getMethod("main", String[].class); } catch (Exception e) { throw new IllegalStateException("Main class of command " + commandName + " does not have a static main method: " + mainClass, e); } try { // WARNING, Definitely do *not* unwrap 'new Object[]{args}' to 'args' mainMethod.invoke(clazz, new Object[]{args}); } catch (Throwable e) { e.printStackTrace(); System.exit(-10); } } private String[] processSystemProperties(String[] args) { ArrayList<String> argsList = new ArrayList<String>(); // We have to pre-screen for openejb.base as it has a direct affect // on where we look for the conf/system.properties file which we // need to read in and apply before we apply the command line -D // properties. Once SystemInstance.init() is called in the next // section of code, the openejb.base value is cemented and cannot // be changed. for (String arg : args) { if (arg.indexOf("-Dopenejb.base") != -1) { String prop = arg.substring(arg.indexOf("-D") + 2, arg.indexOf("=")); String val = arg.substring(arg.indexOf("=") + 1); System.setProperty(prop, val); } } // get SystemInstance (the only static class in the system) // so we'll set up all the props in it SystemInstance systemInstance = null; try { SystemInstance.init(System.getProperties()); systemInstance = SystemInstance.get(); } catch (Exception e) { e.printStackTrace(); System.exit(2); } // Read in and apply the conf/system.properties try { File conf = systemInstance.getBase().getDirectory("conf"); File file = new File(conf, "system.properties"); if (file.exists()){ Properties systemProperties = new Properties(); FileInputStream fin = new FileInputStream(file); InputStream in = new BufferedInputStream(fin); systemProperties.load(in); System.getProperties().putAll(systemProperties); } } catch (IOException e) { System.out.println("Processing conf/system.properties failed: "+e.getMessage()); } // Now read in and apply the properties specified on the command line for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.indexOf("-D") != -1) { String prop = arg.substring(arg.indexOf("-D") + 2, arg.indexOf("=")); String val = arg.substring(arg.indexOf("=") + 1); System.setProperty(prop, val); } else { argsList.add(arg); } } args = (String[]) argsList.toArray(new String[argsList.size()]); return args; } //DMB: TODO: Delete me public static Enumeration<URL> doFindCommands() throws IOException { return Thread.currentThread().getContextClassLoader().getResources(BASE_PATH); } private static void help() { help(true); } private static void help(boolean printHeader) { // Here we are using commons-cli to create the list of available commands // We actually use a different Options object to parse the 'openejb' command try { Options options = new Options(); ResourceFinder commandFinder = new ResourceFinder("META-INF"); Map<String, Properties> commands = commandFinder.mapAvailableProperties("org.apache.openejb.cli"); for (Map.Entry<String, Properties> command : commands.entrySet()) { if (command.getKey().contains(".")) continue; Properties p = command.getValue(); String description = p.getProperty(descriptionI18n, p.getProperty(descriptionBase)); options.addOption(command.getKey(), false, description); } HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String syntax = "openejb <command> [options] [args]"; String header = "\nAvailable commands:"; String footer = "\n" + "Try 'openejb <command> --help' for help on a specific command.\n" + "For example 'openejb deploy --help'.\n" + "\n" + "Apache OpenEJB -- EJB Container System and Server.\n" + "For additional information, see http://openejb.apache.org\n" + "Bug Reports to <users@openejb.apache.org>"; if (!printHeader){ pw.append(header).append("\n\n"); formatter.printOptions(pw, 74, options, 1, 3); } else { formatter.printHelp(pw, 74, syntax, header, options, 1, 3, footer, false); } pw.flush(); // Fix up the commons-cli output to our liking. String text = sw.toString().replaceAll("\n -", "\n "); text = text.replace("\nApache OpenEJB","\n\nApache OpenEJB"); System.out.print(text); } catch (IOException e) { e.printStackTrace(); } } }
package cn.garymb.ygomobile.fragment; import java.util.List; import com.avast.android.dialogs.core.BaseDialogBuilder; import com.avast.android.dialogs.fragment.SimpleDialogFragment; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnShowListener; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; import cn.garymb.ygodata.YGOGameOptions; import cn.garymb.ygomobile.R; import cn.garymb.ygomobile.YGOMobileActivity; import cn.garymb.ygomobile.core.Controller; import cn.garymb.ygomobile.model.Model; import cn.garymb.ygomobile.model.data.ResourcesConstants; import cn.garymb.ygomobile.widget.AppUpdateController; import cn.garymb.ygomobile.widget.BaseDialogConfigController; import cn.garymb.ygomobile.widget.DialogConfigUIBase; import cn.garymb.ygomobile.widget.DonateDialogConfigController; import cn.garymb.ygomobile.widget.GridSelectionDialogController; import cn.garymb.ygomobile.widget.RangeDialogConfigController; import cn.garymb.ygomobile.widget.RoomDialogConfigController; import cn.garymb.ygomobile.widget.ServerDialogController; import cn.garymb.ygomobile.ygo.YGOServerInfo; public class CustomDialogFragment extends SimpleDialogFragment implements OnClickListener, ResourcesConstants, OnTouchListener, OnShowListener { public class SimpleDialogConfigUiBase implements DialogConfigUIBase { private Builder mBuilder; public SimpleDialogConfigUiBase(Builder builder) { mBuilder = builder; } @Override public Context getContext() { return getActivity(); } @Override public BaseDialogConfigController getController() { return mController; } @Override public void setPositiveButton(CharSequence text) { mBuilder.setPositiveButton(text, CustomDialogFragment.this); } @Override public void setCancelButton(CharSequence text) { mBuilder.setNegativeButton(text, CustomDialogFragment.this); } @Override public Button getPositiveButton() { return (Button) (mContent != null ? mContent.findViewById(R.id.sdl_button_positive) : null); } @Override public Button getCancelButton() { return (Button) (mContent != null ? mContent.findViewById(R.id.sdl_button_negative) : null); } @Override public void setTitle(CharSequence text) { mBuilder.setTitle(text); } @Override public void setTitle(int resId) { mBuilder.setTitle(resId); } } public static CustomDialogFragment newInstance(Bundle bundle) { CustomDialogFragment f = new CustomDialogFragment(); f.setArguments(bundle); return f; } private static final String TAG = "CommonDialogFragment"; private BaseDialogConfigController mController; private SimpleDialogConfigUiBase mSimpleUiWrapper; private int mDialogMode = DIALOG_MODE_SIMPLE; private View mContent; public static SimpleDialogBuilder createBuilder(Context context, FragmentManager fragmentManager) { return new DialogBuilder(context, fragmentManager, CustomDialogFragment.class); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { mDialogMode = getArguments().getInt(MODE_OPTIONS, DIALOG_MODE_SIMPLE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContent = super.onCreateView(inflater, container, savedInstanceState); return mContent; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle args = getArguments(); Dialog dlg = new Dialog(getActivity(), R.style.CustomDialog); if (args != null) { dlg.setCanceledOnTouchOutside( args.getBoolean(BaseDialogBuilder.ARG_CANCELABLE_ON_TOUCH_OUTSIDE)); } dlg.setOnShowListener(this); return dlg; } /* * (non-Javadoc) * * @see android.support.v4.app.Fragment#onViewCreated(android.view.View, * android.os.Bundle) */ @Override public void onViewCreated(View view, Bundle savedInstanceState) { view.setOnTouchListener(this); super.onViewCreated(view, savedInstanceState); } @SuppressLint("InflateParams") @Override protected Builder build(Builder builder) { mSimpleUiWrapper = new SimpleDialogConfigUiBase(builder); View content = null; LayoutInflater inflater = builder.getLayoutInflater(); switch (mDialogMode) { case ResourcesConstants.DIALOG_MODE_SIMPLE: return super.build(builder); case ResourcesConstants.DIALOG_MODE_CREATE_ROOM: case ResourcesConstants.DIALOG_MODE_QUICK_JOIN: case ResourcesConstants.DIALOG_MODE_JOIN_GAME: { Bundle param = getArguments(); content = inflater.inflate(R.layout.room_detail_content, null); mController = new RoomDialogConfigController(mSimpleUiWrapper, content, param); break; } case ResourcesConstants.DIALOG_MODE_DONATE: content = inflater.inflate(R.layout.donate_content, null); mController = new DonateDialogConfigController(mSimpleUiWrapper, content); break; case ResourcesConstants.DIALOG_MODE_FILTER_ATK: { content = inflater.inflate(R.layout.range_dialog_content, null); Bundle param = getArguments(); int max = param.getInt("max"); int min = param.getInt("min"); mController = new RangeDialogConfigController(mSimpleUiWrapper, content, RangeDialogConfigController.RANGE_DIALOG_TYPE_ATK, max, min); break; } case ResourcesConstants.DIALOG_MODE_FILTER_DEF: { content = inflater.inflate(R.layout.range_dialog_content, null); Bundle param = getArguments(); int max = param.getInt("max"); int min = param.getInt("min"); mController = new RangeDialogConfigController(mSimpleUiWrapper, content, RangeDialogConfigController.RANGE_DIALOG_TYPE_DEF, max, min); break; } case ResourcesConstants.DIALOG_MODE_FILTER_LEVEL: { content = inflater.inflate(R.layout.grid_slection_dialog_content, null); Bundle param = getArguments(); List<Integer> selection = param.getIntegerArrayList("selection"); mController = new GridSelectionDialogController(mSimpleUiWrapper, content, R.array.card_level, GridSelectionDialogController.GRID_SELECTION_TYPE_LEVEL, selection); break; } case ResourcesConstants.DIALOG_MODE_FILTER_EFFECT: { content = inflater.inflate(R.layout.grid_slection_dialog_content, null); Bundle param = getArguments(); List<Integer> selection = param.getIntegerArrayList("selection"); mController = new GridSelectionDialogController(mSimpleUiWrapper, content, R.array.card_effect, GridSelectionDialogController.GRID_SELECTION_TYPE_EFFECT, selection); } break; case ResourcesConstants.DIALOG_MODE_ADD_NEW_SERVER: case ResourcesConstants.DIALOG_MODE_EDIT_SERVER: content = inflater.inflate(R.layout.create_server_content, null); mController = new ServerDialogController(mSimpleUiWrapper, content, getArguments()); break; case ResourcesConstants.DIALOG_MODE_DIRECTORY_CHOOSE: content = inflater.inflate(R.layout.file_browser_layout, null); mController = new ServerDialogController(mSimpleUiWrapper, content, getArguments()); break; case ResourcesConstants.DIALOG_MODE_APP_UPDATE: content = inflater.inflate(R.layout.app_update_content, null); mController = new AppUpdateController(mSimpleUiWrapper, content, getArguments()); break; default: break; } builder.setView(content); return builder; } @Override public void onClick(View v) { if (v.getId() == R.id.sdl_button_positive) { switch (mDialogMode) { case ResourcesConstants.DIALOG_MODE_CREATE_ROOM: case ResourcesConstants.DIALOG_MODE_QUICK_JOIN: case ResourcesConstants.DIALOG_MODE_JOIN_GAME: { Intent intent = new Intent(getActivity(), YGOMobileActivity.class); YGOGameOptions options = ((RoomDialogConfigController) mController).getGameOption() ; if (mDialogMode == DIALOG_MODE_CREATE_ROOM) { options.mServerAddr = Model.peekInstance().getMyCardServer().ipAddrString; options.mPort = Model.peekInstance().getMyCardServer().port; options.mName = Controller.peekInstance().getLoginName(); } else if (mDialogMode == DIALOG_MODE_JOIN_GAME) { } else if (mDialogMode == DIALOG_MODE_QUICK_JOIN) { Fragment f = getTargetFragment(); ((DuelFragment)f).handleMessage(Message.obtain(null, getTargetRequestCode(), 0, 0, options)); return; } intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.putExtra(YGOGameOptions.YGO_GAME_OPTIONS_BUNDLE_KEY, options); startActivity(intent); break; } case ResourcesConstants.DIALOG_MODE_DONATE: { Intent intent = new Intent(); int method = ((DonateDialogConfigController) mController).getAlipayDonateMethod(); switch (method) { case DonateDialogConfigController.DONATE_METHOD_ALIPAY_MOBILE_APP_INSTALLED: ComponentName component = new ComponentName("com.eg.android.AlipayGphone", "com.eg.android.AlipayGphone.AlipayLogin"); intent.setComponent(component); intent.setAction(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); String alipayVersionString = ((DonateDialogConfigController) mController).getAlipayVersionString(); Log.d(TAG, "alipay version = " + alipayVersionString); String urlString = String.format("alipayqr://platformapi/startapp?saId=10000007&clientVersion=%s&qrcode=%s", alipayVersionString, ResourcesConstants.DONATE_URL_MOBILE); intent.setData(Uri.parse(urlString)); break; case DonateDialogConfigController.DONATE_METHOD_ALIPAY_MOBILE_APP_NOT_INSTALLED: intent.setAction(Intent.ACTION_VIEW); intent.setData(Uri.parse(ResourcesConstants.DONATE_URL_MOBILE)); break; case DonateDialogConfigController.DONATE_METHOD_ALIPAY_WAP: intent.setAction(Intent.ACTION_VIEW); intent.setData(Uri.parse(ResourcesConstants.DONATE_URL_WAP)); break; default: break; } startActivity(intent); break; } case ResourcesConstants.DIALOG_MODE_FILTER_ATK: case ResourcesConstants.DIALOG_MODE_FILTER_DEF: { int max = ((RangeDialogConfigController) mController).getMaxValue(); int min = ((RangeDialogConfigController) mController).getMinValue();; ((BaseFragment)getTargetFragment()).onEventFromChild(getTargetRequestCode(), FragmentNavigationListener.FRAGMENT_NAVIGATION_CARD_EVENT, min, max, null); break; } case ResourcesConstants.DIALOG_MODE_FILTER_LEVEL: case ResourcesConstants.DIALOG_MODE_FILTER_EFFECT: { List<Integer> list = ((GridSelectionDialogController) mController).getSelections(); ((BaseFragment)getTargetFragment()).onEventFromChild(getTargetRequestCode(), FragmentNavigationListener.FRAGMENT_NAVIGATION_CARD_EVENT, -1, -1, list); break; } case ResourcesConstants.DIALOG_MODE_ADD_NEW_SERVER: case ResourcesConstants.DIALOG_MODE_EDIT_SERVER: YGOServerInfo info = ((ServerDialogController) mController).getServerInfo(); Model.peekInstance().addNewServer(info); ((BaseFragment)getTargetFragment()).onEventFromChild(getTargetRequestCode(), FragmentNavigationListener.FRAGMENT_NAVIGATION_DUEL_CREATE_SERVER_EVENT, -1, -1, null); case ResourcesConstants.DIALOG_MODE_DIRECTORY_CHOOSE: break; default: break; } } dismiss(); } @SuppressLint("ClickableViewAccessibility") public boolean onTouch(View v, MotionEvent event) { return true; } @Override public void onShow(DialogInterface dialog) { if (mController != null) { mController.enableSubmitIfAppropriate(); } } public static class DialogBuilder extends SimpleDialogFragment.SimpleDialogBuilder { protected DialogBuilder(Context context, FragmentManager fragmentManager, Class<? extends SimpleDialogFragment> clazz) { super(context, fragmentManager, clazz); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db.compaction; import java.util.*; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.collect.*; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.cql3.statements.CFPropDefs; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.lifecycle.LifecycleTransaction; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.utils.Pair; public class DateTieredCompactionStrategy extends AbstractCompactionStrategy { private static final Logger logger = LoggerFactory.getLogger(DateTieredCompactionStrategy.class); private final DateTieredCompactionStrategyOptions options; protected volatile int estimatedRemainingTasks; private final Set<SSTableReader> sstables = new HashSet<>(); public DateTieredCompactionStrategy(ColumnFamilyStore cfs, Map<String, String> options) { super(cfs, options); this.estimatedRemainingTasks = 0; this.options = new DateTieredCompactionStrategyOptions(options); if (!options.containsKey(AbstractCompactionStrategy.TOMBSTONE_COMPACTION_INTERVAL_OPTION) && !options.containsKey(AbstractCompactionStrategy.TOMBSTONE_THRESHOLD_OPTION)) { disableTombstoneCompactions = true; logger.debug("Disabling tombstone compactions for DTCS"); } else logger.debug("Enabling tombstone compactions for DTCS"); } @Override @SuppressWarnings("resource") public synchronized AbstractCompactionTask getNextBackgroundTask(int gcBefore) { if (!isEnabled()) return null; while (true) { List<SSTableReader> latestBucket = getNextBackgroundSSTables(gcBefore); if (latestBucket.isEmpty()) return null; LifecycleTransaction modifier = cfs.getTracker().tryModify(latestBucket, OperationType.COMPACTION); if (modifier != null) return new CompactionTask(cfs, modifier, gcBefore, false); } } /** * * @param gcBefore * @return */ private List<SSTableReader> getNextBackgroundSSTables(final int gcBefore) { if (!isEnabled() || cfs.getSSTables().isEmpty()) return Collections.emptyList(); Set<SSTableReader> uncompacting = Sets.intersection(sstables, cfs.getUncompactingSSTables()); // Find fully expired SSTables. Those will be included no matter what. Set<SSTableReader> expired = CompactionController.getFullyExpiredSSTables(cfs, uncompacting, cfs.getOverlappingSSTables(uncompacting), gcBefore); Set<SSTableReader> candidates = Sets.newHashSet(filterSuspectSSTables(uncompacting)); List<SSTableReader> compactionCandidates = new ArrayList<>(getNextNonExpiredSSTables(Sets.difference(candidates, expired), gcBefore)); if (!expired.isEmpty()) { logger.debug("Including expired sstables: {}", expired); compactionCandidates.addAll(expired); } return compactionCandidates; } private List<SSTableReader> getNextNonExpiredSSTables(Iterable<SSTableReader> nonExpiringSSTables, final int gcBefore) { int base = cfs.getMinimumCompactionThreshold(); long now = getNow(); List<SSTableReader> mostInteresting = getCompactionCandidates(nonExpiringSSTables, now, base); if (mostInteresting != null) { return mostInteresting; } // if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone // ratio is greater than threshold. List<SSTableReader> sstablesWithTombstones = Lists.newArrayList(); for (SSTableReader sstable : nonExpiringSSTables) { if (worthDroppingTombstones(sstable, gcBefore)) sstablesWithTombstones.add(sstable); } if (sstablesWithTombstones.isEmpty()) return Collections.emptyList(); return Collections.singletonList(Collections.min(sstablesWithTombstones, new SSTableReader.SizeComparator())); } private List<SSTableReader> getCompactionCandidates(Iterable<SSTableReader> candidateSSTables, long now, int base) { Iterable<SSTableReader> candidates = filterOldSSTables(Lists.newArrayList(candidateSSTables), options.maxSSTableAge, now); List<List<SSTableReader>> buckets = getBuckets(createSSTableAndMinTimestampPairs(candidates), options.baseTime, base, now); logger.debug("Compaction buckets are {}", buckets); updateEstimatedCompactionsByTasks(buckets); List<SSTableReader> mostInteresting = newestBucket(buckets, cfs.getMinimumCompactionThreshold(), cfs.getMaximumCompactionThreshold(), now, options.baseTime); if (!mostInteresting.isEmpty()) return mostInteresting; return null; } /** * Gets the timestamp that DateTieredCompactionStrategy considers to be the "current time". * @return the maximum timestamp across all SSTables. * @throws java.util.NoSuchElementException if there are no SSTables. */ private long getNow() { return Collections.max(cfs.getSSTables(), new Comparator<SSTableReader>() { public int compare(SSTableReader o1, SSTableReader o2) { return Long.compare(o1.getMaxTimestamp(), o2.getMaxTimestamp()); } }).getMaxTimestamp(); } /** * Removes all sstables with max timestamp older than maxSSTableAge. * @param sstables all sstables to consider * @param maxSSTableAge the age in milliseconds when an SSTable stops participating in compactions * @param now current time. SSTables with max timestamp less than (now - maxSSTableAge) are filtered. * @return a list of sstables with the oldest sstables excluded */ @VisibleForTesting static Iterable<SSTableReader> filterOldSSTables(List<SSTableReader> sstables, long maxSSTableAge, long now) { if (maxSSTableAge == 0) return sstables; final long cutoff = now - maxSSTableAge; return Iterables.filter(sstables, new Predicate<SSTableReader>() { @Override public boolean apply(SSTableReader sstable) { return sstable.getMaxTimestamp() >= cutoff; } }); } /** * * @param sstables * @return */ public static List<Pair<SSTableReader, Long>> createSSTableAndMinTimestampPairs(Iterable<SSTableReader> sstables) { List<Pair<SSTableReader, Long>> sstableMinTimestampPairs = Lists.newArrayListWithCapacity(Iterables.size(sstables)); for (SSTableReader sstable : sstables) sstableMinTimestampPairs.add(Pair.create(sstable, sstable.getMinTimestamp())); return sstableMinTimestampPairs; } @Override public void addSSTable(SSTableReader sstable) { sstables.add(sstable); } @Override public void removeSSTable(SSTableReader sstable) { sstables.remove(sstable); } /** * A target time span used for bucketing SSTables based on timestamps. */ private static class Target { // How big a range of timestamps fit inside the target. public final long size; // A timestamp t hits the target iff t / size == divPosition. public final long divPosition; public Target(long size, long divPosition) { this.size = size; this.divPosition = divPosition; } /** * Compares the target to a timestamp. * @param timestamp the timestamp to compare. * @return a negative integer, zero, or a positive integer as the target lies before, covering, or after than the timestamp. */ public int compareToTimestamp(long timestamp) { return Long.compare(divPosition, timestamp / size); } /** * Tells if the timestamp hits the target. * @param timestamp the timestamp to test. * @return <code>true</code> iff timestamp / size == divPosition. */ public boolean onTarget(long timestamp) { return compareToTimestamp(timestamp) == 0; } /** * Gets the next target, which represents an earlier time span. * @param base The number of contiguous targets that will have the same size. Targets following those will be <code>base</code> times as big. * @return */ public Target nextTarget(int base) { if (divPosition % base > 0) return new Target(size, divPosition - 1); else return new Target(size * base, divPosition / base - 1); } } /** * Group files with similar min timestamp into buckets. Files with recent min timestamps are grouped together into * buckets designated to short timespans while files with older timestamps are grouped into buckets representing * longer timespans. * @param files pairs consisting of a file and its min timestamp * @param timeUnit * @param base * @param now * @return a list of buckets of files. The list is ordered such that the files with newest timestamps come first. * Each bucket is also a list of files ordered from newest to oldest. */ @VisibleForTesting static <T> List<List<T>> getBuckets(Collection<Pair<T, Long>> files, long timeUnit, int base, long now) { // Sort files by age. Newest first. final List<Pair<T, Long>> sortedFiles = Lists.newArrayList(files); Collections.sort(sortedFiles, Collections.reverseOrder(new Comparator<Pair<T, Long>>() { public int compare(Pair<T, Long> p1, Pair<T, Long> p2) { return p1.right.compareTo(p2.right); } })); List<List<T>> buckets = Lists.newArrayList(); Target target = getInitialTarget(now, timeUnit); PeekingIterator<Pair<T, Long>> it = Iterators.peekingIterator(sortedFiles.iterator()); outerLoop: while (it.hasNext()) { while (!target.onTarget(it.peek().right)) { // If the file is too new for the target, skip it. if (target.compareToTimestamp(it.peek().right) < 0) { it.next(); if (!it.hasNext()) break outerLoop; } else // If the file is too old for the target, switch targets. target = target.nextTarget(base); } List<T> bucket = Lists.newArrayList(); while (target.onTarget(it.peek().right)) { bucket.add(it.next().left); if (!it.hasNext()) break; } buckets.add(bucket); } return buckets; } @VisibleForTesting static Target getInitialTarget(long now, long timeUnit) { return new Target(timeUnit, now / timeUnit); } private void updateEstimatedCompactionsByTasks(List<List<SSTableReader>> tasks) { int n = 0; for (List<SSTableReader> bucket : tasks) { if (bucket.size() >= cfs.getMinimumCompactionThreshold()) n += Math.ceil((double)bucket.size() / cfs.getMaximumCompactionThreshold()); } estimatedRemainingTasks = n; } /** * @param buckets list of buckets, sorted from newest to oldest, from which to return the newest bucket within thresholds. * @param minThreshold minimum number of sstables in a bucket to qualify. * @param maxThreshold maximum number of sstables to compact at once (the returned bucket will be trimmed down to this). * @return a bucket (list) of sstables to compact. */ @VisibleForTesting static List<SSTableReader> newestBucket(List<List<SSTableReader>> buckets, int minThreshold, int maxThreshold, long now, long baseTime) { // If the "incoming window" has at least minThreshold SSTables, choose that one. // For any other bucket, at least 2 SSTables is enough. // In any case, limit to maxThreshold SSTables. Target incomingWindow = getInitialTarget(now, baseTime); for (List<SSTableReader> bucket : buckets) { if (bucket.size() >= minThreshold || (bucket.size() >= 2 && !incomingWindow.onTarget(bucket.get(0).getMinTimestamp()))) return trimToThreshold(bucket, maxThreshold); } return Collections.emptyList(); } /** * @param bucket list of sstables, ordered from newest to oldest by getMinTimestamp(). * @param maxThreshold maximum number of sstables in a single compaction task. * @return A bucket trimmed to the <code>maxThreshold</code> newest sstables. */ @VisibleForTesting static List<SSTableReader> trimToThreshold(List<SSTableReader> bucket, int maxThreshold) { // Trim the oldest sstables off the end to meet the maxThreshold return bucket.subList(0, Math.min(bucket.size(), maxThreshold)); } @Override @SuppressWarnings("resource") public synchronized Collection<AbstractCompactionTask> getMaximalTask(int gcBefore, boolean splitOutput) { LifecycleTransaction modifier = cfs.markAllCompacting(OperationType.COMPACTION); if (modifier == null) return null; return Arrays.<AbstractCompactionTask>asList(new CompactionTask(cfs, modifier, gcBefore, false)); } @Override @SuppressWarnings("resource") public synchronized AbstractCompactionTask getUserDefinedTask(Collection<SSTableReader> sstables, int gcBefore) { assert !sstables.isEmpty(); // checked for by CM.submitUserDefined LifecycleTransaction modifier = cfs.getTracker().tryModify(sstables, OperationType.COMPACTION); if (modifier == null) { logger.debug("Unable to mark {} for compaction; probably a background compaction got to it first. You can disable background compactions temporarily if this is a problem", sstables); return null; } return new CompactionTask(cfs, modifier, gcBefore, false).setUserDefined(true); } public int getEstimatedRemainingTasks() { return estimatedRemainingTasks; } public long getMaxSSTableBytes() { return Long.MAX_VALUE; } public static Map<String, String> validateOptions(Map<String, String> options) throws ConfigurationException { Map<String, String> uncheckedOptions = AbstractCompactionStrategy.validateOptions(options); uncheckedOptions = DateTieredCompactionStrategyOptions.validateOptions(options, uncheckedOptions); uncheckedOptions.remove(CFPropDefs.KW_MINCOMPACTIONTHRESHOLD); uncheckedOptions.remove(CFPropDefs.KW_MAXCOMPACTIONTHRESHOLD); return uncheckedOptions; } public String toString() { return String.format("DateTieredCompactionStrategy[%s/%s]", cfs.getMinimumCompactionThreshold(), cfs.getMaximumCompactionThreshold()); } }
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.keymap.impl.ui; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.QuickList; import com.intellij.openapi.keymap.KeymapGroup; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class Group implements KeymapGroup { private Group myParent; private final String myName; private String myId; private final Icon myIcon; /** * Group or action id (String) or Separator or QuickList or Hyperlink */ private final ArrayList<Object> myChildren; private final Set<String> myIds = new HashSet<>(); public Group(String name, String id, Icon icon) { myName = name; myId = id; myIcon = icon; myChildren = new ArrayList<>(); } public Group(final String name, final Icon icon) { myChildren = new ArrayList<>(); myIcon = icon; myName = name; } public String getName() { return myName; } public Icon getIcon() { return myIcon; } @Nullable public String getId() { return myId; } @Override public void addActionId(String id) { if (myChildren.contains(id)) return; myChildren.add(id); } public void addQuickList(QuickList list) { myChildren.add(list); } public void addHyperlink(Hyperlink link) { myChildren.add(link); } @Override public void addGroup(KeymapGroup keymapGroup) { Group group = (Group) keymapGroup; myChildren.add(group); group.myParent = this; } public void addSeparator() { myChildren.add(Separator.getInstance()); } public boolean containsId(String id) { return myIds.contains(id); } public Set<String> initIds(){ for (Object child : myChildren) { if (child instanceof String) { myIds.add((String)child); } else if (child instanceof QuickList) { myIds.add(((QuickList)child).getActionId()); } else if (child instanceof Group) { Group childGroup = (Group)child; myIds.addAll(childGroup.initIds()); if (childGroup.myId != null) myIds.add(childGroup.myId); } } return myIds; } public ArrayList<Object> getChildren() { return myChildren; } public int getSize() { return myChildren.size(); } public void normalizeSeparators() { while (myChildren.size() > 0 && myChildren.get(0) instanceof Separator) { myChildren.remove(0); } while (myChildren.size() > 0 && myChildren.get(myChildren.size() - 1) instanceof Separator) { myChildren.remove(myChildren.size() - 1); } for (int i=1; i < myChildren.size() - 1; i++) { if (myChildren.get(i) instanceof Separator && myChildren.get(i + 1) instanceof Separator) { myChildren.remove(i); i--; } } } public String getActionQualifiedPath(String id) { Group cur = myParent; StringBuilder answer = new StringBuilder(); while (cur != null && !cur.isRoot()) { answer.insert(0, cur.getName() + " | "); cur = cur.myParent; } String suffix = calcActionQualifiedPath(id); if (StringUtil.isEmpty(suffix)) return null; answer.append(suffix); return answer.toString(); } private String calcActionQualifiedPath(String id) { if (!isRoot() && StringUtil.equals(id, myId)) { return getName(); } for (Object child : myChildren) { if (child instanceof QuickList) { child = ((QuickList)child).getActionId(); } if (child instanceof String) { if (id.equals(child)) { AnAction action = ActionManager.getInstance().getActionOrStub(id); String path; if (action != null) { path = action.getTemplatePresentation().getText(); } else { path = id; } return !isRoot() ? getName() + " | " + path : path; } } else if (child instanceof Group) { String path = ((Group)child).calcActionQualifiedPath(id); if (path != null) { return !isRoot() ? getName() + " | " + path : path; } } } return null; } public boolean isRoot() { return myParent == null; } public String getQualifiedPath() { StringBuilder path = new StringBuilder(64); Group group = this; while (group != null && !group.isRoot()) { if (path.length() > 0) path.insert(0, " | "); path.insert(0, group.getName()); group = group.myParent; } return path.toString(); } public void addAll(Group group) { for (Object o : group.getChildren()) { if (o instanceof String) { addActionId((String)o); } else if (o instanceof QuickList) { addQuickList((QuickList)o); } else if (o instanceof Group) { addGroup((Group)o); } else if (o instanceof Separator) { addSeparator(); } } } public ActionGroup constructActionGroup(final boolean popup){ ActionManager actionManager = ActionManager.getInstance(); DefaultActionGroup group = new DefaultActionGroup(getName(), popup); AnAction groupToRestorePresentation = null; if (getName() != null){ groupToRestorePresentation = actionManager.getAction(getName()); } else { if (getId() != null){ groupToRestorePresentation = actionManager.getAction(getId()); } } if (groupToRestorePresentation != null){ group.copyFrom(groupToRestorePresentation); } for (Object o : myChildren) { if (o instanceof String) { group.add(actionManager.getAction((String)o)); } else if (o instanceof Separator) { group.addSeparator(); } else if (o instanceof Group) { group.add(((Group)o).constructActionGroup(popup)); } } return group; } public boolean equals(Object object) { if (!(object instanceof Group)) return false; final Group group = ((Group)object); if (group.getName() != null && getName() != null){ return group.getName().equals(getName()); } if (getChildren() != null && group.getChildren() != null){ if (getChildren().size() != group.getChildren().size()){ return false; } for (int i = 0; i < getChildren().size(); i++) { if (!getChildren().get(i).equals(group.getChildren().get(i))){ return false; } } return true; } return false; } public int hashCode() { return getName() != null ? getName().hashCode() : 0; } public String toString() { return getName(); } }
/* * Copyright 2018 LinkedIn Corp. * * 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 azkaban.reportal.util; import azkaban.executor.ExecutionOptions; import azkaban.flow.Flow; import azkaban.project.Project; import azkaban.project.ProjectManager; import azkaban.scheduler.Schedule; import azkaban.scheduler.ScheduleManager; import azkaban.scheduler.ScheduleManagerException; import azkaban.user.Permission; import azkaban.user.Permission.Type; import azkaban.user.User; import azkaban.utils.Utils; import azkaban.viewer.reportal.ReportalMailCreator; import azkaban.viewer.reportal.ReportalTypeManager; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Days; import org.joda.time.Hours; import org.joda.time.Minutes; import org.joda.time.Months; import org.joda.time.ReadablePeriod; import org.joda.time.Weeks; import org.joda.time.Years; import org.joda.time.format.DateTimeFormat; public class Reportal { public static final String REPORTAL_CONFIG_PREFIX = "reportal.config."; public static final String REPORTAL_CONFIG_PREFIX_REGEX = "^reportal[.]config[.].+"; public static final String REPORTAL_CONFIG_PREFIX_NEGATION_REGEX = "(?!(^reportal[.]config[.])).+"; public static final String ACCESS_LIST_SPLIT_REGEX = "\\s*,\\s*|\\s*;\\s*|\\s+"; // One Schedule's default End Time: 01/01/2050, 00:00:00, UTC private static final long DEFAULT_SCHEDULE_END_EPOCH_TIME = 2524608000000L; private static final Logger logger = Logger.getLogger(Reportal.class); public static Getter<Boolean> boolGetter = new Getter<>(false, Boolean.class); public static Getter<Integer> intGetter = new Getter<>(0, Integer.class); public static Getter<String> stringGetter = new Getter<>("", String.class); public String reportalUser; public String ownerEmail; public String title; public String description; public List<Query> queries; public List<Variable> variables; public boolean schedule; public String scheduleHour; public String scheduleMinute; public String scheduleAmPm; public String scheduleTimeZone; public String scheduleDate; public boolean scheduleRepeat; public String scheduleIntervalQuantity; public String scheduleInterval; public String endSchedule; public boolean renderResultsAsHtml; public String accessViewer; public String accessExecutor; public String accessOwner; public String notifications; public String failureNotifications; public Project project; public static Reportal loadFromProject(final Project project) { if (project == null) { return null; } final Reportal reportal = new Reportal(); final Map<String, Object> metadata = project.getMetadata(); reportal.loadImmutableFromProject(project); if (reportal.reportalUser == null || reportal.reportalUser.isEmpty()) { return null; } reportal.title = stringGetter.get(metadata.get("title")); reportal.description = project.getDescription(); final int queries = intGetter.get(project.getMetadata().get("queryNumber")); final int variables = intGetter.get(project.getMetadata().get("variableNumber")); reportal.schedule = boolGetter.get(project.getMetadata().get("schedule")); reportal.scheduleHour = stringGetter.get(project.getMetadata().get("scheduleHour")); reportal.scheduleMinute = stringGetter.get(project.getMetadata().get("scheduleMinute")); reportal.scheduleAmPm = stringGetter.get(project.getMetadata().get("scheduleAmPm")); reportal.scheduleTimeZone = stringGetter.get(project.getMetadata().get("scheduleTimeZone")); reportal.scheduleDate = stringGetter.get(project.getMetadata().get("scheduleDate")); reportal.scheduleRepeat = boolGetter.get(project.getMetadata().get("scheduleRepeat")); reportal.scheduleIntervalQuantity = stringGetter.get(project.getMetadata().get("scheduleIntervalQuantity")); reportal.scheduleInterval = stringGetter.get(project.getMetadata().get("scheduleInterval")); reportal.endSchedule = stringGetter.get(project.getMetadata().get("endSchedule")); reportal.renderResultsAsHtml = boolGetter.get(project.getMetadata().get("renderResultsAsHtml")); reportal.accessViewer = stringGetter.get(project.getMetadata().get("accessViewer")); reportal.accessExecutor = stringGetter.get(project.getMetadata().get("accessExecutor")); reportal.accessOwner = stringGetter.get(project.getMetadata().get("accessOwner")); reportal.notifications = stringGetter.get(project.getMetadata().get("notifications")); reportal.failureNotifications = stringGetter.get(project.getMetadata().get("failureNotifications")); reportal.queries = new ArrayList<>(); for (int i = 0; i < queries; i++) { final Query query = new Query(); reportal.queries.add(query); query.title = stringGetter.get(project.getMetadata().get("query" + i + "title")); query.type = stringGetter.get(project.getMetadata().get("query" + i + "type")); query.script = stringGetter.get(project.getMetadata().get("query" + i + "script")); } reportal.variables = new ArrayList<>(); for (int i = 0; i < variables; i++) { final String title = stringGetter.get(project.getMetadata().get("variable" + i + "title")); final String name = stringGetter.get(project.getMetadata().get("variable" + i + "name")); final Variable variable = new Variable(title, name); reportal.variables.add(variable); } reportal.project = project; return reportal; } public void saveToProject(final Project project) { this.project = project; project.getMetadata().put("reportal-user", this.reportalUser); project.getMetadata().put("owner-email", this.ownerEmail); project.getMetadata().put("title", this.title); project.setDescription(this.description); project.getMetadata().put("schedule", this.schedule); project.getMetadata().put("scheduleHour", this.scheduleHour); project.getMetadata().put("scheduleMinute", this.scheduleMinute); project.getMetadata().put("scheduleAmPm", this.scheduleAmPm); project.getMetadata().put("scheduleTimeZone", this.scheduleTimeZone); project.getMetadata().put("scheduleDate", this.scheduleDate); project.getMetadata().put("scheduleRepeat", this.scheduleRepeat); project.getMetadata().put("scheduleIntervalQuantity", this.scheduleIntervalQuantity); project.getMetadata().put("scheduleInterval", this.scheduleInterval); project.getMetadata().put("endSchedule", this.endSchedule); project.getMetadata().put("renderResultsAsHtml", this.renderResultsAsHtml); project.getMetadata().put("accessViewer", this.accessViewer); project.getMetadata().put("accessExecutor", this.accessExecutor); project.getMetadata().put("accessOwner", this.accessOwner); project.getMetadata().put("queryNumber", this.queries.size()); for (int i = 0; i < this.queries.size(); i++) { final Query query = this.queries.get(i); project.getMetadata().put("query" + i + "title", query.title); project.getMetadata().put("query" + i + "type", query.type); project.getMetadata().put("query" + i + "script", query.script); } project.getMetadata().put("variableNumber", this.variables.size()); for (int i = 0; i < this.variables.size(); i++) { final Variable variable = this.variables.get(i); project.getMetadata().put("variable" + i + "title", variable.title); project.getMetadata().put("variable" + i + "name", variable.name); } project.getMetadata().put("notifications", this.notifications); project.getMetadata().put("failureNotifications", this.failureNotifications); } public void removeSchedules(final ScheduleManager scheduleManager) throws ScheduleManagerException { final List<Flow> flows = this.project.getFlows(); for (final Flow flow : flows) { final Schedule sched = scheduleManager.getSchedule(this.project.getId(), flow.getId()); if (sched != null) { scheduleManager.removeSchedule(sched); } } } public void updateSchedules(final Reportal report, final ScheduleManager scheduleManager, final User user, final Flow flow) throws ScheduleManagerException { // Clear previous schedules removeSchedules(scheduleManager); // Add new schedule if (this.schedule) { final int hour = (Integer.parseInt(this.scheduleHour) % 12) + (this.scheduleAmPm.equalsIgnoreCase("pm") ? 12 : 0); final int minute = Integer.parseInt(this.scheduleMinute) % 60; final DateTimeZone timeZone = this.scheduleTimeZone.equalsIgnoreCase("UTC") ? DateTimeZone.UTC : DateTimeZone.getDefault(); DateTime firstSchedTime = DateTimeFormat.forPattern("MM/dd/yyyy").withZone(timeZone) .parseDateTime(this.scheduleDate); firstSchedTime = firstSchedTime.withHourOfDay(hour).withMinuteOfHour(minute) .withSecondOfMinute(0).withMillisOfSecond(0); ReadablePeriod period = null; if (this.scheduleRepeat) { final int intervalQuantity = Integer.parseInt(this.scheduleIntervalQuantity); if (this.scheduleInterval.equals("y")) { period = Years.years(intervalQuantity); } else if (this.scheduleInterval.equals("m")) { period = Months.months(intervalQuantity); } else if (this.scheduleInterval.equals("w")) { period = Weeks.weeks(intervalQuantity); } else if (this.scheduleInterval.equals("d")) { period = Days.days(intervalQuantity); } else if (this.scheduleInterval.equals("h")) { period = Hours.hours(intervalQuantity); } else if (this.scheduleInterval.equals("M")) { period = Minutes.minutes(intervalQuantity); } } final ExecutionOptions options = new ExecutionOptions(); options.getFlowParameters().put("reportal.execution.user", user.getUserId()); options.getFlowParameters().put("reportal.title", report.title); options.getFlowParameters().put("reportal.render.results.as.html", report.renderResultsAsHtml ? "true" : "false"); options.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR); final long endScheduleTime = report.endSchedule == null ? DEFAULT_SCHEDULE_END_EPOCH_TIME : parseDateToEpoch(report.endSchedule); logger.info("This report scheudle end time is " + endScheduleTime); scheduleManager.scheduleFlow(-1, this.project.getId(), this.project.getName(), flow.getId(), "ready", firstSchedTime.getMillis(), endScheduleTime, firstSchedTime.getZone(), period, DateTime.now().getMillis(), firstSchedTime.getMillis(), firstSchedTime.getMillis(), user.getUserId(), options); } } private long parseDateToEpoch(final String date) throws ScheduleManagerException { final DateFormat dffrom = new SimpleDateFormat("MM/dd/yyyy h:mm a"); try { // this string will be parsed according to system's timezone setting. return dffrom.parse(date).getTime(); } catch (final Exception ex) { throw new ScheduleManagerException("can not parse this date " + date); } } /** * Updates the project permissions in MEMORY, but does NOT update the project * in the database. */ public void updatePermissions() { final String[] accessViewerList = this.accessViewer.trim().split(ACCESS_LIST_SPLIT_REGEX); final String[] accessExecutorList = this.accessExecutor.trim().split(ACCESS_LIST_SPLIT_REGEX); final String[] accessOwnerList = this.accessOwner.trim().split(ACCESS_LIST_SPLIT_REGEX); // Prepare permission types final Permission admin = new Permission(); admin.addPermission(Type.READ); admin.addPermission(Type.EXECUTE); admin.addPermission(Type.ADMIN); final Permission executor = new Permission(); executor.addPermission(Type.READ); executor.addPermission(Type.EXECUTE); final Permission viewer = new Permission(); viewer.addPermission(Type.READ); // Sets the permissions this.project.clearUserPermission(); for (String user : accessViewerList) { user = user.trim(); if (!user.isEmpty()) { this.project.setUserPermission(user, viewer); } } for (String user : accessExecutorList) { user = user.trim(); if (!user.isEmpty()) { this.project.setUserPermission(user, executor); } } for (String user : accessOwnerList) { user = user.trim(); if (!user.isEmpty()) { this.project.setUserPermission(user, admin); } } this.project.setUserPermission(this.reportalUser, admin); } public void createZipAndUpload(final ProjectManager projectManager, final User user, final String reportalStorageUser) throws Exception { // Create temp folder to make the zip file for upload final File tempDir = Utils.createTempDir(); final File dataDir = new File(tempDir, "data"); dataDir.mkdirs(); // Create all job files String dependentJob = null; final List<String> jobs = new ArrayList<>(); final Map<String, String> extraProps = ReportalUtil.getVariableMapByPrefix(this.variables, REPORTAL_CONFIG_PREFIX); for (final Query query : this.queries) { // Create .job file final File jobFile = ReportalHelper.findAvailableFileName(dataDir, ReportalHelper.sanitizeText(query.title), ".job"); final String fileName = jobFile.getName(); final String jobName = fileName.substring(0, fileName.length() - 4); jobs.add(jobName); // Populate the job file ReportalTypeManager.createJobAndFiles(this, jobFile, jobName, query.title, query.type, query.script, dependentJob, this.reportalUser, extraProps); // For dependency of next query dependentJob = jobName; } // Create the data collector job if (dependentJob != null) { final String jobName = "data-collector"; // Create .job file final File jobFile = ReportalHelper.findAvailableFileName(dataDir, ReportalHelper.sanitizeText(jobName), ".job"); final Map<String, String> extras = new HashMap<>(); extras.put("reportal.job.number", Integer.toString(jobs.size())); for (int i = 0; i < jobs.size(); i++) { extras.put("reportal.job." + i, jobs.get(i)); } ReportalTypeManager.createJobAndFiles(this, jobFile, jobName, "", ReportalTypeManager.DATA_COLLECTOR_JOB, "", dependentJob, reportalStorageUser, extras); } // Zip jobs together final File archiveFile = new File(tempDir, this.project.getName() + ".zip"); Utils.zipFolderContent(dataDir, archiveFile); // Upload zip projectManager.uploadProject(this.project, archiveFile, "zip", user, null, null); // Empty temp if (tempDir.exists()) { FileUtils.deleteDirectory(tempDir); } } public void loadImmutableFromProject(final Project project) { this.reportalUser = stringGetter.get(project.getMetadata().get("reportal-user")); this.ownerEmail = stringGetter.get(project.getMetadata().get("owner-email")); } /** * @return A set of users explicitly granted viewer access to the report. */ public Set<String> getAccessViewers() { final Set<String> viewers = new HashSet<>(); for (final String user : this.accessViewer.trim().split(ACCESS_LIST_SPLIT_REGEX)) { if (!user.isEmpty()) { viewers.add(user); } } return viewers; } /** * @return A set of users explicitly granted executor access to the report. */ public Set<String> getAccessExecutors() { final Set<String> executors = new HashSet<>(); for (final String user : this.accessExecutor.trim().split(ACCESS_LIST_SPLIT_REGEX)) { if (!user.isEmpty()) { executors.add(user); } } return executors; } public static class Getter<T> { Class<?> cls; T defaultValue; public Getter(final T defaultValue, final Class<?> cls) { this.cls = cls; this.defaultValue = defaultValue; } @SuppressWarnings("unchecked") public T get(final Object object) { if (object == null || !(this.cls.isAssignableFrom(object.getClass()))) { return this.defaultValue; } return (T) object; } } public static class Query { public String title; public String type; public String script; public String getTitle() { return this.title; } public String getType() { return this.type; } public String getScript() { return this.script; } } public static class Variable { public String title; public String name; public Variable() { } public Variable(final String title, final String name) { this.title = title; this.name = name; } public String getTitle() { return this.title; } public String getName() { return this.name; } } }
package alec_wam.CrystalMod.blocks.underwater; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; import javax.vecmath.Matrix4f; import org.apache.commons.lang3.tuple.Pair; import org.lwjgl.util.vector.Vector3f; import alec_wam.CrystalMod.CrystalMod; import alec_wam.CrystalMod.blocks.connected.BlockConnectedTexture; import alec_wam.CrystalMod.blocks.connected.ConnectedBlockState; import alec_wam.CrystalMod.client.model.dynamic.DynamicBaseModel; import alec_wam.CrystalMod.util.FluidUtil; import alec_wam.CrystalMod.util.client.CustomModelUtil; import alec_wam.CrystalMod.util.client.RenderUtil; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.BlockFaceUV; import net.minecraft.client.renderer.block.model.BlockPartFace; import net.minecraft.client.renderer.block.model.BlockPartRotation; import net.minecraft.client.renderer.block.model.FaceBakery; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.block.model.ItemOverrideList; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.block.model.ModelRotation; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.client.model.IPerspectiveAwareModel; public class ModelCoral implements IPerspectiveAwareModel { public static final ModelResourceLocation BAKED_MODEL = new ModelResourceLocation("crystalmod:coral"); public static FaceBakery faceBakery; static { faceBakery = new FaceBakery(); } private final EnumDyeColor color; public ModelCoral() { color = EnumDyeColor.WHITE; } public ModelCoral(EnumDyeColor color) { this.color = color; } @Override public List<BakedQuad> getQuads( @Nullable IBlockState state, @Nullable EnumFacing side, long rand ) { if(side !=null) { return Collections.emptyList(); } boolean renderU = false, renderD = false, renderN = false, renderS = false, renderW = false, renderE = false; boolean renderWater = false; ConnectedBlockState cState = null; if(state !=null){ renderU = state.getValue(BlockConnectedTexture.CONNECTED_UP); renderD = state.getValue(BlockConnectedTexture.CONNECTED_DOWN); renderN = state.getValue(BlockConnectedTexture.CONNECTED_NORTH); renderS = state.getValue(BlockConnectedTexture.CONNECTED_SOUTH); renderW = state.getValue(BlockConnectedTexture.CONNECTED_WEST); renderE = state.getValue(BlockConnectedTexture.CONNECTED_EAST); if(state instanceof ConnectedBlockState){ cState = (ConnectedBlockState)state; renderWater = cState.blockAccess.isAirBlock(cState.pos.up()); } } List<BakedQuad> quads = new ArrayList<BakedQuad>(); TextureAtlasSprite sprite = getTexture(); float min = 16.0F * 0.25f; float max = 16.0F * 0.75f; final BlockFaceUV uv = new BlockFaceUV(new float[]{min, min, max, max}, 0); final BlockPartFace faceU = new BlockPartFace(EnumFacing.UP, 0, "", uv); final BlockPartFace faceD = new BlockPartFace(EnumFacing.DOWN, 0, "", uv); final BlockPartFace faceN = new BlockPartFace(EnumFacing.NORTH, 0, "", uv); final BlockPartFace faceS = new BlockPartFace(EnumFacing.SOUTH, 0, "", uv); final BlockPartFace faceW = new BlockPartFace(EnumFacing.WEST, 0, "", uv); final BlockPartFace faceE = new BlockPartFace(EnumFacing.EAST, 0, "", uv); ModelRotation rot = ModelRotation.X0_Y0; boolean uvLocked = false; if(state == null || MinecraftForgeClient.getRenderLayer() == BlockRenderLayer.CUTOUT){ quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(min, max, min), new Vector3f(max, max, max), faceU, sprite, EnumFacing.UP, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(min, min, min), new Vector3f(max, min, max), faceD, sprite, EnumFacing.DOWN, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(min, min, min), new Vector3f(max, max, min), faceN, sprite, EnumFacing.NORTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(min, min, max), new Vector3f(max, max, max), faceS, sprite, EnumFacing.SOUTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(min, min, min), new Vector3f(min, max, max), faceW, sprite, EnumFacing.WEST, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(max, min, min), new Vector3f(max, max, max), faceE, sprite, EnumFacing.EAST, rot, (BlockPartRotation)null, uvLocked)); float newMin = 16.0F * 0.36f; float newMax = 16.0F * 0.64f; if(renderU){ quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, 16F, newMin), new Vector3f(newMax, 16F, newMax), faceU, sprite, EnumFacing.UP, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, max, newMin), new Vector3f(newMax, 16F, newMin), faceN, sprite, EnumFacing.NORTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, max, newMax), new Vector3f(newMax, 16F, newMax), faceS, sprite, EnumFacing.SOUTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, max, newMin), new Vector3f(newMin, 16F, newMax), faceW, sprite, EnumFacing.WEST, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMax, max, newMin), new Vector3f(newMax, 16F, newMax), faceE, sprite, EnumFacing.EAST, rot, (BlockPartRotation)null, uvLocked)); } if(renderD){ quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, 0F, newMin), new Vector3f(newMax, 0F, newMax), faceD, sprite, EnumFacing.DOWN, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, 0F, newMin), new Vector3f(newMax, min, newMin), faceN, sprite, EnumFacing.NORTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, 0F, newMax), new Vector3f(newMax, min, newMax), faceS, sprite, EnumFacing.SOUTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, 0F, newMin), new Vector3f(newMin, min, newMax), faceW, sprite, EnumFacing.WEST, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMax, 0F, newMin), new Vector3f(newMax, min, newMax), faceE, sprite, EnumFacing.EAST, rot, (BlockPartRotation)null, uvLocked)); } if(renderN){ quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, newMax, 0F), new Vector3f(newMax, newMax, min), faceU, sprite, EnumFacing.UP, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, newMin, 0F), new Vector3f(newMax, newMin, min), faceD, sprite, EnumFacing.DOWN, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, newMin, 0F), new Vector3f(newMax, newMax, 0F), faceN, sprite, EnumFacing.NORTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, newMin, 0F), new Vector3f(newMax, newMax, min), faceW, sprite, EnumFacing.WEST, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMax, newMin, 0F), new Vector3f(newMax, newMax, min), faceE, sprite, EnumFacing.EAST, rot, (BlockPartRotation)null, uvLocked)); } if(renderS){ quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, newMax, max), new Vector3f(newMax, newMax, 16F), faceU, sprite, EnumFacing.UP, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, newMin, max), new Vector3f(newMax, newMin, 16F), faceD, sprite, EnumFacing.DOWN, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, newMin, 16F), new Vector3f(newMax, newMax, 16F), faceS, sprite, EnumFacing.SOUTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMin, newMin, max), new Vector3f(newMax, newMax, 16F), faceW, sprite, EnumFacing.WEST, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(newMax, newMin, max), new Vector3f(newMax, newMax, 16F), faceE, sprite, EnumFacing.EAST, rot, (BlockPartRotation)null, uvLocked)); } if(renderW){ quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(0F, newMax, newMin), new Vector3f(min, newMax, newMax), faceU, sprite, EnumFacing.UP, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(0F, newMin, newMin), new Vector3f(min, newMin, newMax), faceD, sprite, EnumFacing.DOWN, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(0F, newMin, newMin), new Vector3f(min, newMax, newMin), faceN, sprite, EnumFacing.NORTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(0F, newMin, newMax), new Vector3f(min, newMax, newMax), faceS, sprite, EnumFacing.SOUTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(0F, newMin, newMin), new Vector3f(0F, newMax, newMax), faceW, sprite, EnumFacing.WEST, rot, (BlockPartRotation)null, uvLocked)); } if(renderE){ quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(max, newMax, newMin), new Vector3f(16F, newMax, newMax), faceU, sprite, EnumFacing.UP, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(max, newMin, newMin), new Vector3f(16F, newMin, newMax), faceD, sprite, EnumFacing.DOWN, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(max, newMin, newMin), new Vector3f(16F, newMax, newMin), faceN, sprite, EnumFacing.NORTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(max, newMin, newMax), new Vector3f(16F, newMax, newMax), faceS, sprite, EnumFacing.SOUTH, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(16F, newMin, newMin), new Vector3f(16F, newMax, newMax), faceE, sprite, EnumFacing.EAST, rot, (BlockPartRotation)null, uvLocked)); } } if(cState !=null && renderWater && MinecraftForgeClient.getRenderLayer() == BlockRenderLayer.TRANSLUCENT){ TextureAtlasSprite waterSprite = RenderUtil.getSprite("minecraft:blocks/water_still"); float height = FluidUtil.getFluidHeight(cState.blockAccess, cState.pos, Material.WATER) * 16F; height -= 0.015F; final BlockFaceUV uvFull = new BlockFaceUV(new float[]{0, 0, 16, 16}, 0); final BlockPartFace faceFull = new BlockPartFace(EnumFacing.UP, 0, "", uvFull); final BlockPartFace faceFullDown = new BlockPartFace(EnumFacing.DOWN, 0, "", uvFull); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(0, height, 0), new Vector3f(16F, height, 16F), faceFull, waterSprite, EnumFacing.UP, rot, (BlockPartRotation)null, uvLocked)); quads.add(CustomModelUtil.INSTANCE.makeBakedQuad(new Vector3f(0, height-0.001f, 0), new Vector3f(16F, height-0.001f, 16F), faceFullDown, waterSprite, EnumFacing.DOWN, rot, (BlockPartRotation)null, uvLocked)); } return quads; } public TextureAtlasSprite getTexture(){ return RenderUtil.getSprite(CrystalMod.resourceL("blocks/coral/coral_"+color.getName())); } @Override public boolean isAmbientOcclusion() { return true; } @Override public boolean isGui3d() { return true; } @Override public boolean isBuiltInRenderer() { return false; } @Override public TextureAtlasSprite getParticleTexture() { return getTexture(); } @Override public ItemCameraTransforms getItemCameraTransforms() { return ItemCameraTransforms.DEFAULT; } @Override public ItemOverrideList getOverrides() { return ItemOverrideList.NONE; } @Override public Pair<? extends IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) { return IPerspectiveAwareModel.MapWrapper.handlePerspective(this, DynamicBaseModel.DEFAULT_PERSPECTIVE_TRANSFORMS, cameraTransformType); } }
/* * Copyright 2014 Bersenev Dmitry molasdin@outlook.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.molasdin.wbase.xml.parser.light.basic; import org.apache.commons.lang3.tuple.Pair; import org.molasdin.wbase.xml.parser.light.Element; import org.molasdin.wbase.xml.parser.light.ElementsTreeWalker; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * User: dbersenev * Date: 07.02.13 * Time: 13:29 */ public class BasicElement implements Element { private String tagName = ""; private Element parent; private List<StringBuilder> characters = new ArrayList<StringBuilder>(); private boolean isClosed; private boolean shorten; private List<Pair<String, String>> attributes = new ArrayList<Pair<String, String>>(); private List<Element> children = new ArrayList<Element>(); private List<Object> positions = new ArrayList<Object>(); private final static String START_FORMAT = "<%s>"; private final static String CLOSED_FORMAT = "<%s/>"; private final static String END_FORMAT = "</%s>"; private boolean valid; private boolean isValidClosing; public void setValid(boolean valid) { this.valid = valid; } public boolean isValid() { return valid; } public void setClosed(boolean valid) { this.isClosed = valid; } public boolean isClosed() { return isClosed; } @Override public void setShortenIfEmpty(boolean flag) { shorten = flag; } @Override public boolean isValidClosing() { return isValidClosing; } public void setValidClosing(boolean validClosing) { isValidClosing = validClosing; } @Override public void setAttributes(List<Pair<String, String>> attributes) { this.attributes = attributes; } @Override public List<Pair<String, String>> attributes() { return attributes; } @Override public boolean hasAttribute(String name) { return attribute(name) != null; } @Override public String attribute(String name) { for (Pair<String, String> entry : attributes()) { if (entry.getRight().equals(name)) { return entry.getRight(); } } return null; } public void addChild(Element element) { children.add(element); positions.add(element); element.setParent(this); } public void setParent(Element element) { this.parent = element; } public Element parent() { return parent; } public List<Element> children() { return Collections.unmodifiableList(children); } @Override public List<Element> childrenByTag(String name) { List<Element> result = new LinkedList<Element>(); for (Element elm : children) { if (elm.tagName().equalsIgnoreCase(name)) { result.add(elm); } } return result; } public void addCharacters(String value) { // addString(value, false); if (positions.size() > 0 && positions.get(positions.size() - 1) instanceof String) { characters.get(characters.size() - 1).append(value); } else { addString(value, false); } } public void addCharacter(char value) { addCharacters(String.valueOf(value)); } public StringBuilder lastCharacters() { return characters.size() > 0 ? characters.get(characters.size() - 1) : null; } public String tagName() { return this.tagName; } public void setTagName(String name) { this.tagName = name; } public void setValue(String value) { positions.removeAll(characters); characters.clear(); addString(value, true); } private void addString(String value, boolean first) { StringBuilder builder = new StringBuilder(); builder.append(value); characters.add(builder); if (first) { positions.add(0, builder); } else { positions.add(builder); } } public String value() { StringBuilder builder = new StringBuilder(); for (StringBuilder entry : characters) { builder.append(entry.toString()); } return builder.toString(); } @Override public void remove() { this.parent().removeChild(this); } @Override public void removeChild(Element element) { children.remove(element); positions.remove(element); } public void walkTree(ElementsTreeWalker walker) { if (!walker.process(this)) { return; } for (int i = 0; i < children.size(); i++) { children.get(i).walkTree(walker); } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Object entry : positions) { builder.append(entry.toString()); } if (tagName().length() > 0) { StringBuilder withNameBuilder = new StringBuilder(); withNameBuilder.append(String.format("<%s", this.tagName())); if (!attributes().isEmpty()) { withNameBuilder.append(' '); } boolean addSpace = false; for (Pair<String, String> attrib : attributes()) { if (addSpace) { withNameBuilder.append(' '); } withNameBuilder.append(String.format("%s = \"%s\"", attrib.getLeft(), attrib.getRight())); addSpace = true; } if (positions.isEmpty() && isClosed() && shorten) { withNameBuilder.append("/>"); } else { withNameBuilder.append('>'); if (isClosed()) { withNameBuilder.append(builder); withNameBuilder.append(String.format("</%s>", this.tagName())); } } return withNameBuilder.toString(); } return builder.toString(); } public void consumeContent(BasicElement element) { if (element.parent() != this) { return; } for (int i = 0; i < element.positions.size(); i++) { Object item = element.positions.get(i); if (item instanceof Element) { addChild((Element) item); } else { addCharacters(item.toString()); } } element.positions.clear(); element.children.clear(); element.characters.clear(); } }
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, 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. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.server.web; import com.thoughtworks.go.domain.ServerSiteUrlConfig; import com.thoughtworks.go.server.GoServer; import com.thoughtworks.go.server.util.HttpTestUtil; import com.thoughtworks.go.server.util.ServletHelper; import com.thoughtworks.go.util.SystemEnvironment; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.WebAppContext; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.springframework.web.context.WebApplicationContext; import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter; import javax.servlet.DispatcherType; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import static com.thoughtworks.go.util.DataStructureUtils.m; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(Theories.class) public class UrlRewriterIntegrationTest { private static final DateTime BACKUP_RUNNING_SINCE = new DateTime(); private static final String BACKUP_STARTED_BY = "admin"; public HttpTestUtil httpUtil; public static final int HTTP = 5197; public static final int HTTPS = 9071; public WebApplicationContext wac; public boolean useConfiguredUrls; public String originalSslPort; public UrlRewriterIntegrationTest() throws Exception { ServletHelper.init(); httpUtil = new HttpTestUtil(new HttpTestUtil.ContextCustomizer() { public void customize(WebAppContext ctx) throws Exception { wac = mock(WebApplicationContext.class); ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); URL resource = getClass().getClassLoader().getResource("WEB-INF/urlrewrite.xml"); if (resource == null) { throw new RuntimeException("Cannot load WEB-INF/urlrewrite.xml"); } ctx.setBaseResource(Resource.newResource(new File(resource.getFile()).getParent())); ctx.addFilter(UrlRewriteFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)).setInitParameter("confPath", "/urlrewrite.xml"); ctx.addServlet(HttpTestUtil.EchoServlet.class, "/*"); } }); httpUtil.httpConnector(HTTP); httpUtil.httpsConnector(HTTPS); when(wac.getBean("serverConfigService")).thenReturn(new BaseUrlProvider() { public boolean hasAnyUrlConfigured() { return useConfiguredUrls; } public String siteUrlFor(String url, boolean forceSsl) throws URISyntaxException { ServerSiteUrlConfig siteUrl = forceSsl ? new ServerSiteUrlConfig("https://127.2.2.2:" + 9071) : new ServerSiteUrlConfig("http://127.2.2.2:" + 5197); return siteUrl.siteUrlFor(url); } }); } @Before public void setUp() throws IOException, InterruptedException { httpUtil.start(); Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new PermissiveSSLSocketFactory(), HTTPS)); originalSslPort = System.getProperty(SystemEnvironment.CRUISE_SERVER_SSL_PORT); System.setProperty(SystemEnvironment.CRUISE_SERVER_SSL_PORT, String.valueOf(9071)); } @After public void tearDown() { if (originalSslPort == null) { System.getProperties().remove(SystemEnvironment.CRUISE_SERVER_SSL_PORT); } else { System.setProperty(SystemEnvironment.CRUISE_SERVER_SSL_PORT, originalSslPort); } httpUtil.stop(); } enum METHOD { GET, POST, PUT } private static class ResponseAssertion { private final String requestedUrl; private final String servedUrl; private boolean useConfiguredUrls = false; private String serverBackupRunningSince; private Map<String, String> responseHeaders = new HashMap<String, String>(); private String referrer; private int responseCode = 200; private METHOD method; public ResponseAssertion(String requestedUrl, String servedUrl, METHOD method) { this.requestedUrl = requestedUrl; this.servedUrl = servedUrl; this.method = method; } public ResponseAssertion(String requestedUrl, String servedUrl) { this(requestedUrl, servedUrl, METHOD.GET); } public ResponseAssertion(String requestedUrl, String servedUrl, boolean useConfiguredUrls) { this(requestedUrl, servedUrl); this.useConfiguredUrls = useConfiguredUrls; } public ResponseAssertion(String requestedUrl, String servedUrl, METHOD method, boolean useConfiguredUrls) { this(requestedUrl, servedUrl, method); this.useConfiguredUrls = useConfiguredUrls; } public ResponseAssertion(String requestedUrl, String servedUrl, boolean useConfiguredUrls, final DateTime backupRunningSince) { this(requestedUrl, servedUrl, useConfiguredUrls); this.serverBackupRunningSince = backupRunningSince == null ? null : backupRunningSince.toString(); } public ResponseAssertion(String requestedUrl, String servedUrl, boolean useConfiguredUrls, boolean serverBackupRunningSince, Map<String, String> responseHeaders) { this(requestedUrl, servedUrl, useConfiguredUrls, serverBackupRunningSince ? BACKUP_RUNNING_SINCE : null); this.responseHeaders = responseHeaders; } public ResponseAssertion(String requestedUrl, String servedUrl, boolean useConfiguredUrls, boolean serverBackupRunningSince, Map<String, String> responseHeaders, String referrer) { this(requestedUrl, servedUrl, useConfiguredUrls, serverBackupRunningSince, responseHeaders); this.referrer = referrer; } public ResponseAssertion(String requestedUrl, String servedUrl, boolean useConfiguredUrls, boolean serverBackupRunningSince, int responseCode) { this(requestedUrl, servedUrl,useConfiguredUrls, serverBackupRunningSince ? BACKUP_RUNNING_SINCE : null); this.responseCode = responseCode; } @Override public String toString() { return String.format("ResponseAssertion{requestedUrl='%s', servedUrl='%s', useConfiguredUrls=%s, responseHeaders=%s, backupInProgress=%s, referrer=%s, responseCode=%d}", requestedUrl, servedUrl, useConfiguredUrls, responseHeaders, serverBackupRunningSince, referrer, responseCode); } } @DataPoint public static ResponseAssertion NO_REWRITE = new ResponseAssertion("http://127.1.1.1:" + HTTP + "/go/quux?hello=world", "http://127.1.1.1:" + HTTP + "/go/quux?hello=world"); @DataPoint public static ResponseAssertion NO_REWRITE_SSL = new ResponseAssertion("https://127.1.1.1:" + HTTPS +"/go/quux?hello=world", "https://127.1.1.1:" + HTTPS + "/go/quux?hello=world"); @DataPoint public static ResponseAssertion OAUTH = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/foo/oauth/bar?hello=world", "http://127.1.1.1:" + HTTP + "/go/foo/oauth/bar?hello=world");//error handled in ssh_helper @DataPoint public static ResponseAssertion RAILS_BOUND = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/agents/foo?hello=world", "http://127.1.1.1:" + HTTP + "/go/rails/agents/foo?hello=world"); @DataPoint public static ResponseAssertion RAILS_BOUND_SSL = new ResponseAssertion("https://127.1.1.1:" + HTTPS +"/go/agents/foo?hello=world", "https://127.1.1.1:" + HTTPS + "/go/rails/agents/foo?hello=world"); @DataPoint public static ResponseAssertion GADGET_RENDERING_IFRAME = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/gadgets/ifr?hello=world", "http://127.1.1.1:" + HTTP + "/go/rails/gadgets/ifr?hello=world"); @DataPoint public static ResponseAssertion UNDER_GADGET_RENDERING_IFRAME = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/gadgets/ifr/foo?hello=world", "http://127.1.1.1:" + HTTP + "/go/rails/gadgets/ifr/foo?hello=world");//error handled in ssh_helper @DataPoint public static ResponseAssertion GADGET_REQUEST = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/gadgets/makeRequest?hello=world", "http://127.1.1.1:" + HTTP + "/go/rails/gadgets/makeRequest?hello=world"); @DataPoint public static ResponseAssertion UNDER_GADGET_REQUEST = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/gadgets/makeRequest/junk?hello=world", "http://127.1.1.1:" + HTTP + "/go/rails/gadgets/makeRequest/junk?hello=world");//error handled in ssh_helper @DataPoint public static ResponseAssertion GADGET_JS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/gadgets/js/foo.js?version=24", "http://127.1.1.1:" + HTTP + "/go/rails/gadgets/js/foo.js?version=24"); @DataPoint public static ResponseAssertion GADGET_JS_NESTED = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/gadgets/js/foo/bar/baz/quux.js?version=24", "http://127.1.1.1:" + HTTP + "/go/rails/gadgets/js/foo/bar/baz/quux.js?version=24"); @DataPoint public static ResponseAssertion GADGET_CONCAT = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/gadgets/concat?foo=bar&baz=quux", "http://127.1.1.1:" + HTTP + "/go/rails/gadgets/concat?foo=bar&baz=quux"); @DataPoint public static ResponseAssertion GADGET_PROXY = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/gadgets/proxy?foo=bar&baz=quux", "http://127.1.1.1:" + HTTP + "/go/rails/gadgets/proxy?foo=bar&baz=quux"); @DataPoint public static ResponseAssertion GADGET_ADMIN = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/gadgets/bar?foo=bar&baz=quux", "http://127.1.1.1:" + HTTP + "/go/rails/admin/gadgets/bar?foo=bar&baz=quux");//error handled in ssh_helper @DataPoint public static ResponseAssertion GADGET_ADMIN_SSL = new ResponseAssertion("https://127.1.1.1:" + HTTPS +"/go/admin/gadgets/bar?foo=bar&baz=quux", "https://127.1.1.1:" + HTTPS + "/go/rails/admin/gadgets/bar?foo=bar&baz=quux");//error handled in ssh_helper @DataPoint public static ResponseAssertion GADGET_ADMIN_WITH_URLS_CONFIGURED = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/gadgets/bar?foo=bar&baz=quux", "https://127.2.2.2:" + HTTPS + "/go/rails/admin/gadgets/bar?foo=bar&baz=quux", true); @DataPoint public static ResponseAssertion PIPELINE_GROUPS_LISTING = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/pipelines?foo=bar&baz=quux", "http://127.1.1.1:" + HTTP + "/go/rails/admin/pipelines?foo=bar&baz=quux", true); @DataPoint public static ResponseAssertion PIPELINE_GROUP_EDIT = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/pipeline_group/group.name?foo=bar&baz=quux", "http://127.1.1.1:" + HTTP + "/go/rails/admin/pipeline_group/group.name?foo=bar&baz=quux", true); @DataPoint public static ResponseAssertion PIPELINE_GROUP_CREATE = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/pipeline_group", "http://127.1.1.1:" + HTTP + "/go/rails/admin/pipeline_group", true); @DataPoint public static ResponseAssertion TEMPLATES_LISTING = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/templates?foo=bar&baz=quux", "http://127.1.1.1:" + HTTP + "/go/rails/admin/templates?foo=bar&baz=quux", true); @DataPoint public static ResponseAssertion CONFIG_VIEW = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/config_view/templates/template_name", "http://127.1.1.1:" + HTTP + "/go/rails/config_view/templates/template_name"); @DataPoint public static ResponseAssertion PIPELINE_NEW = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/pipeline/new", "http://127.1.1.1:" + HTTP + "/go/rails/admin/pipeline/new", true); @DataPoint public static ResponseAssertion PIPELINE_CREATE = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/pipelines", "http://127.1.1.1:" + HTTP + "/go/rails/admin/pipelines", METHOD.POST); @DataPoint public static ResponseAssertion SERVER_BACKUP = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/backup", "http://127.1.1.1:" + HTTP + "/go/rails/admin/backup", true); @DataPoint public static ResponseAssertion SERVER_BACKUP_OTHER_ACTIONS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/backup/foo?abc=dfx", "http://127.1.1.1:" + HTTP + "/go/rails/admin/backup/foo?abc=dfx", true); @DataPoint public static ResponseAssertion STATIC_PAGES = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/static/foo.html?bar=baz", "http://127.1.1.1:" + HTTP + "/go/static/foo.html?bar=baz", true); @DataPoint public static final ResponseAssertion CONFIG_FILE_XML = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/configuration/file.xml", "http://127.1.1.1:" + HTTP +"/go/admin/restful/configuration/file/GET/xml"); @DataPoint public static final ResponseAssertion CONFIG_API_FOR_CURRENT = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/api/admin/config.xml", "http://127.1.1.1:" + HTTP + "/go/admin/restful/configuration/file/GET/xml?version=current"); @DataPoint public static final ResponseAssertion CONFIG_API_FOR_HISTORICAL = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/api/admin/config/some-md5.xml", "http://127.1.1.1:" + HTTP +"/go/admin/restful/configuration/file/GET/historical-xml?version=some-md5"); @DataPoint public static ResponseAssertion STATIC_PAGE_WHILE_BACKUP_IS_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/static/something/else?foo=bar", "http://127.1.1.1:" + HTTP +"/go/static/something/else?foo=bar", true, BACKUP_RUNNING_SINCE); @DataPoint public static ResponseAssertion IMAGES_WHILE_BACKUP_IS_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/images/foo.png", "http://127.1.1.1:" + HTTP +"/go/images/foo.png", true, BACKUP_RUNNING_SINCE); @DataPoint public static ResponseAssertion JAVASCRIPT_WHILE_BACKUP_IS_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/javascripts/foo.js", "http://127.1.1.1:" + HTTP +"/go/javascripts/foo.js", true, BACKUP_RUNNING_SINCE); @DataPoint public static ResponseAssertion COMPRESSED_JAVASCRIPT_WHILE_BACKUP_IS_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/compressed/all.js", "http://127.1.1.1:" + HTTP +"/go/compressed/all.js", true, BACKUP_RUNNING_SINCE); @DataPoint public static ResponseAssertion STYLESHEETS_WHILE_BACKUP_IS_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/stylesheets/foo.css", "http://127.1.1.1:" + HTTP +"/go/stylesheets/foo.css", true, BACKUP_RUNNING_SINCE); @DataPoint public static ResponseAssertion APP_PAGE_WHILE_SERVER_BACKUP_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/some/url?foo=bar&baz=quux", "http://127.1.1.1:" + HTTP + "/go/static/backup_in_progress.html?from=" + enc( "/go/some/url?foo=bar&baz=quux") + "&backup_started_at=" + enc(BACKUP_RUNNING_SINCE.toString()) + "&backup_started_by=" + BACKUP_STARTED_BY, true, BACKUP_RUNNING_SINCE); @DataPoint public static ResponseAssertion SERVER_HEALTH_URL_WHILE_SERVER_BACKUP_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/server/messages.json?bar=baz&quux=bang", "http://127.1.1.1:" + HTTP + "/go/echo-attribute/echo?bar=baz&quux=bang", true, true, m(GoServer.GO_FORCE_LOAD_PAGE_HEADER, "/go/static/backup_in_progress.html?from=" + enc("http://127.1.1.1:5197/go/some/url?foo=bar&baz=quux") + "&backup_started_at=" + enc(BACKUP_RUNNING_SINCE.toString()) + "&backup_started_by=" + BACKUP_STARTED_BY, "Content-Type", "application/json; charset=utf-8"), "http://127.1.1.1:" + HTTP +"/go/some/url?foo=bar&baz=quux"); @DataPoint public static ResponseAssertion BACKUP_POLLING_URL_WHILE_SERVER_BACKUP_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP + "/go/is_backup_finished.json?from=/go/foo/page?bar=baz", "http://127.1.1.1:" + HTTP + "/go/echo-attribute/echo?from=/go/foo/page?bar=baz", true, true, m(GoServer.GO_FORCE_LOAD_PAGE_HEADER, (String) null, "Content-Type", "application/json; charset=utf-8")); @DataPoint public static ResponseAssertion API_WHILE_SERVER_BACKUP_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP + "/go/api/pipelines/go_pipeline/stages.xml", "http://127.1.1.1:" + HTTP + "/go/echo-attribute/echo", true, true, 503); @DataPoint public static ResponseAssertion XML_ACTION_WHILE_SERVER_BACKUP_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP + "/go/foo.xml", "http://127.1.1.1:" + HTTP + "/go/echo-attribute/echo", true, true, 503); @DataPoint public static ResponseAssertion XML_ACTION_WITH_QUERY_STRING_WHILE_SERVER_BACKUP_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP + "/go/foo.xml?bar=baz", "http://127.1.1.1:" + HTTP + "/go/echo-attribute/echo?bar=baz", true, true, 503); @DataPoint public static ResponseAssertion JSON_ACTION_WHILE_SERVER_BACKUP_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP + "/go/foo.json", "http://127.1.1.1:" + HTTP + "/go/echo-attribute/echo", true, true, 503); @DataPoint public static ResponseAssertion JSON_ACTION_WITH_QUERY_STRING_WHILE_SERVER_BACKUP_IN_PROGRESS = new ResponseAssertion("http://127.1.1.1:" + HTTP + "/go/foo.json?quux=bang", "http://127.1.1.1:" + HTTP + "/go/echo-attribute/echo?quux=bang", true, true, 503); @DataPoint public static ResponseAssertion BACKUP_PAGE_WHEN_BACKUP_FINISHES = new ResponseAssertion("http://127.1.1.1:" + HTTP + "/go/static/backup_in_progress.html?from=" + enc("/go/some/url?foo=bar&baz=quux"), "http://127.1.1.1:" + HTTP + "/go/some/url?foo=bar&baz=quux", true, null); @DataPoint public static ResponseAssertion BACKUP_POLLING_URL_WHEN_BACKUP_FINISHES = new ResponseAssertion("http://127.1.1.1:" + HTTP + "/go/is_backup_finished.json?from=" + enc("/go/foo/page?bar=baz&foo=quux"), "http://127.1.1.1:" + HTTP + "/go/echo-attribute/echo?from="+ enc("/go/foo/page?bar=baz&foo=quux"), true, false, m(GoServer.GO_FORCE_LOAD_PAGE_HEADER, "/go/foo/page?bar=baz&foo=quux", "Content-Type", "application/json; charset=utf-8")); @DataPoint public static ResponseAssertion TASKS_LOOKUP_LISTING = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/commands", "http://127.1.1.1:" + HTTP + "/go/rails/admin/commands", true); @DataPoint public static ResponseAssertion TASKS_LOOKUP_SHOW = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/commands/show", "http://127.1.1.1:" + HTTP + "/go/rails/admin/commands/show", true); @DataPoint public static ResponseAssertion PLUGINS_LISTING = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/plugins", "http://127.1.1.1:" + HTTP + "/go/rails/admin/plugins", true); @DataPoint public static ResponseAssertion PACKAGE_REPOSITORIES_LISTING = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/package_repositories", "http://127.1.1.1:" + HTTP + "/go/rails/admin/package_repositories", true); @DataPoint public static ResponseAssertion PACKAGE_DEFINITIONS = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/package_definitions", "http://127.1.1.1:" + HTTP + "/go/rails/admin/package_definitions", true); @DataPoint public static ResponseAssertion PLUGGABLE_SCM = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/materials/pluggable_scm/check_connection/plugin_id", "http://127.1.1.1:" + HTTP + "/go/rails/admin/materials/pluggable_scm/check_connection/plugin_id", true); @DataPoint public static ResponseAssertion CONFIG_CHANGE = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/config_change/md5_value", "http://127.1.1.1:" + HTTP + "/go/rails/config_change/md5_value", true); @DataPoint public static ResponseAssertion CONFIG_XML_VIEW = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/config_xml", "http://127.1.1.1:" + HTTP + "/go/rails/admin/config_xml", METHOD.GET, true); @DataPoint public static ResponseAssertion CONFIG_XML_EDIT = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/config_xml/edit", "http://127.1.1.1:" + HTTP + "/go/rails/admin/config_xml/edit", METHOD.GET, true); @DataPoint public static ResponseAssertion ARTIFACT_API_HTML_LISTING = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/files/pipeline/1/stage/1/job.html", "http://127.1.1.1:" + HTTP + "/go/repository/restful/artifact/GET/html?pipelineName=pipeline&pipelineLabel=1&stageName=stage&stageCounter=1&buildName=job&filePath=", true); @DataPoint public static ResponseAssertion ARTIFACT_API_HTML_LISTING_FILENAME = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/files/pipeline/1/stage/1/target/abc%2Bfoo.txt", "http://127.1.1.1:" + HTTP + "/go/repository/restful/artifact/GET/?pipelineName=pipeline&pipelineLabel=1&stageName=stage&stageCounter=1&buildName=target&filePath=abc%2Bfoo.txt", true); @DataPoint public static ResponseAssertion ARTIFACT_API_JSON_LISTING = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/files/pipeline/1/stage/1/job.json", "http://127.1.1.1:" + HTTP + "/go/repository/restful/artifact/GET/json?pipelineName=pipeline&pipelineLabel=1&stageName=stage&stageCounter=1&buildName=job&filePath=", true); @DataPoint public static ResponseAssertion ARTIFACT_API_GET_FILE = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/files/pipeline/1/stage/1/job//tmp/file", "http://127.1.1.1:" + HTTP + "/go/repository/restful/artifact/GET/?pipelineName=pipeline&pipelineLabel=1&stageName=stage&stageCounter=1&buildName=job&filePath=%2Ftmp%2Ffile", true); @DataPoint public static ResponseAssertion ARTIFACT_API_PUSH_FILE = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/files/pipeline/1/stage/1/job//tmp/file", "http://127.1.1.1:" + HTTP + "/go/repository/restful/artifact/POST/?pipelineName=pipeline&pipelineLabel=1&stageName=stage&stageCounter=1&buildName=job&filePath=%2Ftmp%2Ffile", METHOD.POST, true); @DataPoint public static ResponseAssertion ARTIFACT_API_CHANGE_FILE = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/files/pipeline/1/stage/1/job/file", "http://127.1.1.1:" + HTTP + "/go/repository/restful/artifact/PUT/?pipelineName=pipeline&pipelineLabel=1&stageName=stage&stageCounter=1&buildName=job&filePath=file", METHOD.PUT, true); @DataPoint public static ResponseAssertion ADMIN_GARAGE_INDEX = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/garage", "http://127.1.1.1:" + HTTP + "/go/rails/admin/garage"); @DataPoint public static ResponseAssertion ADMIN_GARAGE_GC = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/admin/garage/gc", "http://127.1.1.1:" + HTTP + "/go/rails/admin/garage/gc", METHOD.POST); @DataPoint public static ResponseAssertion PIPELINE_DASHBOARD_JSON = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/pipelines.json", "http://127.1.1.1:" + HTTP + "/go/rails/pipelines.json", METHOD.GET); @DataPoint public static ResponseAssertion MATERIALS_VALUE_STREAM_MAP = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/materials/value_stream_map/fingerprint/revision", "http://127.1.1.1:" + HTTP + "/go/rails/materials/value_stream_map/fingerprint/revision", METHOD.GET); @DataPoint public static ResponseAssertion RAILS_INTERNAL_API = new ResponseAssertion("http://127.1.1.1:" + HTTP +"/go/api/config/internal/pluggable_task/indix.s3fetch", "http://127.1.1.1:" + HTTP + "/go/rails/api/config/internal/pluggable_task/indix.s3fetch", METHOD.GET); public static String enc(String str) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @Theory public void shouldRewrite(final ResponseAssertion assertion) throws IOException { when(wac.getBean("backupService")).thenReturn(new BackupStatusProvider() { public boolean isBackingUp() { return assertion.serverBackupRunningSince != null; } public String backupRunningSinceISO8601() { return assertion.serverBackupRunningSince; } public String backupStartedBy() { return "admin"; } }); useConfiguredUrls = assertion.useConfiguredUrls; HttpClient httpClient = new HttpClient(new HttpClientParams()); HttpMethod httpMethod; if (assertion.method == METHOD.GET) { httpMethod = new GetMethod(assertion.requestedUrl); } else if (assertion.method == METHOD.POST) { httpMethod = new PostMethod(assertion.requestedUrl); } else if (assertion.method == METHOD.PUT) { httpMethod = new PutMethod(assertion.requestedUrl); } else { throw new RuntimeException("Method has to be one of GET, POST and PUT. Was: " + assertion.method); } if (assertion.referrer != null) { httpMethod.setRequestHeader(new Header("Referer", assertion.referrer)); } int resp = httpClient.executeMethod(httpMethod); assertThat("status code match failed", resp, is(assertion.responseCode)); assertThat("handler url match failed", httpMethod.getResponseBodyAsString(), is(assertion.servedUrl)); for (Map.Entry<String, String> headerValPair : assertion.responseHeaders.entrySet()) { Header responseHeader = httpMethod.getResponseHeader(headerValPair.getKey()); if (headerValPair.getValue() == null) { assertThat("header match failed", responseHeader, is(nullValue())); } else { assertThat("header match failed", responseHeader.getValue(), is(headerValPair.getValue())); } } } }
package in.uncod.android.media.widget; import java.io.IOException; import android.content.Context; import android.media.MediaPlayer; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.SeekBar; public class AudioPlayerView extends LinearLayout implements MediaPlayer.OnPreparedListener, View.OnClickListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, SeekBar.OnSeekBarChangeListener { private MediaPlayer mMediaPlayer; private ImageButton mPlayPauseButton; private SeekBar mSeekBar; private String mMediaLocation; private PlayerState mPlayerState; Thread playbackProgressUpdater; Handler mHandler = new Handler(); int position = -1; enum PlayerState { Playing, Paused, Preparing } public AudioPlayerView(Context context) { super(context); initPlayer(); } public AudioPlayerView(Context context, AttributeSet attrs) { super(context, attrs); initPlayer(); } public AudioPlayerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initPlayer(); } private void initPlayer() { mPlayPauseButton = new ImageButton(getContext()); mPlayPauseButton.setOnClickListener(this); addView(mPlayPauseButton); updateButtonState(PlayerState.Preparing); mSeekBar = new SeekBar(getContext()); mSeekBar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); addView(mSeekBar); mSeekBar.setOnSeekBarChangeListener(this); setGravity(Gravity.CENTER_VERTICAL); } @Override public void onPrepared(MediaPlayer mediaPlayer) { updateButtonState(PlayerState.Paused); if (position > 0) { mMediaPlayer.start(); mMediaPlayer.seekTo(position); updateButtonState(PlayerState.Playing); } playbackProgressUpdater = new Thread(new ProgressUpdate()); playbackProgressUpdater.start(); } @Override public void onCompletion(MediaPlayer mediaPlayer) { updateButtonState(PlayerState.Paused); } @Override public boolean onError(MediaPlayer mediaPlayer, int i, int i1) { return false; } @Override public void onClick(View view) { switch (mPlayerState) { case Paused: mMediaPlayer.start(); updateButtonState(PlayerState.Playing); break; case Playing: pausePlaying(); break; } } public void setMediaLocation(String location) { setMediaLocation(location, -1); } public void setMediaLocation(String location, int position) { this.position = position; mMediaPlayer = new MediaPlayer(); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnErrorListener(this); mMediaLocation = location; prepareMediaPlayer(); } private void prepareMediaPlayer() { updateButtonState(PlayerState.Preparing); if (mMediaLocation != null) { try { mMediaPlayer.setDataSource(mMediaLocation); mMediaPlayer.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } } private void updateButtonState(final PlayerState playerState) { mPlayerState = playerState; mHandler.post(new Runnable() { @Override public void run() { switch (playerState) { case Paused: mPlayPauseButton.setImageResource(android.R.drawable.ic_media_play); mPlayPauseButton.setEnabled(true); break; case Playing: mPlayPauseButton.setImageResource(android.R.drawable.ic_media_pause); mPlayPauseButton.setEnabled(true); break; case Preparing: mPlayPauseButton.setImageResource(android.R.drawable.ic_media_play); mPlayPauseButton.setEnabled(false); break; } } }); } private class ProgressUpdate implements Runnable { public void run() { while (mMediaPlayer != null) { double percent = (double) mMediaPlayer.getCurrentPosition() / mMediaPlayer.getDuration(); final int progress = (int) (percent * 100.0); mHandler.post(new Runnable() { public void run() { mSeekBar.setProgress(progress); mSeekBar.setMax(100); } }); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); mPlayPauseButton.setEnabled(enabled); mSeekBar.setProgress(0); try { if (mMediaPlayer != null) { mMediaPlayer.seekTo(0); } } finally { // Ignore exception; should only happen when no media has been loaded into the player } } @Override public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) { if (fromUser && mMediaPlayer != null) { int position = (int) (mMediaPlayer.getDuration() * (i / 100.0)); mMediaPlayer.seekTo(position); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } public boolean isPlaying() { return mMediaPlayer != null && mMediaPlayer.isPlaying(); } public void pausePlaying() { if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); updateButtonState(PlayerState.Paused); } } public void stopPlaying() { if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); mMediaPlayer.seekTo(0); updateButtonState(PlayerState.Paused); } } public int getCurrentPosition() { if (mMediaPlayer != null) { try { return mMediaPlayer.getCurrentPosition(); } catch (IllegalStateException e) { } } return -1; } }
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * 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. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package spec4j.asm.tree; import java.util.ListIterator; import java.util.NoSuchElementException; import spec4j.asm.MethodVisitor; /** * A doubly linked list of {@link AbstractInsnNode} objects. <i>This * implementation is not thread safe</i>. */ public class InsnList { /** * The number of instructions in this list. */ private int size; /** * The first instruction in this list. May be <tt>null</tt>. */ private AbstractInsnNode first; /** * The last instruction in this list. May be <tt>null</tt>. */ private AbstractInsnNode last; /** * A cache of the instructions of this list. This cache is used to improve * the performance of the {@link #get} method. */ AbstractInsnNode[] cache; /** * Returns the number of instructions in this list. * * @return the number of instructions in this list. */ public int size() { return size; } /** * Returns the first instruction in this list. * * @return the first instruction in this list, or <tt>null</tt> if the list * is empty. */ public AbstractInsnNode getFirst() { return first; } /** * Returns the last instruction in this list. * * @return the last instruction in this list, or <tt>null</tt> if the list * is empty. */ public AbstractInsnNode getLast() { return last; } /** * Returns the instruction whose index is given. This method builds a cache * of the instructions in this list to avoid scanning the whole list each * time it is called. Once the cache is built, this method run in constant * time. This cache is invalidated by all the methods that modify the list. * * @param index * the index of the instruction that must be returned. * @return the instruction whose index is given. * @throws IndexOutOfBoundsException * if (index &lt; 0 || index &gt;= size()). */ public AbstractInsnNode get(final int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } if (cache == null) { cache = toArray(); } return cache[index]; } /** * Returns <tt>true</tt> if the given instruction belongs to this list. This * method always scans the instructions of this list until it finds the * given instruction or reaches the end of the list. * * @param insn * an instruction. * @return <tt>true</tt> if the given instruction belongs to this list. */ public boolean contains(final AbstractInsnNode insn) { AbstractInsnNode i = first; while (i != null && i != insn) { i = i.next; } return i != null; } /** * Returns the index of the given instruction in this list. This method * builds a cache of the instruction indexes to avoid scanning the whole * list each time it is called. Once the cache is built, this method run in * constant time. The cache is invalidated by all the methods that modify * the list. * * @param insn * an instruction <i>of this list</i>. * @return the index of the given instruction in this list. <i>The result of * this method is undefined if the given instruction does not belong * to this list</i>. Use {@link #contains contains} to test if an * instruction belongs to an instruction list or not. */ public int indexOf(final AbstractInsnNode insn) { if (cache == null) { cache = toArray(); } return insn.index; } /** * Makes the given visitor visit all of the instructions in this list. * * @param mv * the method visitor that must visit the instructions. */ public void accept(final MethodVisitor mv) { AbstractInsnNode insn = first; while (insn != null) { insn.accept(mv); insn = insn.next; } } /** * Returns an iterator over the instructions in this list. * * @return an iterator over the instructions in this list. */ public ListIterator<AbstractInsnNode> iterator() { return iterator(0); } /** * Returns an iterator over the instructions in this list. * * @param index * index of instruction for the iterator to start at * * @return an iterator over the instructions in this list. */ @SuppressWarnings("unchecked") public ListIterator<AbstractInsnNode> iterator(int index) { return new InsnListIterator(index); } /** * Returns an array containing all of the instructions in this list. * * @return an array containing all of the instructions in this list. */ public AbstractInsnNode[] toArray() { int i = 0; AbstractInsnNode elem = first; AbstractInsnNode[] insns = new AbstractInsnNode[size]; while (elem != null) { insns[i] = elem; elem.index = i++; elem = elem.next; } return insns; } /** * Replaces an instruction of this list with another instruction. * * @param location * an instruction <i>of this list</i>. * @param insn * another instruction, <i>which must not belong to any * {@link InsnList}</i>. */ public void set(final AbstractInsnNode location, final AbstractInsnNode insn) { AbstractInsnNode next = location.next; insn.next = next; if (next != null) { next.prev = insn; } else { last = insn; } AbstractInsnNode prev = location.prev; insn.prev = prev; if (prev != null) { prev.next = insn; } else { first = insn; } if (cache != null) { int index = location.index; cache[index] = insn; insn.index = index; } else { insn.index = 0; // insn now belongs to an InsnList } location.index = -1; // i no longer belongs to an InsnList location.prev = null; location.next = null; } /** * Adds the given instruction to the end of this list. * * @param insn * an instruction, <i>which must not belong to any * {@link InsnList}</i>. */ public void add(final AbstractInsnNode insn) { ++size; if (last == null) { first = insn; last = insn; } else { last.next = insn; insn.prev = last; } last = insn; cache = null; insn.index = 0; // insn now belongs to an InsnList } /** * Adds the given instructions to the end of this list. * * @param insns * an instruction list, which is cleared during the process. This * list must be different from 'this'. */ public void add(final InsnList insns) { if (insns.size == 0) { return; } size += insns.size; if (last == null) { first = insns.first; last = insns.last; } else { AbstractInsnNode elem = insns.first; last.next = elem; elem.prev = last; last = insns.last; } cache = null; insns.removeAll(false); } /** * Inserts the given instruction at the begining of this list. * * @param insn * an instruction, <i>which must not belong to any * {@link InsnList}</i>. */ public void insert(final AbstractInsnNode insn) { ++size; if (first == null) { first = insn; last = insn; } else { first.prev = insn; insn.next = first; } first = insn; cache = null; insn.index = 0; // insn now belongs to an InsnList } /** * Inserts the given instructions at the begining of this list. * * @param insns * an instruction list, which is cleared during the process. This * list must be different from 'this'. */ public void insert(final InsnList insns) { if (insns.size == 0) { return; } size += insns.size; if (first == null) { first = insns.first; last = insns.last; } else { AbstractInsnNode elem = insns.last; first.prev = elem; elem.next = first; first = insns.first; } cache = null; insns.removeAll(false); } /** * Inserts the given instruction after the specified instruction. * * @param location * an instruction <i>of this list</i> after which insn must be * inserted. * @param insn * the instruction to be inserted, <i>which must not belong to * any {@link InsnList}</i>. */ public void insert(final AbstractInsnNode location, final AbstractInsnNode insn) { ++size; AbstractInsnNode next = location.next; if (next == null) { last = insn; } else { next.prev = insn; } location.next = insn; insn.next = next; insn.prev = location; cache = null; insn.index = 0; // insn now belongs to an InsnList } /** * Inserts the given instructions after the specified instruction. * * @param location * an instruction <i>of this list</i> after which the * instructions must be inserted. * @param insns * the instruction list to be inserted, which is cleared during * the process. This list must be different from 'this'. */ public void insert(final AbstractInsnNode location, final InsnList insns) { if (insns.size == 0) { return; } size += insns.size; AbstractInsnNode ifirst = insns.first; AbstractInsnNode ilast = insns.last; AbstractInsnNode next = location.next; if (next == null) { last = ilast; } else { next.prev = ilast; } location.next = ifirst; ilast.next = next; ifirst.prev = location; cache = null; insns.removeAll(false); } /** * Inserts the given instruction before the specified instruction. * * @param location * an instruction <i>of this list</i> before which insn must be * inserted. * @param insn * the instruction to be inserted, <i>which must not belong to * any {@link InsnList}</i>. */ public void insertBefore(final AbstractInsnNode location, final AbstractInsnNode insn) { ++size; AbstractInsnNode prev = location.prev; if (prev == null) { first = insn; } else { prev.next = insn; } location.prev = insn; insn.next = location; insn.prev = prev; cache = null; insn.index = 0; // insn now belongs to an InsnList } /** * Inserts the given instructions before the specified instruction. * * @param location * an instruction <i>of this list</i> before which the * instructions must be inserted. * @param insns * the instruction list to be inserted, which is cleared during * the process. This list must be different from 'this'. */ public void insertBefore(final AbstractInsnNode location, final InsnList insns) { if (insns.size == 0) { return; } size += insns.size; AbstractInsnNode ifirst = insns.first; AbstractInsnNode ilast = insns.last; AbstractInsnNode prev = location.prev; if (prev == null) { first = ifirst; } else { prev.next = ifirst; } location.prev = ilast; ilast.next = location; ifirst.prev = prev; cache = null; insns.removeAll(false); } /** * Removes the given instruction from this list. * * @param insn * the instruction <i>of this list</i> that must be removed. */ public void remove(final AbstractInsnNode insn) { --size; AbstractInsnNode next = insn.next; AbstractInsnNode prev = insn.prev; if (next == null) { if (prev == null) { first = null; last = null; } else { prev.next = null; last = prev; } } else { if (prev == null) { first = next; next.prev = null; } else { prev.next = next; next.prev = prev; } } cache = null; insn.index = -1; // insn no longer belongs to an InsnList insn.prev = null; insn.next = null; } /** * Removes all of the instructions of this list. * * @param mark * if the instructions must be marked as no longer belonging to * any {@link InsnList}. */ void removeAll(final boolean mark) { if (mark) { AbstractInsnNode insn = first; while (insn != null) { AbstractInsnNode next = insn.next; insn.index = -1; // insn no longer belongs to an InsnList insn.prev = null; insn.next = null; insn = next; } } size = 0; first = null; last = null; cache = null; } /** * Removes all of the instructions of this list. */ public void clear() { removeAll(false); } /** * Reset all labels in the instruction list. This method should be called * before reusing same instructions list between several * <code>ClassWriter</code>s. */ public void resetLabels() { AbstractInsnNode insn = first; while (insn != null) { if (insn instanceof LabelNode) { ((LabelNode) insn).resetLabel(); } insn = insn.next; } } // this class is not generified because it will create bridges @SuppressWarnings("rawtypes") private final class InsnListIterator implements ListIterator { AbstractInsnNode next; AbstractInsnNode prev; AbstractInsnNode remove; InsnListIterator(int index) { if (index == size()) { next = null; prev = getLast(); } else { next = get(index); prev = next.prev; } } public boolean hasNext() { return next != null; } public Object next() { if (next == null) { throw new NoSuchElementException(); } AbstractInsnNode result = next; prev = result; next = result.next; remove = result; return result; } public void remove() { if (remove != null) { if (remove == next) { next = next.next; } else { prev = prev.prev; } InsnList.this.remove(remove); remove = null; } else { throw new IllegalStateException(); } } public boolean hasPrevious() { return prev != null; } public Object previous() { AbstractInsnNode result = prev; next = result; prev = result.prev; remove = result; return result; } public int nextIndex() { if (next == null) { return size(); } if (cache == null) { cache = toArray(); } return next.index; } public int previousIndex() { if (prev == null) { return -1; } if (cache == null) { cache = toArray(); } return prev.index; } public void add(Object o) { if (next != null) { InsnList.this.insertBefore(next, (AbstractInsnNode) o); } else if (prev != null) { InsnList.this.insert(prev, (AbstractInsnNode) o); } else { InsnList.this.add((AbstractInsnNode) o); } prev = (AbstractInsnNode) o; remove = null; } public void set(Object o) { if (remove != null) { InsnList.this.set(remove, (AbstractInsnNode) o); if (remove == prev) { prev = (AbstractInsnNode) o; } else { next = (AbstractInsnNode) o; } } else { throw new IllegalStateException(); } } } }
/* * Copyright 2017 Antti Nieminen * * 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.haulmont.cuba.web.widgets.addons.aceeditor; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Collections; import java.util.EventObject; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.haulmont.cuba.web.widgets.WebJarResource; import com.vaadin.shared.Registration; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceAnnotation; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceAnnotation.MarkerAnnotation; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceAnnotation.RowAnnotation; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceDoc; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceEditorClientRpc; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceEditorServerRpc; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceEditorState; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceMarker; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceMarker.OnTextChange; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceMarker.Type; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceRange; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.TransportDiff; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.TransportDoc.TransportRange; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.Util; import com.vaadin.event.FieldEvents.BlurEvent; import com.vaadin.event.FieldEvents.BlurListener; import com.vaadin.event.FieldEvents.BlurNotifier; import com.vaadin.event.FieldEvents.FocusEvent; import com.vaadin.event.FieldEvents.FocusListener; import com.vaadin.event.FieldEvents.FocusNotifier; import com.vaadin.ui.AbstractField; import com.vaadin.util.ReflectTools; /** * * AceEditor wraps an Ace code editor inside a TextField-like Vaadin component. * */ @SuppressWarnings("serial") @WebJarResource(value = { "ace-builds:ace.js", "ace-builds:ext-searchbox.js", "diff-match-patch:diff_match_patch.js" }) public class AceEditor extends AbstractField<String> implements BlurNotifier, FocusNotifier { private String value; public static class DiffEvent extends Event { public static String EVENT_ID = "aceeditor-diff"; private final ServerSideDocDiff diff; public DiffEvent(AceEditor ed, ServerSideDocDiff diff) { super(ed); this.diff = diff; } public ServerSideDocDiff getDiff() { return diff; } } public interface DiffListener extends Serializable { Method diffMethod = ReflectTools.findMethod( DiffListener.class, "diff", DiffEvent.class); void diff(DiffEvent e); } public static class SelectionChangeEvent extends Event { public static String EVENT_ID = "aceeditor-selection"; private final TextRange selection; public SelectionChangeEvent(AceEditor ed) { super(ed); this.selection = ed.getSelection(); } public TextRange getSelection() { return selection; } } public interface SelectionChangeListener extends Serializable { Method selectionChangedMethod = ReflectTools .findMethod(SelectionChangeListener.class, "selectionChanged", SelectionChangeEvent.class); void selectionChanged(SelectionChangeEvent e); } public static class TextChangeEventImpl extends EventObject { private final TextRange selection; private final String text; private TextChangeEventImpl(final AceEditor ace, String text, AceRange selection) { super(ace); this.text = text; this.selection = ace.getSelection(); } // @Override // public AbstractTextField getComponent() { // return (AbstractTextField) super.getComponent(); // } // @Override public int getCursorPosition() { return selection.getEnd(); } // @Override public String getText() { return text; } } // By default, using the version 1.1.9 of Ace from GitHub via rawgit.com. // It's recommended to host the Ace files yourself as described in README. private static final String DEFAULT_ACE_PATH = "//cdn.rawgit.com/ajaxorg/ace-builds/e3ccd2c654cf45ee41ffb09d0e7fa5b40cf91a8f/src-min-noconflict"; private AceDoc doc = new AceDoc(); private boolean isFiringTextChangeEvent; private boolean latestFocus = false; private long latestMarkerId = 0L; private static final Logger logger = Logger.getLogger(AceEditor.class .getName()); private boolean onRoundtrip = false; private AceEditorServerRpc rpc = new AceEditorServerRpc() { @Override public void changed(TransportDiff diff, TransportRange selection, boolean focused) { clientChanged(diff, selection, focused); } @Override public void changedDelayed(TransportDiff diff, TransportRange selection, boolean focused) { clientChanged(diff, selection, focused); } }; private TextRange selection = new TextRange("", 0, 0, 0, 0); // {startPos,endPos} or {startRow,startCol,endRow,endCol} private Integer[] selectionToClient = null; private AceDoc shadow = new AceDoc(); { logger.setLevel(Level.WARNING); } public AceEditor() { super(); setWidth("300px"); setHeight("200px"); setModePath(DEFAULT_ACE_PATH); setThemePath(DEFAULT_ACE_PATH); setWorkerPath(DEFAULT_ACE_PATH); registerRpc(rpc); } @Override protected void doSetValue(String s) { this.value = s; } public void addDiffListener(DiffListener listener) { addListener(DiffEvent.EVENT_ID, DiffEvent.class, listener, DiffListener.diffMethod); } @Override public Registration addFocusListener(FocusListener listener) { Registration registration = addListener(FocusEvent.EVENT_ID, FocusEvent.class, listener, FocusListener.focusMethod); getState().listenToFocusChanges = true; return registration; } @Override public Registration addBlurListener(BlurListener listener) { Registration registration = addListener(BlurEvent.EVENT_ID, BlurEvent.class, listener, BlurListener.blurMethod); getState().listenToFocusChanges = true; return registration; } /** * Adds an ace marker. The id of the marker must be unique within this * editor. * * @param marker * @return marker id */ public String addMarker(AceMarker marker) { doc = doc.withAdditionalMarker(marker); markAsDirty(); return marker.getMarkerId(); } /** * Adds an ace marker with a generated id. The id is unique within this * editor. * * @param range * @param cssClass * @param type * @param inFront * @param onChange * @return marker id */ public String addMarker(AceRange range, String cssClass, Type type, boolean inFront, OnTextChange onChange) { return addMarker(new AceMarker(newMarkerId(), range, cssClass, type, inFront, onChange)); } public void addMarkerAnnotation(AceAnnotation ann, AceMarker marker) { addMarkerAnnotation(ann, marker.getMarkerId()); } public void addMarkerAnnotation(AceAnnotation ann, String markerId) { doc = doc.withAdditionalMarkerAnnotation(new MarkerAnnotation(markerId, ann)); markAsDirty(); } public void addRowAnnotation(AceAnnotation ann, int row) { doc = doc.withAdditionalRowAnnotation(new RowAnnotation(row, ann)); markAsDirty(); } public void addSelectionChangeListener(SelectionChangeListener listener) { addListener(SelectionChangeEvent.EVENT_ID, SelectionChangeEvent.class, listener, SelectionChangeListener.selectionChangedMethod); getState().listenToSelectionChanges = true; } @Override public void beforeClientResponse(boolean initial) { super.beforeClientResponse(initial); if (initial) { getState().initialValue = doc.asTransport(); shadow = doc; } else if (onRoundtrip) { ServerSideDocDiff diff = ServerSideDocDiff.diff(shadow, doc); shadow = doc; TransportDiff td = diff.asTransport(); getRpcProxy(AceEditorClientRpc.class).diff(td); onRoundtrip = false; } else if (true /* TODO !shadow.equals(doc) */) { getRpcProxy(AceEditorClientRpc.class).changedOnServer(); } if (selectionToClient != null) { // {startPos,endPos} if (selectionToClient.length == 2) { AceRange r = AceRange.fromPositions(selectionToClient[0], selectionToClient[1], doc.getText()); getState().selection = r.asTransport(); } // {startRow,startCol,endRow,endCol} else if (selectionToClient.length == 4) { TransportRange tr = new TransportRange(selectionToClient[0], selectionToClient[1], selectionToClient[2], selectionToClient[3]); getState().selection = tr; } selectionToClient = null; } } public void clearMarkerAnnotations() { Set<MarkerAnnotation> manns = Collections.emptySet(); doc = doc.withMarkerAnnotations(manns); markAsDirty(); } public void clearMarkers() { doc = doc.withoutMarkers(); markAsDirty(); } public void clearRowAnnotations() { Set<RowAnnotation> ranns = Collections.emptySet(); doc = doc.withRowAnnotations(ranns); markAsDirty(); } public int getCursorPosition() { return selection.getEnd(); } public AceDoc getDoc() { return doc; } public TextRange getSelection() { return selection; } public Class<? extends String> getType() { return String.class; } public void removeDiffListener(DiffListener listener) { removeListener(DiffEvent.EVENT_ID, DiffEvent.class, listener); } public void removeFocusListener(FocusListener listener) { removeListener(FocusEvent.EVENT_ID, FocusEvent.class, listener); getState().listenToFocusChanges = !getListeners(FocusEvent.class) .isEmpty() || !getListeners(BlurEvent.class).isEmpty(); } public void removeBlurListener(BlurListener listener) { removeListener(BlurEvent.EVENT_ID, BlurEvent.class, listener); getState().listenToFocusChanges = !getListeners(FocusEvent.class) .isEmpty() || !getListeners(BlurEvent.class).isEmpty(); } public void removeMarker(AceMarker marker) { removeMarker(marker.getMarkerId()); } public void removeMarker(String markerId) { doc = doc.withoutMarker(markerId); markAsDirty(); } public void removeSelectionChangeListener(SelectionChangeListener listener) { removeListener(SelectionChangeEvent.EVENT_ID, SelectionChangeEvent.class, listener); getState().listenToSelectionChanges = !getListeners( SelectionChangeEvent.class).isEmpty(); } // @Override // public void removeTextChangeListener(ValueChangeListener<String> listener) { // removeListener(listener); // } public void setBasePath(String path) { setAceConfig("basePath", path); } /** * Sets the cursor position to be pos characters from the beginning of the * text. * * @param pos */ public void setCursorPosition(int pos) { setSelection(pos, pos); } /** * Sets the cursor on the given row and column. * * @param row * starting from 0 * @param col * starting from 0 */ public void setCursorRowCol(int row, int col) { setSelectionRowCol(row, col, row, col); } public void setDoc(AceDoc doc) { if (this.doc.equals(doc)) { return; } this.doc = doc; boolean wasReadOnly = isReadOnly(); setReadOnly(false); setValue(doc.getText()); setReadOnly(wasReadOnly); markAsDirty(); } public void setMode(AceMode mode) { getState().mode = mode.toString(); } public void setMode(String mode) { getState().mode = mode; } public void setModePath(String path) { setAceConfig("modePath", path); } /** * Sets the selection to be between characters [start,end). * * The cursor will be at the end. * * @param start * @param end */ // TODO public void setSelection(int start, int end) { setSelectionToClient(new Integer[] { start, end }); setInternalSelection(new TextRange(getValue(), start, end)); } /** * Sets the selection to be between the given (startRow,startCol) and * (endRow, endCol). * * The cursor will be at the end. * * @param startRow * starting from 0 * @param startCol * starting from 0 * @param endRow * starting from 0 * @param endCol * starting from 0 */ public void setSelectionRowCol(int startRow, int startCol, int endRow, int endCol) { setSelectionToClient(new Integer[] { startRow, startCol, endRow, endCol }); setInternalSelection(new TextRange(doc.getText(), startRow, startCol, endRow, endCol)); } // /** // * Sets the mode how the TextField triggers {@link TextChangeEvent}s. // * // * @param inputEventMode // * the new mode // * // * @see TextChangeEventMode // */ // public void setTextChangeEventMode(TextChangeEventMode inputEventMode) { // getState().changeMode = inputEventMode.toString(); // } // // /** // * The text change timeout modifies how often text change events are // * communicated to the application when {@link #setTextChangeEventMode} is // * {@link TextChangeEventMode#LAZY} or {@link TextChangeEventMode#TIMEOUT}. // * // * // * @param timeoutMs // * the timeout in milliseconds // */ // public void setTextChangeTimeout(int timeoutMs) { // getState().changeTimeout = timeoutMs; // // } /** * Scrolls to the given row. First row is 0. * */ public void scrollToRow(int row) { getState().scrollToRow = row; } /** * Scrolls the to the given position (characters from the start of the * file). * */ public void scrollToPosition(int pos) { int[] rowcol = Util.lineColFromCursorPos(getValue(), pos, 0); scrollToRow(rowcol[0]); } public void setTheme(AceTheme theme) { getState().theme = theme.toString(); } public void setTheme(String theme) { getState().theme = theme; } public void setThemePath(String path) { setAceConfig("themePath", path); } public void setUseWorker(boolean useWorker) { getState().useWorker = useWorker; } public void setWordWrap(boolean ww) { getState().wordwrap = ww; } public void setShowGutter(boolean showGutter) { getState().showGutter = showGutter; } public boolean isShowGutter() { return getState(false).showGutter; } public void setShowPrintMargin(boolean showPrintMargin) { getState().showPrintMargin = showPrintMargin; } public boolean isShowPrintMargin() { return getState(false).showPrintMargin; } public void setHighlightActiveLine(boolean highlightActiveLine) { getState().highlightActiveLine = highlightActiveLine; } public boolean isHighlightActiveLine() { return getState(false).highlightActiveLine; } public void setWorkerPath(String path) { setAceConfig("workerPath", path); } /** * Use "auto" if you want to detect font size from CSS * * @param size * auto or font size */ public void setFontSize(String size) { getState().fontSize = size; } public String getFontSize() { return getState(false).fontSize; } public void setHighlightSelectedWord(boolean highlightSelectedWord) { getState().highlightSelectedWord = highlightSelectedWord; } public boolean isHighlightSelectedWord() { return getState(false).highlightSelectedWord; } public void setShowInvisibles(boolean showInvisibles) { getState().showInvisibles = showInvisibles; } public boolean isShowInvisibles() { return getState(false).showInvisibles; } public void setDisplayIndentGuides(boolean displayIndentGuides) { getState().displayIndentGuides = displayIndentGuides; } public boolean isDisplayIndentGuides() { return getState(false).displayIndentGuides; } public void setTabSize(int size) { getState().tabSize = size; } public void setUseSoftTabs(boolean softTabs) { getState().softTabs = softTabs; } protected void clientChanged(TransportDiff diff, TransportRange selection, boolean focused) { diffFromClient(diff); selectionFromClient(selection); if (latestFocus != focused) { latestFocus = focused; if (focused) { fireFocus(); } else { fireBlur(); } } clearStateFromServerToClient(); } // Here we clear the selection etc. we sent earlier. // The client has already received the values, // and we must clear them at some point to not keep // setting the same selection etc. over and over. // TODO: this is a bit messy... private void clearStateFromServerToClient() { getState().selection = null; getState().scrollToRow = -1; } @Override protected AceEditorState getState() { return (AceEditorState) super.getState(); } @Override protected AceEditorState getState(boolean markAsDirty) { return (AceEditorState) super.getState(markAsDirty); } @Override public void setValue(String newValue) { super.setValue(newValue); doc = doc.withText(newValue); } @Override public String getValue() { return value; } private void diffFromClient(TransportDiff d) { String previousText = doc.getText(); ServerSideDocDiff diff = ServerSideDocDiff.fromTransportDiff(d); shadow = diff.applyTo(shadow); doc = diff.applyTo(doc); if (!TextUtils.equals(doc.getText(), previousText)) { setValue(doc.getText(), true); fireTextChangeEvent(); } if (!diff.isIdentity()) { fireDiff(diff); } onRoundtrip = true; markAsDirty(); } private void fireBlur() { fireEvent(new BlurEvent(this)); } private void fireDiff(ServerSideDocDiff diff) { fireEvent(new DiffEvent(this, diff)); } private void fireFocus() { fireEvent(new FocusEvent(this)); } private void fireSelectionChanged() { fireEvent(new SelectionChangeEvent(this)); } private void fireTextChangeEvent() { if (!isFiringTextChangeEvent) { isFiringTextChangeEvent = true; try { fireEvent(new TextChangeEventImpl(this, getValue(), selection)); } finally { isFiringTextChangeEvent = false; } } } private String newMarkerId() { return "m" + (++latestMarkerId); } private void selectionFromClient(TransportRange sel) { TextRange newSel = new TextRange(doc.getText(), AceRange.fromTransport(sel)); if (newSel.equals(selection)) { return; } setInternalSelection(newSel); fireSelectionChanged(); } private void setAceConfig(String key, String value) { getState().config.put(key, value); } private void setInternalSelection(TextRange selection) { this.selection = selection; getState().selection = selection.asTransport(); } private void setSelectionToClient(Integer[] stc) { selectionToClient = stc; markAsDirty(); } }
/** * For copyright information see the LICENSE document. */ package gwlpr.loginshard.models; import gwlpr.database.jpa.MapJpaController; import gwlpr.protocol.intershard.utils.DistrictLanguage; import gwlpr.protocol.intershard.utils.DistrictRegion; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import realityshard.container.gameapp.GameAppContext; import realityshard.container.gameapp.GameAppManager; import realityshard.container.util.Handle; /** * Stores created mapshard references and manages them. * * TODO: If a mapshard is filled with people, create a new instance rather * than returning it when requested. * * TODO: Enhance this to better manage the mapshards * * TODO: Add fields for pvp and outpost to the mapshards * * @author _rusty */ public final class MapDispatchModel { private static final Logger LOGGER = LoggerFactory.getLogger(MapDispatchModel.class); private final Map<Handle<GameAppContext>, MapShardBean> mapShardMetaInfo = new ConcurrentHashMap<>(); private final Handle<GameAppContext> context; /** * Constructor. * * @param context We need the context to create mapshards * or shut them down... */ public MapDispatchModel(Handle<GameAppContext> context) { this.context = context; } /** * Get or create a map shard context with the game-map-id and default * region / language settings. * * @param gameMapId * @return The context's bean, or null if it couldn't be created. */ public Handle<GameAppContext> getOrCreateExplorable(int gameMapId) { return getOrCreate(gameMapId, DistrictRegion.Default, DistrictLanguage.Default, 0, false); } /** * Get or create a map shard context with the game-map-id and specified * region / language settings. * * @param gameMapId * @param region * @param language * @return The context, or null if it couldn't be created. */ public Handle<GameAppContext> getOrCreate(int gameMapId, DistrictRegion region, DistrictLanguage language, int instanceNum, boolean isOutpost) { DistrictRegion reg = region; DistrictLanguage lan = language; if (region == DistrictRegion.Default || language == DistrictLanguage.Default) { reg = DistrictRegion.Europe; lan = DistrictLanguage.English; } MapShardBean result = null; // search for the mapshard... for (MapShardBean mapShard : mapShardMetaInfo.values()) { if ( mapShard.getMap().getGameID() == gameMapId && mapShard.getInstanceNumber() == instanceNum && mapShard.getRegion() == reg && mapShard.getLanguage() == lan) { // found the perfect shard... result = mapShard; } } // none found, creating a new one if (result == null) { result = tryCreate(gameMapId, reg, lan, instanceNum, isOutpost); // failcheck if (result == null) { return null; } } return result.getMapShardContext(); } /** * We've instructed a server to accept a client, and wait for it to reply. * * @param clientHandle * @param mapShardContext */ public void clientWaitingFor(Handle<ClientBean> clientHandle, Handle<GameAppContext> mapShardContext) { MapShardBean mapShard = mapShardMetaInfo.get(mapShardContext); if (mapShard != null) { mapShard.getWaitingClients().add(clientHandle); } } /** * Try to resolve a pending client dispatch and add it to the * list of connected clients. * * * @param clientHandle * @param mapShardContext * @param accepted True or false, depending on the client has * been accepted by the mapshard. */ public void clientGotAcceptedBy(Handle<ClientBean> clientHandle, Handle<GameAppContext> mapShardContext, boolean accepted) { MapShardBean mapShard = mapShardMetaInfo.get(mapShardContext); if (mapShard != null) { mapShard.getWaitingClients().remove(clientHandle); if (accepted) { mapShard.getPendingClients().add(clientHandle); } } } /** * Needs to be called when the dispatch of a client is done. * This will remove the client from the pending clients and add it to the * connected clients list. * * * @param clientHandle * @param mapShardContext */ public void dispatchDone(Handle<ClientBean> clientHandle, Handle<GameAppContext> mapShardContext) { MapShardBean mapShard = mapShardMetaInfo.get(mapShardContext); if (mapShard != null) { mapShard.getWaitingClients().remove(clientHandle); mapShard.getPendingClients().add(clientHandle); } } /** * Getter. * * @param mapShardContext * @return Get the bean attached to this mapshard handle. */ public MapShardBean getBean(Handle<GameAppContext> mapShardContext) { return mapShardMetaInfo.get(mapShardContext); } /** * Try to create a new map shard (fails by returning null) * TODO: allow pvp mapshards here. */ private MapShardBean tryCreate(int gameMapId, DistrictRegion region, DistrictLanguage language, int instanceNumber, boolean isOutpost) { gwlpr.database.entities.Map mapEntity = MapJpaController.get().findByGameId(gameMapId); // failcheck if (mapEntity == null) { return null; } // try create the game app (with mapid parameter) GameAppManager manager = context.get().getManager(); // failcheck if (manager == null || !manager.canCreateGameApp("MapShard")) { return null; } // create the gameapp HashMap<String,String> params = new HashMap<>(); params.put("MapId", String.valueOf(mapEntity.getId())); params.put("IsPvP", String.valueOf(false)); params.put("IsOutpost", String.valueOf(isOutpost)); params.put("InstanceNumber", String.valueOf(instanceNumber)); params.put("DistrictRegion", region.toString()); params.put("DistrictLanguage", language.toString()); Handle<GameAppContext> mapShardContext = manager.createGameApp("MapShard", context, params); // failcheck if (mapShardContext == null) { return null; } // create the bean MapShardBean mapShard = new MapShardBean(mapShardContext, mapEntity, instanceNumber, region, language); // register it mapShardMetaInfo.put(mapShardContext, mapShard); return mapShard; } }
/* * Copyright (c) 2007, 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 6572263 6571808 8005920 @summary PIT:FileDialog minimized to taskbar(through 'Show Desktop')selecting the fileDialog using windowList @author dmitry.cherepanov: area=awt.modal @run main/manual Winkey */ /** * Winkey.java * * summary: the test verifies that pressing combination of Windows key * and M key to minimize all windows doesn't break AWT modality */ import java.awt.*; import java.awt.event.*; public class Winkey { private static void init() { //*** Create instructions for the user here *** String[] instructions = { " 0. This test is for MS Windows only, if you use other OS, press \"pass\" button.", " 1. there is a frame with a 'show modal' button, ", " 2. press the button to show a modal dialog, ", " 3. the modal dialog will be shown over the frame, ", " 4. please verify that all (5.1, 5.2.1, 5.2.2) the following tests pass: ", " ", " 5.1. press combination Windows Key and M key to minimize all windows, ", " note that the modal dialog and modal blocked windows are NOT minimized", " 5.2. press combination Windows Key and D key to show desktop, ", " 5.2.1. restore the dialog by choosing this one in the ALT-TAB list, ", " 5.2.2. restore the dialog by mouse click on taskbar (on java or any other item)", " ", " 6. make sure that the dialog and the frame are visible, ", " the bounds of the windows should be the same as before, ", " if it's true, then the test passed; otherwise, it failed. " }; Sysout.createDialog( ); Sysout.printInstructions( instructions ); final Frame frame = new Frame(); Button button = new Button("show modal"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { FileDialog dialog = new FileDialog((Frame)null, "Sample", FileDialog.LOAD); dialog.setVisible(true); } }); frame.add(button); frame.setBounds(400, 400, 200, 200); frame.setVisible(true); }//End init() /***************************************************** * Standard Test Machinery Section * DO NOT modify anything in this section -- it's a * standard chunk of code which has all of the * synchronisation necessary for the test harness. * By keeping it the same in all tests, it is easier * to read and understand someone else's test, as * well as insuring that all tests behave correctly * with the test harness. * There is a section following this for test-defined * classes ******************************************************/ private static boolean theTestPassed = false; private static boolean testGeneratedInterrupt = false; private static String failureMessage = ""; private static Thread mainThread = null; private static int sleepTime = 300000; public static void main( String args[] ) throws InterruptedException { mainThread = Thread.currentThread(); try { init(); } catch( TestPassedException e ) { //The test passed, so just return from main and harness will // interepret this return as a pass return; } //At this point, neither test passed nor test failed has been // called -- either would have thrown an exception and ended the // test, so we know we have multiple threads. //Test involves other threads, so sleep and wait for them to // called pass() or fail() try { Thread.sleep( sleepTime ); //Timed out, so fail the test throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" ); } catch (InterruptedException e) { if( ! testGeneratedInterrupt ) throw e; //reset flag in case hit this code more than once for some reason (just safety) testGeneratedInterrupt = false; if ( theTestPassed == false ) { throw new RuntimeException( failureMessage ); } } }//main public static synchronized void setTimeoutTo( int seconds ) { sleepTime = seconds * 1000; } public static synchronized void pass() { Sysout.println( "The test passed." ); Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); //first check if this is executing in main thread if ( mainThread == Thread.currentThread() ) { //Still in the main thread, so set the flag just for kicks, // and throw a test passed exception which will be caught // and end the test. theTestPassed = true; throw new TestPassedException(); } //pass was called from a different thread, so set the flag and interrupt // the main thead. theTestPassed = true; testGeneratedInterrupt = true; mainThread.interrupt(); }//pass() public static synchronized void fail() { //test writer didn't specify why test failed, so give generic fail( "it just plain failed! :-)" ); } public static synchronized void fail( String whyFailed ) { Sysout.println( "The test failed: " + whyFailed ); Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); //check if this called from main thread if ( mainThread == Thread.currentThread() ) { //If main thread, fail now 'cause not sleeping throw new RuntimeException( whyFailed ); } theTestPassed = false; testGeneratedInterrupt = true; failureMessage = whyFailed; mainThread.interrupt(); }//fail() }// class ManualMainTest //This exception is used to exit from any level of call nesting // when it's determined that the test has passed, and immediately // end the test. class TestPassedException extends RuntimeException { } //*********** End Standard Test Machinery Section ********** //************ Begin classes defined for the test **************** // make listeners in a class defined here, and instantiate them in init() /* Example of a class which may be written as part of a test class NewClass implements anInterface { static int newVar = 0; public void eventDispatched(AWTEvent e) { //Counting events to see if we get enough eventCount++; if( eventCount == 20 ) { //got enough events, so pass ManualMainTest.pass(); } else if( tries == 20 ) { //tried too many times without getting enough events so fail ManualMainTest.fail(); } }// eventDispatched() }// NewClass class */ //************** End classes defined for the test ******************* /**************************************************** Standard Test Machinery DO NOT modify anything below -- it's a standard chunk of code whose purpose is to make user interaction uniform, and thereby make it simpler to read and understand someone else's test. ****************************************************/ /** This is part of the standard test machinery. It creates a dialog (with the instructions), and is the interface for sending text messages to the user. To print the instructions, send an array of strings to Sysout.createDialog WithInstructions method. Put one line of instructions per array entry. To display a message for the tester to see, simply call Sysout.println with the string to be displayed. This mimics System.out.println but works within the test harness as well as standalone. */ class Sysout { private static TestDialog dialog; public static void createDialogWithInstructions( String[] instructions ) { dialog = new TestDialog( new Frame(), "Instructions" ); dialog.printInstructions( instructions ); dialog.setVisible(true); println( "Any messages for the tester will display here." ); } public static void createDialog( ) { dialog = new TestDialog( new Frame(), "Instructions" ); String[] defInstr = { "Instructions will appear here. ", "" } ; dialog.printInstructions( defInstr ); dialog.setVisible(true); println( "Any messages for the tester will display here." ); } public static void printInstructions( String[] instructions ) { dialog.printInstructions( instructions ); } public static void println( String messageIn ) { dialog.displayMessage( messageIn ); } }// Sysout class /** This is part of the standard test machinery. It provides a place for the test instructions to be displayed, and a place for interactive messages to the user to be displayed. To have the test instructions displayed, see Sysout. To have a message to the user be displayed, see Sysout. Do not call anything in this dialog directly. */ class TestDialog extends Dialog implements ActionListener { TextArea instructionsText; TextArea messageText; int maxStringLength = 80; Panel buttonP = new Panel(); Button passB = new Button( "pass" ); Button failB = new Button( "fail" ); //DO NOT call this directly, go through Sysout public TestDialog( Frame frame, String name ) { super( frame, name ); int scrollBoth = TextArea.SCROLLBARS_BOTH; instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); add( "North", instructionsText ); messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); add("Center", messageText); passB = new Button( "pass" ); passB.setActionCommand( "pass" ); passB.addActionListener( this ); buttonP.add( "East", passB ); failB = new Button( "fail" ); failB.setActionCommand( "fail" ); failB.addActionListener( this ); buttonP.add( "West", failB ); add( "South", buttonP ); pack(); setVisible(true); }// TestDialog() //DO NOT call this directly, go through Sysout public void printInstructions( String[] instructions ) { //Clear out any current instructions instructionsText.setText( "" ); //Go down array of instruction strings String printStr, remainingStr; for( int i=0; i < instructions.length; i++ ) { //chop up each into pieces maxSringLength long remainingStr = instructions[ i ]; while( remainingStr.length() > 0 ) { //if longer than max then chop off first max chars to print if( remainingStr.length() >= maxStringLength ) { //Try to chop on a word boundary int posOfSpace = remainingStr. lastIndexOf( ' ', maxStringLength - 1 ); if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; printStr = remainingStr.substring( 0, posOfSpace + 1 ); remainingStr = remainingStr.substring( posOfSpace + 1 ); } //else just print else { printStr = remainingStr; remainingStr = ""; } instructionsText.append( printStr + "\n" ); }// while }// for }//printInstructions() //DO NOT call this directly, go through Sysout public void displayMessage( String messageIn ) { messageText.append( messageIn + "\n" ); System.out.println(messageIn); } //catch presses of the passed and failed buttons. //simply call the standard pass() or fail() static methods of //ManualMainTest public void actionPerformed( ActionEvent e ) { if( e.getActionCommand() == "pass" ) { Winkey.pass(); } else { Winkey.fail(); } } }// TestDialog class
/** * 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.oozie.coord; import java.io.StringReader; import java.util.Date; import org.apache.hadoop.conf.Configuration; import org.apache.oozie.service.Services; import org.apache.oozie.test.XTestCase; import org.apache.oozie.util.DateUtils; import org.apache.oozie.util.ELEvaluator; import org.apache.oozie.util.XConfiguration; import org.apache.oozie.util.XmlUtils; import org.jdom.Element; public class TestCoordELEvaluator extends XTestCase { @Override public void setUp() throws Exception { super.setUp(); new Services().init(); } @Override protected void tearDown() throws Exception { if (Services.get() != null) { Services.get().destroy(); } super.tearDown(); } public void testCreateFreqELValuator() throws Exception { // System.out.println("CP :" + System.getProperty("java.class.path")); // Configuration conf = new // XConfiguration(IOUtils.getResourceAsReader("org/apache/oozie/coord/conf.xml", // -1)); Configuration conf = new XConfiguration(new StringReader( getConfString())); ELEvaluator eval = CoordELEvaluator.createELEvaluatorForGroup(conf, "coord-job-submit-freq"); String expr = "<coordinator-app name=\"mycoordinator-app\" start=\"${start}\" end=\"${end}\"" + " frequency=\"${coord:hours(12)}\"><data-in name=\"A\" dataset=\"a\"></data-in>"; String reply = expr.replace("${start}", conf.get("start")).replace( "${end}", conf.get("end")).replace("${coord:hours(12)}", "720"); assertEquals(reply, CoordELFunctions.evalAndWrap(eval, expr)); expr = "<coordinator-app name=\"mycoordinator-app\" start=\"${start}\" end=\"${end}\"" + " frequency=\"${coord:days(7)}\"><data-in name=\"A\" dataset=\"a\"></data-in>"; reply = expr.replace("${start}", conf.get("start")).replace("${end}", conf.get("end")).replace("${coord:days(7)}", "7"); assertEquals(reply, CoordELFunctions.evalAndWrap(eval, expr)); expr = "<coordinator-app name=\"mycoordinator-app\" start=\"${start}\" end=\"${end}\"" + " frequency=\"${coord:months(1)}\"><data-in name=\"A\" dataset=\"a\"></data-in>"; reply = expr.replace("${start}", conf.get("start")).replace("${end}", conf.get("end")).replace("${coord:months(1)}", "1"); // System.out.println("****testCreateELValuator :"+ // CoordELFunctions.evaluateFunction(eval, expr)); assertEquals(reply, CoordELFunctions.evalAndWrap(eval, expr)); expr = "frequency=${coord:days(2)}"; expr = "frequency=60"; CoordELFunctions.evalAndWrap(eval, expr); expr = "frequency=${coord:daysInMonth(2)}"; try { CoordELFunctions.evalAndWrap(eval, expr); fail(); } catch (Exception ex) { } expr = "frequency=${coord:hoursInDay(2)}"; try { CoordELFunctions.evalAndWrap(eval, expr); fail(); } catch (Exception ex) { } expr = "frequency=${coord:tzOffset()}"; try { CoordELFunctions.evalAndWrap(eval, expr); fail(); } catch (Exception ex) { } expr = "<frequency=120"; assertEquals(expr, CoordELFunctions.evalAndWrap(eval, expr)); } public void testCreateURIELEvaluator() throws Exception { ELEvaluator eval = CoordELEvaluator .createURIELEvaluator("2009-08-09T23:59Z"); String expr = "hdfs://p1/p2/${YEAR}/${MONTH}/${DAY}/${HOUR}/${MINUTE}/"; // System.out.println("OUTPUT "+ eval.evaluate(expr, String.class)); assertEquals("hdfs://p1/p2/2009/08/09/23/59/", CoordELFunctions .evalAndWrap(eval, expr)); expr = "hdfs://p1/p2/${YEAR}/${MONTH}/${DAY}/${MINUTE}/"; assertEquals("hdfs://p1/p2/2009/08/09/59/", CoordELFunctions .evalAndWrap(eval, expr)); } public void testCreateDataEvaluator() throws Exception { String jobXml = "<coordinator-app name=\"mycoordinator-app\" start=\"2009-02-01T01:00GMT\"" + " end=\"2009-02-03T23:59GMT\" timezone=\"UTC\""; jobXml += " frequency=\"720\" freq_timeunit=\"MINUTE\""; jobXml += " action-nominal-time='2009-09-01T00:00Z' action-actual-time='2010-10-01T00:00Z'>"; jobXml += "<input-events><data-in name=\"A\" dataset=\"a\">" + "<uris>file:///tmp/coord/US/2009/1/30|file:///tmp/coord/US/2009/1/31</uris>"; jobXml += "<dataset name=\"a\" frequency=\"1440\" initial-instance=\"2009-01-01T00:00Z\">"; jobXml += "<uri-template>file:///tmp/coord/US/${YEAR}/${MONTH}/${DAY}</uri-template></dataset></data-in></input-events>"; jobXml += "<action><workflow><url>http://foobar.com:8080/oozie</url>" + "<app-path>hdfs://foobarfoobar.com:9000/usr/tucu/mywf</app-path>"; jobXml += "<configuration><property><name>inputA</name><value>${coord:dataIn('A')}</value></property>"; jobXml += "<property><name>ACTIONID</name><value>${coord:actionId()}</value></property>"; jobXml += "<property><name>NAME</name><value>${coord:name()}</value></property>"; jobXml += "<property><name>NOMINALTIME</name><value>${coord:nominalTime()}</value></property>"; jobXml += "<property><name>ACTUALTIME</name><value>${coord:actualTime()}</value></property>"; jobXml += "</configuration></workflow></action></coordinator-app>"; String reply = "<action><workflow><url>http://foobar.com:8080/oozie</url>" + "<app-path>hdfs://foobarfoobar.com:9000/usr/tucu/mywf</app-path>"; reply += "<configuration><property><name>inputA</name>" + "<value>file:///tmp/coord/US/2009/1/30|file:///tmp/coord/US/2009/1/31</value></property>"; reply += "<property><name>ACTIONID</name><value>00000-oozie-C@1</value></property>"; reply += "<property><name>NAME</name><value>mycoordinator-app</value></property>"; reply += "<property><name>NOMINALTIME</name><value>2009-09-01T00:00Z</value></property>"; reply += "<property><name>ACTUALTIME</name><value>2010-10-01T00:00Z</value></property>"; reply += "</configuration></workflow></action>"; Element eJob = XmlUtils.parseXml(jobXml); Configuration conf = new XConfiguration(new StringReader(getConfString())); ELEvaluator eval = CoordELEvaluator.createDataEvaluator(eJob, conf, "00000-oozie-C@1"); Element action = eJob.getChild("action", eJob.getNamespace()); String str = XmlUtils.prettyPrint(action).toString(); assertEquals(XmlUtils.prettyPrint(XmlUtils.parseXml(reply)).toString(), CoordELFunctions.evalAndWrap(eval, str)); } public void testCreateInstancesELEvaluator() throws Exception { String dataEvntXML = "<data-in name=\"A\" dataset=\"a\">" + "<uris>file:///tmp/coord/US/2009/1/30|file:///tmp/coord/US/2009/1/31</uris>"; dataEvntXML += "<dataset name=\"a\" frequency=\"1440\" initial-instance=\"2009-01-01T00:00Z\"" + " freq_timeunit=\"MINUTE\" timezone=\"UTC\" end_of_duration=\"NONE\">"; dataEvntXML += "<uri-template>file:///tmp/coord/US/${YEAR}/${MONTH}/${DAY}</uri-template></dataset></data-in>"; Element event = XmlUtils.parseXml(dataEvntXML); SyncCoordAction appInst = new SyncCoordAction(); appInst.setNominalTime(DateUtils.parseDateOozieTZ("2009-09-08T01:00Z")); appInst.setActualTime(DateUtils.parseDateOozieTZ("2010-10-01T00:00Z")); appInst.setTimeUnit(TimeUnit.MINUTE); // Configuration conf = new // XConfiguration(IOUtils.getResourceAsReader("org/apache/oozie/coord/conf.xml", // -1)); Configuration conf = new XConfiguration(new StringReader( getConfString())); ELEvaluator eval = CoordELEvaluator.createInstancesELEvaluator(event, appInst, conf); String expr = "${coord:current(0)}"; // System.out.println("OUTPUT :" + eval.evaluate(expr, String.class)); assertEquals("2009-09-08T00:00Z", eval.evaluate(expr, String.class)); } public void testCreateLazyEvaluator() throws Exception { // Configuration conf = new // XConfiguration(IOUtils.getResourceAsReader("org/apache/oozie/coord/conf.xml", // -1)); String testCaseDir = getTestCaseDir(); Configuration conf = new XConfiguration(new StringReader(getConfString())); Date actualTime = DateUtils.parseDateOozieTZ("2009-09-01T01:00Z"); Date nominalTime = DateUtils.parseDateOozieTZ("2009-09-01T00:00Z"); String dataEvntXML = "<data-in name=\"A\" dataset=\"a\"><uris>" + getTestCaseFileUri("US/2009/1/30") + "|file:///tmp/coord/US/2009/1/31</uris>"; dataEvntXML += "<dataset name=\"a\" frequency=\"1440\" initial-instance=\"2009-01-01T00:00Z\"" + " freq_timeunit=\"MINUTE\" timezone=\"UTC\" end_of_duration=\"NONE\">"; dataEvntXML += "<uri-template>" + getTestCaseFileUri("${YEAR}/${MONTH}/${DAY}") + "</uri-template></dataset></data-in>"; Element dEvent = XmlUtils.parseXml(dataEvntXML); ELEvaluator eval = CoordELEvaluator.createLazyEvaluator(actualTime, nominalTime, dEvent, conf); createTestCaseSubDir("2009/01/02/_SUCCESS".split("/")); String expr = "${coord:latest(0)} ${coord:latest(-1)}"; // Dependent on the directory structure // TODO: Create the directory assertEquals("2009-01-02T00:00Z ${coord:latest(-1)}", eval.evaluate(expr, String.class)); // future createTestCaseSubDir("2009/09/04/_SUCCESS".split("/")); createTestCaseSubDir("2009/09/05/_SUCCESS".split("/")); expr = "${coord:future(1, 30)}"; assertEquals("2009-09-05T00:00Z", eval.evaluate(expr, String.class)); // System.out.println("OUTPUT :" + eval.evaluate(expr, String.class)); } public void testCleanup() throws Exception { Services.get().destroy(); } private String getConfString() { StringBuilder conf = new StringBuilder(); conf.append("<configuration> <property><name>baseFsURI</name> <value>file:///tmp/coord/</value> </property>"); conf.append("<property><name>language</name> <value>en</value> </property>"); conf .append("<property> <name>country</name> <value>US</value> </property> " + "<property> <name>market</name> <value>teens</value> </property> " + "<property> <name>app_path</name> <value>file:///tmp/coord/workflows</value> </property> " + "<property> <name>start</name> <value>2009-02-01T01:00Z</value> </property>" + "<property> <name>end</name> <value>2009-02-03T23:59Z</value> </property> " + "<property> <name>timezone</name> <value>UTC</value> </property> " + "<property> <name>user.name</name> <value>test_user</value> </property> " + "<property> <name>timeout</name> <value>180</value> </property> " + "<property> <name>concurrency_level</name> <value>1</value> </property> " + "<property> <name>execution_order</name> <value>LIFO</value> </property>" + "<property> <name>include_ds_files</name> <value>file:///homes/" + getTestUser() + "/workspace/oozie-main/core/src/main/java/org/apache/oozie/coord/datasets.xml</value>" + " </property></configuration>"); return conf.toString(); } }
package de.fhpotsdam.unfolding.interactions; import java.util.Arrays; import java.util.List; import java.util.Stack; import org.apache.log4j.Logger; import processing.core.PApplet; import processing.core.PFont; import processing.core.PVector; import TUIO.TuioClient; import TUIO.TuioCursor; import TUIO.TuioListener; import TUIO.TuioObject; import TUIO.TuioPoint; import TUIO.TuioTime; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.events.MapEventBroadcaster; import de.fhpotsdam.unfolding.events.PanMapEvent; import de.fhpotsdam.unfolding.events.ZoomMapEvent; import de.fhpotsdam.unfolding.geo.Location; /** * Handles finger input (TUIO cursors) from the user and broadcasts MapEvents such as zoom and pan. */ // FIXME Implement tuio to map interactions as events! // REVISIT Check how to use simpletouch's TuioTransformableObject. For use in events, as in here. public class TuioCursorHandler extends MapEventBroadcaster implements TuioListener { public static Logger log = Logger.getLogger(TuioCursorHandler.class); private PApplet p; protected TuioClient tuioClient; TuioCursor tuioCursor1; TuioCursor tuioCursor2; Stack<TuioCursor> unusedTuioCursorStack = new Stack<TuioCursor>(); float oldAngle; float oldDist; PFont font; public TuioCursorHandler(PApplet p, UnfoldingMap... maps) { this(p, Arrays.asList(maps)); } public TuioCursorHandler(PApplet p, boolean listenToTuio, UnfoldingMap... maps) { this(p, listenToTuio, Arrays.asList(maps)); } public TuioCursorHandler(PApplet p, boolean listenToTuio, List<UnfoldingMap> maps) { super(maps); this.p = p; this.font = p.createFont("Sans-Serif", 12); tuioClient = new TuioClient(); if (listenToTuio) { tuioClient.addTuioListener(this); } tuioClient.connect(); p.registerDispose(this); } public TuioCursorHandler(PApplet p, List<UnfoldingMap> maps) { this(p, true, maps); } public void dispose() { tuioClient.disconnect(); } public TuioClient getTuioClient() { return tuioClient; } public void updateTuioCursor(TuioCursor tcur) { int x = tcur.getScreenX(p.width); int y = tcur.getScreenY(p.height); // Updates go to all hit ones, independent of z-index for (UnfoldingMap map : maps) { if (map.isHit(x, y)) { if (tuioCursor1 != null && tuioCursor2 != null) { // Two fingers: Zoom + Rotate // FIXME In very high zoom levels zooming is off. Precision problem? // (float/double) // Uses inner zoom and inner rotation, thus fingers are on same location // Flags to test various combinations boolean zoom = true; boolean rotate = true; PVector transCenter = new PVector(); if (tuioCursor2.getCursorID() == tcur.getCursorID()) { transCenter.x = tuioCursor1.getScreenX(p.width); transCenter.y = tuioCursor1.getScreenY(p.height); } else { transCenter.x = tuioCursor2.getScreenX(p.width); transCenter.y = tuioCursor2.getScreenY(p.height); } if (zoom) { ZoomMapEvent zoomMapEvent = new ZoomMapEvent(this, map.getId(), ZoomMapEvent.ZOOM_BY); // 3 variations to zoom with two finger gestures // TODO Do study on usability for different interaction approaches. // 1. pos of last finger Location centerLocation = map.getLocation(transCenter.x, transCenter.y); zoomMapEvent.setTransformationCenterLocation(centerLocation); // 2. object center: pinch gesture w/o fixed finger-location connection // float[] objectCenterXY = // map.mapDisplay.getScreenFromObjectPosition(map.mapDisplay.getWidth()/2, // map.mapDisplay.getHeight()/2); // PVector objectCenter = new PVector(objectCenterXY[0], objectCenterXY[1]); // map.mapDisplay.setInnerTransformationCenter(objectCenter); // 3. middle pos between both fingers float newDist = getDistance(tuioCursor1, tuioCursor2); float scaleDelta = newDist / oldDist; oldDist = newDist; zoomMapEvent.setZoomDelta(scaleDelta); eventDispatcher.fireMapEvent(zoomMapEvent); } if (rotate) { // TODO Use events (instead of direct map manipulation) // rotate center map.mapDisplay.setTransformationCenter(transCenter); float newAngle = getAngleBetween(tuioCursor1, tuioCursor2); float angle = newAngle - oldAngle; oldAngle = newAngle; map.rotate(angle); } } else if (tuioCursor1 != null) { // One finger: pan if (tuioCursor1.getCursorID() == tcur.getCursorID()) { TuioPoint oldTuioPoint = tcur.getPath().get(tcur.getPath().size() - 2); Location fromLocation = map.mapDisplay.getLocation(oldTuioPoint.getScreenX(p.width), oldTuioPoint.getScreenY(p.height)); Location toLocation = map.mapDisplay.getLocation(tuioCursor1.getScreenX(p.width), tuioCursor1.getScreenY(p.height)); PanMapEvent panMapEvent = new PanMapEvent(this, map.getId(), PanMapEvent.PAN_BY); panMapEvent.setFromLocation(fromLocation); panMapEvent.setToLocation(toLocation); eventDispatcher.fireMapEvent(panMapEvent); } } } } } public void addTuioCursor(TuioCursor tuioCursor) { if (tuioCursor1 == null) { tuioCursor1 = tuioCursor; } else if (tuioCursor2 == null) { tuioCursor2 = tuioCursor; oldAngle = getAngleBetween(tuioCursor1, tuioCursor2); oldDist = getDistance(tuioCursor1, tuioCursor2); } else { // PApplet.println("Already 2 cursors in use. Adding further ones to stack."); unusedTuioCursorStack.add(tuioCursor); } } public void removeTuioCursor(TuioCursor tuioCursor) { if (tuioCursor2 != null && tuioCursor2.getCursorID() == tuioCursor.getCursorID()) { tuioCursor2 = null; if (!unusedTuioCursorStack.isEmpty()) { tuioCursor2 = unusedTuioCursorStack.pop(); oldAngle = getAngleBetween(tuioCursor1, tuioCursor2); oldDist = getDistance(tuioCursor1, tuioCursor2); } } if (tuioCursor1 != null && tuioCursor1.getCursorID() == tuioCursor.getCursorID()) { tuioCursor1 = null; // If second still is on object, switch cursors if (tuioCursor2 != null) { tuioCursor1 = tuioCursor2; if (!unusedTuioCursorStack.isEmpty()) { tuioCursor2 = unusedTuioCursorStack.pop(); oldAngle = getAngleBetween(tuioCursor1, tuioCursor2); oldDist = getDistance(tuioCursor1, tuioCursor2); } else { tuioCursor2 = null; } } } // TODO check only if the other were no hits TuioCursor toRemoveTC = null; for (TuioCursor unusedTuioCursor : unusedTuioCursorStack) { if (tuioCursor.getCursorID() == unusedTuioCursor.getCursorID()) { toRemoveTC = tuioCursor; break; } } if (toRemoveTC != null) { unusedTuioCursorStack.remove(toRemoveTC); } } protected float getDistance(TuioCursor tuioCursor1, TuioCursor tuioCursor2) { return PApplet.dist(tuioCursor1.getScreenX(p.width), tuioCursor1.getScreenY(p.height), tuioCursor2.getScreenX(p.width), tuioCursor2.getScreenY(p.height)); } protected float getAngleBetween(TuioCursor tuioCursor1, TuioCursor tuioCursor2) { return getAngleBetween(tuioCursor1.getScreenX(p.width), tuioCursor1.getScreenY(p.height), tuioCursor2.getScreenX(p.width), tuioCursor2.getScreenY(p.height)); } protected float getAngleBetween(float x1, float y1, float x2, float y2) { float difY = y1 - y2; float difX = x1 - x2; float angle = PApplet.atan2(difY, difX); return angle; } @Override public void addTuioObject(TuioObject arg0) { } @Override public void removeTuioObject(TuioObject arg0) { } @Override public void updateTuioObject(TuioObject arg0) { } @Override public void refresh(TuioTime arg0) { } /** * Draws all TuioCursors. */ public void drawCursors() { for (TuioCursor tuioCursor : tuioClient.getTuioCursors()) { drawCursor(tuioCursor); } } /** * Draws a TuioCursor as small circle with ID as label. * * @param tc * The cursor to draw. */ public void drawCursor(TuioCursor tc) { if (tc == null) return; p.textFont(font); // p.stroke(0, 20); p.noStroke(); p.fill(80, 30); p.ellipse(tc.getScreenX(p.width), tc.getScreenY(p.height), 27, 27); p.fill(80, 80); p.ellipse(tc.getScreenX(p.width), tc.getScreenY(p.height), 25, 25); p.fill(0, 200); p.textSize(12); p.text(tc.getCursorID(), tc.getScreenX(p.width) - 4, tc.getScreenY(p.height) + 4); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred.gridmix; import org.junit.Test; import static org.junit.Assert.*; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapred.DummyResourceCalculatorPlugin; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.gridmix.DebugJobProducer.MockJob; import org.apache.hadoop.mapred.gridmix.TestHighRamJob.DummyGridmixJob; import org.apache.hadoop.mapred.gridmix.TestResourceUsageEmulators.FakeProgressive; import org.apache.hadoop.mapred.gridmix.emulators.resourceusage.TotalHeapUsageEmulatorPlugin; import org.apache.hadoop.mapred.gridmix.emulators.resourceusage.TotalHeapUsageEmulatorPlugin.DefaultHeapUsageEmulator; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.util.ResourceCalculatorPlugin; import org.apache.hadoop.tools.rumen.ResourceUsageMetrics; /** * Test Gridmix memory emulation. */ public class TestGridmixMemoryEmulation { /** * This is a dummy class that fakes heap usage. */ private static class FakeHeapUsageEmulatorCore extends DefaultHeapUsageEmulator { private int numCalls = 0; @Override public void load(long sizeInMB) { ++numCalls; super.load(sizeInMB); } // Get the total number of times load() was invoked int getNumCalls() { return numCalls; } // Get the total number of 1mb objects stored within long getHeapUsageInMB() { return heapSpace.size(); } @Override public void reset() { // no op to stop emulate() from resetting } /** * For re-testing purpose. */ void resetFake() { numCalls = 0; super.reset(); } } /** * This is a dummy class that fakes the heap usage emulator plugin. */ private static class FakeHeapUsageEmulatorPlugin extends TotalHeapUsageEmulatorPlugin { private FakeHeapUsageEmulatorCore core; public FakeHeapUsageEmulatorPlugin(FakeHeapUsageEmulatorCore core) { super(core); this.core = core; } @Override protected long getMaxHeapUsageInMB() { return Long.MAX_VALUE / ONE_MB; } @Override protected long getTotalHeapUsageInMB() { return core.getHeapUsageInMB(); } } /** * Test {@link TotalHeapUsageEmulatorPlugin}'s core heap usage emulation * engine. */ @Test public void testHeapUsageEmulator() throws IOException { FakeHeapUsageEmulatorCore heapEmulator = new FakeHeapUsageEmulatorCore(); long testSizeInMB = 10; // 10 mb long previousHeap = heapEmulator.getHeapUsageInMB(); heapEmulator.load(testSizeInMB); long currentHeap = heapEmulator.getHeapUsageInMB(); // check if the heap has increased by expected value assertEquals("Default heap emulator failed to load 10mb", previousHeap + testSizeInMB, currentHeap); // test reset heapEmulator.resetFake(); assertEquals("Default heap emulator failed to reset", 0, heapEmulator.getHeapUsageInMB()); } /** * Test {@link TotalHeapUsageEmulatorPlugin}. */ @Test public void testTotalHeapUsageEmulatorPlugin() throws Exception { Configuration conf = new Configuration(); // set the dummy resource calculator for testing ResourceCalculatorPlugin monitor = new DummyResourceCalculatorPlugin(); long maxHeapUsage = 1024 * TotalHeapUsageEmulatorPlugin.ONE_MB; // 1GB conf.setLong(DummyResourceCalculatorPlugin.MAXPMEM_TESTING_PROPERTY, maxHeapUsage); monitor.setConf(conf); // no buffer to be reserved conf.setFloat(TotalHeapUsageEmulatorPlugin.MIN_HEAP_FREE_RATIO, 0F); // only 1 call to be made per cycle conf.setFloat(TotalHeapUsageEmulatorPlugin.HEAP_LOAD_RATIO, 1F); long targetHeapUsageInMB = 200; // 200mb // fake progress indicator FakeProgressive fakeProgress = new FakeProgressive(); // fake heap usage generator FakeHeapUsageEmulatorCore fakeCore = new FakeHeapUsageEmulatorCore(); // a heap usage emulator with fake core FakeHeapUsageEmulatorPlugin heapPlugin = new FakeHeapUsageEmulatorPlugin(fakeCore); // test with invalid or missing resource usage value ResourceUsageMetrics invalidUsage = TestResourceUsageEmulators.createMetrics(0); heapPlugin.initialize(conf, invalidUsage, null, null); // test if disabled heap emulation plugin's emulate() call is a no-operation // this will test if the emulation plugin is disabled or not int numCallsPre = fakeCore.getNumCalls(); long heapUsagePre = fakeCore.getHeapUsageInMB(); heapPlugin.emulate(); int numCallsPost = fakeCore.getNumCalls(); long heapUsagePost = fakeCore.getHeapUsageInMB(); // test if no calls are made heap usage emulator core assertEquals("Disabled heap usage emulation plugin works!", numCallsPre, numCallsPost); // test if no calls are made heap usage emulator core assertEquals("Disabled heap usage emulation plugin works!", heapUsagePre, heapUsagePost); // test with wrong/invalid configuration Boolean failed = null; invalidUsage = TestResourceUsageEmulators.createMetrics(maxHeapUsage + TotalHeapUsageEmulatorPlugin.ONE_MB); try { heapPlugin.initialize(conf, invalidUsage, monitor, null); failed = false; } catch (Exception e) { failed = true; } assertNotNull("Fail case failure!", failed); assertTrue("Expected failure!", failed); // test with valid resource usage value ResourceUsageMetrics metrics = TestResourceUsageEmulators.createMetrics(targetHeapUsageInMB * TotalHeapUsageEmulatorPlugin.ONE_MB); // test with default emulation interval // in every interval, the emulator will add 100% of the expected usage // (since gridmix.emulators.resource-usage.heap.load-ratio=1) // so at 10%, emulator will add 10% (difference), at 20% it will add 10% ... // So to emulate 200MB, it will add // 20mb + 20mb + 20mb + 20mb + .. = 200mb testEmulationAccuracy(conf, fakeCore, monitor, metrics, heapPlugin, 200, 10); // test with custom value for emulation interval of 20% conf.setFloat(TotalHeapUsageEmulatorPlugin.HEAP_EMULATION_PROGRESS_INTERVAL, 0.2F); // 40mb + 40mb + 40mb + 40mb + 40mb = 200mb testEmulationAccuracy(conf, fakeCore, monitor, metrics, heapPlugin, 200, 5); // test with custom value of free heap ratio and load ratio = 1 conf.setFloat(TotalHeapUsageEmulatorPlugin.HEAP_LOAD_RATIO, 1F); conf.setFloat(TotalHeapUsageEmulatorPlugin.MIN_HEAP_FREE_RATIO, 0.5F); // 40mb + 0mb + 80mb + 0mb + 0mb = 120mb testEmulationAccuracy(conf, fakeCore, monitor, metrics, heapPlugin, 120, 2); // test with custom value of heap load ratio and min free heap ratio = 0 conf.setFloat(TotalHeapUsageEmulatorPlugin.HEAP_LOAD_RATIO, 0.5F); conf.setFloat(TotalHeapUsageEmulatorPlugin.MIN_HEAP_FREE_RATIO, 0F); // 20mb (call#1) + 20mb (call#1) + 20mb (call#2) + 20mb (call#2) +.. = 200mb testEmulationAccuracy(conf, fakeCore, monitor, metrics, heapPlugin, 200, 10); // test with custom value of free heap ratio = 0.3 and load ratio = 0.5 conf.setFloat(TotalHeapUsageEmulatorPlugin.MIN_HEAP_FREE_RATIO, 0.25F); conf.setFloat(TotalHeapUsageEmulatorPlugin.HEAP_LOAD_RATIO, 0.5F); // 20mb (call#1) + 20mb (call#1) + 30mb (call#2) + 0mb (call#2) // + 30mb (call#3) + 0mb (call#3) + 35mb (call#4) + 0mb (call#4) // + 37mb (call#5) + 0mb (call#5) = 162mb testEmulationAccuracy(conf, fakeCore, monitor, metrics, heapPlugin, 162, 6); // test if emulation interval boundary is respected fakeProgress = new FakeProgressive(); // initialize conf.setFloat(TotalHeapUsageEmulatorPlugin.MIN_HEAP_FREE_RATIO, 0F); conf.setFloat(TotalHeapUsageEmulatorPlugin.HEAP_LOAD_RATIO, 1F); conf.setFloat(TotalHeapUsageEmulatorPlugin.HEAP_EMULATION_PROGRESS_INTERVAL, 0.25F); heapPlugin.initialize(conf, metrics, monitor, fakeProgress); fakeCore.resetFake(); // take a snapshot after the initialization long initHeapUsage = fakeCore.getHeapUsageInMB(); long initNumCallsUsage = fakeCore.getNumCalls(); // test with 0 progress testEmulationBoundary(0F, fakeCore, fakeProgress, heapPlugin, initHeapUsage, initNumCallsUsage, "[no-op, 0 progress]"); // test with 24% progress testEmulationBoundary(0.24F, fakeCore, fakeProgress, heapPlugin, initHeapUsage, initNumCallsUsage, "[no-op, 24% progress]"); // test with 25% progress testEmulationBoundary(0.25F, fakeCore, fakeProgress, heapPlugin, targetHeapUsageInMB / 4, 1, "[op, 25% progress]"); // test with 80% progress testEmulationBoundary(0.80F, fakeCore, fakeProgress, heapPlugin, (targetHeapUsageInMB * 4) / 5, 2, "[op, 80% progress]"); // now test if the final call with 100% progress ramps up the heap usage testEmulationBoundary(1F, fakeCore, fakeProgress, heapPlugin, targetHeapUsageInMB, 3, "[op, 100% progress]"); } // test whether the heap usage emulator achieves the desired target using // desired calls to the underling core engine. private static void testEmulationAccuracy(Configuration conf, FakeHeapUsageEmulatorCore fakeCore, ResourceCalculatorPlugin monitor, ResourceUsageMetrics metrics, TotalHeapUsageEmulatorPlugin heapPlugin, long expectedTotalHeapUsageInMB, long expectedTotalNumCalls) throws Exception { FakeProgressive fakeProgress = new FakeProgressive(); fakeCore.resetFake(); heapPlugin.initialize(conf, metrics, monitor, fakeProgress); int numLoops = 0; while (fakeProgress.getProgress() < 1) { ++numLoops; float progress = numLoops / 100.0F; fakeProgress.setProgress(progress); heapPlugin.emulate(); } // test if the resource plugin shows the expected usage assertEquals("Cumulative heap usage emulator plugin failed (total usage)!", expectedTotalHeapUsageInMB, fakeCore.getHeapUsageInMB(), 1L); // test if the resource plugin shows the expected num calls assertEquals("Cumulative heap usage emulator plugin failed (num calls)!", expectedTotalNumCalls, fakeCore.getNumCalls(), 0L); } // tests if the heap usage emulation plugin emulates only at the expected // progress gaps private static void testEmulationBoundary(float progress, FakeHeapUsageEmulatorCore fakeCore, FakeProgressive fakeProgress, TotalHeapUsageEmulatorPlugin heapPlugin, long expectedTotalHeapUsageInMB, long expectedTotalNumCalls, String info) throws Exception { fakeProgress.setProgress(progress); heapPlugin.emulate(); // test heap usage assertEquals("Emulation interval test for heap usage failed " + info + "!", expectedTotalHeapUsageInMB, fakeCore.getHeapUsageInMB(), 0L); // test num calls assertEquals("Emulation interval test for heap usage failed " + info + "!", expectedTotalNumCalls, fakeCore.getNumCalls(), 0L); } /** * Test the specified task java heap options. */ @SuppressWarnings("deprecation") private void testJavaHeapOptions(String mapOptions, String reduceOptions, String taskOptions, String defaultMapOptions, String defaultReduceOptions, String defaultTaskOptions, String expectedMapOptions, String expectedReduceOptions, String expectedTaskOptions) throws Exception { Configuration simulatedConf = new Configuration(); // reset the configuration parameters simulatedConf.unset(MRJobConfig.MAP_JAVA_OPTS); simulatedConf.unset(MRJobConfig.REDUCE_JAVA_OPTS); simulatedConf.unset(JobConf.MAPRED_TASK_JAVA_OPTS); // set the default map task options if (defaultMapOptions != null) { simulatedConf.set(MRJobConfig.MAP_JAVA_OPTS, defaultMapOptions); } // set the default reduce task options if (defaultReduceOptions != null) { simulatedConf.set(MRJobConfig.REDUCE_JAVA_OPTS, defaultReduceOptions); } // set the default task options if (defaultTaskOptions != null) { simulatedConf.set(JobConf.MAPRED_TASK_JAVA_OPTS, defaultTaskOptions); } Configuration originalConf = new Configuration(); // reset the configuration parameters originalConf.unset(MRJobConfig.MAP_JAVA_OPTS); originalConf.unset(MRJobConfig.REDUCE_JAVA_OPTS); originalConf.unset(JobConf.MAPRED_TASK_JAVA_OPTS); // set the map task options if (mapOptions != null) { originalConf.set(MRJobConfig.MAP_JAVA_OPTS, mapOptions); } // set the reduce task options if (reduceOptions != null) { originalConf.set(MRJobConfig.REDUCE_JAVA_OPTS, reduceOptions); } // set the task options if (taskOptions != null) { originalConf.set(JobConf.MAPRED_TASK_JAVA_OPTS, taskOptions); } // configure the task jvm's heap options GridmixJob.configureTaskJVMOptions(originalConf, simulatedConf); assertEquals("Map heap options mismatch!", expectedMapOptions, simulatedConf.get(MRJobConfig.MAP_JAVA_OPTS)); assertEquals("Reduce heap options mismatch!", expectedReduceOptions, simulatedConf.get(MRJobConfig.REDUCE_JAVA_OPTS)); assertEquals("Task heap options mismatch!", expectedTaskOptions, simulatedConf.get(JobConf.MAPRED_TASK_JAVA_OPTS)); } /** * Test task-level java heap options configuration in {@link GridmixJob}. */ @Test public void testJavaHeapOptions() throws Exception { // test missing opts testJavaHeapOptions(null, null, null, null, null, null, null, null, null); // test original heap opts and missing default opts testJavaHeapOptions("-Xms10m", "-Xms20m", "-Xms30m", null, null, null, null, null, null); // test missing opts with default opts testJavaHeapOptions(null, null, null, "-Xms10m", "-Xms20m", "-Xms30m", "-Xms10m", "-Xms20m", "-Xms30m"); // test empty option testJavaHeapOptions("", "", "", null, null, null, null, null, null); // test empty default option and no original heap options testJavaHeapOptions(null, null, null, "", "", "", "", "", ""); // test empty opts and default opts testJavaHeapOptions("", "", "", "-Xmx10m -Xms1m", "-Xmx50m -Xms2m", "-Xms2m -Xmx100m", "-Xmx10m -Xms1m", "-Xmx50m -Xms2m", "-Xms2m -Xmx100m"); // test custom heap opts with no default opts testJavaHeapOptions("-Xmx10m", "-Xmx20m", "-Xmx30m", null, null, null, "-Xmx10m", "-Xmx20m", "-Xmx30m"); // test heap opts with default opts (multiple value) testJavaHeapOptions("-Xms5m -Xmx200m", "-Xms15m -Xmx300m", "-Xms25m -Xmx50m", "-XXabc", "-XXxyz", "-XXdef", "-XXabc -Xmx200m", "-XXxyz -Xmx300m", "-XXdef -Xmx50m"); // test heap opts with default opts (duplication of -Xmx) testJavaHeapOptions("-Xms5m -Xmx200m", "-Xms15m -Xmx300m", "-Xms25m -Xmx50m", "-XXabc -Xmx500m", "-XXxyz -Xmx600m", "-XXdef -Xmx700m", "-XXabc -Xmx200m", "-XXxyz -Xmx300m", "-XXdef -Xmx50m"); // test heap opts with default opts (single value) testJavaHeapOptions("-Xmx10m", "-Xmx20m", "-Xmx50m", "-Xms2m", "-Xms3m", "-Xms5m", "-Xms2m -Xmx10m", "-Xms3m -Xmx20m", "-Xms5m -Xmx50m"); // test heap opts with default opts (duplication of -Xmx) testJavaHeapOptions("-Xmx10m", "-Xmx20m", "-Xmx50m", "-Xmx2m", "-Xmx3m", "-Xmx5m", "-Xmx10m", "-Xmx20m", "-Xmx50m"); } /** * Test disabled task heap options configuration in {@link GridmixJob}. */ @Test @SuppressWarnings("deprecation") public void testJavaHeapOptionsDisabled() throws Exception { Configuration gridmixConf = new Configuration(); gridmixConf.setBoolean(GridmixJob.GRIDMIX_TASK_JVM_OPTIONS_ENABLE, false); // set the default values of simulated job gridmixConf.set(MRJobConfig.MAP_JAVA_OPTS, "-Xmx1m"); gridmixConf.set(MRJobConfig.REDUCE_JAVA_OPTS, "-Xmx2m"); gridmixConf.set(JobConf.MAPRED_TASK_JAVA_OPTS, "-Xmx3m"); // set the default map and reduce task options for original job final JobConf originalConf = new JobConf(); originalConf.set(MRJobConfig.MAP_JAVA_OPTS, "-Xmx10m"); originalConf.set(MRJobConfig.REDUCE_JAVA_OPTS, "-Xmx20m"); originalConf.set(JobConf.MAPRED_TASK_JAVA_OPTS, "-Xmx30m"); // define a mock job MockJob story = new MockJob(originalConf) { public JobConf getJobConf() { return originalConf; } }; GridmixJob job = new DummyGridmixJob(gridmixConf, story); Job simulatedJob = job.getJob(); Configuration simulatedConf = simulatedJob.getConfiguration(); assertEquals("Map heap options works when disabled!", "-Xmx1m", simulatedConf.get(MRJobConfig.MAP_JAVA_OPTS)); assertEquals("Reduce heap options works when disabled!", "-Xmx2m", simulatedConf.get(MRJobConfig.REDUCE_JAVA_OPTS)); assertEquals("Task heap options works when disabled!", "-Xmx3m", simulatedConf.get(JobConf.MAPRED_TASK_JAVA_OPTS)); } }
package io.cattle.platform.schema.processor; import io.cattle.platform.json.JsonMapper; import io.github.ibuildthecloud.gdapi.factory.SchemaFactory; import io.github.ibuildthecloud.gdapi.factory.impl.SchemaPostProcessor; import io.github.ibuildthecloud.gdapi.model.Action; import io.github.ibuildthecloud.gdapi.model.Field; import io.github.ibuildthecloud.gdapi.model.Schema; import io.github.ibuildthecloud.gdapi.model.impl.FieldImpl; import io.github.ibuildthecloud.gdapi.model.impl.SchemaImpl; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AuthOverlayPostProcessor implements SchemaPostProcessor { private static final Pattern NOT_PATTERN = Pattern.compile("[a-zA-Z0-9]*(\\.[a-zA-Z0-9]*)?"); private static final Logger log = LoggerFactory.getLogger(AuthOverlayPostProcessor.class); Map<String, Perm> perms = new LinkedHashMap<String, Perm>(); List<Pair<Pattern, Perm>> wildcards = new ArrayList<Pair<Pattern, Perm>>(); List<URL> resources; JsonMapper jsonMapper; @Override public SchemaImpl postProcessRegister(SchemaImpl schema, SchemaFactory factory) { Perm perm = getPerm(schema.getId()); return perm == null || perm.isRead() ? schema : null; } @Override public SchemaImpl postProcess(SchemaImpl schema, SchemaFactory factory) { Perm perm = getPerm(schema.getId()); if (perm != null) { schema.setCreate(perm.isCreate()); schema.setUpdate(perm.isUpdate()); schema.setDeletable(perm.isDelete()); } Iterator<Map.Entry<String, Field>> fieldIter = schema.getResourceFields().entrySet().iterator(); while (fieldIter.hasNext()) { Map.Entry<String, Field> entry = fieldIter.next(); Field field = entry.getValue(); perm = getPerm(factory, schema, entry.getKey()); if (perm == null) { continue; } if (!perm.isRead()) { fieldIter.remove(); } if (!(field instanceof FieldImpl)) { continue; } FieldImpl fieldImpl = (FieldImpl) field; fieldImpl.setCreate(perm.isCreate()); fieldImpl.setUpdate(perm.isUpdate()); fieldImpl.setReadOnCreateOnly(perm.isReadOnCreateOnly()); } Iterator<Map.Entry<String, Action>> actionIter = schema.getResourceActions().entrySet().iterator(); while (actionIter.hasNext()) { Map.Entry<String, Action> entry = actionIter.next(); perm = getPerm(factory, schema, "resourceActions." + entry.getKey()); if (perm == null) { continue; } if (!perm.isCreate()) { actionIter.remove(); } } return schema; } protected Perm getPerm(SchemaFactory factory, Schema schema, String field) { Schema start = schema; while (schema != null) { String name = String.format("%s.%s", schema.getId(), field); Perm perm = getPerm(name, false); if (perm != null) return perm; schema = factory.getSchema(schema.getParent()); } schema = start; while (schema != null) { String name = String.format("%s.%s", schema.getId(), field); Perm perm = getPerm(name, true); if (perm != null) return perm; schema = factory.getSchema(schema.getParent()); } return null; } protected Perm getPerm(String name) { return getPerm(name, true); } protected Perm getPerm(String name, boolean wildcard) { List<Perm> result = new ArrayList<Perm>(); if (wildcard) { for (Pair<Pattern, Perm> entry : wildcards) { if (entry.getLeft().matcher(name).matches()) { result.add(entry.getValue()); } } } Perm perm = perms.get(name); if (perm != null) { result.add(perm); } return result.size() == 0 ? null : result.get(result.size() - 1); } @PostConstruct public void init() throws IOException { for (URL url : resources) { log.info("Loading [{}] for schema auth", url); InputStream is = url.openStream(); try { Map<String, Object> values = jsonMapper.readValue(is); Object value = values.get("authorize"); if (value instanceof Map) { load((Map<?, ?>) value); } } finally { IOUtils.closeQuietly(is); } } } protected void load(Map<?, ?> values) { for (Map.Entry<?, ?> entry : values.entrySet()) { String key = entry.getKey().toString(); Perm perm = new Perm(entry.getValue().toString()); if (NOT_PATTERN.matcher(key).matches()) { perms.put(key, perm); } else { wildcards.add(new ImmutablePair<Pattern, Perm>(Pattern.compile(key), perm)); } } } public List<URL> getResources() { return resources; } @Inject public void setResources(List<URL> resources) { this.resources = resources; } public JsonMapper getJsonMapper() { return jsonMapper; } @Inject public void setJsonMapper(JsonMapper jsonMapper) { this.jsonMapper = jsonMapper; } private static class Perm { boolean read, create, update, delete, readOnCreateOnly; public Perm(String value) { super(); create = value.contains("c"); read = value.contains("r"); update = value.contains("u"); delete = value.contains("d"); readOnCreateOnly = value.contains("o"); } public boolean isRead() { return read; } public boolean isCreate() { return create; } public boolean isUpdate() { return update; } public boolean isDelete() { return delete; } public boolean isReadOnCreateOnly() { return readOnCreateOnly; } } }
package br.com.university.web.rest; import br.com.university.ScientificweekApp; import br.com.university.domain.Authority; import br.com.university.domain.User; import br.com.university.repository.UserRepository; import br.com.university.repository.search.UserSearchRepository; import br.com.university.security.AuthoritiesConstants; import br.com.university.service.MailService; import br.com.university.service.UserService; import br.com.university.service.dto.UserDTO; import br.com.university.service.mapper.UserMapper; import br.com.university.web.rest.errors.ExceptionTranslator; import br.com.university.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.time.Instant; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the UserResource REST controller. * * @see UserResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ScientificweekApp.class) public class UserResourceIntTest { private static final Long DEFAULT_ID = 1L; private static final String DEFAULT_LOGIN = "johndoe"; private static final String UPDATED_LOGIN = "jhipster"; private static final String DEFAULT_PASSWORD = "passjohndoe"; private static final String UPDATED_PASSWORD = "passjhipster"; private static final String DEFAULT_EMAIL = "johndoe@localhost"; private static final String UPDATED_EMAIL = "jhipster@localhost"; private static final String DEFAULT_FIRSTNAME = "john"; private static final String UPDATED_FIRSTNAME = "jhipsterFirstName"; private static final String DEFAULT_LASTNAME = "doe"; private static final String UPDATED_LASTNAME = "jhipsterLastName"; private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40"; private static final String DEFAULT_LANGKEY = "en"; private static final String UPDATED_LANGKEY = "fr"; @Autowired private UserRepository userRepository; @Autowired private UserSearchRepository userSearchRepository; @Autowired private MailService mailService; @Autowired private UserService userService; @Autowired private UserMapper userMapper; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restUserMockMvc; private User user; @Before public void setup() { MockitoAnnotations.initMocks(this); UserResource userResource = new UserResource(userRepository, mailService, userService, userSearchRepository); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setMessageConverters(jacksonMessageConverter) .build(); } /** * Create a User. * * This is a static method, as tests for other entities might also need it, * if they test an entity which has a required relationship to the User entity. */ public static User createEntity(EntityManager em) { User user = new User(); user.setLogin(DEFAULT_LOGIN); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setEmail(DEFAULT_EMAIL); user.setFirstName(DEFAULT_FIRSTNAME); user.setLastName(DEFAULT_LASTNAME); user.setImageUrl(DEFAULT_IMAGEURL); user.setLangKey(DEFAULT_LANGKEY); return user; } @Before public void initTest() { user = createEntity(em); } @Test @Transactional public void createUser() throws Exception { int databaseSizeBeforeCreate = userRepository.findAll().size(); // Create the User Set<String> authorities = new HashSet<>(); authorities.add("ROLE_USER"); ManagedUserVM managedUserVM = new ManagedUserVM( null, DEFAULT_LOGIN, DEFAULT_PASSWORD, DEFAULT_FIRSTNAME, DEFAULT_LASTNAME, DEFAULT_EMAIL, true, DEFAULT_IMAGEURL, DEFAULT_LANGKEY, null, null, null, null, authorities); restUserMockMvc.perform(post("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isCreated()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeCreate + 1); User testUser = userList.get(userList.size() - 1); assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN); assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME); assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL); assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY); } @Test @Transactional public void createUserWithExistingId() throws Exception { int databaseSizeBeforeCreate = userRepository.findAll().size(); Set<String> authorities = new HashSet<>(); authorities.add("ROLE_USER"); ManagedUserVM managedUserVM = new ManagedUserVM( 1L, DEFAULT_LOGIN, DEFAULT_PASSWORD, DEFAULT_FIRSTNAME, DEFAULT_LASTNAME, DEFAULT_EMAIL, true, DEFAULT_IMAGEURL, DEFAULT_LANGKEY, null, null, null, null, authorities); // An entity with an existing ID cannot be created, so this API call must fail restUserMockMvc.perform(post("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void createUserWithExistingLogin() throws Exception { // Initialize the database userRepository.saveAndFlush(user); userSearchRepository.save(user); int databaseSizeBeforeCreate = userRepository.findAll().size(); Set<String> authorities = new HashSet<>(); authorities.add("ROLE_USER"); ManagedUserVM managedUserVM = new ManagedUserVM( null, DEFAULT_LOGIN, // this login should already be used DEFAULT_PASSWORD, DEFAULT_FIRSTNAME, DEFAULT_LASTNAME, "anothermail@localhost", true, DEFAULT_IMAGEURL, DEFAULT_LANGKEY, null, null, null, null, authorities); // Create the User restUserMockMvc.perform(post("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void createUserWithExistingEmail() throws Exception { // Initialize the database userRepository.saveAndFlush(user); userSearchRepository.save(user); int databaseSizeBeforeCreate = userRepository.findAll().size(); Set<String> authorities = new HashSet<>(); authorities.add("ROLE_USER"); ManagedUserVM managedUserVM = new ManagedUserVM( null, "anotherlogin", DEFAULT_PASSWORD, DEFAULT_FIRSTNAME, DEFAULT_LASTNAME, DEFAULT_EMAIL, // this email should already be used true, DEFAULT_IMAGEURL, DEFAULT_LANGKEY, null, null, null, null, authorities); // Create the User restUserMockMvc.perform(post("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllUsers() throws Exception { // Initialize the database userRepository.saveAndFlush(user); userSearchRepository.save(user); // Get all the users restUserMockMvc.perform(get("/api/users?sort=id,desc") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); } @Test @Transactional public void getUser() throws Exception { // Initialize the database userRepository.saveAndFlush(user); userSearchRepository.save(user); // Get the user restUserMockMvc.perform(get("/api/users/{login}", user.getLogin())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.login").value(user.getLogin())) .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); } @Test @Transactional public void getNonExistingUser() throws Exception { restUserMockMvc.perform(get("/api/users/unknown")) .andExpect(status().isNotFound()); } @Test @Transactional public void updateUser() throws Exception { // Initialize the database userRepository.saveAndFlush(user); userSearchRepository.save(user); int databaseSizeBeforeUpdate = userRepository.findAll().size(); // Update the user User updatedUser = userRepository.findOne(user.getId()); Set<String> authorities = new HashSet<>(); authorities.add("ROLE_USER"); ManagedUserVM managedUserVM = new ManagedUserVM( updatedUser.getId(), updatedUser.getLogin(), UPDATED_PASSWORD, UPDATED_FIRSTNAME, UPDATED_LASTNAME, UPDATED_EMAIL, updatedUser.getActivated(), UPDATED_IMAGEURL, UPDATED_LANGKEY, updatedUser.getCreatedBy(), updatedUser.getCreatedDate(), updatedUser.getLastModifiedBy(), updatedUser.getLastModifiedDate(), authorities); restUserMockMvc.perform(put("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isOk()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeUpdate); User testUser = userList.get(userList.size() - 1); assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); } @Test @Transactional public void updateUserLogin() throws Exception { // Initialize the database userRepository.saveAndFlush(user); userSearchRepository.save(user); int databaseSizeBeforeUpdate = userRepository.findAll().size(); // Update the user User updatedUser = userRepository.findOne(user.getId()); Set<String> authorities = new HashSet<>(); authorities.add("ROLE_USER"); ManagedUserVM managedUserVM = new ManagedUserVM( updatedUser.getId(), UPDATED_LOGIN, UPDATED_PASSWORD, UPDATED_FIRSTNAME, UPDATED_LASTNAME, UPDATED_EMAIL, updatedUser.getActivated(), UPDATED_IMAGEURL, UPDATED_LANGKEY, updatedUser.getCreatedBy(), updatedUser.getCreatedDate(), updatedUser.getLastModifiedBy(), updatedUser.getLastModifiedDate(), authorities); restUserMockMvc.perform(put("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isOk()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeUpdate); User testUser = userList.get(userList.size() - 1); assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN); assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); } @Test @Transactional public void updateUserExistingEmail() throws Exception { // Initialize the database with 2 users userRepository.saveAndFlush(user); userSearchRepository.save(user); User anotherUser = new User(); anotherUser.setLogin("jhipster"); anotherUser.setPassword(RandomStringUtils.random(60)); anotherUser.setActivated(true); anotherUser.setEmail("jhipster@localhost"); anotherUser.setFirstName("java"); anotherUser.setLastName("hipster"); anotherUser.setImageUrl(""); anotherUser.setLangKey("en"); userRepository.saveAndFlush(anotherUser); userSearchRepository.save(anotherUser); // Update the user User updatedUser = userRepository.findOne(user.getId()); Set<String> authorities = new HashSet<>(); authorities.add("ROLE_USER"); ManagedUserVM managedUserVM = new ManagedUserVM( updatedUser.getId(), updatedUser.getLogin(), updatedUser.getPassword(), updatedUser.getFirstName(), updatedUser.getLastName(), "jhipster@localhost", // this email should already be used by anotherUser updatedUser.getActivated(), updatedUser.getImageUrl(), updatedUser.getLangKey(), updatedUser.getCreatedBy(), updatedUser.getCreatedDate(), updatedUser.getLastModifiedBy(), updatedUser.getLastModifiedDate(), authorities); restUserMockMvc.perform(put("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); } @Test @Transactional public void updateUserExistingLogin() throws Exception { // Initialize the database userRepository.saveAndFlush(user); userSearchRepository.save(user); User anotherUser = new User(); anotherUser.setLogin("jhipster"); anotherUser.setPassword(RandomStringUtils.random(60)); anotherUser.setActivated(true); anotherUser.setEmail("jhipster@localhost"); anotherUser.setFirstName("java"); anotherUser.setLastName("hipster"); anotherUser.setImageUrl(""); anotherUser.setLangKey("en"); userRepository.saveAndFlush(anotherUser); userSearchRepository.save(anotherUser); // Update the user User updatedUser = userRepository.findOne(user.getId()); Set<String> authorities = new HashSet<>(); authorities.add("ROLE_USER"); ManagedUserVM managedUserVM = new ManagedUserVM( updatedUser.getId(), "jhipster", // this login should already be used by anotherUser updatedUser.getPassword(), updatedUser.getFirstName(), updatedUser.getLastName(), updatedUser.getEmail(), updatedUser.getActivated(), updatedUser.getImageUrl(), updatedUser.getLangKey(), updatedUser.getCreatedBy(), updatedUser.getCreatedDate(), updatedUser.getLastModifiedBy(), updatedUser.getLastModifiedDate(), authorities); restUserMockMvc.perform(put("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); } @Test @Transactional public void deleteUser() throws Exception { // Initialize the database userRepository.saveAndFlush(user); userSearchRepository.save(user); int databaseSizeBeforeDelete = userRepository.findAll().size(); // Delete the user restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void getAllAuthorities() throws Exception { restUserMockMvc.perform(get("/api/users/authorities") .accept(TestUtil.APPLICATION_JSON_UTF8) .contentType(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$").isArray()) .andExpect(jsonPath("$").value(containsInAnyOrder("ROLE_USER", "ROLE_ADMIN"))); } @Test @Transactional public void testUserEquals() { User userA = new User(); assertThat(userA).isEqualTo(userA); assertThat(userA).isNotEqualTo(null); assertThat(userA).isNotEqualTo(new Object()); assertThat(userA.toString()).isNotNull(); userA.setLogin("AAA"); User userB = new User(); userB.setLogin("BBB"); assertThat(userA).isNotEqualTo(userB); userB.setLogin("AAA"); assertThat(userA).isEqualTo(userB); assertThat(userA.hashCode()).isEqualTo(userB.hashCode()); } @Test public void testUserFromId() { assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID); assertThat(userMapper.userFromId(null)).isNull(); } @Test public void testUserDTOtoUser() { UserDTO userDTO = new UserDTO( DEFAULT_ID, DEFAULT_LOGIN, DEFAULT_FIRSTNAME, DEFAULT_LASTNAME, DEFAULT_EMAIL, true, DEFAULT_IMAGEURL, DEFAULT_LANGKEY, DEFAULT_LOGIN, null, DEFAULT_LOGIN, null, Stream.of(AuthoritiesConstants.USER).collect(Collectors.toSet())); User user = userMapper.userDTOToUser(userDTO); assertThat(user.getId()).isEqualTo(DEFAULT_ID); assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN); assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME); assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL); assertThat(user.getActivated()).isEqualTo(true); assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY); assertThat(user.getCreatedBy()).isNull(); assertThat(user.getCreatedDate()).isNotNull(); assertThat(user.getLastModifiedBy()).isNull(); assertThat(user.getLastModifiedDate()).isNotNull(); assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER); } @Test public void testUserToUserDTO() { user.setId(DEFAULT_ID); user.setCreatedBy(DEFAULT_LOGIN); user.setCreatedDate(Instant.now()); user.setLastModifiedBy(DEFAULT_LOGIN); user.setLastModifiedDate(Instant.now()); Set<Authority> authorities = new HashSet<>(); Authority authority = new Authority(); authority.setName(AuthoritiesConstants.USER); authorities.add(authority); user.setAuthorities(authorities); UserDTO userDTO = userMapper.userToUserDTO(user); assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID); assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN); assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME); assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL); assertThat(userDTO.isActivated()).isEqualTo(true); assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY); assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN); assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate()); assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN); assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate()); assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER); assertThat(userDTO.toString()).isNotNull(); } @Test public void testAuthorityEquals() throws Exception { Authority authorityA = new Authority(); assertThat(authorityA).isEqualTo(authorityA); assertThat(authorityA).isNotEqualTo(null); assertThat(authorityA).isNotEqualTo(new Object()); assertThat(authorityA.hashCode()).isEqualTo(0); assertThat(authorityA.toString()).isNotNull(); Authority authorityB = new Authority(); assertThat(authorityA).isEqualTo(authorityB); authorityB.setName(AuthoritiesConstants.ADMIN); assertThat(authorityA).isNotEqualTo(authorityB); authorityA.setName(AuthoritiesConstants.USER); assertThat(authorityA).isNotEqualTo(authorityB); authorityB.setName(AuthoritiesConstants.USER); assertThat(authorityA).isEqualTo(authorityB); assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode()); } }
/* * 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 android.support.v4.util; /** * CircularArray is a generic circular array data structure that provides O(1) random read, O(1) * prepend and O(1) append. The CircularArray automatically grows its capacity when number of added * items is over its capacity. */ public final class CircularArray<E> { private E[] mElements; private int mHead; private int mTail; private int mCapacityBitmask; private void doubleCapacity() { int n = mElements.length; int r = n - mHead; int newCapacity = n << 1; if (newCapacity < 0) { throw new RuntimeException("Max array capacity exceeded"); } Object[] a = new Object[newCapacity]; System.arraycopy(mElements, mHead, a, 0, r); System.arraycopy(mElements, 0, a, r, mHead); mElements = (E[]) a; mHead = 0; mTail = n; mCapacityBitmask = newCapacity - 1; } /** * Creates a circular array with default capacity. */ public CircularArray() { this(8); } /** * Creates a circular array with capacity for at least {@code minCapacity} * elements. * * @param minCapacity the minimum capacity, between 1 and 2^30 inclusive */ public CircularArray(int minCapacity) { if (minCapacity < 1) { throw new IllegalArgumentException("capacity must be >= 1"); } if (minCapacity > (2 << 29)) { throw new IllegalArgumentException("capacity must be <= 2^30"); } // If minCapacity isn't a power of 2, round up to the next highest // power of 2. final int arrayCapacity; if (Integer.bitCount(minCapacity) != 1) { arrayCapacity = Integer.highestOneBit(minCapacity - 1) << 1; } else { arrayCapacity = minCapacity; } mCapacityBitmask = arrayCapacity - 1; mElements = (E[]) new Object[arrayCapacity]; } /** * Add an element in front of the CircularArray. * @param e Element to add. */ public void addFirst(E e) { mHead = (mHead - 1) & mCapacityBitmask; mElements[mHead] = e; if (mHead == mTail) { doubleCapacity(); } } /** * Add an element at end of the CircularArray. * @param e Element to add. */ public void addLast(E e) { mElements[mTail] = e; mTail = (mTail + 1) & mCapacityBitmask; if (mTail == mHead) { doubleCapacity(); } } /** * Remove first element from front of the CircularArray and return it. * @return The element removed. * @throws ArrayIndexOutOfBoundsException if CircularArray is empty. */ public E popFirst() { if (mHead == mTail) { throw new ArrayIndexOutOfBoundsException(); } E result = mElements[mHead]; mElements[mHead] = null; mHead = (mHead + 1) & mCapacityBitmask; return result; } /** * Remove last element from end of the CircularArray and return it. * @return The element removed. * @throws ArrayIndexOutOfBoundsException if CircularArray is empty. */ public E popLast() { if (mHead == mTail) { throw new ArrayIndexOutOfBoundsException(); } int t = (mTail - 1) & mCapacityBitmask; E result = mElements[t]; mElements[t] = null; mTail = t; return result; } /** * Remove all elements from the CircularArray. */ public void clear() { removeFromStart(size()); } /** * Remove multiple elements from front of the CircularArray, ignore when numOfElements * is less than or equals to 0. * @param numOfElements Number of elements to remove. * @throws ArrayIndexOutOfBoundsException if numOfElements is larger than * {@link #size()} */ public void removeFromStart(int numOfElements) { if (numOfElements <= 0) { return; } if (numOfElements > size()) { throw new ArrayIndexOutOfBoundsException(); } int end = mElements.length; if (numOfElements < end - mHead) { end = mHead + numOfElements; } for (int i = mHead; i < end; i++) { mElements[i] = null; } int removed = (end - mHead); numOfElements -= removed; mHead = (mHead + removed) & mCapacityBitmask; if (numOfElements > 0) { // mHead wrapped to 0 for (int i = 0; i < numOfElements; i++) { mElements[i] = null; } mHead = numOfElements; } } /** * Remove multiple elements from end of the CircularArray, ignore when numOfElements * is less than or equals to 0. * @param numOfElements Number of elements to remove. * @throws ArrayIndexOutOfBoundsException if numOfElements is larger than * {@link #size()} */ public void removeFromEnd(int numOfElements) { if (numOfElements <= 0) { return; } if (numOfElements > size()) { throw new ArrayIndexOutOfBoundsException(); } int start = 0; if (numOfElements < mTail) { start = mTail - numOfElements; } for (int i = start; i < mTail; i++) { mElements[i] = null; } int removed = (mTail - start); numOfElements -= removed; mTail = mTail - removed; if (numOfElements > 0) { // mTail wrapped to mElements.length mTail = mElements.length; int newTail = mTail - numOfElements; for (int i = newTail; i < mTail; i++) { mElements[i] = null; } mTail = newTail; } } /** * Get first element of the CircularArray. * @return The first element. * @throws {@link ArrayIndexOutOfBoundsException} if CircularArray is empty. */ public E getFirst() { if (mHead == mTail) { throw new ArrayIndexOutOfBoundsException(); } return mElements[mHead]; } /** * Get last element of the CircularArray. * @return The last element. * @throws {@link ArrayIndexOutOfBoundsException} if CircularArray is empty. */ public E getLast() { if (mHead == mTail) { throw new ArrayIndexOutOfBoundsException(); } return mElements[(mTail - 1) & mCapacityBitmask]; } /** * Get nth (0 <= n <= size()-1) element of the CircularArray. * @param n The zero based element index in the CircularArray. * @return The nth element. * @throws {@link ArrayIndexOutOfBoundsException} if n < 0 or n >= size(). */ public E get(int n) { if (n < 0 || n >= size()) { throw new ArrayIndexOutOfBoundsException(); } return mElements[(mHead + n) & mCapacityBitmask]; } /** * Get number of elements in the CircularArray. * @return Number of elements in the CircularArray. */ public int size() { return (mTail - mHead) & mCapacityBitmask; } /** * Return true if size() is 0. * @return true if size() is 0. */ public boolean isEmpty() { return mHead == mTail; } }
/** */ package visualizacionMetricas3.visualizacion.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import visualizacionMetricas3.visualizacion.Borde; import visualizacionMetricas3.visualizacion.Clase; import visualizacionMetricas3.visualizacion.Conector; import visualizacionMetricas3.visualizacion.Contenedor; import visualizacionMetricas3.visualizacion.ElementoDiagrama; import visualizacionMetricas3.visualizacion.Label; import visualizacionMetricas3.visualizacion.VisualizacionPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Clase</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link visualizacionMetricas3.visualizacion.impl.ClaseImpl#getDiagrama <em>Diagrama</em>}</li> * <li>{@link visualizacionMetricas3.visualizacion.impl.ClaseImpl#getName <em>Name</em>}</li> * <li>{@link visualizacionMetricas3.visualizacion.impl.ClaseImpl#getLabel <em>Label</em>}</li> * <li>{@link visualizacionMetricas3.visualizacion.impl.ClaseImpl#getBorde <em>Borde</em>}</li> * <li>{@link visualizacionMetricas3.visualizacion.impl.ClaseImpl#getConectores <em>Conectores</em>}</li> * <li>{@link visualizacionMetricas3.visualizacion.impl.ClaseImpl#getElementos <em>Elementos</em>}</li> * </ul> * </p> * * @generated */ public class ClaseImpl extends EObjectImpl implements Clase { /** * The cached value of the '{@link #getDiagrama() <em>Diagrama</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDiagrama() * @generated * @ordered */ protected Contenedor diagrama; /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getLabel() <em>Label</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLabel() * @generated * @ordered */ protected Label label; /** * The cached value of the '{@link #getBorde() <em>Borde</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getBorde() * @generated * @ordered */ protected Borde borde; /** * The cached value of the '{@link #getConectores() <em>Conectores</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getConectores() * @generated * @ordered */ protected EList<Conector> conectores; /** * The cached value of the '{@link #getElementos() <em>Elementos</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getElementos() * @generated * @ordered */ protected EList<ElementoDiagrama> elementos; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ClaseImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return VisualizacionPackage.Literals.CLASE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Contenedor getDiagrama() { if (diagrama != null && diagrama.eIsProxy()) { InternalEObject oldDiagrama = (InternalEObject)diagrama; diagrama = (Contenedor)eResolveProxy(oldDiagrama); if (diagrama != oldDiagrama) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, VisualizacionPackage.CLASE__DIAGRAMA, oldDiagrama, diagrama)); } } return diagrama; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Contenedor basicGetDiagrama() { return diagrama; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDiagrama(Contenedor newDiagrama) { Contenedor oldDiagrama = diagrama; diagrama = newDiagrama; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, VisualizacionPackage.CLASE__DIAGRAMA, oldDiagrama, diagrama)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, VisualizacionPackage.CLASE__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Label getLabel() { return label; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetLabel(Label newLabel, NotificationChain msgs) { Label oldLabel = label; label = newLabel; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, VisualizacionPackage.CLASE__LABEL, oldLabel, newLabel); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLabel(Label newLabel) { if (newLabel != label) { NotificationChain msgs = null; if (label != null) msgs = ((InternalEObject)label).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - VisualizacionPackage.CLASE__LABEL, null, msgs); if (newLabel != null) msgs = ((InternalEObject)newLabel).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - VisualizacionPackage.CLASE__LABEL, null, msgs); msgs = basicSetLabel(newLabel, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, VisualizacionPackage.CLASE__LABEL, newLabel, newLabel)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Borde getBorde() { return borde; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetBorde(Borde newBorde, NotificationChain msgs) { Borde oldBorde = borde; borde = newBorde; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, VisualizacionPackage.CLASE__BORDE, oldBorde, newBorde); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBorde(Borde newBorde) { if (newBorde != borde) { NotificationChain msgs = null; if (borde != null) msgs = ((InternalEObject)borde).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - VisualizacionPackage.CLASE__BORDE, null, msgs); if (newBorde != null) msgs = ((InternalEObject)newBorde).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - VisualizacionPackage.CLASE__BORDE, null, msgs); msgs = basicSetBorde(newBorde, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, VisualizacionPackage.CLASE__BORDE, newBorde, newBorde)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Conector> getConectores() { if (conectores == null) { conectores = new EObjectContainmentEList<Conector>(Conector.class, this, VisualizacionPackage.CLASE__CONECTORES); } return conectores; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ElementoDiagrama> getElementos() { if (elementos == null) { elementos = new EObjectContainmentEList<ElementoDiagrama>(ElementoDiagrama.class, this, VisualizacionPackage.CLASE__ELEMENTOS); } return elementos; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case VisualizacionPackage.CLASE__LABEL: return basicSetLabel(null, msgs); case VisualizacionPackage.CLASE__BORDE: return basicSetBorde(null, msgs); case VisualizacionPackage.CLASE__CONECTORES: return ((InternalEList<?>)getConectores()).basicRemove(otherEnd, msgs); case VisualizacionPackage.CLASE__ELEMENTOS: return ((InternalEList<?>)getElementos()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case VisualizacionPackage.CLASE__DIAGRAMA: if (resolve) return getDiagrama(); return basicGetDiagrama(); case VisualizacionPackage.CLASE__NAME: return getName(); case VisualizacionPackage.CLASE__LABEL: return getLabel(); case VisualizacionPackage.CLASE__BORDE: return getBorde(); case VisualizacionPackage.CLASE__CONECTORES: return getConectores(); case VisualizacionPackage.CLASE__ELEMENTOS: return getElementos(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case VisualizacionPackage.CLASE__DIAGRAMA: setDiagrama((Contenedor)newValue); return; case VisualizacionPackage.CLASE__NAME: setName((String)newValue); return; case VisualizacionPackage.CLASE__LABEL: setLabel((Label)newValue); return; case VisualizacionPackage.CLASE__BORDE: setBorde((Borde)newValue); return; case VisualizacionPackage.CLASE__CONECTORES: getConectores().clear(); getConectores().addAll((Collection<? extends Conector>)newValue); return; case VisualizacionPackage.CLASE__ELEMENTOS: getElementos().clear(); getElementos().addAll((Collection<? extends ElementoDiagrama>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case VisualizacionPackage.CLASE__DIAGRAMA: setDiagrama((Contenedor)null); return; case VisualizacionPackage.CLASE__NAME: setName(NAME_EDEFAULT); return; case VisualizacionPackage.CLASE__LABEL: setLabel((Label)null); return; case VisualizacionPackage.CLASE__BORDE: setBorde((Borde)null); return; case VisualizacionPackage.CLASE__CONECTORES: getConectores().clear(); return; case VisualizacionPackage.CLASE__ELEMENTOS: getElementos().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case VisualizacionPackage.CLASE__DIAGRAMA: return diagrama != null; case VisualizacionPackage.CLASE__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case VisualizacionPackage.CLASE__LABEL: return label != null; case VisualizacionPackage.CLASE__BORDE: return borde != null; case VisualizacionPackage.CLASE__CONECTORES: return conectores != null && !conectores.isEmpty(); case VisualizacionPackage.CLASE__ELEMENTOS: return elementos != null && !elementos.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); result.append(name); result.append(')'); return result.toString(); } } //ClaseImpl
package org.blackchip.scorebored; import java.awt.event.KeyEvent; import java.io.IOException; import javax.swing.DefaultListModel; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import org.blackchip.scorebored.swing.Swing; import org.blackchip.scorebored.talker.SwingTalker; public class JacobExcusesFrame extends javax.swing.JFrame { private SwingTalker talker; private JacobExcuses jacobExcuses; private String defaultExcuse = "Select excuse to edit or enter new excuse"; private static String LAME_EXCUSE = "Lame excuse"; public JacobExcusesFrame(JMenuBar menu, SwingTalker talker) { this.talker = talker; this.jacobExcuses = JacobExcuses.getInstance(); initComponents(); this.resetModel(); excuseList.setSelectedIndex(0); this.setJMenuBar(menu); } private void resetModel() { DefaultListModel newModel = new DefaultListModel(); for(String s : jacobExcuses.getList()) { newModel.addElement(s); } excuseList.setListData(new String[0]); excuseList.setModel(newModel); } private void editExcuse() { String oldExcuse = (String)excuseList.getSelectedValue(); String newExcuse = editText.getText(); if ( oldExcuse.equals(newExcuse) ) { return; } try { if ( ! jacobExcuses.modify(oldExcuse, newExcuse) ) { Swing.showNotice("You already have that excuse"); editText.setText(oldExcuse); editText.requestFocusInWindow(); return; } jacobExcuses.save(); this.resetModel(); excuseList.setSelectedIndex(jacobExcuses.getList() .indexOf(newExcuse)); } catch ( IOException ie ) { Swing.showError("Unable to save Jacob excuses", ie); } addButton.requestFocusInWindow(); } private void addExcuse() { try { if ( ! jacobExcuses.add(LAME_EXCUSE) ) { Swing.showNotice("We don't accept lame excuses here!\n" + "Edit your lame excuse before creating another one."); } else { jacobExcuses.save(); this.resetModel(); excuseList.setSelectedIndex(jacobExcuses.getList() .indexOf(LAME_EXCUSE)); editText.requestFocusInWindow(); } } catch ( IOException ie ) { Swing.showError("Unable to save Jacob excuses", ie); } } private void deleteExcuse() { try { String excuse = (String)excuseList.getSelectedValue(); int index = excuseList.getSelectedIndex(); if ( excuse != null ) { int dialogButton = JOptionPane.YES_NO_OPTION; int result = JOptionPane.showConfirmDialog(null, "Are you sure you wish " + "to delete this Fantastic Excuse??", "Warning", dialogButton); if(result == JOptionPane.YES_OPTION) { if ( jacobExcuses.remove(excuse) ) { jacobExcuses.save(); } this.resetModel(); int size = excuseList.getModel().getSize(); index = ( index < size ) ? index : size - 1; excuseList.setSelectedIndex(index); excuseList.requestFocusInWindow(); } } } catch ( IOException ie ) { Swing.showError("Unable to save Jacob excuses", ie); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); excuseList = new javax.swing.JList(); editText = new javax.swing.JTextField(); deleteExcuse = new javax.swing.JButton(); addButton = new javax.swing.JButton(); speakerButton = new javax.swing.JButton(); setTitle("Excuses"); excuseList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); excuseList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION); excuseList.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { setExcusesText(evt); } }); jScrollPane1.setViewportView(excuseList); editText.setText("Select excuse to edit or enter new excuse"); editText.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editTextActionPerformed(evt); } }); editText.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { removeDefault(evt); } public void focusLost(java.awt.event.FocusEvent evt) { editTextFocusLost(evt); } }); deleteExcuse.setText("Delete"); deleteExcuse.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteExcuseActionPerformed(evt); } }); deleteExcuse.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { deleteExcuseKeyPressed(evt); } }); addButton.setText("Add"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); addButton.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { addButtonKeyPressed(evt); } }); speakerButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/speaker.png"))); // NOI18N speakerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { speakerButtonActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(deleteExcuse) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(addButton)) .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1) .add(layout.createSequentialGroup() .add(editText, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(speakerButton))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(16, 16, 16) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(speakerButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(editText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(addButton) .add(deleteExcuse)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void setExcusesText(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_setExcusesText if(excuseList.getSelectedValue() != null) { editText.setText(excuseList.getSelectedValue().toString()); } else { editText.setText(defaultExcuse); } }//GEN-LAST:event_setExcusesText private void editTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editTextActionPerformed editExcuse(); }//GEN-LAST:event_editTextActionPerformed private void deleteExcuseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteExcuseActionPerformed deleteExcuse(); }//GEN-LAST:event_deleteExcuseActionPerformed private void removeDefault(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_removeDefault editText.selectAll(); }//GEN-LAST:event_removeDefault private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed addExcuse(); }//GEN-LAST:event_addButtonActionPerformed private void editTextFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_editTextFocusLost editExcuse(); }//GEN-LAST:event_editTextFocusLost private void speakerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_speakerButtonActionPerformed if ( !editText.getText().isEmpty() ) { talker.say(editText.getText()); } }//GEN-LAST:event_speakerButtonActionPerformed private void addButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_addButtonKeyPressed if ( evt.getKeyCode() == KeyEvent.VK_ENTER ) { addExcuse(); } }//GEN-LAST:event_addButtonKeyPressed private void deleteExcuseKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_deleteExcuseKeyPressed if ( evt.getKeyCode() == KeyEvent.VK_ENTER ) { deleteExcuse(); } }//GEN-LAST:event_deleteExcuseKeyPressed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addButton; private javax.swing.JButton deleteExcuse; private javax.swing.JTextField editText; private javax.swing.JList excuseList; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton speakerButton; // End of variables declaration//GEN-END:variables }
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.*; import org.junit.*; import org.mockito.InOrder; import io.reactivex.*; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.*; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; public class ObservableTakeTest { @Test public void testTake1() { Observable<String> w = Observable.fromIterable(Arrays.asList("one", "two", "three")); Observable<String> take = w.take(2); Observer<String> observer = TestHelper.mockObserver(); take.subscribe(observer); verify(observer, times(1)).onNext("one"); verify(observer, times(1)).onNext("two"); verify(observer, never()).onNext("three"); verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); } @Test public void testTake2() { Observable<String> w = Observable.fromIterable(Arrays.asList("one", "two", "three")); Observable<String> take = w.take(1); Observer<String> observer = TestHelper.mockObserver(); take.subscribe(observer); verify(observer, times(1)).onNext("one"); verify(observer, never()).onNext("two"); verify(observer, never()).onNext("three"); verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); } @Test(expected = IllegalArgumentException.class) public void testTakeWithError() { Observable.fromIterable(Arrays.asList(1, 2, 3)).take(1) .map(new Function<Integer, Integer>() { @Override public Integer apply(Integer t1) { throw new IllegalArgumentException("some error"); } }).blockingSingle(); } @Test public void testTakeWithErrorHappeningInOnNext() { Observable<Integer> w = Observable.fromIterable(Arrays.asList(1, 2, 3)) .take(2).map(new Function<Integer, Integer>() { @Override public Integer apply(Integer t1) { throw new IllegalArgumentException("some error"); } }); Observer<Integer> observer = TestHelper.mockObserver(); w.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError(any(IllegalArgumentException.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testTakeWithErrorHappeningInTheLastOnNext() { Observable<Integer> w = Observable.fromIterable(Arrays.asList(1, 2, 3)).take(1).map(new Function<Integer, Integer>() { @Override public Integer apply(Integer t1) { throw new IllegalArgumentException("some error"); } }); Observer<Integer> observer = TestHelper.mockObserver(); w.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError(any(IllegalArgumentException.class)); inOrder.verifyNoMoreInteractions(); } @Test public void testTakeDoesntLeakErrors() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposables.empty()); observer.onNext("one"); observer.onError(new Throwable("test failed")); } }); Observer<String> observer = TestHelper.mockObserver(); source.take(1).subscribe(observer); verify(observer).onSubscribe((Disposable)notNull()); verify(observer, times(1)).onNext("one"); // even though onError is called we take(1) so shouldn't see it verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); verifyNoMoreInteractions(observer); } @Test @Ignore("take(0) is now empty() and doesn't even subscribe to the original source") public void testTakeZeroDoesntLeakError() { final AtomicBoolean subscribed = new AtomicBoolean(false); final Disposable bs = Disposables.empty(); Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { subscribed.set(true); observer.onSubscribe(bs); observer.onError(new Throwable("test failed")); } }); Observer<String> observer = TestHelper.mockObserver(); source.take(0).subscribe(observer); assertTrue("source subscribed", subscribed.get()); assertTrue("source unsubscribed", bs.isDisposed()); verify(observer, never()).onNext(anyString()); // even though onError is called we take(0) so shouldn't see it verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); verifyNoMoreInteractions(observer); } @Test public void testUnsubscribeAfterTake() { TestObservableFunc f = new TestObservableFunc("one", "two", "three"); Observable<String> w = Observable.unsafeCreate(f); Observer<String> observer = TestHelper.mockObserver(); Observable<String> take = w.take(1); take.subscribe(observer); // wait for the Observable to complete try { f.t.join(); } catch (Throwable e) { e.printStackTrace(); fail(e.getMessage()); } System.out.println("TestObservable thread finished"); verify(observer).onSubscribe((Disposable)notNull()); verify(observer, times(1)).onNext("one"); verify(observer, never()).onNext("two"); verify(observer, never()).onNext("three"); verify(observer, times(1)).onComplete(); // FIXME no longer assertable // verify(s, times(1)).unsubscribe(); verifyNoMoreInteractions(observer); } @Test(timeout = 2000) public void testUnsubscribeFromSynchronousInfiniteObservable() { final AtomicLong count = new AtomicLong(); INFINITE_OBSERVABLE.take(10).subscribe(new Consumer<Long>() { @Override public void accept(Long l) { count.set(l); } }); assertEquals(10, count.get()); } @Test(timeout = 2000) public void testMultiTake() { final AtomicInteger count = new AtomicInteger(); Observable.unsafeCreate(new ObservableSource<Integer>() { @Override public void subscribe(Observer<? super Integer> observer) { Disposable bs = Disposables.empty(); observer.onSubscribe(bs); for (int i = 0; !bs.isDisposed(); i++) { System.out.println("Emit: " + i); count.incrementAndGet(); observer.onNext(i); } } }).take(100).take(1).blockingForEach(new Consumer<Integer>() { @Override public void accept(Integer t1) { System.out.println("Receive: " + t1); } }); assertEquals(1, count.get()); } static class TestObservableFunc implements ObservableSource<String> { final String[] values; Thread t; TestObservableFunc(String... values) { this.values = values; } @Override public void subscribe(final Observer<? super String> observer) { observer.onSubscribe(Disposables.empty()); System.out.println("TestObservable subscribed to ..."); t = new Thread(new Runnable() { @Override public void run() { try { System.out.println("running TestObservable thread"); for (String s : values) { System.out.println("TestObservable onNext: " + s); observer.onNext(s); } observer.onComplete(); } catch (Throwable e) { throw new RuntimeException(e); } } }); System.out.println("starting TestObservable thread"); t.start(); System.out.println("done starting TestObservable thread"); } } private static Observable<Long> INFINITE_OBSERVABLE = Observable.unsafeCreate(new ObservableSource<Long>() { @Override public void subscribe(Observer<? super Long> op) { Disposable d = Disposables.empty(); op.onSubscribe(d); long l = 1; while (!d.isDisposed()) { op.onNext(l++); } op.onComplete(); } }); @Test(timeout = 2000) public void testTakeObserveOn() { Observer<Object> o = TestHelper.mockObserver(); TestObserver<Object> to = new TestObserver<Object>(o); INFINITE_OBSERVABLE .observeOn(Schedulers.newThread()).take(1).subscribe(to); to.awaitTerminalEvent(); to.assertNoErrors(); verify(o).onNext(1L); verify(o, never()).onNext(2L); verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void testInterrupt() throws InterruptedException { final AtomicReference<Object> exception = new AtomicReference<Object>(); final CountDownLatch latch = new CountDownLatch(1); Observable.just(1).subscribeOn(Schedulers.computation()).take(1) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer t1) { try { Thread.sleep(100); } catch (Exception e) { exception.set(e); e.printStackTrace(); } finally { latch.countDown(); } } }); latch.await(); assertNull(exception.get()); } @Test public void takeFinalValueThrows() { Observable<Integer> source = Observable.just(1).take(1); TestObserver<Integer> to = new TestObserver<Integer>() { @Override public void onNext(Integer t) { throw new TestException(); } }; source.safeSubscribe(to); to.assertNoValues(); to.assertError(TestException.class); to.assertNotComplete(); } @Test public void testReentrantTake() { final PublishSubject<Integer> source = PublishSubject.create(); TestObserver<Integer> to = new TestObserver<Integer>(); source.take(1).doOnNext(new Consumer<Integer>() { @Override public void accept(Integer v) { source.onNext(2); } }).subscribe(to); source.onNext(1); to.assertValue(1); to.assertNoErrors(); to.assertComplete(); } @Test public void takeNegative() { try { Observable.just(1).take(-99); fail("Should have thrown"); } catch (IllegalArgumentException ex) { assertEquals("count >= 0 required but it was -99", ex.getMessage()); } } @Test public void takeZero() { Observable.just(1) .take(0) .test() .assertResult(); } @Test public void dispose() { TestHelper.checkDisposed(PublishSubject.create().take(2)); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<Object>>() { @Override public ObservableSource<Object> apply(Observable<Object> o) throws Exception { return o.take(2); } }); } @Test public void errorAfterLimitReached() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { Observable.error(new TestException()) .take(0) .test() .assertResult(); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } }
/* * 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.tephra.hbase.coprocessor; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.CoprocessorEnvironment; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.OperationWithAttributes; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.FilterBase; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.InternalScanner; import org.apache.hadoop.hbase.regionserver.KeyValueScanner; import org.apache.hadoop.hbase.regionserver.RegionScanner; import org.apache.hadoop.hbase.regionserver.ScanType; import org.apache.hadoop.hbase.regionserver.Store; import org.apache.hadoop.hbase.regionserver.StoreFile; import org.apache.hadoop.hbase.regionserver.StoreScanner; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest; import org.apache.hadoop.hbase.regionserver.wal.WALEdit; import org.apache.hadoop.hbase.util.Bytes; import org.apache.tephra.Transaction; import org.apache.tephra.TransactionCodec; import org.apache.tephra.TxConstants; import org.apache.tephra.coprocessor.CacheSupplier; import org.apache.tephra.coprocessor.TransactionStateCache; import org.apache.tephra.coprocessor.TransactionStateCacheSupplier; import org.apache.tephra.hbase.txprune.CompactionState; import org.apache.tephra.persist.TransactionVisibilityState; import org.apache.tephra.util.TxUtils; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * {@code org.apache.hadoop.hbase.coprocessor.RegionObserver} coprocessor that handles server-side processing * for transactions: * <ul> * <li>applies filtering to exclude data from invalid and in-progress transactions</li> * <li>overrides the scanner returned for flush and compaction to drop data written by invalidated transactions, * or expired due to TTL.</li> * </ul> * * <p>In order to use this coprocessor for transactions, configure the class on any table involved in transactions, * or on all user tables by adding the following to hbase-site.xml: * {@code * <property> * <name>hbase.coprocessor.region.classes</name> * <value>org.apache.tephra.hbase.coprocessor.TransactionProcessor</value> * </property> * } * </p> * * <p>HBase {@code Get} and {@code Scan} operations should have the current transaction serialized on to the operation * as an attribute: * {@code * Transaction t = ...; * Get get = new Get(...); * TransactionCodec codec = new TransactionCodec(); * codec.addToOperation(get, t); * } * </p> */ public class TransactionProcessor extends BaseRegionObserver { private static final Log LOG = LogFactory.getLog(TransactionProcessor.class); private final TransactionCodec txCodec; private TransactionStateCache cache; private volatile CompactionState compactionState; private CacheSupplier<TransactionStateCache> cacheSupplier; protected volatile Boolean pruneEnable; protected volatile Long txMaxLifetimeMillis; protected Map<byte[], Long> ttlByFamily = Maps.newTreeMap(Bytes.BYTES_COMPARATOR); protected boolean allowEmptyValues = TxConstants.ALLOW_EMPTY_VALUES_DEFAULT; protected boolean readNonTxnData = TxConstants.DEFAULT_READ_NON_TX_DATA; public TransactionProcessor() { this.txCodec = new TransactionCodec(); } /* RegionObserver implementation */ @Override public void start(CoprocessorEnvironment e) throws IOException { if (e instanceof RegionCoprocessorEnvironment) { RegionCoprocessorEnvironment env = (RegionCoprocessorEnvironment) e; this.cacheSupplier = getTransactionStateCacheSupplier(env); this.cache = cacheSupplier.get(); HTableDescriptor tableDesc = env.getRegion().getTableDesc(); for (HColumnDescriptor columnDesc : tableDesc.getFamilies()) { String columnTTL = columnDesc.getValue(TxConstants.PROPERTY_TTL); long ttl = 0; if (columnTTL != null) { try { ttl = Long.parseLong(columnTTL); LOG.info("Family " + columnDesc.getNameAsString() + " has TTL of " + columnTTL); } catch (NumberFormatException nfe) { LOG.warn("Invalid TTL value configured for column family " + columnDesc.getNameAsString() + ", value = " + columnTTL); } } ttlByFamily.put(columnDesc.getName(), ttl); } this.allowEmptyValues = getAllowEmptyValues(env, tableDesc); this.txMaxLifetimeMillis = getTxMaxLifetimeMillis(env); this.readNonTxnData = Boolean.valueOf(tableDesc.getValue(TxConstants.READ_NON_TX_DATA)); if (readNonTxnData) { LOG.info("Reading pre-existing data enabled for table " + tableDesc.getNameAsString()); } initializePruneState(env); } } /** * Fetch the {@link Configuration} that contains the properties required by the coprocessor. By default, * the HBase configuration is returned. This method will never return {@code null} in Tephra but the derived * classes might do so if {@link Configuration} is not available temporarily (for example, if it is being fetched * from a HBase Table. * * @param env {@link RegionCoprocessorEnvironment} of the Region to which the coprocessor is associated * @return {@link Configuration}, can be null if it is not available */ @Nullable protected Configuration getConfiguration(CoprocessorEnvironment env) { return env.getConfiguration(); } protected CacheSupplier<TransactionStateCache> getTransactionStateCacheSupplier(RegionCoprocessorEnvironment env) { return new TransactionStateCacheSupplier(env.getConfiguration()); } @Override public void stop(CoprocessorEnvironment e) throws IOException { try { resetPruneState(); } finally { if (cacheSupplier != null) { cacheSupplier.release(); } } } @Override public void preGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get, List<Cell> results) throws IOException { Transaction tx = getFromOperation(get); if (tx != null) { projectFamilyDeletes(get); get.setMaxVersions(); get.setTimeRange(TxUtils.getOldestVisibleTimestamp(ttlByFamily, tx, readNonTxnData), TxUtils.getMaxVisibleTimestamp(tx)); Filter newFilter = getTransactionFilter(tx, ScanType.USER_SCAN, get.getFilter()); get.setFilter(newFilter); } } @Override public void prePut(ObserverContext<RegionCoprocessorEnvironment> e, Put put, WALEdit edit, Durability durability) throws IOException { Transaction tx = getFromOperation(put); ensureValidTxLifetime(e.getEnvironment(), put, tx); } @Override public void preDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit, Durability durability) throws IOException { // Translate deletes into our own delete tombstones // Since HBase deletes cannot be undone, we need to translate deletes into special puts, which allows // us to rollback the changes (by a real delete) if the transaction fails // Deletes that are part of a transaction rollback do not need special handling. // They will never be rolled back, so are performed as normal HBase deletes. if (isRollbackOperation(delete)) { return; } Transaction tx = getFromOperation(delete); ensureValidTxLifetime(e.getEnvironment(), delete, tx); // Other deletes are client-initiated and need to be translated into our own tombstones // TODO: this should delegate to the DeleteStrategy implementation. Put deleteMarkers = new Put(delete.getRow(), delete.getTimeStamp()); for (byte[] family : delete.getFamilyCellMap().keySet()) { List<Cell> familyCells = delete.getFamilyCellMap().get(family); if (isFamilyDelete(familyCells)) { deleteMarkers.add(family, TxConstants.FAMILY_DELETE_QUALIFIER, familyCells.get(0).getTimestamp(), HConstants.EMPTY_BYTE_ARRAY); } else { for (Cell cell : familyCells) { deleteMarkers.add(family, CellUtil.cloneQualifier(cell), cell.getTimestamp(), HConstants.EMPTY_BYTE_ARRAY); } } } for (Map.Entry<String, byte[]> entry : delete.getAttributesMap().entrySet()) { deleteMarkers.setAttribute(entry.getKey(), entry.getValue()); } e.getEnvironment().getRegion().put(deleteMarkers); // skip normal delete handling e.bypass(); } private boolean getAllowEmptyValues(RegionCoprocessorEnvironment env, HTableDescriptor htd) { String allowEmptyValuesFromTableDesc = htd.getValue(TxConstants.ALLOW_EMPTY_VALUES_KEY); Configuration conf = getConfiguration(env); boolean allowEmptyValuesFromConfig = (conf != null) ? conf.getBoolean(TxConstants.ALLOW_EMPTY_VALUES_KEY, TxConstants.ALLOW_EMPTY_VALUES_DEFAULT) : TxConstants.ALLOW_EMPTY_VALUES_DEFAULT; // If the property is not present in the tableDescriptor, get it from the Configuration return (allowEmptyValuesFromTableDesc != null) ? Boolean.valueOf(allowEmptyValuesFromTableDesc) : allowEmptyValuesFromConfig; } private long getTxMaxLifetimeMillis(RegionCoprocessorEnvironment env) { Configuration conf = getConfiguration(env); if (conf != null) { return TimeUnit.SECONDS.toMillis(conf.getInt(TxConstants.Manager.CFG_TX_MAX_LIFETIME, TxConstants.Manager.DEFAULT_TX_MAX_LIFETIME)); } return TimeUnit.SECONDS.toMillis(TxConstants.Manager.DEFAULT_TX_MAX_LIFETIME); } private boolean isFamilyDelete(List<Cell> familyCells) { return familyCells.size() == 1 && CellUtil.isDeleteFamily(familyCells.get(0)); } @Override public RegionScanner preScannerOpen(ObserverContext<RegionCoprocessorEnvironment> e, Scan scan, RegionScanner s) throws IOException { Transaction tx = getFromOperation(scan); if (tx != null) { projectFamilyDeletes(scan); scan.setMaxVersions(); scan.setTimeRange(TxUtils.getOldestVisibleTimestamp(ttlByFamily, tx, readNonTxnData), TxUtils.getMaxVisibleTimestamp(tx)); Filter newFilter = getTransactionFilter(tx, ScanType.USER_SCAN, scan.getFilter()); scan.setFilter(newFilter); } return s; } /** * Ensures that family delete markers are present in the columns requested for any scan operation. * @param scan The original scan request * @return The modified scan request with the family delete qualifiers represented */ private Scan projectFamilyDeletes(Scan scan) { for (Map.Entry<byte[], NavigableSet<byte[]>> entry : scan.getFamilyMap().entrySet()) { NavigableSet<byte[]> columns = entry.getValue(); // wildcard scans will automatically include the delete marker, so only need to add it when we have // explicit columns listed if (columns != null && !columns.isEmpty()) { scan.addColumn(entry.getKey(), TxConstants.FAMILY_DELETE_QUALIFIER); } } return scan; } /** * Ensures that family delete markers are present in the columns requested for any get operation. * @param get The original get request * @return The modified get request with the family delete qualifiers represented */ private Get projectFamilyDeletes(Get get) { for (Map.Entry<byte[], NavigableSet<byte[]>> entry : get.getFamilyMap().entrySet()) { NavigableSet<byte[]> columns = entry.getValue(); // wildcard scans will automatically include the delete marker, so only need to add it when we have // explicit columns listed if (columns != null && !columns.isEmpty()) { get.addColumn(entry.getKey(), TxConstants.FAMILY_DELETE_QUALIFIER); } } return get; } @Override public InternalScanner preFlushScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Store store, KeyValueScanner memstoreScanner, InternalScanner scanner) throws IOException { return createStoreScanner(c.getEnvironment(), "flush", cache.getLatestState(), store, Collections.singletonList(memstoreScanner), ScanType.COMPACT_RETAIN_DELETES, HConstants.OLDEST_TIMESTAMP); } @Override public void postFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException { // Record whether the region is empty after a flush HRegion region = e.getEnvironment().getRegion(); // After a flush, if the memstore size is zero and there are no store files for any stores in the region // then the region must be empty long numStoreFiles = numStoreFilesForRegion(e); long memstoreSize = region.getMemstoreSize().get(); LOG.debug(String.format("Region %s: memstore size = %s, num store files = %s", region.getRegionInfo().getRegionNameAsString(), memstoreSize, numStoreFiles)); if (memstoreSize == 0 && numStoreFiles == 0) { if (compactionState != null) { compactionState.persistRegionEmpty(System.currentTimeMillis()); } } } @Override public InternalScanner preCompactScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Store store, List<? extends KeyValueScanner> scanners, ScanType scanType, long earliestPutTs, InternalScanner s, CompactionRequest request) throws IOException { // Get the latest tx snapshot state for the compaction TransactionVisibilityState snapshot = cache.getLatestState(); // Record tx state before the compaction if (compactionState != null) { compactionState.record(request, snapshot); } // Also make sure to use the same snapshot for the compaction return createStoreScanner(c.getEnvironment(), "compaction", snapshot, store, scanners, scanType, earliestPutTs); } @Override public void postCompact(ObserverContext<RegionCoprocessorEnvironment> e, Store store, StoreFile resultFile, CompactionRequest request) throws IOException { // Persist the compaction state after a successful compaction if (compactionState != null) { compactionState.persist(); } } protected InternalScanner createStoreScanner(RegionCoprocessorEnvironment env, String action, TransactionVisibilityState snapshot, Store store, List<? extends KeyValueScanner> scanners, ScanType type, long earliestPutTs) throws IOException { if (snapshot == null) { if (LOG.isDebugEnabled()) { LOG.debug("Region " + env.getRegion().getRegionNameAsString() + ", no current transaction state found, defaulting to normal " + action + " scanner"); } return null; } // construct a dummy transaction from the latest snapshot Transaction dummyTx = TxUtils.createDummyTransaction(snapshot); Scan scan = new Scan(); // need to see all versions, since we filter out excludes and applications may rely on multiple versions scan.setMaxVersions(); scan.setFilter( new IncludeInProgressFilter(dummyTx.getVisibilityUpperBound(), snapshot.getInvalid(), getTransactionFilter(dummyTx, type, null))); return new StoreScanner(store, store.getScanInfo(), scan, scanners, type, store.getSmallestReadPoint(), earliestPutTs); } private Transaction getFromOperation(OperationWithAttributes op) throws IOException { byte[] encoded = op.getAttribute(TxConstants.TX_OPERATION_ATTRIBUTE_KEY); if (encoded == null) { // to support old clients encoded = op.getAttribute(TxConstants.OLD_TX_OPERATION_ATTRIBUTE_KEY); } if (encoded != null) { return txCodec.decode(encoded); } return null; } /** * Make sure that the transaction is within the max valid transaction lifetime. * * @param env {@link RegionCoprocessorEnvironment} of the Region to which the coprocessor is associated * @param op {@link OperationWithAttributes} HBase operation to access its attributes if required * @param tx {@link Transaction} supplied by the * @throws DoNotRetryIOException thrown if the transaction is older than the max lifetime of a transaction * IOException throw if the value of max lifetime of transaction is unavailable */ protected void ensureValidTxLifetime(RegionCoprocessorEnvironment env, @SuppressWarnings("unused") OperationWithAttributes op, @Nullable Transaction tx) throws IOException { if (tx == null) { return; } boolean validLifetime = (TxUtils.getTimestamp(tx.getTransactionId()) + txMaxLifetimeMillis) > System.currentTimeMillis(); if (!validLifetime) { throw new DoNotRetryIOException(String.format("Transaction %s has exceeded max lifetime %s ms", tx.getTransactionId(), txMaxLifetimeMillis)); } } private boolean isRollbackOperation(OperationWithAttributes op) throws IOException { return op.getAttribute(TxConstants.TX_ROLLBACK_ATTRIBUTE_KEY) != null || // to support old clients op.getAttribute(TxConstants.OLD_TX_ROLLBACK_ATTRIBUTE_KEY) != null; } /** * Derived classes can override this method to customize the filter used to return data visible for the current * transaction. * * @param tx the current transaction to apply * @param type the type of scan being performed */ protected Filter getTransactionFilter(Transaction tx, ScanType type, Filter filter) { return TransactionFilters.getVisibilityFilter(tx, ttlByFamily, allowEmptyValues, type, filter); } /** * Refresh the properties related to transaction pruning. This method needs to be invoked if there is change in the * prune related properties after clearing the state by calling {@link #resetPruneState}. * * @param env {@link RegionCoprocessorEnvironment} of this region */ protected void initializePruneState(RegionCoprocessorEnvironment env) { Configuration conf = getConfiguration(env); if (conf != null) { pruneEnable = conf.getBoolean(TxConstants.TransactionPruning.PRUNE_ENABLE, TxConstants.TransactionPruning.DEFAULT_PRUNE_ENABLE); if (Boolean.TRUE.equals(pruneEnable)) { TableName pruneTable = TableName.valueOf(conf.get(TxConstants.TransactionPruning.PRUNE_STATE_TABLE, TxConstants.TransactionPruning.DEFAULT_PRUNE_STATE_TABLE)); long pruneFlushInterval = TimeUnit.SECONDS.toMillis(conf.getLong( TxConstants.TransactionPruning.PRUNE_FLUSH_INTERVAL, TxConstants.TransactionPruning.DEFAULT_PRUNE_FLUSH_INTERVAL)); compactionState = new CompactionState(env, pruneTable, pruneFlushInterval); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Automatic invalid list pruning is enabled for table %s. Compaction state " + "will be recorded in table %s", env.getRegionInfo().getTable().getNameWithNamespaceInclAsString(), pruneTable.getNameWithNamespaceInclAsString())); } } } } /** * Stop and clear state related to pruning. */ protected void resetPruneState() { pruneEnable = false; if (compactionState != null) { compactionState.stop(); compactionState = null; } } private long numStoreFilesForRegion(ObserverContext<RegionCoprocessorEnvironment> c) { long numStoreFiles = 0; for (Store store : c.getEnvironment().getRegion().getStores().values()) { numStoreFiles += store.getStorefiles().size(); } return numStoreFiles; } /** * Filter used to include cells visible to in-progress transactions on flush and commit. */ static class IncludeInProgressFilter extends FilterBase { private final long visibilityUpperBound; private final Set<Long> invalidIds; private final Filter txFilter; public IncludeInProgressFilter(long upperBound, Collection<Long> invalids, Filter transactionFilter) { this.visibilityUpperBound = upperBound; this.invalidIds = Sets.newHashSet(invalids); this.txFilter = transactionFilter; } @Override public ReturnCode filterKeyValue(Cell cell) throws IOException { // include all cells visible to in-progress transactions, except for those already marked as invalid long ts = cell.getTimestamp(); if (ts > visibilityUpperBound) { // include everything that could still be in-progress except invalids if (invalidIds.contains(ts)) { return ReturnCode.SKIP; } return ReturnCode.INCLUDE; } return txFilter.filterKeyValue(cell); } } }
/** * * @author greg (at) myrobotlab.org * * This file is part of MyRobotLab (http://myrobotlab.org). * * MyRobotLab 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 (subject to the "Classpath" exception * as provided in the LICENSE.txt file that accompanied this code). * * MyRobotLab is distributed in the hope that it will be useful or fun, * 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. * * All libraries in thirdParty bundle are subject to their own license * requirements - please refer to http://myrobotlab.org/libraries for * details. * * Enjoy ! * * */ package org.myrobotlab.service; import java.util.Vector; import org.myrobotlab.framework.MRLError; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.Status; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.serial.VirtualSerialPort; import org.myrobotlab.service.interfaces.ServoControl; import org.myrobotlab.service.interfaces.ServoController; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.slf4j.Logger; /** * @author GroG * * Servos have both input and output. Input is usually of the range of * integers between 0 - 180, and output can relay those values directly * to the servo's firmware (Arduino ServoLib, I2C controller, etc) * * However there can be the occasion that the input comes from a system * which does not have the same range. Such that input can vary from 0.0 * to 1.0. For example, OpenCV coordinates are often returned in this * range. When a mapping is needed Servo.map can be used. For this * mapping Servo.map(0.0, 1.0, 0, 180) might be desired. Reversing input * would be done with Servo.map(180, 0, 0, 180) * * outputY - is the values sent to the firmware, and should not * necessarily be confused with the inputX which is the input values * sent to the servo * */ @Root public class Servo extends Service implements ServoControl { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Servo.class); ServoController controller; private Float inputX; // clipping @Element private float outputYMin = 0; @Element private float outputYMax = 180; // range mapping @Element private float minX = 0; @Element private float maxX = 180; @Element private float minY = 0; @Element private float maxY = 180; @Element private int rest = 90; private long lastActivityTime = 0; /** * the pin is a necessary part of servo - even though this is really * controller's information a pin is a integral part of a "servo" - so it is * beneficial to store it allowing a re-attach during runtime * * FIXME - not true - attach on the controller puts in the data - it should * leave it even on a detach - a attach with pin should only replace it - * that way pin does not need to be stored on the Servo */ private Integer pin; Vector<String> controllers; // computer thread based sweeping boolean isSweeping = false; // sweep types // TODO - computer implemented speed control (non-sweep) boolean speedControlOnUC = true; transient Thread sweeper = null; private boolean isAttached = false; private boolean inverted = false; public Servo(String n) { super(n); load(); lastActivityTime = System.currentTimeMillis(); } public void releaseService() { detach(); super.releaseService(); } @Override public boolean setController(ServoController controller) { if (controller == null) { error("setting null as controller"); return false; } log.info(String.format("%s setController %s", getName(), controller.getName())); if (isAttached()) { warn("can not set controller %s when servo %s is attached", controller, getName()); return false; } this.controller = controller; broadcastState(); return true; } /* * (non-Javadoc) * * @see org.myrobotlab.service.interfaces.ServoControl#setPin(int) */ @Override public boolean setPin(int pin) { log.info(String.format("setting %s pin to %d", getName(), pin)); if (isAttached()) { warn("%s can not set pin %d when servo is attached", getName(), pin); return false; } this.pin = pin; broadcastState(); return true; } /* * (non-Javadoc) * * @see * org.myrobotlab.service.interfaces.ServoControl#attach(java.lang.String, * int) */ public boolean attach(String controller, Integer pin) { return attach((Arduino) Runtime.getService(controller), pin); } public boolean attach(Arduino controller, Integer pin) { setPin(pin); if (setController(controller)) { return attach(); } return false; } /* * (non-Javadoc) * * @see org.myrobotlab.service.interfaces.ServoControl#attach() */ public boolean attach() { lastActivityTime = System.currentTimeMillis(); if (isAttached) { log.info(String.format("%s.attach() - already attached - detach first", getName())); return false; } if (controller == null) { error("no valid controller can not attach %s", getName()); return false; } isAttached = controller.servoAttach(getName(), pin); if (isAttached) { // changed state broadcastState(); } return isAttached; } public void setInverted(boolean invert) { if (!inverted && invert) { map(maxX, minX, minY, maxY); inverted = true; } else { inverted = false; } } public boolean isInverted() { return inverted; } public float getMinInput(){ return minX; } public float getMaxInput(){ return maxX; } public void map(float minX, float maxX, float minY, float maxY) { this.minX = minX; this.maxX = maxX; this.minY = minY; this.maxY = maxY; broadcastState(); } public void map(int minX, int maxX, int minY, int maxY) { this.minX = minX; this.maxX = maxX; this.minY = minY; this.maxY = maxY; broadcastState(); } public int calc(float s) { return Math.round(minY + ((s - minX) * (maxY - minY)) / (maxX - minX)); } /** * basic move command of the servo - usually is 0 - 180 valid range but can * be adjusted and / or re-mapped with min / max and map commands * * TODO - moveToBlocking - blocks until servo sends "ARRIVED_TO_POSITION" * response */ @Override public void moveTo(Integer pos) { if (controller == null) { error(String.format("%s's controller is not set", getName())); return; } inputX = pos.floatValue(); // the magic mapping int outputY = calc(inputX); if (outputY > outputYMax || outputY < outputYMin) { warn(String.format("%s.moveTo(%d) out of range", getName(), (int) outputY)); return; } // FIXME - currently their is no timerPosition // this could be gotten with 100 * outputY for some valid range log.info("servoWrite({})", outputY); controller.servoWrite(getName(), outputY); lastActivityTime = System.currentTimeMillis(); } public void writeMicroseconds(Integer pos) { if (controller == null) { error(String.format("%s's controller is not set", getName())); return; } inputX = pos.floatValue(); // the magic mapping int outputY = calc(inputX); if (outputY > outputYMax || outputY < outputYMin) { warn(String.format("%s.moveTo(%d) out of range", getName(), (int) outputY)); return; } // FIXME - currently their is no timerPosition // this could be gotten with 100 * outputY for some valid range log.info("servoWrite({})", outputY); controller.servoWriteMicroseconds(getName(), outputY); lastActivityTime = System.currentTimeMillis(); } public boolean isAttached() { return isAttached; } public void setMinMax(int min, int max) { outputYMin = min; outputYMax = max; broadcastState(); } public Integer getMin() { return (int) outputYMin; } public Integer getMax() { return (int) outputYMax; } public Float getPosFloat() { return inputX; } public int getPos() { return Math.round(inputX); } public long getLastActivityTime() { return lastActivityTime; } @Override public String getDescription() { return "basic servo service"; } /** * Sweeper - TODO - should be implemented in the arduino code for smoother * function * */ public class Sweeper extends Thread { int min; int max; int delay; // depending on type - this is 2 different things COMPUTER // its ms delay - CONTROLLER its modulus loop count int step; public Sweeper(String name, int min, int max, int delay, int step) { super(String.format("%s.sweeper", name)); this.min = min; this.max = max; this.delay = delay; this.step = step; } @Override public void run() { if (inputX == null) { inputX = (float) min; } isSweeping = true; try { while (isSweeping) { inputX += step; // switch directions if ((inputX <= min && step < 0) || (inputX >= max && step > 0)) { step = step * -1; } moveTo(inputX.intValue()); Thread.sleep(delay); } } catch (Exception e) { isSweeping = false; if (e instanceof InterruptedException) { info("shutting down sweeper"); } else { logException(e); } } } } public void sweep(int min, int max) { sweep(min, max, 1, 1); } // FIXME - is it really speed control - you don't currently thread for // factional speed values public void sweep(int min, int max, int delay, int step) { // CONTROLLER TYPE SWITCH if (speedControlOnUC) { controller.servoSweep(getName(), min, max, step); // delay & step // implemented } else { if (isSweeping) { stop(); } sweeper = new Sweeper(getName(), min, max, delay, step); sweeper.start(); } } public void sweep() { sweep(Math.round(minX), Math.round(maxX), 1, 1); } @Override public String getControllerName() { if (controller == null) { return null; } return controller.getName(); } // FIXME - really this could be normalized... // attach / detach - the detach would not remove the ServoData from // the controller only another attach with a different pin would // change it @Override public Integer getPin() { /* * valiant attempt of normalizing - but Servo needs to know its own pin * to support attach() * * if (controller == null) { return null; } * * return controller.getServoPin(getName()); */ return pin; } public void setSpeed(Float speed) { if (speed == null) { return; } if (controller == null) { error("setSpeed - controller not set"); return; } controller.setServoSpeed(getName(), speed); } public boolean detach() { if (!isAttached) { log.info(String.format("%s.detach() - already detach - attach first", getName())); return false; } if (controller != null) { if (controller.servoDetach(getName())) { isAttached = false; // changed state broadcastState(); return true; } } return false; } public Vector<String> refreshControllers() { controllers = Runtime.getServicesFromInterface(ServoController.class.getCanonicalName()); return controllers; } /* * (non-Javadoc) * * @see org.myrobotlab.service.interfaces.ServoControl#stopServo() */ @Override public void stop() { // stop sweeper thread if running isSweeping = false; sweeper = null; // send a stop to the uC controller.servoStop(getName()); } public int setRest(int i) { rest = i; return rest; } public int getRest() { return rest; } public void rest() { moveTo(rest); } @Override public boolean setController(String controller) { ServoController sc = (ServoController) Runtime.getService(controller); if (sc == null) { return false; } return setController(sc); } public boolean setEventsEnabled(boolean b) { controller.setServoEventsEnabled(getName(), b); return b; } public void setSpeedControlOnUC(boolean b) { speedControlOnUC = b; } // uber good public Integer publishServoEvent(Integer position) { return position; } // uber good public void addServoEventListener(Service service) { addListener("publishServoEvent", service.getName(), "onServoEvent", Integer.class); } public Status test(String port, int pin) { Status status = null; try { super.test(); // FIXME GSON or PYTHON MESSAGES boolean useGUI = false; boolean useVirtualPorts = false; boolean testBasicMoves = false; boolean testSweep = true; boolean testDetachReAttach = false; boolean testBlocking = false; if (useVirtualPorts) { // virtual testing VirtualSerialPort.createNullModemCable("COM15", "UART"); Serial uart = (Serial) Runtime.start("uart", "Serial"); uart.connect("UART"); } // dependencies - hardware - servocontroll & servo & port // challenges - no "real" feedback - even with hardware (visual? // contact?) // without hardware - possible serial binary MRLFile comparison ! // TODO - check if !headless if (useGUI) { Runtime.start("gui", "GUIService"); } // step 1 - test for success // step 2 - test for failures & recovery String arduinoName = "arduino"; int min = 10; int max = 170; int pause = 2000; // weird notation - but its nice when copying out // into some script or other code // also good to guarantee being started Servo servo = (Servo) Runtime.start(getName(), "Arduino"); // TODO test errros on servo move before attach Arduino arduino = (Arduino) Runtime.start(arduinoName, "Arduino"); arduino.connect(port); info("attaching to pin %d", pin); if (!servo.attach(arduino, pin)) { throw new MRLError("could not attach to arduino"); } if (servo.getPin() != pin) { throw new MRLError("bad pin value"); } Vector<String> controllers = servo.refreshControllers(); if (controllers.size() != 1) { throw new MRLError("should be on controller"); } servo.setMinMax(min, max); info("should not move"); sleep(pause); servo.moveTo(min - 1); servo.moveTo(max + 1); if (testBasicMoves) { info("testing 10 speeds on uC"); sleep(pause); // TODO - moveToBlocking or callback when // servo reaches position would be nice here ! for (int i = 0; i < 10; ++i) { float newSpeed = 1.0f - ((float) i * 0.1f); info("moveTo(pos=%d) %03f speed ", min, newSpeed); servo.setSpeed(newSpeed); servo.moveTo(min); sleep(pause); info("moveTo(pos=%d) %03f speed ", max, newSpeed); servo.moveTo(max); sleep(pause); } } info("back to rest"); servo.setSpeed(1.0f); servo.rest(); servo.setEventsEnabled(true); if (testSweep) { servo.setSpeed(0.9f); servo.sweep(min, max, 30, 1); servo.setEventsEnabled(false); /* * * info("computer controlled sweep speed"); int newDelay; for (int i * = 0; i < 10; ++i) { newDelay = i * 100 + 1; // FIXME - make GSON * or PYTHON message output * info("sweep (min=%d max=%d delay=%d step=%d )", min, max, * newDelay, 1); servo.setSpeed(0.3f); servo.sweep(min, max, * newDelay, 1); sleep(3 * pause); servo.stop(); servo.rest(); } */ info("uc controlled sweep speed"); servo.stop(); // TODO - test blocking .. servo.setSpeed(1.0f); servo.setSpeedControlOnUC(false); servo.sweep(min, max, 10, 1); } // TODO - detach - re-attach - detach (move) - re-attach - check for no // move ! if (testDetachReAttach) { info("testing detach re-attach"); servo.detach(); sleep(pause); servo.attach(); info("make sure we can move after a re-attach"); // put in testMode - collect controller data servo.moveTo(min); sleep(pause); servo.moveTo(max); } info("test completed"); } catch(Exception e){ status.addError(e); } return status; } public static void main(String[] args) throws InterruptedException { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); try { Servo servo = (Servo) Runtime.start("servo", "Servo"); /* * Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino"); * servo.setSpeedControlOnUC(true); * Serial.createNullModemCable("COM15", "UART"); */ servo.test(); } catch (Exception e) { Logging.logException(e); } } }
/* * Copyright (C) 2006 The Android Open Source Project * Copyright (C) 2012 YIXIA.COM * Copyright (C) 2013 Zhang Rui <bbcallen@gmail.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 tv.danmaku.ijk.media.player.widget; import java.util.Locale; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.media.AudioManager; import android.os.Build; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import tv.danmaku.ijk.media.player.R; /** * A view containing controls for a MediaPlayer. Typically contains the buttons * like "Play/Pause" and a progress slider. It takes care of synchronizing the * controls with the state of the MediaPlayer. * <p/> * The way to use this class is to a) instantiate it programatically or b) * create it in your xml layout. * <p/> * a) The MediaController will create a default set of controls and put them in * a window floating above your application. Specifically, the controls will * float above the view specified with setAnchorView(). By default, the window * will disappear if left idle for three seconds and reappear when the user * touches the anchor view. To customize the MediaController's style, layout and * controls you should extend MediaController and override the {#link * {@link #makeControllerView()} method. * <p/> * b) The MediaController is a FrameLayout, you can put it in your layout xml * and get it through {@link #findViewById(int)}. * <p/> * NOTES: In each way, if you want customize the MediaController, * the SeekBar's id must be {@link R.id#mediacontroller_progress}},<br> * the Play/Pause's must be {@link R.id#mediacontroller_pause}, <br> * current time's must be {@link R.id#mediacontroller_time_current},<br> * total time's must be {@link R.id#mediacontroller_time_total}, <br> * file name's must be {@link R.id#mediacontroller_file_name}. <br> * And your resources must have a pause_button drawable and a play_button drawable. * <p/> * Functions like show() and hide() have no effect when MediaController is * created in an xml layout. */ public class MediaController extends FrameLayout { private static final String TAG = MediaController.class.getSimpleName(); private MediaPlayerControl mPlayer; private Context mContext; private PopupWindow mWindow; private int mAnimStyle; private View mAnchor; private View mRoot; private ProgressBar mProgress; private TextView mEndTime, mCurrentTime; private TextView mFileName; private OutlineTextView mInfoView; private String mTitle; private long mDuration; private boolean mShowing; private boolean mDragging; private boolean mInstantSeeking = true; private static final int sDefaultTimeout = 3000; private static final int FADE_OUT = 1; private static final int SHOW_PROGRESS = 2; private boolean mFromXml = false; private ImageButton mPauseButton; private AudioManager mAM; public MediaController(Context context, AttributeSet attrs) { super(context, attrs); mRoot = this; mFromXml = true; initController(context); } public MediaController(Context context) { super(context); if (!mFromXml && initController(context)) initFloatingWindow(); } private boolean initController(Context context) { mContext = context; mAM = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); return true; } @Override public void onFinishInflate() { super.onFinishInflate();//add super to suppress warning if (mRoot != null) initControllerView(mRoot); } private void initFloatingWindow() { mWindow = new PopupWindow(mContext); mWindow.setFocusable(false); mWindow.setBackgroundDrawable(null); mWindow.setOutsideTouchable(true); mAnimStyle = android.R.style.Animation; } /** * Set the view that acts as the anchor for the control view. This can for * example be a VideoView, or your Activity's main view. * * @param view * The view to which to anchor the controller when it is visible. */ public void setAnchorView(View view) { mAnchor = view; if (!mFromXml) { removeAllViews(); mRoot = makeControllerView(); mWindow.setContentView(mRoot); mWindow.setWidth(LayoutParams.MATCH_PARENT); mWindow.setHeight(LayoutParams.WRAP_CONTENT); } initControllerView(mRoot); } /** * Create the view that holds the widgets that control playback. Derived * classes can override this to create their own. * * @return The controller view. */ protected View makeControllerView() { return ((LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate( R.layout.mediacontroller, this); } private void initControllerView(View v) { mPauseButton = (ImageButton) v .findViewById(R.id.mediacontroller_pause); if (mPauseButton != null) { mPauseButton.requestFocus(); mPauseButton.setOnClickListener(mPauseListener); } mProgress = (SeekBar) v.findViewById(R.id.mediacontroller_progress); if (mProgress != null) { if (mProgress instanceof SeekBar) { SeekBar seeker = (SeekBar) mProgress; seeker.setOnSeekBarChangeListener(mSeekListener); seeker.setThumbOffset(1); } mProgress.setMax(1000); } mEndTime = (TextView) v.findViewById(R.id.mediacontroller_time_total); mCurrentTime = (TextView) v .findViewById(R.id.mediacontroller_time_current); mFileName = (TextView) v.findViewById(R.id.mediacontroller_file_name); if (mFileName != null) mFileName.setText(mTitle); } public void setMediaPlayer(MediaPlayerControl player) { mPlayer = player; updatePausePlay(); } /** * Control the action when the seekbar dragged by user * * @param seekWhenDragging * True the media will seek periodically */ public void setInstantSeeking(boolean seekWhenDragging) { mInstantSeeking = seekWhenDragging; } public void show() { show(sDefaultTimeout); } /** * Set the content of the file_name TextView * * @param name */ public void setFileName(String name) { mTitle = name; if (mFileName != null) mFileName.setText(mTitle); } /** * Set the View to hold some information when interact with the * MediaController * * @param v */ public void setInfoView(OutlineTextView v) { mInfoView = v; } private void disableUnsupportedButtons() { try { if (mPauseButton != null && !mPlayer.canPause()) mPauseButton.setEnabled(false); } catch (IncompatibleClassChangeError ex) { } } /** * <p> * Change the animation style resource for this controller. * </p> * * <p> * If the controller is showing, calling this method will take effect only * the next time the controller is shown. * </p> * * @param animationStyle * animation style to use when the controller appears and * disappears. Set to -1 for the default animation, 0 for no * animation, or a resource identifier for an explicit animation. * */ public void setAnimationStyle(int animationStyle) { mAnimStyle = animationStyle; } /** * Show the controller on screen. It will go away automatically after * 'timeout' milliseconds of inactivity. * * @param timeout * The timeout in milliseconds. Use 0 to show the controller * until hide() is called. */ @SuppressLint("InlinedApi") public void show(int timeout) { if (!mShowing && mAnchor != null && mAnchor.getWindowToken() != null) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){ mAnchor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); } if (mPauseButton != null) mPauseButton.requestFocus(); disableUnsupportedButtons(); if (mFromXml) { setVisibility(View.VISIBLE); } else { int[] location = new int[2]; mAnchor.getLocationOnScreen(location); Rect anchorRect = new Rect(location[0], location[1], location[0] + mAnchor.getWidth(), location[1] + mAnchor.getHeight()); mWindow.setAnimationStyle(mAnimStyle); mWindow.showAtLocation(mAnchor, Gravity.BOTTOM, anchorRect.left, 0); } mShowing = true; if (mShownListener != null) mShownListener.onShown(); } updatePausePlay(); mHandler.sendEmptyMessage(SHOW_PROGRESS); if (timeout != 0) { mHandler.removeMessages(FADE_OUT); mHandler.sendMessageDelayed(mHandler.obtainMessage(FADE_OUT), timeout); } } public boolean isShowing() { return mShowing; } @SuppressLint("InlinedApi") public void hide() { if (mAnchor == null) return; if (mShowing) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){ mAnchor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } try { mHandler.removeMessages(SHOW_PROGRESS); if (mFromXml) setVisibility(View.GONE); else mWindow.dismiss(); } catch (IllegalArgumentException ex) { DebugLog.d(TAG, "MediaController already removed"); } mShowing = false; if (mHiddenListener != null) mHiddenListener.onHidden(); } } public interface OnShownListener { public void onShown(); } private OnShownListener mShownListener; public void setOnShownListener(OnShownListener l) { mShownListener = l; } public interface OnHiddenListener { public void onHidden(); } private OnHiddenListener mHiddenListener; public void setOnHiddenListener(OnHiddenListener l) { mHiddenListener = l; } @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { long pos; switch (msg.what) { case FADE_OUT: hide(); break; case SHOW_PROGRESS: pos = setProgress(); if (!mDragging && mShowing) { msg = obtainMessage(SHOW_PROGRESS); sendMessageDelayed(msg, 1000 - (pos % 1000)); updatePausePlay(); } break; } } }; private long setProgress() { if (mPlayer == null || mDragging) return 0; int position = mPlayer.getCurrentPosition(); int duration = mPlayer.getDuration(); if (mProgress != null) { if (duration > 0) { long pos = 1000L * position / duration; mProgress.setProgress((int) pos); } int percent = mPlayer.getBufferPercentage(); mProgress.setSecondaryProgress(percent * 10); } mDuration = duration; if (mEndTime != null) mEndTime.setText(generateTime(mDuration)); if (mCurrentTime != null) mCurrentTime.setText(generateTime(position)); return position; } private static String generateTime(long position) { int totalSeconds = (int) ((position / 1000.0)+0.5); int seconds = totalSeconds % 60; int minutes = (totalSeconds / 60) % 60; int hours = totalSeconds / 3600; if (hours > 0) { return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes, seconds).toString(); } else { return String.format(Locale.US, "%02d:%02d", minutes, seconds) .toString(); } } @Override public boolean onTouchEvent(MotionEvent event) { show(sDefaultTimeout); return true; } @Override public boolean onTrackballEvent(MotionEvent ev) { show(sDefaultTimeout); return false; } @Override public boolean dispatchKeyEvent(KeyEvent event) { int keyCode = event.getKeyCode(); if (event.getRepeatCount() == 0 && (keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keyCode == KeyEvent.KEYCODE_SPACE)) { doPauseResume(); show(sDefaultTimeout); if (mPauseButton != null) mPauseButton.requestFocus(); return true; } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) { if (mPlayer.isPlaying()) { mPlayer.pause(); updatePausePlay(); } return true; } else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) { hide(); return true; } else { show(sDefaultTimeout); } return super.dispatchKeyEvent(event); } private View.OnClickListener mPauseListener = new View.OnClickListener() { public void onClick(View v) { doPauseResume(); show(sDefaultTimeout); } }; private void updatePausePlay() { if (mRoot == null || mPauseButton == null) return; if (mPlayer.isPlaying()) mPauseButton .setImageResource(R.drawable.mediacontroller_pause_button); else mPauseButton .setImageResource(R.drawable.mediacontroller_play_button); } private void doPauseResume() { if (mPlayer.isPlaying()) mPlayer.pause(); else mPlayer.start(); updatePausePlay(); } private Runnable lastRunnable; private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() { public void onStartTrackingTouch(SeekBar bar) { mDragging = true; show(3600000); mHandler.removeMessages(SHOW_PROGRESS); if (mInstantSeeking) mAM.setStreamMute(AudioManager.STREAM_MUSIC, true); if (mInfoView != null) { mInfoView.setText(""); mInfoView.setVisibility(View.VISIBLE); } } public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) { if (!fromuser) return; final long newposition = (mDuration * progress) / 1000; String time = generateTime(newposition); if (mInstantSeeking) { mHandler.removeCallbacks(lastRunnable); lastRunnable = new Runnable() { @Override public void run() { mPlayer.seekTo(newposition); } }; mHandler.postDelayed(lastRunnable, 200); } if (mInfoView != null) mInfoView.setText(time); if (mCurrentTime != null) mCurrentTime.setText(time); } public void onStopTrackingTouch(SeekBar bar) { if (!mInstantSeeking) mPlayer.seekTo((mDuration * bar.getProgress()) / 1000); if (mInfoView != null) { mInfoView.setText(""); mInfoView.setVisibility(View.GONE); } show(sDefaultTimeout); mHandler.removeMessages(SHOW_PROGRESS); mAM.setStreamMute(AudioManager.STREAM_MUSIC, false); mDragging = false; mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000); } }; @Override public void setEnabled(boolean enabled) { if (mPauseButton != null) mPauseButton.setEnabled(enabled); if (mProgress != null) mProgress.setEnabled(enabled); disableUnsupportedButtons(); super.setEnabled(enabled); } public interface MediaPlayerControl { void start(); void pause(); int getDuration(); int getCurrentPosition(); void seekTo(long pos); boolean isPlaying(); int getBufferPercentage(); boolean canPause(); boolean canSeekBackward(); boolean canSeekForward(); } }
/* * * Copyright 2011 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.curator.x.discovery; import com.google.common.collect.Lists; import com.google.common.io.Closeables; import com.netflix.curator.framework.CuratorFramework; import com.netflix.curator.framework.CuratorFrameworkFactory; import com.netflix.curator.framework.state.ConnectionState; import com.netflix.curator.retry.RetryOneTime; import com.netflix.curator.test.TestingServer; import com.netflix.curator.x.discovery.details.ServiceCacheListener; import org.testng.Assert; import org.testng.annotations.Test; import java.io.Closeable; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class TestServiceCache { @Test public void testInitialLoad() throws Exception { List<Closeable> closeables = Lists.newArrayList(); TestingServer server = new TestingServer(); closeables.add(server); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); closeables.add(discovery); discovery.start(); ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); final CountDownLatch latch = new CountDownLatch(3); ServiceCacheListener listener = new ServiceCacheListener() { @Override public void cacheChanged() { latch.countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; cache.addListener(listener); cache.start(); ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("test").name("test").port(10064).build(); ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("test").name("test").port(10065).build(); ServiceInstance<String> instance3 = ServiceInstance.<String>builder().payload("test").name("test").port(10066).build(); discovery.registerService(instance1); discovery.registerService(instance2); discovery.registerService(instance3); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); ServiceCache<String> cache2 = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache2); cache2.start(); Assert.assertEquals(cache2.getInstances().size(), 3); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { Closeables.closeQuietly(c); } } } @Test public void testViaProvider() throws Exception { List<Closeable> closeables = Lists.newArrayList(); TestingServer server = new TestingServer(); closeables.add(server); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); closeables.add(discovery); discovery.start(); ServiceProvider<String> serviceProvider = discovery.serviceProviderBuilder().serviceName("test").build(); closeables.add(serviceProvider); serviceProvider.start(); ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build(); discovery.registerService(instance); int count = 0; ServiceInstance<String> foundInstance = null; while ( foundInstance == null ) { Assert.assertTrue(count++ < 5); foundInstance = serviceProvider.getInstance(); Thread.sleep(1000); } Assert.assertEquals(foundInstance, instance); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { Closeables.closeQuietly(c); } } } @Test public void testUpdate() throws Exception { List<Closeable> closeables = Lists.newArrayList(); TestingServer server = new TestingServer(); closeables.add(server); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build(); ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build(); closeables.add(discovery); discovery.start(); final CountDownLatch latch = new CountDownLatch(1); ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); ServiceCacheListener listener = new ServiceCacheListener() { @Override public void cacheChanged() { latch.countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; cache.addListener(listener); cache.start(); instance = ServiceInstance.<String>builder().payload("changed").name("test").port(10064).id(instance.getId()).build(); discovery.updateService(instance); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertEquals(cache.getInstances().size(), 1); Assert.assertEquals(cache.getInstances().get(0).getPayload(), instance.getPayload()); } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { Closeables.closeQuietly(c); } } } @Test public void testCache() throws Exception { List<Closeable> closeables = Lists.newArrayList(); TestingServer server = new TestingServer(); closeables.add(server); try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); closeables.add(discovery); discovery.start(); ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); cache.start(); final Semaphore semaphore = new Semaphore(0); ServiceCacheListener listener = new ServiceCacheListener() { @Override public void cacheChanged() { semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; cache.addListener(listener); ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build(); ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("thing").name("test").port(10065).build(); discovery.registerService(instance1); Assert.assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS)); discovery.registerService(instance2); Assert.assertTrue(semaphore.tryAcquire(3, TimeUnit.SECONDS)); ServiceInstance<String> instance3 = ServiceInstance.<String>builder().payload("thing").name("another").port(10064).build(); discovery.registerService(instance3); Assert.assertFalse(semaphore.tryAcquire(3, TimeUnit.SECONDS)); // should not get called for a different service } finally { Collections.reverse(closeables); for ( Closeable c : closeables ) { Closeables.closeQuietly(c); } } } }
/* * 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.hadoop.pig; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.util.*; import org.apache.cassandra.db.IColumn; import org.apache.cassandra.db.marshal.*; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.hadoop.*; import org.apache.cassandra.thrift.*; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.Hex; import org.apache.hadoop.mapreduce.*; import org.apache.pig.Expression; import org.apache.pig.ResourceSchema; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.data.*; import org.apache.pig.impl.util.UDFContext; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; import org.apache.thrift.TSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A LoadStoreFunc for retrieving data from and storing data to Cassandra * * A row from a standard CF will be returned as nested tuples: (key, ((name1, val1), (name2, val2))). */ public class CassandraStorage extends AbstractCassandraStorage { public final static String PIG_ALLOW_DELETES = "PIG_ALLOW_DELETES"; public final static String PIG_WIDEROW_INPUT = "PIG_WIDEROW_INPUT"; public final static String PIG_USE_SECONDARY = "PIG_USE_SECONDARY"; private final static ByteBuffer BOUND = ByteBufferUtil.EMPTY_BYTE_BUFFER; private static final Logger logger = LoggerFactory.getLogger(CassandraStorage.class); private ByteBuffer slice_start = BOUND; private ByteBuffer slice_end = BOUND; private boolean slice_reverse = false; private boolean allow_deletes = false; private RecordReader<ByteBuffer, Map<ByteBuffer, IColumn>> reader; private RecordWriter<ByteBuffer, List<Mutation>> writer; private boolean widerows = false; private int limit; // wide row hacks private ByteBuffer lastKey; private Map<ByteBuffer,IColumn> lastRow; private boolean hasNext = true; public CassandraStorage() { this(1024); } /**@param limit number of columns to fetch in a slice */ public CassandraStorage(int limit) { super(); this.limit = limit; DEFAULT_INPUT_FORMAT = "org.apache.cassandra.hadoop.ColumnFamilyInputFormat"; DEFAULT_OUTPUT_FORMAT = "org.apache.cassandra.hadoop.ColumnFamilyOutputFormat"; } public int getLimit() { return limit; } public void prepareToRead(RecordReader reader, PigSplit split) { this.reader = reader; } /** read wide row*/ public Tuple getNextWide() throws IOException { CfInfo cfInfo = getCfInfo(loadSignature); CfDef cfDef = cfInfo.cfDef; ByteBuffer key = null; Tuple tuple = null; DefaultDataBag bag = new DefaultDataBag(); try { while(true) { hasNext = reader.nextKeyValue(); if (!hasNext) { if (tuple == null) tuple = TupleFactory.getInstance().newTuple(); if (lastRow != null) { if (tuple.size() == 0) // lastRow is a new one { key = (ByteBuffer)reader.getCurrentKey(); tuple = keyToTuple(key, cfDef, parseType(cfDef.getKey_validation_class())); } for (Map.Entry<ByteBuffer, IColumn> entry : lastRow.entrySet()) { bag.add(columnToTuple(entry.getValue(), cfInfo, parseType(cfDef.getComparator_type()))); } lastKey = null; lastRow = null; tuple.append(bag); return tuple; } else { if (tuple.size() == 1) // rare case of just one wide row, key already set { tuple.append(bag); return tuple; } else return null; } } if (key != null && !((ByteBuffer)reader.getCurrentKey()).equals(key)) // key changed { // read too much, hold on to it for next time lastKey = (ByteBuffer)reader.getCurrentKey(); lastRow = (SortedMap<ByteBuffer,IColumn>)reader.getCurrentValue(); // but return what we have so far tuple.append(bag); return tuple; } if (key == null) // only set the key on the first iteration { key = (ByteBuffer)reader.getCurrentKey(); if (lastKey != null && !(key.equals(lastKey))) // last key only had one value { if (tuple == null) tuple = keyToTuple(lastKey, cfDef, parseType(cfDef.getKey_validation_class())); else addKeyToTuple(tuple, lastKey, cfDef, parseType(cfDef.getKey_validation_class())); for (Map.Entry<ByteBuffer, IColumn> entry : lastRow.entrySet()) { bag.add(columnToTuple(entry.getValue(), cfInfo, parseType(cfDef.getComparator_type()))); } tuple.append(bag); lastKey = key; lastRow = (SortedMap<ByteBuffer,IColumn>)reader.getCurrentValue(); return tuple; } if (tuple == null) tuple = keyToTuple(key, cfDef, parseType(cfDef.getKey_validation_class())); else addKeyToTuple(tuple, lastKey, cfDef, parseType(cfDef.getKey_validation_class())); } SortedMap<ByteBuffer,IColumn> row = (SortedMap<ByteBuffer,IColumn>)reader.getCurrentValue(); if (lastRow != null) // prepend what was read last time { for (Map.Entry<ByteBuffer, IColumn> entry : lastRow.entrySet()) { bag.add(columnToTuple(entry.getValue(), cfInfo, parseType(cfDef.getComparator_type()))); } lastKey = null; lastRow = null; } for (Map.Entry<ByteBuffer, IColumn> entry : row.entrySet()) { bag.add(columnToTuple(entry.getValue(), cfInfo, parseType(cfDef.getComparator_type()))); } } } catch (InterruptedException e) { throw new IOException(e.getMessage()); } } @Override /** read next row */ public Tuple getNext() throws IOException { if (widerows) return getNextWide(); try { // load the next pair if (!reader.nextKeyValue()) return null; CfInfo cfInfo = getCfInfo(loadSignature); CfDef cfDef = cfInfo.cfDef; ByteBuffer key = reader.getCurrentKey(); Map<ByteBuffer, IColumn> cf = reader.getCurrentValue(); assert key != null && cf != null; // output tuple, will hold the key, each indexed column in a tuple, then a bag of the rest // NOTE: we're setting the tuple size here only for the key so we can use setTupleValue on it Tuple tuple = keyToTuple(key, cfDef, parseType(cfDef.getKey_validation_class())); DefaultDataBag bag = new DefaultDataBag(); // we must add all the indexed columns first to match the schema Map<ByteBuffer, Boolean> added = new HashMap<ByteBuffer, Boolean>(); // take care to iterate these in the same order as the schema does for (ColumnDef cdef : cfDef.column_metadata) { boolean hasColumn = false; boolean cql3Table = false; try { hasColumn = cf.containsKey(cdef.name); } catch (Exception e) { cql3Table = true; } if (hasColumn) { tuple.append(columnToTuple(cf.get(cdef.name), cfInfo, parseType(cfDef.getComparator_type()))); } else if (!cql3Table) { // otherwise, we need to add an empty tuple to take its place tuple.append(TupleFactory.getInstance().newTuple()); } added.put(cdef.name, true); } // now add all the other columns for (Map.Entry<ByteBuffer, IColumn> entry : cf.entrySet()) { if (!added.containsKey(entry.getKey())) bag.add(columnToTuple(entry.getValue(), cfInfo, parseType(cfDef.getComparator_type()))); } tuple.append(bag); // finally, special top-level indexes if needed if (usePartitionFilter) { for (ColumnDef cdef : getIndexes()) { Tuple throwaway = columnToTuple(cf.get(cdef.name), cfInfo, parseType(cfDef.getComparator_type())); tuple.append(throwaway.get(1)); } } return tuple; } catch (InterruptedException e) { throw new IOException(e.getMessage()); } } /** set hadoop cassandra connection settings */ protected void setConnectionInformation() throws IOException { super.setConnectionInformation(); if (System.getenv(PIG_ALLOW_DELETES) != null) allow_deletes = Boolean.parseBoolean(System.getenv(PIG_ALLOW_DELETES)); } /** set read configuration settings */ public void setLocation(String location, Job job) throws IOException { conf = job.getConfiguration(); setLocationFromUri(location); if (ConfigHelper.getInputSlicePredicate(conf) == null) { SliceRange range = new SliceRange(slice_start, slice_end, slice_reverse, limit); SlicePredicate predicate = new SlicePredicate().setSlice_range(range); ConfigHelper.setInputSlicePredicate(conf, predicate); } if (System.getenv(PIG_WIDEROW_INPUT) != null) widerows = Boolean.valueOf(System.getenv(PIG_WIDEROW_INPUT)); if (System.getenv(PIG_USE_SECONDARY) != null) usePartitionFilter = Boolean.valueOf(System.getenv(PIG_USE_SECONDARY)); if (System.getenv(PIG_INPUT_SPLIT_SIZE) != null) { try { ConfigHelper.setInputSplitSize(conf, Integer.valueOf(System.getenv(PIG_INPUT_SPLIT_SIZE))); } catch (NumberFormatException e) { throw new IOException("PIG_INPUT_SPLIT_SIZE is not a number", e); } } if (usePartitionFilter && getIndexExpressions() != null) ConfigHelper.setInputRange(conf, getIndexExpressions()); if (username != null && password != null) ConfigHelper.setInputKeyspaceUserNameAndPassword(conf, username, password); if (splitSize > 0) ConfigHelper.setInputSplitSize(conf, splitSize); if (partitionerClass!= null) ConfigHelper.setInputPartitioner(conf, partitionerClass); if (rpcPort != null) ConfigHelper.setInputRpcPort(conf, rpcPort); if (initHostAddress != null) ConfigHelper.setInputInitialAddress(conf, initHostAddress); ConfigHelper.setInputColumnFamily(conf, keyspace, column_family, widerows); setConnectionInformation(); if (ConfigHelper.getInputRpcPort(conf) == 0) throw new IOException("PIG_INPUT_RPC_PORT or PIG_RPC_PORT environment variable not set"); if (ConfigHelper.getInputInitialAddress(conf) == null) throw new IOException("PIG_INPUT_INITIAL_ADDRESS or PIG_INITIAL_ADDRESS environment variable not set"); if (ConfigHelper.getInputPartitioner(conf) == null) throw new IOException("PIG_INPUT_PARTITIONER or PIG_PARTITIONER environment variable not set"); if (loadSignature == null) loadSignature = location; initSchema(loadSignature); } /** set store configuration settings */ public void setStoreLocation(String location, Job job) throws IOException { conf = job.getConfiguration(); // don't combine mappers to a single mapper per node conf.setBoolean("pig.noSplitCombination", true); setLocationFromUri(location); if (username != null && password != null) ConfigHelper.setOutputKeyspaceUserNameAndPassword(conf, username, password); if (splitSize > 0) ConfigHelper.setInputSplitSize(conf, splitSize); if (partitionerClass!= null) ConfigHelper.setOutputPartitioner(conf, partitionerClass); if (rpcPort != null) { ConfigHelper.setOutputRpcPort(conf, rpcPort); ConfigHelper.setInputRpcPort(conf, rpcPort); } if (initHostAddress != null) { ConfigHelper.setOutputInitialAddress(conf, initHostAddress); ConfigHelper.setInputInitialAddress(conf, initHostAddress); } ConfigHelper.setOutputColumnFamily(conf, keyspace, column_family); setConnectionInformation(); if (ConfigHelper.getOutputRpcPort(conf) == 0) throw new IOException("PIG_OUTPUT_RPC_PORT or PIG_RPC_PORT environment variable not set"); if (ConfigHelper.getOutputInitialAddress(conf) == null) throw new IOException("PIG_OUTPUT_INITIAL_ADDRESS or PIG_INITIAL_ADDRESS environment variable not set"); if (ConfigHelper.getOutputPartitioner(conf) == null) throw new IOException("PIG_OUTPUT_PARTITIONER or PIG_PARTITIONER environment variable not set"); // we have to do this again here for the check in writeColumnsFromTuple if (System.getenv(PIG_USE_SECONDARY) != null) usePartitionFilter = Boolean.valueOf(System.getenv(PIG_USE_SECONDARY)); initSchema(storeSignature); } /** define the schema */ public ResourceSchema getSchema(String location, Job job) throws IOException { setLocation(location, job); CfInfo cfInfo = getCfInfo(loadSignature); CfDef cfDef = cfInfo.cfDef; if (cfDef.column_type.equals("Super")) return null; /* Our returned schema should look like this: (key, index1:(name, value), index2:(name, value), columns:{(name, value)}) Which is to say, columns that have metadata will be returned as named tuples, but unknown columns will go into a bag. This way, wide rows can still be handled by the bag, but known columns can easily be referenced. */ // top-level schema, no type ResourceSchema schema = new ResourceSchema(); // get default marshallers and validators Map<MarshallerType, AbstractType> marshallers = getDefaultMarshallers(cfDef); Map<ByteBuffer,AbstractType> validators = getValidatorMap(cfDef); // add key ResourceFieldSchema keyFieldSchema = new ResourceFieldSchema(); keyFieldSchema.setName("key"); keyFieldSchema.setType(getPigType(marshallers.get(MarshallerType.KEY_VALIDATOR))); ResourceSchema bagSchema = new ResourceSchema(); ResourceFieldSchema bagField = new ResourceFieldSchema(); bagField.setType(DataType.BAG); bagField.setName("columns"); // inside the bag, place one tuple with the default comparator/validator schema ResourceSchema bagTupleSchema = new ResourceSchema(); ResourceFieldSchema bagTupleField = new ResourceFieldSchema(); bagTupleField.setType(DataType.TUPLE); ResourceFieldSchema bagcolSchema = new ResourceFieldSchema(); ResourceFieldSchema bagvalSchema = new ResourceFieldSchema(); bagcolSchema.setName("name"); bagvalSchema.setName("value"); bagcolSchema.setType(getPigType(marshallers.get(MarshallerType.COMPARATOR))); bagvalSchema.setType(getPigType(marshallers.get(MarshallerType.DEFAULT_VALIDATOR))); bagTupleSchema.setFields(new ResourceFieldSchema[] { bagcolSchema, bagvalSchema }); bagTupleField.setSchema(bagTupleSchema); bagSchema.setFields(new ResourceFieldSchema[] { bagTupleField }); bagField.setSchema(bagSchema); // will contain all fields for this schema List<ResourceFieldSchema> allSchemaFields = new ArrayList<ResourceFieldSchema>(); // add the key first, then the indexed columns, and finally the bag allSchemaFields.add(keyFieldSchema); if (!widerows && (cfInfo.compactCqlTable || !cfInfo.cql3Table)) { // defined validators/indexes for (ColumnDef cdef : cfDef.column_metadata) { // make a new tuple for each col/val pair ResourceSchema innerTupleSchema = new ResourceSchema(); ResourceFieldSchema innerTupleField = new ResourceFieldSchema(); innerTupleField.setType(DataType.TUPLE); innerTupleField.setSchema(innerTupleSchema); innerTupleField.setName(new String(cdef.getName())); ResourceFieldSchema idxColSchema = new ResourceFieldSchema(); idxColSchema.setName("name"); idxColSchema.setType(getPigType(marshallers.get(MarshallerType.COMPARATOR))); ResourceFieldSchema valSchema = new ResourceFieldSchema(); AbstractType validator = validators.get(cdef.name); if (validator == null) validator = marshallers.get(MarshallerType.DEFAULT_VALIDATOR); valSchema.setName("value"); valSchema.setType(getPigType(validator)); innerTupleSchema.setFields(new ResourceFieldSchema[] { idxColSchema, valSchema }); allSchemaFields.add(innerTupleField); } } // bag at the end for unknown columns allSchemaFields.add(bagField); // add top-level index elements if needed if (usePartitionFilter) { for (ColumnDef cdef : getIndexes()) { ResourceFieldSchema idxSchema = new ResourceFieldSchema(); idxSchema.setName("index_" + new String(cdef.getName())); AbstractType validator = validators.get(cdef.name); if (validator == null) validator = marshallers.get(MarshallerType.DEFAULT_VALIDATOR); idxSchema.setType(getPigType(validator)); allSchemaFields.add(idxSchema); } } // top level schema contains everything schema.setFields(allSchemaFields.toArray(new ResourceFieldSchema[allSchemaFields.size()])); return schema; } /** set partition filter */ public void setPartitionFilter(Expression partitionFilter) throws IOException { UDFContext context = UDFContext.getUDFContext(); Properties property = context.getUDFProperties(AbstractCassandraStorage.class); property.setProperty(PARTITION_FILTER_SIGNATURE, indexExpressionsToString(filterToIndexExpressions(partitionFilter))); } /** prepare writer */ public void prepareToWrite(RecordWriter writer) { this.writer = writer; } /** write next row */ public void putNext(Tuple t) throws IOException { /* We support two cases for output: First, the original output: (key, (name, value), (name,value), {(name,value)}) (tuples or bag is optional) For supers, we only accept the original output. */ if (t.size() < 1) { // simply nothing here, we can't even delete without a key logger.warn("Empty output skipped, filter empty tuples to suppress this warning"); return; } ByteBuffer key = objToBB(t.get(0)); if (t.getType(1) == DataType.TUPLE) writeColumnsFromTuple(key, t, 1); else if (t.getType(1) == DataType.BAG) { if (t.size() > 2) throw new IOException("No arguments allowed after bag"); writeColumnsFromBag(key, (DefaultDataBag) t.get(1)); } else throw new IOException("Second argument in output must be a tuple or bag"); } /** write tuple data to cassandra */ private void writeColumnsFromTuple(ByteBuffer key, Tuple t, int offset) throws IOException { ArrayList<Mutation> mutationList = new ArrayList<Mutation>(); for (int i = offset; i < t.size(); i++) { if (t.getType(i) == DataType.BAG) writeColumnsFromBag(key, (DefaultDataBag) t.get(i)); else if (t.getType(i) == DataType.TUPLE) { Tuple inner = (Tuple) t.get(i); if (inner.size() > 0) // may be empty, for an indexed column that wasn't present mutationList.add(mutationFromTuple(inner)); } else if (!usePartitionFilter) { throw new IOException("Output type was not a bag or a tuple"); } } if (mutationList.size() > 0) writeMutations(key, mutationList); } /** compose Cassandra mutation from tuple */ private Mutation mutationFromTuple(Tuple t) throws IOException { Mutation mutation = new Mutation(); if (t.get(1) == null) { if (allow_deletes) { mutation.deletion = new Deletion(); mutation.deletion.predicate = new org.apache.cassandra.thrift.SlicePredicate(); mutation.deletion.predicate.column_names = Arrays.asList(objToBB(t.get(0))); mutation.deletion.setTimestamp(FBUtilities.timestampMicros()); } else throw new IOException("null found but deletes are disabled, set " + PIG_ALLOW_DELETES + "=true in environment or allow_deletes=true in URL to enable"); } else { org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column(); column.setName(objToBB(t.get(0))); column.setValue(objToBB(t.get(1))); column.setTimestamp(FBUtilities.timestampMicros()); mutation.column_or_supercolumn = new ColumnOrSuperColumn(); mutation.column_or_supercolumn.column = column; } return mutation; } /** write bag data to Cassandra */ private void writeColumnsFromBag(ByteBuffer key, DefaultDataBag bag) throws IOException { List<Mutation> mutationList = new ArrayList<Mutation>(); for (Tuple pair : bag) { Mutation mutation = new Mutation(); if (DataType.findType(pair.get(1)) == DataType.BAG) // supercolumn { SuperColumn sc = new SuperColumn(); sc.setName(objToBB(pair.get(0))); List<org.apache.cassandra.thrift.Column> columns = new ArrayList<org.apache.cassandra.thrift.Column>(); for (Tuple subcol : (DefaultDataBag) pair.get(1)) { org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column(); column.setName(objToBB(subcol.get(0))); column.setValue(objToBB(subcol.get(1))); column.setTimestamp(FBUtilities.timestampMicros()); columns.add(column); } if (columns.isEmpty()) { if (allow_deletes) { mutation.deletion = new Deletion(); mutation.deletion.super_column = objToBB(pair.get(0)); mutation.deletion.setTimestamp(FBUtilities.timestampMicros()); } else throw new IOException("SuperColumn deletion attempted with empty bag, but deletes are disabled, set " + PIG_ALLOW_DELETES + "=true in environment or allow_deletes=true in URL to enable"); } else { sc.columns = columns; mutation.column_or_supercolumn = new ColumnOrSuperColumn(); mutation.column_or_supercolumn.super_column = sc; } } else mutation = mutationFromTuple(pair); mutationList.add(mutation); // for wide rows, we need to limit the amount of mutations we write at once if (mutationList.size() >= 10) // arbitrary, CFOF will re-batch this up, and BOF won't care { writeMutations(key, mutationList); mutationList.clear(); } } // write the last batch if (mutationList.size() > 0) writeMutations(key, mutationList); } /** write mutation to Cassandra */ private void writeMutations(ByteBuffer key, List<Mutation> mutations) throws IOException { try { writer.write(key, mutations); } catch (InterruptedException e) { throw new IOException(e); } } /** get a list of Cassandra IndexExpression from Pig expression */ private List<IndexExpression> filterToIndexExpressions(Expression expression) throws IOException { List<IndexExpression> indexExpressions = new ArrayList<IndexExpression>(); Expression.BinaryExpression be = (Expression.BinaryExpression)expression; ByteBuffer name = ByteBuffer.wrap(be.getLhs().toString().getBytes()); ByteBuffer value = ByteBuffer.wrap(be.getRhs().toString().getBytes()); switch (expression.getOpType()) { case OP_EQ: indexExpressions.add(new IndexExpression(name, IndexOperator.EQ, value)); break; case OP_GE: indexExpressions.add(new IndexExpression(name, IndexOperator.GTE, value)); break; case OP_GT: indexExpressions.add(new IndexExpression(name, IndexOperator.GT, value)); break; case OP_LE: indexExpressions.add(new IndexExpression(name, IndexOperator.LTE, value)); break; case OP_LT: indexExpressions.add(new IndexExpression(name, IndexOperator.LT, value)); break; case OP_AND: indexExpressions.addAll(filterToIndexExpressions(be.getLhs())); indexExpressions.addAll(filterToIndexExpressions(be.getRhs())); break; default: throw new IOException("Unsupported expression type: " + expression.getOpType().name()); } return indexExpressions; } /** convert a list of index expression to string */ private static String indexExpressionsToString(List<IndexExpression> indexExpressions) throws IOException { assert indexExpressions != null; // oh, you thought cfdefToString was awful? IndexClause indexClause = new IndexClause(); indexClause.setExpressions(indexExpressions); indexClause.setStart_key("".getBytes()); TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory()); try { return Hex.bytesToHex(serializer.serialize(indexClause)); } catch (TException e) { throw new IOException(e); } } /** convert string to a list of index expression */ private static List<IndexExpression> indexExpressionsFromString(String ie) throws IOException { assert ie != null; TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory()); IndexClause indexClause = new IndexClause(); try { deserializer.deserialize(indexClause, Hex.hexToBytes(ie)); } catch (TException e) { throw new IOException(e); } return indexClause.getExpressions(); } /** get a list of index expression */ private List<IndexExpression> getIndexExpressions() throws IOException { UDFContext context = UDFContext.getUDFContext(); Properties property = context.getUDFProperties(AbstractCassandraStorage.class); if (property.getProperty(PARTITION_FILTER_SIGNATURE) != null) return indexExpressionsFromString(property.getProperty(PARTITION_FILTER_SIGNATURE)); else return null; } /** get a list of column for the column family */ protected List<ColumnDef> getColumnMetadata(Cassandra.Client client) throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, TException, CharacterCodingException, org.apache.cassandra.exceptions.InvalidRequestException, ConfigurationException, NotFoundException { return getColumnMeta(client, true, true); } /** convert key to a tuple */ private Tuple keyToTuple(ByteBuffer key, CfDef cfDef, AbstractType comparator) throws IOException { Tuple tuple = TupleFactory.getInstance().newTuple(1); addKeyToTuple(tuple, key, cfDef, comparator); return tuple; } /** add key to a tuple */ private void addKeyToTuple(Tuple tuple, ByteBuffer key, CfDef cfDef, AbstractType comparator) throws IOException { if( comparator instanceof AbstractCompositeType ) { setTupleValue(tuple, 0, composeComposite((AbstractCompositeType)comparator,key)); } else { setTupleValue(tuple, 0, cassandraToObj(getDefaultMarshallers(cfDef).get(MarshallerType.KEY_VALIDATOR), key)); } } /** cassandra://[username:password@]<keyspace>/<columnfamily>[?slice_start=<start>&slice_end=<end> * [&reversed=true][&limit=1][&allow_deletes=true][&widerows=true] * [&use_secondary=true][&comparator=<comparator>][&partitioner=<partitioner>]]*/ private void setLocationFromUri(String location) throws IOException { try { if (!location.startsWith("cassandra://")) throw new Exception("Bad scheme." + location); String[] urlParts = location.split("\\?"); if (urlParts.length > 1) { Map<String, String> urlQuery = getQueryMap(urlParts[1]); AbstractType comparator = BytesType.instance; if (urlQuery.containsKey("comparator")) comparator = TypeParser.parse(urlQuery.get("comparator")); if (urlQuery.containsKey("slice_start")) slice_start = comparator.fromString(urlQuery.get("slice_start")); if (urlQuery.containsKey("slice_end")) slice_end = comparator.fromString(urlQuery.get("slice_end")); if (urlQuery.containsKey("reversed")) slice_reverse = Boolean.parseBoolean(urlQuery.get("reversed")); if (urlQuery.containsKey("limit")) limit = Integer.parseInt(urlQuery.get("limit")); if (urlQuery.containsKey("allow_deletes")) allow_deletes = Boolean.parseBoolean(urlQuery.get("allow_deletes")); if (urlQuery.containsKey("widerows")) widerows = Boolean.parseBoolean(urlQuery.get("widerows")); if (urlQuery.containsKey("use_secondary")) usePartitionFilter = Boolean.parseBoolean(urlQuery.get("use_secondary")); if (urlQuery.containsKey("split_size")) splitSize = Integer.parseInt(urlQuery.get("split_size")); if (urlQuery.containsKey("partitioner")) partitionerClass = urlQuery.get("partitioner"); if (urlQuery.containsKey("init_address")) initHostAddress = urlQuery.get("init_address"); if (urlQuery.containsKey("rpc_port")) rpcPort = urlQuery.get("rpc_port"); } String[] parts = urlParts[0].split("/+"); String[] credentialsAndKeyspace = parts[1].split("@"); if (credentialsAndKeyspace.length > 1) { String[] credentials = credentialsAndKeyspace[0].split(":"); username = credentials[0]; password = credentials[1]; keyspace = credentialsAndKeyspace[1]; } else { keyspace = parts[1]; } column_family = parts[2]; } catch (Exception e) { throw new IOException("Expected 'cassandra://[username:password@]<keyspace>/<columnfamily>" + "[?slice_start=<start>&slice_end=<end>[&reversed=true][&limit=1]" + "[&allow_deletes=true][&widerows=true][&use_secondary=true]" + "[&comparator=<comparator>][&split_size=<size>][&partitioner=<partitioner>]" + "[&init_address=<host>][&rpc_port=<port>]]': " + e.getMessage()); } } }
/* * 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.html.dom; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; /** * This class is duplicated for each JAXP subpackage so keep it in sync. * It is package private and therefore is not exposed as part of the JAXP * API. * <p> * This code is designed to implement the JAXP 1.1 spec pluggability * feature and is designed to run on JDK version 1.1 and * later, and to compile on JDK 1.2 and onward. * The code also runs both as part of an unbundled jar file and * when bundled as part of the JDK. * <p> * * @xerces.internal * * @version $Id$ */ final class ObjectFactory { // // Constants // // name of default properties file to look for in JDK's jre/lib directory private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties"; /** Set to true for debugging */ private static final boolean DEBUG = isDebugEnabled(); /** * Default columns per line. */ private static final int DEFAULT_LINE_LENGTH = 80; /** cache the contents of the xerces.properties file. * Until an attempt has been made to read this file, this will * be null; if the file does not exist or we encounter some other error * during the read, this will be empty. */ private static Properties fXercesProperties = null; /*** * Cache the time stamp of the xerces.properties file so * that we know if it's been modified and can invalidate * the cache when necessary. */ private static long fLastModified = -1; // // static methods // /** * Finds the implementation Class object in the specified order. The * specified order is the following: * <ol> * <li>query the system property using <code>System.getProperty</code> * <li>read <code>META-INF/services/<i>factoryId</i></code> file * <li>use fallback classname * </ol> * * @return Class object of factory, never null * * @param factoryId Name of the factory to find, same as * a property name * @param fallbackClassName Implementation class name, if nothing else * is found. Use null to mean no fallback. * * @exception ObjectFactory.ConfigurationError */ static Object createObject(String factoryId, String fallbackClassName) throws ConfigurationError { return createObject(factoryId, null, fallbackClassName); } // createObject(String,String):Object /** * Finds the implementation Class object in the specified order. The * specified order is the following: * <ol> * <li>query the system property using <code>System.getProperty</code> * <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file * <li>read <code>META-INF/services/<i>factoryId</i></code> file * <li>use fallback classname * </ol> * * @return Class object of factory, never null * * @param factoryId Name of the factory to find, same as * a property name * @param propertiesFilename The filename in the $java.home/lib directory * of the properties file. If none specified, * ${java.home}/lib/xerces.properties will be used. * @param fallbackClassName Implementation class name, if nothing else * is found. Use null to mean no fallback. * * @exception ObjectFactory.ConfigurationError */ static Object createObject(String factoryId, String propertiesFilename, String fallbackClassName) throws ConfigurationError { try { return Class.forName(fallbackClassName).newInstance(); } catch (Exception e) { throw new ConfigurationError(e.getMessage(), e); } } // createObject(String,String,String):Object // // Private static methods // /** Returns true if debug has been enabled. */ private static boolean isDebugEnabled() { try { String val = SecuritySupport.getSystemProperty("xerces.debug"); // Allow simply setting the prop to turn on debug return (val != null && (!"false".equals(val))); } catch (SecurityException se) {} return false; } // isDebugEnabled() /** Prints a message to standard error if debugging is enabled. */ private static void debugPrintln(String msg) { if (DEBUG) { System.err.println("XERCES: " + msg); } } // debugPrintln(String) /** * Figure out which ClassLoader to use. For JDK 1.2 and later use * the context ClassLoader. */ static ClassLoader findClassLoader() throws ConfigurationError { return ObjectFactory.class.getClassLoader(); } // findClassLoader():ClassLoader /** * Create an instance of a class using the specified ClassLoader */ static Object newInstance(String className, ClassLoader cl, boolean doFallback) throws ConfigurationError { // assert(className != null); try{ Class providerClass = findProviderClass(className, cl, doFallback); Object instance = providerClass.newInstance(); if (DEBUG) debugPrintln("created new instance of " + providerClass + " using ClassLoader: " + cl); return instance; } catch (ClassNotFoundException x) { throw new ConfigurationError( "Provider " + className + " not found", x); } catch (Exception x) { throw new ConfigurationError( "Provider " + className + " could not be instantiated: " + x, x); } } /** * Find a Class using the specified ClassLoader */ static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { return Class.forName(className); } /* * Try to find provider using Jar Service Provider Mechanism * * @return instance of provider class if found or null */ private static Object findJarServiceProvider(String factoryId) throws ConfigurationError { String serviceId = "META-INF/services/" + factoryId; InputStream is = null; // First try the Context ClassLoader ClassLoader cl = findClassLoader(); is = SecuritySupport.getResourceAsStream(cl, serviceId); // If no provider found then try the current ClassLoader if (is == null) { ClassLoader current = ObjectFactory.class.getClassLoader(); if (cl != current) { cl = current; is = SecuritySupport.getResourceAsStream(cl, serviceId); } } if (is == null) { // No provider found return null; } if (DEBUG) debugPrintln("found jar resource=" + serviceId + " using ClassLoader: " + cl); // Read the service provider name in UTF-8 as specified in // the jar spec. Unfortunately this fails in Microsoft // VJ++, which does not implement the UTF-8 // encoding. Theoretically, we should simply let it fail in // that case, since the JVM is obviously broken if it // doesn't support such a basic standard. But since there // are still some users attempting to use VJ++ for // development, we have dropped in a fallback which makes a // second attempt using the platform's default encoding. In // VJ++ this is apparently ASCII, which is a subset of // UTF-8... and since the strings we'll be reading here are // also primarily limited to the 7-bit ASCII range (at // least, in English versions), this should work well // enough to keep us on the air until we're ready to // officially decommit from VJ++. [Edited comment from // jkesselm] BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH); } catch (java.io.UnsupportedEncodingException e) { rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH); } String factoryClassName = null; try { // XXX Does not handle all possible input as specified by the // Jar Service Provider specification factoryClassName = rd.readLine(); } catch (IOException x) { // No provider found return null; } finally { try { // try to close the reader. rd.close(); } // Ignore the exception. catch (IOException exc) {} } if (factoryClassName != null && ! "".equals(factoryClassName)) { if (DEBUG) debugPrintln("found in resource, value=" + factoryClassName); // Note: here we do not want to fall back to the current // ClassLoader because we want to avoid the case where the // resource file was found using one ClassLoader and the // provider class was instantiated using a different one. return newInstance(factoryClassName, cl, false); } // No provider found return null; } // // Classes // /** * A configuration error. */ static final class ConfigurationError extends Error { /** Serialization version. */ static final long serialVersionUID = 2646822752226280048L; // // Data // /** Exception. */ private Exception exception; // // Constructors // /** * Construct a new instance with the specified detail string and * exception. */ ConfigurationError(String msg, Exception x) { super(msg); this.exception = x; } // <init>(String,Exception) // // methods // /** Returns the exception associated to this error. */ Exception getException() { return exception; } // getException():Exception } // class ConfigurationError } // class ObjectFactory
package com.grishman.rssfeed.sync; import android.accounts.Account; import android.accounts.AccountManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SyncRequest; import android.content.SyncResult; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.util.Log; import com.grishman.rssfeed.MainActivity; import com.grishman.rssfeed.R; import com.grishman.rssfeed.data.RSSFeedContract; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import java.io.IOException; import java.net.URL; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class RSSFeedSyncAdapter extends AbstractThreadedSyncAdapter { public final String LOG_TAG = RSSFeedSyncAdapter.class.getSimpleName(); RSSHandler rssHandler; List<RSSFeedItem> articleList2; // Interval at which to sync with the weather, in seconds. // 60 seconds (1 minute) * 180 = 3 hours private static final int DAY_IN_MILLIS = 1000 * 60 * 60 * 24; public static final int SYNC_INTERVAL = DAY_IN_MILLIS; //Day interval (24 hr) public static final int SYNC_FLEXTIME = SYNC_INTERVAL / 2; // Half of the day interval private static final int FEED_NOTIFICATION_ID = 2801; private int numMessages = 0; public RSSFeedSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.d(LOG_TAG, "onPerformSync Called."); URL url = null; rssHandler = new RSSHandler(); try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); String feedUrl = "http://feeds.abcnews.com/abcnews/topstories"; url = new URL(feedUrl); xr.setContentHandler(rssHandler); xr.parse(new InputSource(url.openStream())); } catch (IOException e) { Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString()); } catch (SAXException e) { Log.e("RSS Handler SAX", e.toString()); } catch (ParserConfigurationException e) { Log.e("RSS Handler Parser Config", e.toString()); } // Delete feeds getContext().getContentResolver().delete(RSSFeedContract.FeedsEntry.CONTENT_URI, null, null); // TODO refactor this sht // Insert new feeds ContentValues cv = new ContentValues(); for (RSSFeedItem item : articleList2 = rssHandler.getArticleList()) { Log.d(LOG_TAG, item.getImgLink()); cv.put("title", item.getTitle()); cv.put("description", item.getDescription()); cv.put("link", item.getLink()); cv.put("img_url", item.getImgLink()); cv.put("category", item.getCategory()); cv.put("pub_date", item.getPubDate()); getContext().getContentResolver().insert(RSSFeedContract.FeedsEntry.CONTENT_URI, cv); } // Notify user about new feeds notifyNewFeeds(); } /** * Helper method to have the sync adapter sync immediately * * @param context The context used to access the account service */ public static void syncImmediately(Context context) { Log.d("test", "syncImmediatley Called."); Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle); } /** * Helper method to schedule the sync adapter periodic execution */ public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) { Account account = getSyncAccount(context); String authority = context.getString(R.string.content_authority); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // we can enable inexact timers in our periodic sync SyncRequest request = new SyncRequest.Builder(). syncPeriodic(syncInterval, flexTime). setSyncAdapter(account, authority). setExtras(new Bundle()).build(); ContentResolver.requestSync(request); } else { ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval); } } /** * Helper method to get the fake account to be used with SyncAdapter, or make a new one * if the fake account doesn't exist yet. If we make a new account, we call the * onAccountCreated method so we can initialize things. * * @param context The context used to access the account service * @return a fake account. */ public static Account getSyncAccount(Context context) { // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Create the account type and default account Account newAccount = new Account( context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // If the password doesn't exist, the account doesn't exist if (null == accountManager.getPassword(newAccount)) { /* * Add the account and account type, no password or user data * If successful, return the Account object, otherwise report an error. */ if (!accountManager.addAccountExplicitly(newAccount, "", null)) { return null; } /* * If you don't set android:syncable="true" in * in your <provider> element in the manifest, * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1) * here. */ onAccountCreated(newAccount, context); } return newAccount; } private static void onAccountCreated(Account newAccount, Context context) { /* * Since we've created an account */ RSSFeedSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME); /* * Without calling setSyncAutomatically, our periodic sync will not be enabled. */ ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true); /* * Finally, let's do a sync to get things started */ syncImmediately(context); } public static void initializeSyncAdapter(Context context) { getSyncAccount(context); } public void notifyNewFeeds() { Context context = getContext(); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); mBuilder.setContentTitle("Get your fresh RSS!"); mBuilder.setContentText("App complete update feed."); mBuilder.setTicker("RSS feed is up to date"); mBuilder.setSmallIcon(R.drawable.ic_noti_rss); mBuilder.setAutoCancel(true); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(context, MainActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addParentStack(MainActivity.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); /* notificationID allows you to update the notification later on. */ mNotificationManager.notify(FEED_NOTIFICATION_ID, mBuilder.build()); } }
/** * * Copyright (c) Microsoft and contributors. 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. * */ // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. package com.microsoft.windowsazure.management.compute; import com.microsoft.windowsazure.core.OperationResponse; import com.microsoft.windowsazure.core.OperationStatusResponse; import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageCreateParameters; import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageCreateResponse; import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageGetDetailsResponse; import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageGetResponse; import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageListResponse; import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageReplicateParameters; import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageReplicateResponse; import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageUpdateParameters; import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageUpdateResponse; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.net.URISyntaxException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * The Service Management API includes operations for managing the OS images in * your subscription. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157175.aspx for more * information) */ public interface VirtualMachineOSImageOperations { /** * Share an already replicated OS image. This operation is only for * publishers. You have to be registered as image publisher with Windows * Azure to be able to call this. * * @param imageName Required. The name of the virtual machine image to share. * @param permission Required. The sharing permission: public, msdn, or * private. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A standard service response including an HTTP status code and * request ID. */ OperationResponse beginSharing(String imageName, String permission) throws IOException, ServiceException; /** * Share an already replicated OS image. This operation is only for * publishers. You have to be registered as image publisher with Windows * Azure to be able to call this. * * @param imageName Required. The name of the virtual machine image to share. * @param permission Required. The sharing permission: public, msdn, or * private. * @return A standard service response including an HTTP status code and * request ID. */ Future<OperationResponse> beginSharingAsync(String imageName, String permission); /** * Unreplicate an OS image to multiple target locations. This operation is * only for publishers. You have to be registered as image publisher with * Windows Azure to be able to call this. Note: The operation removes the * published copies of the user OS Image. It does not remove the actual * user OS Image. To remove the actual user OS Image, the publisher will * have to call Delete OS Image. * * @param imageName Required. The name of the virtual machine image to * replicate. Note: The OS Image Name should be the user OS Image, not the * published name of the OS Image. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A standard service response including an HTTP status code and * request ID. */ OperationResponse beginUnreplicating(String imageName) throws IOException, ServiceException; /** * Unreplicate an OS image to multiple target locations. This operation is * only for publishers. You have to be registered as image publisher with * Windows Azure to be able to call this. Note: The operation removes the * published copies of the user OS Image. It does not remove the actual * user OS Image. To remove the actual user OS Image, the publisher will * have to call Delete OS Image. * * @param imageName Required. The name of the virtual machine image to * replicate. Note: The OS Image Name should be the user OS Image, not the * published name of the OS Image. * @return A standard service response including an HTTP status code and * request ID. */ Future<OperationResponse> beginUnreplicatingAsync(String imageName); /** * The Create OS Image operation adds an operating system image that is * stored in a storage account and is available from the image repository. * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx * for more information) * * @param parameters Required. Parameters supplied to the Create Virtual * Machine Image operation. * @throws InterruptedException Thrown when a thread is waiting, sleeping, * or otherwise occupied, and the thread is interrupted, either before or * during the activity. Occasionally a method may wish to test whether the * current thread has been interrupted, and if so, to immediately throw * this exception. The following code can be used to achieve this effect: * @throws ExecutionException Thrown when attempting to retrieve the result * of a task that aborted by throwing an exception. This exception can be * inspected using the Throwable.getCause() method. * @throws ServiceException Thrown if the server returned an error for the * request. * @throws IOException Thrown if there was an error setting up tracing for * the request. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws ServiceException Thrown if an unexpected response is found. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return Parameters returned from the Create Virtual Machine Image * operation. */ VirtualMachineOSImageCreateResponse create(VirtualMachineOSImageCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException; /** * The Create OS Image operation adds an operating system image that is * stored in a storage account and is available from the image repository. * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx * for more information) * * @param parameters Required. Parameters supplied to the Create Virtual * Machine Image operation. * @return Parameters returned from the Create Virtual Machine Image * operation. */ Future<VirtualMachineOSImageCreateResponse> createAsync(VirtualMachineOSImageCreateParameters parameters); /** * The Delete OS Image operation deletes the specified OS image from your * image repository. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx for * more information) * * @param imageName Required. The name of the image to delete. * @param deleteFromStorage Required. Specifies that the source blob for the * image should also be deleted from storage. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws InterruptedException Thrown when a thread is waiting, sleeping, * or otherwise occupied, and the thread is interrupted, either before or * during the activity. Occasionally a method may wish to test whether the * current thread has been interrupted, and if so, to immediately throw * this exception. The following code can be used to achieve this effect: * @throws ExecutionException Thrown when attempting to retrieve the result * of a task that aborted by throwing an exception. This exception can be * inspected using the Throwable.getCause() method. * @throws ServiceException Thrown if the server returned an error for the * request. * @return A standard service response including an HTTP status code and * request ID. */ OperationResponse delete(String imageName, boolean deleteFromStorage) throws IOException, ServiceException, InterruptedException, ExecutionException; /** * The Delete OS Image operation deletes the specified OS image from your * image repository. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx for * more information) * * @param imageName Required. The name of the image to delete. * @param deleteFromStorage Required. Specifies that the source blob for the * image should also be deleted from storage. * @return A standard service response including an HTTP status code and * request ID. */ Future<OperationResponse> deleteAsync(String imageName, boolean deleteFromStorage); /** * The Get OS Image operation retrieves the details for an operating system * image from the image repository. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for * more information) * * @param imageName Required. The name of the OS image to retrieve. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return A virtual machine image associated with your subscription. */ VirtualMachineOSImageGetResponse get(String imageName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; /** * The Get OS Image operation retrieves the details for an operating system * image from the image repository. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for * more information) * * @param imageName Required. The name of the OS image to retrieve. * @return A virtual machine image associated with your subscription. */ Future<VirtualMachineOSImageGetResponse> getAsync(String imageName); /** * Gets OS Image's properties and its replication details. This operation is * only for publishers. You have to be registered as image publisher with * Windows Azure to be able to call this. * * @param imageName Required. The name of the virtual machine image to * replicate. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return The Get Details OS Images operation response. */ VirtualMachineOSImageGetDetailsResponse getDetails(String imageName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; /** * Gets OS Image's properties and its replication details. This operation is * only for publishers. You have to be registered as image publisher with * Windows Azure to be able to call this. * * @param imageName Required. The name of the virtual machine image to * replicate. * @return The Get Details OS Images operation response. */ Future<VirtualMachineOSImageGetDetailsResponse> getDetailsAsync(String imageName); /** * The List OS Images operation retrieves a list of the operating system * images from the image repository. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for * more information) * * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return The List OS Images operation response. */ VirtualMachineOSImageListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; /** * The List OS Images operation retrieves a list of the operating system * images from the image repository. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for * more information) * * @return The List OS Images operation response. */ Future<VirtualMachineOSImageListResponse> listAsync(); /** * Replicate an OS image to multiple target locations. This operation is * only for publishers. You have to be registered as image publisher with * Windows Azure to be able to call this. * * @param imageName Required. The name of the virtual machine OS image to * replicate. * @param parameters Required. Parameters supplied to the Replicate Virtual * Machine Image operation. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return The response body contains the published name of the image. */ VirtualMachineOSImageReplicateResponse replicate(String imageName, VirtualMachineOSImageReplicateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; /** * Replicate an OS image to multiple target locations. This operation is * only for publishers. You have to be registered as image publisher with * Windows Azure to be able to call this. * * @param imageName Required. The name of the virtual machine OS image to * replicate. * @param parameters Required. Parameters supplied to the Replicate Virtual * Machine Image operation. * @return The response body contains the published name of the image. */ Future<VirtualMachineOSImageReplicateResponse> replicateAsync(String imageName, VirtualMachineOSImageReplicateParameters parameters); /** * Share an already replicated OS image. This operation is only for * publishers. You have to be registered as image publisher with Windows * Azure to be able to call this. * * @param imageName Required. The name of the virtual machine image to share. * @param permission Required. The sharing permission: public, msdn, or * private. * @throws InterruptedException Thrown when a thread is waiting, sleeping, * or otherwise occupied, and the thread is interrupted, either before or * during the activity. Occasionally a method may wish to test whether the * current thread has been interrupted, and if so, to immediately throw * this exception. The following code can be used to achieve this effect: * @throws ExecutionException Thrown when attempting to retrieve the result * of a task that aborted by throwing an exception. This exception can be * inspected using the Throwable.getCause() method. * @throws ServiceException Thrown if the server returned an error for the * request. * @throws IOException Thrown if there was an error setting up tracing for * the request. * @return The response body contains the status of the specified * asynchronous operation, indicating whether it has succeeded, is * inprogress, or has failed. Note that this status is distinct from the * HTTP status code returned for the Get Operation Status operation itself. * If the asynchronous operation succeeded, the response body includes the * HTTP status code for the successful request. If the asynchronous * operation failed, the response body includes the HTTP status code for * the failed request and error information regarding the failure. */ OperationStatusResponse share(String imageName, String permission) throws InterruptedException, ExecutionException, ServiceException, IOException; /** * Share an already replicated OS image. This operation is only for * publishers. You have to be registered as image publisher with Windows * Azure to be able to call this. * * @param imageName Required. The name of the virtual machine image to share. * @param permission Required. The sharing permission: public, msdn, or * private. * @return The response body contains the status of the specified * asynchronous operation, indicating whether it has succeeded, is * inprogress, or has failed. Note that this status is distinct from the * HTTP status code returned for the Get Operation Status operation itself. * If the asynchronous operation succeeded, the response body includes the * HTTP status code for the successful request. If the asynchronous * operation failed, the response body includes the HTTP status code for * the failed request and error information regarding the failure. */ Future<OperationStatusResponse> shareAsync(String imageName, String permission); /** * Unreplicate an OS image to multiple target locations. This operation is * only for publishers. You have to be registered as image publisher with * Windows Azure to be able to call this. Note: The operation removes the * published copies of the user OS Image. It does not remove the actual * user OS Image. To remove the actual user OS Image, the publisher will * have to call Delete OS Image. * * @param imageName Required. The name of the virtual machine image to * replicate. Note: The OS Image Name should be the user OS Image, not the * published name of the OS Image. * @throws InterruptedException Thrown when a thread is waiting, sleeping, * or otherwise occupied, and the thread is interrupted, either before or * during the activity. Occasionally a method may wish to test whether the * current thread has been interrupted, and if so, to immediately throw * this exception. The following code can be used to achieve this effect: * @throws ExecutionException Thrown when attempting to retrieve the result * of a task that aborted by throwing an exception. This exception can be * inspected using the Throwable.getCause() method. * @throws ServiceException Thrown if the server returned an error for the * request. * @throws IOException Thrown if there was an error setting up tracing for * the request. * @return The response body contains the status of the specified * asynchronous operation, indicating whether it has succeeded, is * inprogress, or has failed. Note that this status is distinct from the * HTTP status code returned for the Get Operation Status operation itself. * If the asynchronous operation succeeded, the response body includes the * HTTP status code for the successful request. If the asynchronous * operation failed, the response body includes the HTTP status code for * the failed request and error information regarding the failure. */ OperationStatusResponse unreplicate(String imageName) throws InterruptedException, ExecutionException, ServiceException, IOException; /** * Unreplicate an OS image to multiple target locations. This operation is * only for publishers. You have to be registered as image publisher with * Windows Azure to be able to call this. Note: The operation removes the * published copies of the user OS Image. It does not remove the actual * user OS Image. To remove the actual user OS Image, the publisher will * have to call Delete OS Image. * * @param imageName Required. The name of the virtual machine image to * replicate. Note: The OS Image Name should be the user OS Image, not the * published name of the OS Image. * @return The response body contains the status of the specified * asynchronous operation, indicating whether it has succeeded, is * inprogress, or has failed. Note that this status is distinct from the * HTTP status code returned for the Get Operation Status operation itself. * If the asynchronous operation succeeded, the response body includes the * HTTP status code for the successful request. If the asynchronous * operation failed, the response body includes the HTTP status code for * the failed request and error information regarding the failure. */ Future<OperationStatusResponse> unreplicateAsync(String imageName); /** * The Update OS Image operation updates an OS image that in your image * repository. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for * more information) * * @param imageName Required. The name of the virtual machine image to be * updated. * @param parameters Required. Parameters supplied to the Update Virtual * Machine Image operation. * @throws InterruptedException Thrown when a thread is waiting, sleeping, * or otherwise occupied, and the thread is interrupted, either before or * during the activity. Occasionally a method may wish to test whether the * current thread has been interrupted, and if so, to immediately throw * this exception. The following code can be used to achieve this effect: * @throws ExecutionException Thrown when attempting to retrieve the result * of a task that aborted by throwing an exception. This exception can be * inspected using the Throwable.getCause() method. * @throws ServiceException Thrown if the server returned an error for the * request. * @throws IOException Thrown if there was an error setting up tracing for * the request. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws ServiceException Thrown if an unexpected response is found. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return Parameters returned from the Create Virtual Machine Image * operation. */ VirtualMachineOSImageUpdateResponse update(String imageName, VirtualMachineOSImageUpdateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException; /** * The Update OS Image operation updates an OS image that in your image * repository. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for * more information) * * @param imageName Required. The name of the virtual machine image to be * updated. * @param parameters Required. Parameters supplied to the Update Virtual * Machine Image operation. * @return Parameters returned from the Create Virtual Machine Image * operation. */ Future<VirtualMachineOSImageUpdateResponse> updateAsync(String imageName, VirtualMachineOSImageUpdateParameters parameters); }
/* * Copyright 2009 Martin Grotzke * * 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 &quot;AS IS&quot; BASIS, * WITHOUT 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 de.javakaffee.web.msm; import static de.javakaffee.web.msm.integration.TestUtils.assertDeepEquals; import static de.javakaffee.web.msm.integration.TestUtils.createSession; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.io.IOException; import java.io.ObjectInputStream; import java.security.Principal; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.Manager; import org.apache.catalina.authenticator.Constants; import org.apache.catalina.authenticator.SavedRequest; import org.apache.catalina.core.StandardContext; import org.apache.catalina.realm.GenericPrincipal; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import de.javakaffee.web.msm.MemcachedSessionService.SessionManager; /** * Test the {@link TranscoderService}. * * @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */ public abstract class TranscoderServiceTest { protected static SessionManager _manager; private static boolean _managerHasGetContainer; static { try { Manager.class.getDeclaredMethod("getContainer"); _managerHasGetContainer = true; } catch (NoSuchMethodException e) { } } @BeforeMethod public void setup() throws LifecycleException, ClassNotFoundException, IOException { _manager = mock( SessionManager.class ); final Context context = new StandardContext(); when( _manager.getContext() ).thenReturn( context ); // needed for createSession // Manager.getContainer no longer available in tc 8.5+ if(_managerHasGetContainer) { when( _manager.getContainer() ).thenReturn( context ); } when( _manager.newMemcachedBackupSession() ).thenAnswer(new Answer<MemcachedBackupSession>() { @Override public MemcachedBackupSession answer(final InvocationOnMock invocation) throws Throwable { return newMemcachedBackupSession( _manager ); } }); final MemcachedSessionService service = new DummyMemcachedSessionService<SessionManager>( _manager ); when( _manager.createSession( anyString() ) ).thenAnswer(new Answer<MemcachedBackupSession>() { @Override public MemcachedBackupSession answer(final InvocationOnMock invocation) throws Throwable { return createSession(service); } }); when( _manager.readPrincipal( (ObjectInputStream)any() ) ).thenReturn( createPrincipal() ); when( _manager.getMemcachedSessionService() ).thenReturn( service ); when( _manager.willAttributeDistribute(anyString(), any())).thenReturn(true); } @Nonnull protected MemcachedBackupSession newMemcachedBackupSession( @Nullable final SessionManager manager ) { return new MemcachedBackupSession( manager ); } @Test public void testSerializeSessionFieldsIncludesFormPrincipalNote() { final MemcachedBackupSession session = (MemcachedBackupSession) _manager.createSession( null ); final Principal saved = createPrincipal(); session.setNote(Constants.FORM_PRINCIPAL_NOTE, saved); final byte[] data = TranscoderService.serializeSessionFields( session ); final MemcachedBackupSession deserialized = TranscoderService.deserializeSessionFields(data, _manager ).getSession(); final Principal actual = (Principal) deserialized.getNote(Constants.FORM_PRINCIPAL_NOTE); assertNotNull(actual); assertDeepEquals(actual, saved); } @Test public void testSerializeSessionFieldsIncludesFormRequestNote() { final MemcachedBackupSession session = (MemcachedBackupSession) _manager.createSession( null ); final SavedRequest saved = new SavedRequest(); saved.setQueryString("foo=bar"); saved.setRequestURI("http://www.foo.org"); session.setNote(Constants.FORM_REQUEST_NOTE, saved); final byte[] data = TranscoderService.serializeSessionFields( session ); final MemcachedBackupSession deserialized = TranscoderService.deserializeSessionFields(data, _manager ).getSession(); final SavedRequest actual = (SavedRequest) deserialized.getNote(Constants.FORM_REQUEST_NOTE); assertNotNull(actual); assertDeepEquals(actual, saved); } @Test public void testVersionUpgrade() { final MemcachedBackupSession session = (MemcachedBackupSession) _manager.createSession( null ); final byte[] data = TranscoderService.serializeSessionFields( session, TranscoderService.VERSION_1 ); final byte[] attributesData = TranscoderService.deserializeSessionFields(data, _manager ).getAttributesData(); // we just check that data is read (w/o) bounds issues and no data // is left (we just passed data in, w/o added attributesData appended) assertEquals(attributesData.length, 0); } @Test public void testSerializeSessionFields() { final MemcachedBackupSession session = (MemcachedBackupSession) _manager.createSession( null ); session.setLastBackupTime( System.currentTimeMillis() ); final byte[] data = TranscoderService.serializeSessionFields( session ); final MemcachedBackupSession deserialized = TranscoderService.deserializeSessionFields(data, _manager ).getSession(); assertSessionFields( session, deserialized ); } @Test public void testSerializeSessionFieldsWithAuthenticatedPrincipal() { final MemcachedBackupSession session = (MemcachedBackupSession) _manager.createSession( null ); session.setAuthType( HttpServletRequest.FORM_AUTH ); session.setPrincipal( createPrincipal() ); session.setLastBackupTime( System.currentTimeMillis() ); final byte[] data = TranscoderService.serializeSessionFields( session ); final MemcachedBackupSession deserialized = TranscoderService.deserializeSessionFields( data, _manager ).getSession(); assertSessionFields( session, deserialized ); } @Nonnull protected abstract GenericPrincipal createPrincipal(); @Test public void testSerializeSessionWithoutAttributes() { final MemcachedBackupSession session = (MemcachedBackupSession) _manager.createSession( null ); session.setLastBackupTime( System.currentTimeMillis() ); final TranscoderService transcoderService = new TranscoderService( new JavaSerializationTranscoder( _manager ) ); final byte[] data = transcoderService.serialize( session ); final MemcachedBackupSession deserialized = transcoderService.deserialize( data, _manager ); assertSessionFields( session, deserialized ); } @Test public void testSerializeSessionWithAttributes() { final MemcachedBackupSession session = (MemcachedBackupSession) _manager.createSession( null ); final TranscoderService transcoderService = new TranscoderService( new JavaSerializationTranscoder( _manager ) ); final String value = "bar"; session.setAttribute( "foo", value ); session.setLastBackupTime( System.currentTimeMillis() ); final byte[] data = transcoderService.serialize( session ); final MemcachedBackupSession deserialized = transcoderService.deserialize( data, _manager ); assertSessionFields( session, deserialized ); Assert.assertEquals( value, deserialized.getAttribute( "foo" ) ); } private void assertSessionFields( final MemcachedBackupSession session, final MemcachedBackupSession deserialized ) { Assert.assertEquals( session.getCreationTimeInternal(), deserialized.getCreationTimeInternal() ); Assert.assertEquals( session.getLastAccessedTimeInternal(), deserialized.getLastAccessedTimeInternal() ); Assert.assertEquals( session.getMaxInactiveInterval(), deserialized.getMaxInactiveInterval() ); Assert.assertEquals( session.isNewInternal(), deserialized.isNewInternal() ); Assert.assertEquals( session.isValidInternal(), deserialized.isValidInternal() ); Assert.assertEquals( session.getThisAccessedTimeInternal(), deserialized.getThisAccessedTimeInternal() ); Assert.assertEquals( session.getLastBackupTime(), deserialized.getLastBackupTime() ); Assert.assertEquals( session.getIdInternal(), deserialized.getIdInternal() ); Assert.assertEquals( session.getAuthType(), deserialized.getAuthType() ); assertDeepEquals( session.getPrincipal(), deserialized.getPrincipal() ); } }
/* * * 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.airavata.gfac.impl.task; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.utils.AiravataUtils; import org.apache.airavata.gfac.core.*; import org.apache.airavata.gfac.core.cluster.JobSubmissionOutput; import org.apache.airavata.gfac.core.cluster.RemoteCluster; import org.apache.airavata.gfac.core.context.ProcessContext; import org.apache.airavata.gfac.core.context.TaskContext; import org.apache.airavata.gfac.core.task.JobSubmissionTask; import org.apache.airavata.gfac.core.task.TaskException; import org.apache.airavata.gfac.impl.Factory; import org.apache.airavata.model.appcatalog.computeresource.ResourceJobManager; import org.apache.airavata.model.commons.ErrorModel; import org.apache.airavata.model.job.JobModel; import org.apache.airavata.model.status.JobState; import org.apache.airavata.model.status.JobStatus; import org.apache.airavata.model.status.TaskState; import org.apache.airavata.model.status.TaskStatus; import org.apache.airavata.model.task.TaskTypes; import org.apache.airavata.registry.cpi.AppCatalogException; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.Map; public class SSHJobSubmissionTask implements JobSubmissionTask { private static final Logger log = LoggerFactory.getLogger(SSHJobSubmissionTask.class); @Override public void init(Map<String, String> propertyMap) throws TaskException { } @Override public TaskStatus execute(TaskContext taskContext){ TaskStatus taskStatus = new TaskStatus(TaskState.COMPLETED); // set to completed. try { ProcessContext processContext = taskContext.getParentProcessContext(); JobModel jobModel = processContext.getJobModel(); jobModel.setTaskId(taskContext.getTaskId()); RemoteCluster remoteCluster = processContext.getRemoteCluster(); JobDescriptor jobDescriptor = GFacUtils.createJobDescriptor(processContext); jobModel.setJobName(jobDescriptor.getJobName()); ResourceJobManager resourceJobManager = GFacUtils.getResourceJobManager(processContext); JobManagerConfiguration jConfig = null; if (resourceJobManager != null) { jConfig = Factory.getJobManagerConfiguration(resourceJobManager); } JobStatus jobStatus = new JobStatus(); File jobFile = GFacUtils.createJobFile(taskContext, jobDescriptor, jConfig); if (jobFile != null && jobFile.exists()) { jobModel.setJobDescription(FileUtils.readFileToString(jobFile)); JobSubmissionOutput jobSubmissionOutput = remoteCluster.submitBatchJob(jobFile.getPath(), processContext.getWorkingDir()); jobModel.setExitCode(jobSubmissionOutput.getExitCode()); jobModel.setStdErr(jobSubmissionOutput.getStdErr()); jobModel.setStdOut(jobSubmissionOutput.getStdOut()); String jobId = jobSubmissionOutput.getJobId(); if (jobId != null && !jobId.isEmpty()) { jobModel.setJobId(jobId); GFacUtils.saveJobModel(processContext, jobModel); jobStatus.setJobState(JobState.SUBMITTED); jobStatus.setReason("Successfully Submitted to " + taskContext.getParentProcessContext() .getComputeResourceDescription().getHostName()); jobModel.setJobStatus(jobStatus); GFacUtils.saveJobStatus(taskContext.getParentProcessContext(), jobModel); if (verifyJobSubmissionByJobId(remoteCluster, jobId)) { jobStatus.setJobState(JobState.QUEUED); jobStatus.setReason("Verification step succeeded"); jobModel.setJobStatus(jobStatus); GFacUtils.saveJobStatus(taskContext.getParentProcessContext(), jobModel); } taskStatus = new TaskStatus(TaskState.COMPLETED); taskStatus.setReason("Submitted job to compute resource"); } else { int verificationTryCount = 0; while (verificationTryCount++ < 3) { String verifyJobId = verifyJobSubmission(remoteCluster, jobModel); if (verifyJobId != null && !verifyJobId.isEmpty()) { // JobStatus either changed from SUBMITTED to QUEUED or directly to QUEUED jobId = verifyJobId; jobModel.setJobId(jobId); GFacUtils.saveJobModel(processContext,jobModel); jobStatus.setJobState(JobState.QUEUED); jobStatus.setReason("Verification step succeeded"); jobModel.setJobStatus(jobStatus); GFacUtils.saveJobStatus(taskContext.getParentProcessContext(), jobModel); taskStatus.setState(TaskState.COMPLETED); taskStatus.setReason("Submitted job to compute resource"); break; } log.info("Verify step return invalid jobId, retry verification step in {} secs", verificationTryCount * 10); Thread.sleep(verificationTryCount * 10000); } } if (jobId == null || jobId.isEmpty()) { String msg = "expId:" + processContext.getProcessModel().getExperimentId() + " Couldn't find " + "remote jobId for JobName:" + jobModel.getJobName() + ", both submit and verify steps " + "doesn't return a valid JobId. " + "Hence changing experiment state to Failed"; log.error(msg); ErrorModel errorModel = new ErrorModel(); errorModel.setUserFriendlyMessage(msg); errorModel.setActualErrorMessage(msg); GFacUtils.saveExperimentError(processContext, errorModel); GFacUtils.saveProcessError(processContext, errorModel); GFacUtils.saveTaskError(taskContext, errorModel); taskStatus.setState(TaskState.FAILED); taskStatus.setReason("Couldn't find job id in both submitted and verified steps"); }else { GFacUtils.saveJobModel(processContext, jobModel); } } else { taskStatus.setState(TaskState.FAILED); if (jobFile == null) { taskStatus.setReason("JobFile is null"); } else { taskStatus.setReason("Job file doesn't exist"); } } } catch (AppCatalogException e) { String msg = "Error while instantiating app catalog"; log.error(msg, e); taskStatus.setState(TaskState.FAILED); taskStatus.setReason(msg); ErrorModel errorModel = new ErrorModel(); errorModel.setActualErrorMessage(e.getMessage()); errorModel.setUserFriendlyMessage(msg); taskContext.getTaskModel().setTaskError(errorModel); } catch (ApplicationSettingsException e) { String msg = "Error occurred while creating job descriptor"; log.error(msg, e); taskStatus.setState(TaskState.FAILED); taskStatus.setReason(msg); ErrorModel errorModel = new ErrorModel(); errorModel.setActualErrorMessage(e.getMessage()); errorModel.setUserFriendlyMessage(msg); taskContext.getTaskModel().setTaskError(errorModel); } catch (GFacException e) { String msg = "Error occurred while creating job descriptor"; log.error(msg, e); taskStatus.setState(TaskState.FAILED); taskStatus.setReason(msg); ErrorModel errorModel = new ErrorModel(); errorModel.setActualErrorMessage(e.getMessage()); errorModel.setUserFriendlyMessage(msg); taskContext.getTaskModel().setTaskError(errorModel); } catch (SSHApiException e) { String msg = "Error occurred while submitting the job"; log.error(msg, e); taskStatus.setState(TaskState.FAILED); taskStatus.setReason(msg); ErrorModel errorModel = new ErrorModel(); errorModel.setActualErrorMessage(e.getMessage()); errorModel.setUserFriendlyMessage(msg); taskContext.getTaskModel().setTaskError(errorModel); } catch (IOException e) { String msg = "Error while reading the content of the job file"; log.error(msg, e); taskStatus.setState(TaskState.FAILED); taskStatus.setReason(msg); ErrorModel errorModel = new ErrorModel(); errorModel.setActualErrorMessage(e.getMessage()); errorModel.setUserFriendlyMessage(msg); taskContext.getTaskModel().setTaskError(errorModel); } catch (InterruptedException e) { String msg = "Error occurred while verifying the job submission"; log.error(msg, e); taskStatus.setState(TaskState.FAILED); taskStatus.setReason(msg); ErrorModel errorModel = new ErrorModel(); errorModel.setActualErrorMessage(e.getMessage()); errorModel.setUserFriendlyMessage(msg); taskContext.getTaskModel().setTaskError(errorModel); } taskContext.setTaskStatus(taskStatus); try { GFacUtils.saveAndPublishTaskStatus(taskContext); } catch (GFacException e) { log.error("Error while saving task status", e); } return taskStatus; } private boolean verifyJobSubmissionByJobId(RemoteCluster remoteCluster, String jobID) throws SSHApiException { JobStatus status = remoteCluster.getJobStatus(jobID); return status != null && status.getJobState() != JobState.UNKNOWN; } private String verifyJobSubmission(RemoteCluster remoteCluster, JobModel jobDetails) { String jobName = jobDetails.getJobName(); String jobId = null; try { jobId = remoteCluster.getJobIdByJobName(jobName, remoteCluster.getServerInfo().getUserName()); } catch (SSHApiException e) { log.error("Error while verifying JobId from JobName"); } return jobId; } @Override public TaskStatus recover(TaskContext taskContext) { ProcessContext processContext = taskContext.getParentProcessContext(); JobModel jobModel = processContext.getJobModel(); // original job failed before submitting if (jobModel == null || jobModel.getJobId() == null ){ return execute(taskContext); }else { // job is already submitted and monitor should handle the recovery return new TaskStatus(TaskState.COMPLETED); } } @Override public TaskTypes getType() { return TaskTypes.JOB_SUBMISSION; } }
/* * 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.solr.util; import com.google.common.collect.ImmutableList; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.common.SolrException; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.NamedList.NamedListEntry; import org.apache.solr.core.CloudConfig; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.CoreDescriptor; import org.apache.solr.core.CorePropertiesLocator; import org.apache.solr.core.CoresLocator; import org.apache.solr.core.NodeConfig; import org.apache.solr.core.SolrConfig; import org.apache.solr.core.SolrCore; import org.apache.solr.core.SolrResourceLoader; import org.apache.solr.core.SolrXmlConfig; import org.apache.solr.handler.UpdateRequestHandler; import org.apache.solr.request.LocalSolrQueryRequest; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrRequestHandler; import org.apache.solr.request.SolrRequestInfo; import org.apache.solr.response.QueryResponseWriter; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.IndexSchemaFactory; import org.apache.solr.servlet.DirectSolrConnection; import org.apache.solr.update.UpdateShardHandlerConfig; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * This class provides a simple harness that may be useful when * writing testcases. * * <p> * This class lives in the tests-framework source tree (and not in the test source * tree), so that it will be included with even the most minimal solr * distribution, in order to encourage plugin writers to create unit * tests for their plugins. * * */ public class TestHarness extends BaseTestHarness { public String coreName; protected volatile CoreContainer container; public UpdateRequestHandler updater; /** * Creates a SolrConfig object for the specified coreName assuming it * follows the basic conventions of being a relative path in the solrHome * dir. (ie: <code>${solrHome}/${coreName}/conf/${confFile}</code> */ public static SolrConfig createConfig(String solrHome, String coreName, String confFile) { // set some system properties for use by tests System.setProperty("solr.test.sys.prop1", "propone"); System.setProperty("solr.test.sys.prop2", "proptwo"); try { return new SolrConfig(solrHome + File.separator + coreName, confFile, null); } catch (Exception xany) { throw new RuntimeException(xany); } } /** * Creates a SolrConfig object for the default test core using {@link #createConfig(String,String,String)} */ public static SolrConfig createConfig(String solrHome, String confFile) { return createConfig(solrHome, SolrTestCaseJ4.DEFAULT_TEST_CORENAME, confFile); } /** * @param coreName to initialize * @param dataDirectory path for index data, will not be cleaned up * @param solrConfig solronfig instance * @param schemaFile schema filename */ public TestHarness( String coreName, String dataDirectory, SolrConfig solrConfig, String schemaFile) { this( coreName, dataDirectory, solrConfig, IndexSchemaFactory.buildIndexSchema(schemaFile, solrConfig)); } /** * @param dataDirectory path for index data, will not be cleaned up * @param solrConfig solronfig instance * @param schemaFile schema filename */ public TestHarness( String dataDirectory, SolrConfig solrConfig, String schemaFile) { this( dataDirectory, solrConfig, IndexSchemaFactory.buildIndexSchema(schemaFile, solrConfig)); } /** * @param dataDirectory path for index data, will not be cleaned up * @param solrConfig solrconfig instance * @param indexSchema schema instance */ public TestHarness( String dataDirectory, SolrConfig solrConfig, IndexSchema indexSchema) { this(SolrTestCaseJ4.DEFAULT_TEST_CORENAME, dataDirectory, solrConfig, indexSchema); } /** * @param coreName to initialize * @param dataDir path for index data, will not be cleaned up * @param solrConfig solrconfig resource name * @param indexSchema schema resource name */ public TestHarness(String coreName, String dataDir, String solrConfig, String indexSchema) { this(buildTestNodeConfig(new SolrResourceLoader(SolrResourceLoader.locateSolrHome())), new TestCoresLocator(coreName, dataDir, solrConfig, indexSchema)); this.coreName = (coreName == null) ? SolrTestCaseJ4.DEFAULT_TEST_CORENAME : coreName; } public TestHarness(String coreName, String dataDir, SolrConfig solrConfig, IndexSchema indexSchema) { this(coreName, dataDir, solrConfig.getResourceName(), indexSchema.getResourceName()); } /** * Create a TestHarness using a specific solr home directory and solr xml * @param solrHome the solr home directory * @param solrXml the text of a solrxml */ public TestHarness(String solrHome, String solrXml) { this(new SolrResourceLoader(solrHome), solrXml); } /** * Create a TestHarness using a specific solr resource loader and solr xml * @param loader the SolrResourceLoader to use * @param solrXml the text of a solrxml */ public TestHarness(SolrResourceLoader loader, String solrXml) { this(SolrXmlConfig.fromString(loader, solrXml)); } public TestHarness(NodeConfig nodeConfig) { this(nodeConfig, new CorePropertiesLocator(nodeConfig.getCoreRootDirectory())); } /** * Create a TestHarness using a specific config * @param config the ConfigSolr to use */ public TestHarness(NodeConfig config, CoresLocator coresLocator) { container = new CoreContainer(config, new Properties(), coresLocator); container.load(); updater = new UpdateRequestHandler(); updater.init(null); } public static NodeConfig buildTestNodeConfig(SolrResourceLoader loader) { CloudConfig cloudConfig = new CloudConfig.CloudConfigBuilder(System.getProperty("host"), Integer.getInteger("hostPort", 8983), System.getProperty("hostContext", "")) .setZkClientTimeout(Integer.getInteger("zkClientTimeout", 30000)) .build(); if (System.getProperty("zkHost") == null) cloudConfig = null; UpdateShardHandlerConfig updateShardHandlerConfig = new UpdateShardHandlerConfig(UpdateShardHandlerConfig.DEFAULT_MAXUPDATECONNECTIONS, UpdateShardHandlerConfig.DEFAULT_MAXUPDATECONNECTIONSPERHOST, 30000, 30000); return new NodeConfig.NodeConfigBuilder("testNode", loader) .setUseSchemaCache(Boolean.getBoolean("shareSchema")) .setCloudConfig(cloudConfig) .setUpdateShardHandlerConfig(updateShardHandlerConfig) .build(); } public static class TestCoresLocator extends ReadOnlyCoresLocator { final String coreName; final String dataDir; final String solrConfig; final String schema; public TestCoresLocator(String coreName, String dataDir, String solrConfig, String schema) { this.coreName = coreName == null ? SolrTestCaseJ4.DEFAULT_TEST_CORENAME : coreName; this.dataDir = dataDir; this.schema = schema; this.solrConfig = solrConfig; } @Override public List<CoreDescriptor> discover(CoreContainer cc) { return ImmutableList.of(new CoreDescriptor(cc, coreName, coreName, CoreDescriptor.CORE_DATADIR, dataDir, CoreDescriptor.CORE_CONFIG, solrConfig, CoreDescriptor.CORE_SCHEMA, schema, CoreDescriptor.CORE_COLLECTION, System.getProperty("collection", "collection1"), CoreDescriptor.CORE_SHARD, System.getProperty("shard", "shard1"))); } } public CoreContainer getCoreContainer() { return container; } /** Gets a core that does not have its refcount incremented (i.e. there is no need to * close when done). This is not MT safe in conjunction with reloads! */ public SolrCore getCore() { // get the core & decrease its refcount: // the container holds the core for the harness lifetime SolrCore core = container.getCore(coreName); if (core != null) core.close(); return core; } /** Gets the core with its reference count incremented. * You must call core.close() when done! */ public SolrCore getCoreInc() { return container.getCore(coreName); } public void reload() throws Exception { container.reload(coreName); } /** * Processes an "update" (add, commit or optimize) and * returns the response as a String. * * @param xml The XML of the update * @return The XML response to the update */ public String update(String xml) { try (SolrCore core = getCoreInc()) { DirectSolrConnection connection = new DirectSolrConnection(core); SolrRequestHandler handler = core.getRequestHandler("/update"); // prefer the handler mapped to /update, but use our generic backup handler // if that lookup fails if (handler == null) { handler = updater; } return connection.request(handler, null, xml); } catch (SolrException e) { throw (SolrException)e; } catch (Exception e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e); } } /** * Validates a "query" response against an array of XPath test strings * * @param req the Query to process * @return null if all good, otherwise the first test that fails. * @exception Exception any exception in the response. * @exception IOException if there is a problem writing the XML * @see LocalSolrQueryRequest */ public String validateQuery(SolrQueryRequest req, String... tests) throws Exception { String res = query(req); return validateXPath(res, tests); } /** * Processes a "query" using a user constructed SolrQueryRequest * * @param req the Query to process, will be closed. * @return The XML response to the query * @exception Exception any exception in the response. * @exception IOException if there is a problem writing the XML * @see LocalSolrQueryRequest */ public String query(SolrQueryRequest req) throws Exception { return query(req.getParams().get(CommonParams.QT), req); } /** * Processes a "query" using a user constructed SolrQueryRequest, and closes the request at the end. * * @param handler the name of the request handler to process the request * @param req the Query to process, will be closed. * @return The XML response to the query * @exception Exception any exception in the response. * @exception IOException if there is a problem writing the XML * @see LocalSolrQueryRequest */ public String query(String handler, SolrQueryRequest req) throws Exception { try { SolrCore core = req.getCore(); SolrQueryResponse rsp = new SolrQueryResponse(); SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp)); core.execute(core.getRequestHandler(handler),req,rsp); if (rsp.getException() != null) { throw rsp.getException(); } StringWriter sw = new StringWriter(32000); QueryResponseWriter responseWriter = core.getQueryResponseWriter(req); responseWriter.write(sw,req,rsp); return sw.toString(); } finally { req.close(); SolrRequestInfo.clearRequestInfo(); } } /** It is the users responsibility to close the request object when done with it. * This method does not set/clear SolrRequestInfo */ public SolrQueryResponse queryAndResponse(String handler, SolrQueryRequest req) throws Exception { try (SolrCore core = getCoreInc()) { SolrQueryResponse rsp = new SolrQueryResponse(); core.execute(core.getRequestHandler(handler), req, rsp); if (rsp.getException() != null) { throw rsp.getException(); } return rsp; } } /** * Shuts down and frees any resources */ public void close() { if (container != null) { for (SolrCore c : container.getCores()) { if (c.getOpenCount() > 1) throw new RuntimeException("SolrCore.getOpenCount()=="+c.getOpenCount()); } } if (container != null) { container.shutdown(); container = null; } } public LocalRequestFactory getRequestFactory(String qtype, int start, int limit) { LocalRequestFactory f = new LocalRequestFactory(); f.qtype = qtype; f.start = start; f.limit = limit; return f; } /** * 0 and Even numbered args are keys, Odd numbered args are values. */ public LocalRequestFactory getRequestFactory(String qtype, int start, int limit, String... args) { LocalRequestFactory f = getRequestFactory(qtype, start, limit); for (int i = 0; i < args.length; i+=2) { f.args.put(args[i], args[i+1]); } return f; } public LocalRequestFactory getRequestFactory(String qtype, int start, int limit, Map<String,String> args) { LocalRequestFactory f = getRequestFactory(qtype, start, limit); f.args.putAll(args); return f; } /** * A Factory that generates LocalSolrQueryRequest objects using a * specified set of default options. */ public class LocalRequestFactory { public String qtype = null; public int start = 0; public int limit = 1000; public Map<String,String> args = new HashMap<>(); public LocalRequestFactory() { } /** * Creates a LocalSolrQueryRequest based on variable args; for * historical reasons, this method has some peculiar behavior: * <ul> * <li>If there is a single arg, then it is treated as the "q" * param, and the LocalSolrQueryRequest consists of that query * string along with "qt", "start", and "rows" params (based * on the qtype, start, and limit properties of this factory) * along with any other default "args" set on this factory. * </li> * <li>If there are multiple args, then there must be an even number * of them, and each pair of args is used as a key=value param in * the LocalSolrQueryRequest. <b>NOTE: In this usage, the "qtype", * "start", "limit", and "args" properties of this factory are * ignored.</b> * </li> * </ul> * * TODO: this isn't really safe in the presense of core reloads! * Perhaps the best we could do is increment the core reference count * and decrement it in the request close() method? */ public LocalSolrQueryRequest makeRequest(String ... q) { if (q.length==1) { return new LocalSolrQueryRequest(TestHarness.this.getCore(), q[0], qtype, start, limit, args); } if (q.length%2 != 0) { throw new RuntimeException("The length of the string array (query arguments) needs to be even"); } Map.Entry<String, String> [] entries = new NamedListEntry[q.length / 2]; for (int i = 0; i < q.length; i += 2) { entries[i/2] = new NamedListEntry<>(q[i], q[i+1]); } NamedList nl = new NamedList(entries); if(nl.get("wt" ) == null) nl.add("wt","xml"); return new LocalSolrQueryRequest(TestHarness.this.getCore(), nl); } } }
package gov.va.hmp.app; import gov.va.cpe.vpr.PointOfCare; import gov.va.cpe.vpr.pom.IGenericPOMObjectDAO; import gov.va.cpe.vpr.pom.POMUtils; import gov.va.cpe.vpr.queryeng.dynamic.IViewDefDefDAO; import gov.va.cpe.vpr.queryeng.dynamic.PatientPanelViewDef; import gov.va.cpe.vpr.queryeng.dynamic.ViewDefDef; import gov.va.cpe.vpr.queryeng.dynamic.columns.ViewDefDefColDef; import gov.va.cpe.vpr.queryeng.dynamic.columns.ViewDefDefColDefConfigTemplate; import gov.va.cpe.vpr.sync.vista.IVistaVprObjectDao; import gov.va.cpe.vpr.util.GenUtil; import gov.va.hmp.web.servlet.mvc.ParameterMap; import gov.va.hmp.web.servlet.view.ModelAndViewFactory; import org.apache.commons.lang.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.InvocationTargetException; import java.util.*; @Controller @RequestMapping("/config/**") public class ConfigController { @RequestMapping(method = RequestMethod.GET) public ModelAndView index() { return new ModelAndView("/config/index", new LinkedHashMap<String, Object>()); } @RequestMapping(value = "pointOfCareOptions", method = RequestMethod.GET) public ModelAndView pointOfCareOptions(HttpServletRequest request, HttpServletResponse response) { List<PointOfCare> rslt = genericDAO.findAll(PointOfCare.class); return ModelAndViewFactory.contentNegotiatingModelAndView(rslt); } @RequestMapping(value = "pointOfCareOption", method = RequestMethod.POST) public ModelAndView setPointOfCareOption(HttpServletRequest request, HttpServletResponse response) { ParameterMap params = new ParameterMap(request); Object uid = params.get("uid"); PointOfCare poc = new PointOfCare(); if (uid!=null && !uid.toString().isEmpty()) { poc = ((PointOfCare) (genericDAO.findByUID(PointOfCare.class, uid.toString()))); } poc.setData(params); genericDAO.save(poc); return ModelAndViewFactory.contentNegotiatingModelAndView(poc); } @RequestMapping(value = "panels", method = RequestMethod.GET) public ModelAndView panels(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) Boolean showDraft) { // build up the param set ParameterMap params = new ParameterMap(request); // Return JSON of panels; List<ViewDefDef> boards = (List<ViewDefDef>) GenUtil.draftFilter(vddDAO.findAll(), showDraft == null ? false : showDraft.booleanValue()); ArrayList<Object> rslt = new ArrayList<Object>(); for (ViewDefDef d : boards) { Map<String, Object> map = d.getData(); map.put("columns", d.getCols()); rslt.add(map); } return ModelAndViewFactory.contentNegotiatingModelAndView(rslt); } @RequestMapping(value = "panel", method = RequestMethod.POST) public ModelAndView savePanel(@RequestParam(required = true) String panel, HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Map<String, Object> pmap = POMUtils.parseJSONtoMap(panel); pmap.put("name", StringEscapeUtils.escapeHtml((String) pmap.get("name"))); // sanitize name Object vdclass = pmap.get("primaryViewDefClassName"); if (vdclass==null || vdclass.toString().isEmpty()) { pmap.put("primaryViewDefClassName", PatientPanelViewDef.class.getName()); } // Funny construction b/c of column polymorphism not reconstructing easily from raw map. // Refactoring out of needing specific class implementations would take care of this, // however that means either front-end widgets for each column, or GSPs. List<Map> cols = (List<Map>) pmap.get("columns"); pmap.remove("columns"); ViewDefDef vdd = new ViewDefDef(pmap); for (Map col : cols) { String className = ((Map)col.get("appInfo")).get("code").toString(); ViewDefDefColDef cdf = (ViewDefDefColDef) Class.forName(className).getConstructor(Map.class).newInstance(col); vdd.addColumn(cdf); } vddDAO.save(vdd); return ModelAndViewFactory.contentNegotiatingModelAndView(vdd); } @RequestMapping(value = "panel/{uid}", method = RequestMethod.DELETE) public ModelAndView deletePanel(@PathVariable String uid, HttpServletRequest request, HttpServletResponse response) { vddDAO.delete(vddDAO.findByUid(uid)); LinkedHashMap<String, Boolean> map = new LinkedHashMap<String, Boolean>(1); map.put("success", true); return ModelAndViewFactory.contentNegotiatingModelAndView(map); } @RequestMapping(value = "column/list", method = RequestMethod.GET) public ModelAndView getColumnList() { ArrayList<Object> rslt = new ArrayList<Object>(); Map<String, Object> apps = appService.getApps("gov.va.cpe.vpr.queryeng.dynamic.columns.ViewDefDefColDef"); Collection<Map<String, Object>> capps = new ArrayList<Map<String, Object>>(); for(String key: apps.keySet()) { Object val = apps.get(key); if(val instanceof Map) { capps.add((Map<String, Object>) val); } } // Collection<Map<String, Object>> capps = appService.getApps("gov.va.cpe.vpr.queryeng.dynamic.columns.ViewDefDefColDef"); for (Map<String, Object> cap : capps) { rslt.add(ctx.getBean(cap.get("code").toString())); } return ModelAndViewFactory.contentNegotiatingModelAndView(rslt); } @RequestMapping(value = {"getColumnConfigOptions"}, method = RequestMethod.GET) public ModelAndView getColumnConfigOptions(@RequestParam(required = true) String code, HttpServletRequest request, HttpServletResponse response) { LinkedHashMap<Object, Object> options = new LinkedHashMap<Object, Object>(); ViewDefDefColDef vddcd = getViewDefDefColDef(code); options.put("viewdefFilterOptions", vddcd.getViewdefFilterOptions()); options.put("configOptions", vddcd.getConfigOptions()); options.put("description", vddcd.getDescription()); options.put("titleEditable", vddcd.getTitleEditable()); options.put("templateOptions", getViewDefDefColDefConfigTemplates(code)); return ModelAndViewFactory.contentNegotiatingModelAndView(options); } private ViewDefDefColDef getViewDefDefColDef(String vddcd) { // if the view is an exact bean name if (ctx.containsBean(vddcd)) { return ctx.getBean(vddcd, ViewDefDefColDef.class); } return null; } private List<ViewDefDefColDefConfigTemplate> getViewDefDefColDefConfigTemplates(String code) { List<ViewDefDefColDefConfigTemplate> tmps = genericDAO.findAll(ViewDefDefColDefConfigTemplate.class); List<ViewDefDefColDefConfigTemplate> rslt = new ArrayList<ViewDefDefColDefConfigTemplate>(); for (ViewDefDefColDefConfigTemplate t : tmps) { if (t.getColumnClass().equals(code)) { ((ArrayList<ViewDefDefColDefConfigTemplate>) rslt).add(t); } } return rslt; } @RequestMapping(value = {"setColTemplate"}, method = RequestMethod.POST) public ModelAndView setColTemplate(@RequestParam(required = true) String columnClass, @RequestParam(required = true) String name, @RequestParam(required = true) String formData, HttpServletRequest request, HttpServletResponse response) { ViewDefDefColDefConfigTemplate tmp = new ViewDefDefColDefConfigTemplate(); tmp.setData("name", name); tmp.setData("columnClass", columnClass); tmp.setData("formVals", POMUtils.parseJSONtoMap(formData)); return ModelAndViewFactory.contentNegotiatingModelAndView(vprDao.save(tmp)); } public IGenericPOMObjectDAO getGenericDAO() { return genericDAO; } public void setGenericDAO(IGenericPOMObjectDAO genericDAO) { this.genericDAO = genericDAO; } public IVistaVprObjectDao getVprDao() { return vprDao; } public void setVprDao(IVistaVprObjectDao vprDao) { this.vprDao = vprDao; } public IAppService getAppService() { return appService; } public void setAppService(IAppService appService) { this.appService = appService; } public IViewDefDefDAO getVddDAO() { return vddDAO; } public void setVddDAO(IViewDefDefDAO vddDAO) { this.vddDAO = vddDAO; } public ApplicationContext getCtx() { return ctx; } public void setCtx(ApplicationContext ctx) { this.ctx = ctx; } @Autowired private IGenericPOMObjectDAO genericDAO; @Autowired private IVistaVprObjectDao vprDao; @Autowired private IAppService appService; @Autowired private IViewDefDefDAO vddDAO; @Autowired private ApplicationContext ctx; }
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * 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. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * BasicProjectInfo.java * --------------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BasicProjectInfo.java,v 1.8 2007/11/02 17:50:34 taqua Exp $ * * Changes * ------- * 07-Jun-2004 : Added source headers (DG); * */ package org.jfree.base; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.jfree.util.ObjectUtilities; /** * Basic project info. * * @author Thomas Morgner */ public class BasicProjectInfo extends Library { /** * A helper class, which simplifies the loading of optional library * implementations. */ private static class OptionalLibraryHolder { private String libraryClass; private transient Library library; public OptionalLibraryHolder(final String libraryClass) { if (libraryClass == null) { throw new NullPointerException("LibraryClass must not be null."); } this.libraryClass = libraryClass; } public OptionalLibraryHolder(final Library library) { if (library == null) { throw new NullPointerException("Library must not be null."); } this.library = library; this.libraryClass = library.getClass().getName(); } public String getLibraryClass() { return libraryClass; } public Library getLibrary() { if (library == null) { library = loadLibrary(libraryClass); } return library; } protected Library loadLibrary(final String classname) { if (classname == null) { return null; } try { final Class c = ObjectUtilities.getClassLoader( getClass()).loadClass(classname); try { final Method m = c.getMethod("getInstance", (Class[]) null); return (Library) m.invoke(null, (Object[]) null); } catch(Exception e) { // ok, fall back ... } return (Library) c.newInstance(); } catch (Exception e) { // ok, this library has no 'getInstance()' method. Check the // default constructor ... return null; } } } /** The project copyright statement. */ private String copyright; /** A list of libraries used by the project. */ private List libraries; private List optionalLibraries; /** * Default constructor. */ public BasicProjectInfo() { this.libraries = new ArrayList(); this.optionalLibraries = new ArrayList(); } /** * Creates a new library reference. * * @param name the name. * @param version the version. * @param licence the licence. * @param info the web address or other info. */ public BasicProjectInfo(final String name, final String version, final String licence, final String info) { this(); setName(name); setVersion(version); setLicenceName(licence); setInfo(info); } /** * Creates a new project info instance. * * @param name the project name. * @param version the project version. * @param info the project info (web site for example). * @param copyright the copyright statement. * @param licenceName the license name. */ public BasicProjectInfo(final String name, final String version, final String info, final String copyright, final String licenceName) { this(name, version, licenceName, info); setCopyright(copyright); } /** * Returns the copyright statement. * * @return The copyright statement. */ public String getCopyright() { return this.copyright; } /** * Sets the project copyright statement. * * @param copyright the project copyright statement. */ public void setCopyright(final String copyright) { this.copyright = copyright; } /** * Sets the project info string (for example, this could be the project URL). * * @param info the info string. */ public void setInfo(final String info) { super.setInfo(info); } /** * Sets the license name. * * @param licence the license name. */ public void setLicenceName(final String licence) { super.setLicenceName(licence); } /** * Sets the project name. * * @param name the project name. */ public void setName(final String name) { super.setName(name); } /** * Sets the project version number. * * @param version the version number. */ public void setVersion(final String version) { super.setVersion(version); } /** * Returns a list of libraries used by the project. * * @return the list of libraries. */ public Library[] getLibraries() { return (Library[]) this.libraries.toArray (new Library[this.libraries.size()]); } /** * Adds a library. * * @param library the library. */ public void addLibrary (final Library library) { if (library == null) { throw new NullPointerException(); } this.libraries.add(library); } /** * Returns a list of optional libraries used by the project. * * @return the list of libraries. */ public Library[] getOptionalLibraries() { final ArrayList libraries = new ArrayList(); for (int i = 0; i < optionalLibraries.size(); i++) { OptionalLibraryHolder holder = (OptionalLibraryHolder) optionalLibraries.get(i); Library l = holder.getLibrary(); if (l != null) { libraries.add(l); } } return (Library[]) libraries.toArray(new Library[libraries.size()]); } /** * Adds an optional library. These libraries will be booted, if they define * a boot class. A missing class is considered non-fatal and it is assumed * that the programm knows how to handle that. * * @param library the library. */ public void addOptionalLibrary (final String libraryClass) { if (libraryClass == null) { throw new NullPointerException("Library classname must be given."); } this.optionalLibraries.add (new OptionalLibraryHolder(libraryClass)); } /** * Adds an optional library. These libraries will be booted, if they define * a boot class. A missing class is considered non-fatal and it is assumed * that the programm knows how to handle that. * * @param library the library. */ public void addOptionalLibrary (final Library library) { if (library == null) { throw new NullPointerException("Library must be given."); } this.optionalLibraries.add(new OptionalLibraryHolder(library)); } }
/* * $Id$ * * Copyright 2006, The jCoderZ.org Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the jCoderZ.org Project 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 REGENTS 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 REGENTS AND CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jcoderz.phoenix.report; import java.io.Serializable; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Comparator; import java.util.Iterator; import org.jcoderz.commons.util.Assert; import org.jcoderz.commons.util.StringUtil; import org.jcoderz.phoenix.report.jaxb.File; import org.jcoderz.phoenix.report.jaxb.Item; /** * This class encapsulates all finding information collected * for a file or a group of files. * * <p>This class also allows to perform the magic quality * calculation for the data collected in the summary.</p> * * @author Andreas Mandel */ public final class FileSummary implements Comparable<FileSummary> { /** Constant used for initial string buffer size. */ private static final int STRING_BUFFER_SIZE = 256; /** Constant for percentage calculation 1% = 1 / MAX_PERCENTAGE. */ private static final int MAX_PERCENTAGE = 100; private static final float MAX_PERCENTAGE_FLOAT = 100; private final NumberFormat mCoveragePercantageFormatter = new DecimalFormat("##0.00"); /** Counts the number of files added up in this summary. */ private int mFiles = 0; /** Lines of code in the file. */ private int mLinesOfCode; /** * Lines of code in the file that contain coverage information * that is not 0. */ private int mCoveredLinesOfCode; /** * Holds the number of violations for each severity level. */ private int[] mViolations = new int[Severity.VALUES.size()]; /** * Percentage values for the violations. * Data stored in here is only valid if <code>mPercentUpToDate</code> * is true. */ private int[] mPercent = new int[Severity.VALUES.size()]; private boolean mPercentUpToDate = false; private final String mClassName; private final String mPackage; private final String mDetailedFile; private boolean mCoverageData; /** * Creates a new empty file summary object used to summarize * findings for classes in all packages. */ public FileSummary () { this ("Global Summary", "all", null, 0, false); } /** * Creates a new empty file summary object used to summarize * findings for classes in in the given package. * * @param packagename name of the package where this summary * is used for. */ public FileSummary (String packagename) { this ("Package Summary", packagename, null, 0, false); } /** * Creates a new empty file summary object used to summarize * findings for the given class in the given package with * link to the file and code information. * @param className the name of the class (without package * information). * @param packagename the name of the package where the class * resides in. * @param reportfile the name of the file where the html report * stored. * @param linesOfCode the number of lines in the file. * @param withCoverage true if coverage information is * available. */ public FileSummary (String className, String packagename, String reportfile, int linesOfCode, boolean withCoverage) { mClassName = className; mPackage = packagename; mDetailedFile = reportfile; mLinesOfCode = linesOfCode; mCoverageData = withCoverage; } /** * Calculates the quality as percentage represented as float. * @param loc total number of lines of code. This is also the maximum * that might be returned by this method. * @param violations the array holding the violations of the severity * related to the position in the array. The elements of the * array are NOT modified. * @return the quality as percentage represented as float. */ public static float calculateQuality (int loc, int[] violations) { float quality = 0; if (loc > 0) { quality = calcUnweightedQuality(loc, violations); quality = (quality * MAX_PERCENTAGE) / loc; } return quality; } /** * Calculates the unweighed quality points scored for the code. * Maximum returned is <code>loc</code> the minimum is <code>0</code>. * @param loc total number of lines of code. This is also the maximum * that might be returned by this method. * @param violations the array holding the violations of the severity * related to the position in the array. The elements of the * array are NOT modified. * @return the unweighed quality score. */ private static int calcUnweightedQuality (int loc, int[] violations) { Assert.assertEquals( "Violations array length must match number of severities.", Severity.VALUES.size(), violations.length); int quality = loc * Severity.PENALTY_SCALE; // lines of code for (int i = 0; i < Severity.VALUES.size() && quality > 0; i++) { // not covered lines are bad this // not files with no coverage test at all get no penalty here! quality -= violations[i] * Severity.fromInt(i).getPenalty(); } if (quality < 0) { quality = 0; } else { quality /= Severity.PENALTY_SCALE; } return quality; } /** * Calculates the quality percentage scored for the code. * Maximum returned is <code>100</code> the minimum is <code>0</code>. * @param loc total number of lines of code. This is also the maximum * that might be returned by this method. * @param info number of info level findings. * @param warning number of warning level findings. * @param error number of error level findings. * @param coverage number of coverage level findings. * @param filtered number of filtered level findings. * @param codestyle number of codestyle level findings. * @param design number of design level findings. * @param cpd number of cpd level findings. * @return the unweighed quality score. */ public static float calculateQuality (int loc, int info, int warning, int error, int coverage, int filtered, int codestyle, int design, int cpd) { final int[] violations = new int[Severity.VALUES.size()]; violations[Severity.INFO.toInt()] = info; violations[Severity.COVERAGE.toInt()] = coverage; violations[Severity.WARNING.toInt()] = warning; violations[Severity.ERROR.toInt()] = error; violations[Severity.FILTERED.toInt()] = filtered; violations[Severity.CODE_STYLE.toInt()] = codestyle; violations[Severity.DESIGN.toInt()] = design; violations[Severity.CPD.toInt()] = cpd; return FileSummary.calculateQuality(loc, violations); } /** @return the name of the class (without package information). */ public String getClassName () { return mClassName; } /** @return the name of the package. */ public String getPackage () { return mPackage; } /** @return the number of files summarized in this file summary. */ public int getNumberOfFiles () { return mFiles; } /** {@inheritDoc} */ public String toString () { final StringBuilder result = new StringBuilder(); calcPercent(); result.append(getFullClassName()); result.append("{ LOC:"); result.append(mLinesOfCode); result.append('('); result.append(mViolations[Severity.OK.toInt()]); result.append("%)"); final Iterator<Severity> i = Severity.VALUES.iterator(); while (i.hasNext()) { final Severity s = i.next(); if (mViolations[s.toInt()] != 0) { result.append(", "); result.append(s.toString()); result.append(':'); result.append(mViolations[s.toInt()]); result.append('('); result.append(mPercent[s.toInt()]); result.append("%)"); } } result.append('}'); return result.toString(); } /** * Add the counters of an other FileSummary to this one. * @param other the FileSummary be added. */ public void add (FileSummary other) { for (int i = 0; i < mViolations.length; i++) { mViolations[i] += other.mViolations[i]; } mLinesOfCode += other.mLinesOfCode; mCoveredLinesOfCode += other.mCoveredLinesOfCode; mPercentUpToDate = false; mFiles++; if (mCoverageData || other.isWithCoverage() || mCoveredLinesOfCode > 0 || getNotCoveredLinesOfCode() > 0) { mCoverageData = true; } } /** * Adds the counters from the given file to this summary. * @param file the data to be added. */ public void add (File file) { mFiles++; mLinesOfCode += file.getLoc(); final Iterator<Item> i = file.getItem().iterator(); while (i.hasNext()) { final Item item = i.next(); final Severity severity = item.getSeverity(); addViolation(severity); } } /** * Returns true if this summary contains coverage data. * @return true if this summary contains coverage data. */ public boolean isWithCoverage () { return mCoverageData; } /** Increments the counter of covered lines. */ public void addCoveredLine () { mPercentUpToDate = false; mCoveredLinesOfCode++; } /** * Increments the counter for the given severity in this summary. * @param severity the severity of the counter to be incremented. */ public void addViolation (Severity severity) { Assert.notNull(severity, "severity"); mPercentUpToDate = false; mViolations[severity.toInt()]++; } /** * @return the full class name including package declaration. */ public String getFullClassName () { final String fullClassName; if (StringUtil.isEmptyOrNull(mPackage)) { fullClassName = mClassName; } else { fullClassName = mPackage + "." + mClassName; } return fullClassName; } /** @return the report file associated to this FileSummary. */ public String getHtmlLink () { return mDetailedFile; } /** @return the number of lines of code. */ public int getLinesOfCode () { return mLinesOfCode; } /** * Returns the magic quality as percentage int. * The maximum quality code gets a score of 100. The lowest score * possible is 0. * @return the magic quality as percentage int (0-100). */ public int getQuality () { int quality = 0; if (mLinesOfCode > 0) { quality = calcUnweightedQuality(mLinesOfCode, mViolations); quality = (quality * MAX_PERCENTAGE) / mLinesOfCode; } return quality; } /** * Returns the magic quality as percentage float. * The maximum quality code gets a score of 100. The lowest score * possible is 0. * @return the magic quality as percentage float (0.0-100.0). */ public float getQualityAsFloat () { // might be we should cache the result? return FileSummary.calculateQuality (mLinesOfCode, mViolations); } /** * Generates a string containing xhtml code that renders to a * percentage bar that can be used as component of a web page. * @return a string containing xhtml. */ public String getPercentBar () { calcPercent(); final StringBuilder sb = new StringBuilder(STRING_BUFFER_SIZE); sb.append("<table width='100%' cellspacing='0' cellpadding='0' " + "summary='quality-bar'><tr valign='middle'>"); for (int i = Severity.OK.toInt(); i < Severity.MAX_SEVERITY_INT; i++) { if (mPercent[i] > 0) { sb.append("<td class='"); sb.append(Severity.fromInt(i).toString()); sb.append("' width='"); sb.append(mPercent[i]); sb.append("%' height='10'></td>"); } } sb.append("</tr></table>"); return sb.toString(); } /** * Generates a string containing xhtml code that renders to a * bar that can be used as component of a web page to represent * the amount of covered code. * @return a string containing xhtml. */ public String getCoverageBar () { final int notCovered = MAX_PERCENTAGE - getCoverage(); final StringBuilder sb = new StringBuilder(STRING_BUFFER_SIZE); sb.append("<table width='100%' cellspacing='0' cellpadding='0' " + "summary='coverage-bar'><tr valign='middle'>"); if (notCovered < MAX_PERCENTAGE) { sb.append("<td class='ok' width='"); sb.append(MAX_PERCENTAGE - notCovered); sb.append("%' height='10'></td>"); } if (notCovered != 0) { sb.append("<td class='error' width='"); sb.append(notCovered); sb.append("%' height='10'></td></tr>"); } sb.append("</tr></table>"); return sb.toString(); } /** * Returns the number of violations for the given severity. * @param severity the severity to check. * @return the number of violations for the given severity */ public int getViolations (Severity severity) { return mViolations[severity.toInt()]; } /** * Get the coverage percentage in double precision. * @return the coverage percentage in double precision. */ public float getCoverageAsFloat () { final float allLinesOfCode = getNotCoveredLinesOfCode() + mCoveredLinesOfCode; float result; if (allLinesOfCode != 0) { result = mCoveredLinesOfCode / allLinesOfCode; } else if (getNotCoveredLinesOfCode() > 0) { result = 0; } else // no coverage at all (might be interface... { result = 1; } return result * MAX_PERCENTAGE_FLOAT; } /** * Returns the coverage as user string. * @return the coverage as user string. */ public String getCoverageAsString () { return mCoveragePercantageFormatter.format(getCoverageAsFloat()) + "%"; } /** @return the coverage percentage as int. */ public int getCoverage () { final int notCoveredLinesOfCode = getNotCoveredLinesOfCode(); int notCovered; if (mCoveredLinesOfCode != 0) { notCovered = (notCoveredLinesOfCode * MAX_PERCENTAGE) / (mCoveredLinesOfCode + notCoveredLinesOfCode); if ((notCovered == 0) && (notCoveredLinesOfCode > 0)) { // below 1% -> round up to 1% notCovered = 1; } } else if (notCoveredLinesOfCode > 0) { notCovered = MAX_PERCENTAGE; } else // no coverage at all (might be interface... { notCovered = 0; } return MAX_PERCENTAGE - notCovered; } /** * @return the number of not covered lines of code. */ public int getNotCoveredLinesOfCode () { return mViolations[Severity.COVERAGE.toInt()]; } /** * All findings that are between {@link Severity#INFO} and * {@link Severity#ERROR} but not {@link Severity#COVERAGE} * are counted. * @return the number of violations summed up in this summary. */ public int getNumberOfFindings () { int sum = 0; for (int i = Severity.INFO.toInt(); i <= Severity.ERROR.toInt(); i++) { if (i != Severity.COVERAGE.toInt()) { sum += mViolations[i]; } } return sum; } /** {@inheritDoc} */ public int compareTo (FileSummary o) { int result = 0; if (mPackage != null) { result = mPackage.compareTo((o).mPackage); } if (result == 0) { if (getClassName() != null) { result = getClassName().compareTo(o.getClassName()); } } return result; } private void calcPercent () { if (!mPercentUpToDate) { doCalcPercent(); } } private void doCalcPercent () { int remainingPercentage = MAX_PERCENTAGE; // errors if (mLinesOfCode != 0) { for (int i = Severity.ERROR.toInt(); i > Severity.INFO.toInt(); i--) { int percent; if (i == Severity.COVERAGE.toInt()) { percent = calcPercentCoverage(); } else { percent = calcPercentage( mViolations[i] * Severity.fromInt(i).getPenalty(), mLinesOfCode * Severity.PENALTY_SCALE); } // do not round to 0. if (mViolations[i] > 0 && percent == 0) { percent = 1; } if (percent > remainingPercentage) { percent = remainingPercentage; } mPercent[i] = percent; remainingPercentage -= percent; } } else { for (int i = Severity.ERROR.toInt(); i > Severity.INFO.toInt(); i--) { mPercent[i] = 0; } } mPercent[Severity.OK.toInt()] = remainingPercentage; mPercentUpToDate = true; } /** * Calculates the penalty percentage of the coverage tests. */ private int calcPercentCoverage () { final int coverageViolationPercentage; if (!mCoverageData) { coverageViolationPercentage = 0; } else { final int notCoveredLines = getNotCoveredLinesOfCode(); coverageViolationPercentage = calcPercentage( notCoveredLines * Severity.COVERAGE.getPenalty(), Severity.PENALTY_SCALE * (mCoveredLinesOfCode + notCoveredLines)); } return coverageViolationPercentage; } private static int calcPercentage (int part, int all) { final int result; if (all == 0) { result = 0; } else { result = part * MAX_PERCENTAGE / all; } return result; } /** * Comparator that allows to sort the FileSummary by name of the package. * @author Andreas Mandel */ static final class SortByPackage implements Comparator<FileSummary>, Serializable { private static final long serialVersionUID = 2244367340241672131L; public int compare (FileSummary o1, FileSummary o2) { return o1.compareTo(o2); } } /** * Comparator that allows to sort the FileSummary by quality. * @author Andreas Mandel */ static final class SortByQuality implements Comparator<FileSummary>, Serializable { private static final long serialVersionUID = 1718175789352629538L; public int compare (FileSummary o1, FileSummary o2) { int result; final float qualityA = o1.getQualityAsFloat(); final float qualityB = o2.getQualityAsFloat(); if (qualityA < qualityB) { result = -1; } else if (qualityA > qualityB) { result = 1; } else { result = o1.compareTo(o2); } return result; } } /** * Comparator that allows to sort the FileSummary by coverage. * @author Andreas Mandel */ static final class SortByCoverage implements Comparator<FileSummary>, Serializable { private static final long serialVersionUID = -4275903074787742250L; public int compare (FileSummary a, FileSummary b) { final float coverA = a.getCoverageAsFloat(); final float coverB = b.getCoverageAsFloat(); final int result; if (coverA < coverB) { result = -1; } else if (coverA > coverB) { result = 1; } else if (a.getNotCoveredLinesOfCode() > b.getNotCoveredLinesOfCode()) { result = -1; } else if (a.getNotCoveredLinesOfCode() < b.getNotCoveredLinesOfCode()) { result = 1; } else { result = a.compareTo(b); } return result; } } }
package de.tblsoft.solr.pipeline; import com.google.common.base.Strings; import com.quasiris.qsc.writer.QscDataPushWriter; import de.tblsoft.solr.compare.SolrCompareFilter; import de.tblsoft.solr.http.HTTPHelper; import de.tblsoft.solr.pipeline.bean.Document; import de.tblsoft.solr.pipeline.bean.Filter; import de.tblsoft.solr.pipeline.bean.Pipeline; import de.tblsoft.solr.pipeline.bean.Processor; import de.tblsoft.solr.pipeline.bean.Reader; import de.tblsoft.solr.pipeline.filter.*; import de.tblsoft.solr.pipeline.filter.nlp.SearchQueryAnalyzerFilter; import de.tblsoft.solr.pipeline.nlp.squad.SquadReader; import de.tblsoft.solr.pipeline.nlp.squad.SquadWriter; import de.tblsoft.solr.pipeline.processor.DownloadResourcesProcessor; import de.tblsoft.solr.pipeline.processor.Json2SingleDocumentsProcessor; import de.tblsoft.solr.pipeline.processor.NoopProcessor; import de.tblsoft.solr.pipeline.processor.OpenNLPPosTaggerTrainProcessor; import de.tblsoft.solr.pipeline.processor.QSFDataRepositoryUploadProcessor; import de.tblsoft.solr.util.IOUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.File; import java.io.FileInputStream; import java.io.Serializable; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; /** * Created by tblsoft on 23.01.16. */ public class PipelineExecuter implements Serializable { private static Logger LOG = LoggerFactory.getLogger(PipelineExecuter.class); private Pipeline pipeline; private String baseDir; private Map<String, Pipeline> pipelineMap = new HashMap<>(); private String webHookStart; private String webHookEnd; private String webHookError; private List<ProcessorIF> preProcessorList; private List<FilterIF> filterList; private List<ProcessorIF> postProcessorList; private ReaderIF reader; private String yamlFileName; private Map<String, String> pipelineVariables = new HashMap<>(); private String processId; private Long expectedDocumentCount = -1L; private static Map<String, Class> classRegestriy = new HashMap<String, Class>(); static { classRegestriy.put("solrcmdutils.DownloadResourcesProcessor", DownloadResourcesProcessor.class); classRegestriy.put("solrcmdutils.StandardReader", StandardReader.class); classRegestriy.put("solrcmdutils.QSFDataReader", QSFDataReader.class); classRegestriy.put("solrcmdutils.RandomReader", RandomReader.class); classRegestriy.put("solrcmdutils.GrokReader", GrokReader.class); classRegestriy.put("solrcmdutils.GCLogReader", GCLogReader.class); classRegestriy.put("solrcmdutils.JsonPathReader", JsonPathReader.class); classRegestriy.put("solrcmdutils.JsonReader", JsonReader.class); classRegestriy.put("solrcmdutils.ElasticJsonPathReader", ElasticJsonPathReader.class); classRegestriy.put("solrcmdutils.ElasticReader", ElasticReader.class); classRegestriy.put("solrcmdutils.XmlReader", XmlReader.class); classRegestriy.put("solrcmdutils.XmlSitemapReader", XmlSitemapReader.class); classRegestriy.put("solrcmdutils.XmlSitemapWriter", XmlSitemapWriter.class); classRegestriy.put("solrcmdutils.HttpFilter", HttpFilter.class); classRegestriy.put("solrcmdutils.SplashFilter", SplashFilter.class); classRegestriy.put("solrcmdutils.HtmlJsoupFilter", HtmlJsoupFilter.class); classRegestriy.put("solrcmdutils.HtmlFilter", HtmlFilter.class); classRegestriy.put("solrcmdutils.EntityExtractionFilter", EntityExtractionFilter.class); classRegestriy.put("solrcmdutils.ValidationFilter", ValidationFilter.class); classRegestriy.put("solrcmdutils.OpenThesaurusReader", OpenThesaurusReader.class); classRegestriy.put("solrcmdutils.DictionaryNormalizationFilter", DictionaryNormalizationFilter.class); classRegestriy.put("solrcmdutils.ThreadDumpReader", ThreadDumpReader.class); classRegestriy.put("solrcmdutils.DateFilter", DateFilter.class); classRegestriy.put("solrcmdutils.ProcessingTimeFilter", ProcessingTimeFilter.class); classRegestriy.put("solrcmdutils.UrlSplitter", UrlSplitter.class); classRegestriy.put("solrcmdutils.GrepFilter", GrepFilter.class); classRegestriy.put("solrcmdutils.KeyValueSplitterFilter", KeyValueSplitterFilter.class); classRegestriy.put("solrcmdutils.FieldJoiner", FieldJoiner.class); classRegestriy.put("solrcmdutils.DocumentJoinerFilter", DocumentJoinerFilter.class); classRegestriy.put("solrcmdutils.JsonWriter", JsonWriter.class); classRegestriy.put("solrcmdutils.ElasticWriter", ElasticWriter.class); classRegestriy.put("solrcmdutils.CSVReader", CSVReader.class); classRegestriy.put("solrcmdutils.JdbcReader", JdbcReader.class); classRegestriy.put("solrcmdutils.SolrQueryLogReader", SolrQueryLogReader.class); classRegestriy.put("solrcmdutils.SpyFilter", SpyFilter.class); classRegestriy.put("solrcmdutils.StatusFilter", StatusFilter.class); classRegestriy.put("solrcmdutils.StatusTimeFilter", StatusTimeFilter.class); classRegestriy.put("solrcmdutils.ExpectedDocumentCountFilter", ExpectedDocumentCountFilter.class); classRegestriy.put("solrcmdutils.StatisticFilter", StatisticFilter.class); classRegestriy.put("solrcmdutils.MappingFilter", MappingFilter.class); classRegestriy.put("solrcmdutils.ValueMappingFilter", ValueMappingFilter.class); classRegestriy.put("solrcmdutils.EncodingCorrectionFilter", EncodingCorrectionFilter.class); classRegestriy.put("solrcmdutils.RegexSplitFilter", RegexSplitFilter.class); classRegestriy.put("solrcmdutils.RegexFindFilter", RegexFindFilter.class); classRegestriy.put("solrcmdutils.FieldSplitter", FieldSplitter.class); classRegestriy.put("solrcmdutils.Multivalue2DocumentFilter", Multivalue2DocumentFilter.class); classRegestriy.put("solrcmdutils.IgnoreDocumentFilter", IgnoreDocumentFilter.class); classRegestriy.put("solrcmdutils.BeanShellFilter", BeanShellFilter.class); classRegestriy.put("solrcmdutils.LookupFilter", LookupFilter.class); classRegestriy.put("solrcmdutils.TokenCounterFilter", TokenCounterFilter.class); classRegestriy.put("solrcmdutils.TokenizerFilter", TokenizerFilter.class); classRegestriy.put("solrcmdutils.LowercaseFilter", LowercaseFilter.class); classRegestriy.put("solrcmdutils.ShingleFilter", ShingleFilter.class); classRegestriy.put("solrcmdutils.RemoveHtmlFilter", RemoveHtmlFilter.class); classRegestriy.put("solrcmdutils.CharCounterFilter", CharCounterFilter.class); classRegestriy.put("solrcmdutils.CompoundWordFilter", CompoundWordFilter.class); classRegestriy.put("solrcmdutils.LinkCheckerFilter", LinkCheckerFilter.class); classRegestriy.put("solrcmdutils.SolrFeeder", SolrFeeder.class); classRegestriy.put("solrcmdutils.SolrNumFoundFilter", SolrNumFoundFilter.class); classRegestriy.put("solrcmdutils.SolrCompareFilter", SolrCompareFilter.class); classRegestriy.put("solrcmdutils.SystemOutWriter", SystemOutWriter.class); classRegestriy.put("solrcmdutils.NounExtractorFilter", NounExtractorFilter.class); classRegestriy.put("solrcmdutils.FileLineWriter", FileLineWriter.class); classRegestriy.put("solrcmdutils.FilelineReader", FilelineReader.class); classRegestriy.put("solrcmdutils.HtmlFileReader", HtmlFileReader.class); classRegestriy.put("solrcmdutils.CSVWriter", CSVWriter.class); classRegestriy.put("solrcmdutils.N3Writer", N3Writer.class); classRegestriy.put("solrcmdutils.KafkaWriter", KafkaWriter.class); classRegestriy.put("solrcmdutils.TestingFilter", TestingFilter.class); classRegestriy.put("solrcmdutils.NoopFilter", NoopFilter.class); classRegestriy.put("solrcmdutils.DuplicateRemovalFilter", DuplicateRemovalFilter.class); classRegestriy.put("solrcmdutils.ForkDocumentFilter", ForkDocumentFilter.class); classRegestriy.put("solrcmdutils.NetbaseReader", NetbaseReader.class); classRegestriy.put("solrcmdutils.BlacklistTopicFilter", BlacklistTopicFilter.class); classRegestriy.put("solrcmdutils.BlacklistFieldFilter", BlacklistFieldFilter.class); classRegestriy.put("solrcmdutils.WhitelistTopicTermsFilter", WhitelistTopicTermsFilter.class); classRegestriy.put("solrcmdutils.TopicMergeFilter", TopicMergeFilter.class); classRegestriy.put("solrcmdutils.TopicAggregationFilter", TopicAggregationFilter.class); classRegestriy.put("solrcmdutils.AggregationCountFilter", AggregationCountFilter.class); classRegestriy.put("solrcmdutils.ElasticdumpFileWriter", ElasticdumpFileWriter.class); classRegestriy.put("solrcmdutils.DocumentGeneratorReader", DocumentGeneratorReader.class); classRegestriy.put("solrcmdutils.JavaScriptFilter", JavaScriptFilter.class); classRegestriy.put("solrcmdutils.RichJavaScriptFilter", RichJavaScriptFilter.class); classRegestriy.put("solrcmdutils.SimpleGenderFilter", SimpleGenderFilter.class); classRegestriy.put("solrcmdutils.RegexReplaceFilter", RegexReplaceFilter.class); classRegestriy.put("solrcmdutils.EmptyFieldDocumentFilter", EmptyFieldDocumentFilter.class); classRegestriy.put("solrcmdutils.EmptyArrayValuesFilter", EmptyArrayValuesFilter.class); classRegestriy.put("solrcmdutils.FileMathFilter", FileMathFilter.class); classRegestriy.put("solrcmdutils.RoundNumberFilter", RoundNumberFilter.class); classRegestriy.put("solrcmdutils.LibSvmWriter", LibSvmWriter.class); classRegestriy.put("solrcmdutils.ElasticdumpJsonReader", ElasticdumpJsonReader.class); classRegestriy.put("solrcmdutils.RemoveFieldFilter", RemoveFieldFilter.class); classRegestriy.put("solrcmdutils.MessageDigestFilter", MessageDigestFilter.class); classRegestriy.put("solrcmdutils.RandomStaticValueFilter", RandomStaticValueFilter.class); classRegestriy.put("solrcmdutils.SleepFilter", SleepFilter.class); classRegestriy.put("solrcmdutils.OffsetPermutationFilter", OffsetPermutationFilter.class); classRegestriy.put("solrcmdutils.TokenPermutationFilter", TokenPermutationFilter.class); classRegestriy.put("solrcmdutils.RestFilter", RestFilter.class); classRegestriy.put("solrcmdutils.Json2SingleDocumentsProcessor", Json2SingleDocumentsProcessor.class); classRegestriy.put("solrcmdutils.StopwordFilter", StopwordFilter.class); classRegestriy.put("solrcmdutils.NoopProcessor", NoopProcessor.class); classRegestriy.put("solrcmdutils.QSFDataRepositoryUploadProcessor", QSFDataRepositoryUploadProcessor.class); classRegestriy.put("solrcmdutils.HtmlTextExtractorFilter", HtmlTextExtractorFilter.class); classRegestriy.put("solrcmdutils.SquadWriter", SquadWriter.class); classRegestriy.put("solrcmdutils.SquadReader", SquadReader.class); classRegestriy.put("solrcmdutils.OpenNlpPosTagFilter", OpenNlpPosTagFilter.class); classRegestriy.put("solrcmdutils.OpenNlpPosTagWriteTrainingFilter", OpenNlpPosTagWriteTrainingFilter.class); classRegestriy.put("solrcmdutils.OpenNLPPosTaggerTrainProcessor", OpenNLPPosTaggerTrainProcessor.class); classRegestriy.put("solrcmdutils.AddStaticValueFilter", AddStaticValueFilter.class); classRegestriy.put("solrcmdutils.ExcludeByValueFilter", ExcludeByValueFilter.class); classRegestriy.put("solrcmdutils.DocumentReader", DocumentReader.class); classRegestriy.put("solrcmdutils.DocumentWriter", DocumentWriter.class); classRegestriy.put("solrcmdutils.SearchQueryAnalyzerFilter", SearchQueryAnalyzerFilter.class); classRegestriy.put("solrcmdutils.QscDataPushWriter", QscDataPushWriter.class); classRegestriy.put("solrcmdutils.GraphQLReader", GraphQLReader.class); } public PipelineExecuter(String yamlFileName) { this.yamlFileName = yamlFileName; } public PipelineExecuter(Pipeline pipeline, String baseDir) { this.pipeline = pipeline; this.baseDir = baseDir; } private String getBaseDirFromYamlFile() { if(yamlFileName.startsWith("http")) { try { URI uri = new URI(yamlFileName); return uri.resolve(".").toString(); } catch (URISyntaxException e) { throw new RuntimeException(e); } } File f = new File(yamlFileName).getAbsoluteFile(); return f.getParentFile().getAbsoluteFile().toString(); } public void init() { try { if(pipeline == null) { LOG.debug("Read the pipeline configuration from the yaml file: {}", yamlFileName); List<Pipeline> pipelines = readPipelinesFromYamlFile(yamlFileName); for (Pipeline p : pipelines) { // the first pipeline is the main pipeline if (pipeline == null) { pipeline = p; } if (p.getId() != null) { pipelineMap.put(p.getId(), p); } } } if(baseDir == null) { baseDir = getBaseDirFromYamlFile(); } processId = pipeline.getProcessId(); if(Strings.isNullOrEmpty(processId)) { processId = UUID.randomUUID().toString(); } webHookStart = pipeline.getWebHookStart(); webHookEnd = pipeline.getWebHookEnd(); webHookError = pipeline.getWebHookError(); HTTPHelper.webHook(webHookStart, "status", "start", "processId", processId); LOG.debug("processId {}", processId); LOG.debug("Default variables in the pipeline {}", pipeline.getVariables()); LOG.debug("Configured variables in the pipeline {}", pipelineVariables); File settingsPropertiesFile = new File(FileUtils.getUserDirectory().getAbsolutePath() + "/.solr-cmd-utils/settings.properties"); if(settingsPropertiesFile.exists()) { Properties prop = new Properties(); prop.load(new FileInputStream(settingsPropertiesFile)); Map<String, String> settings = new HashMap<>(); prop.forEach((key, value) -> settings.put(key.toString(), value.toString())); pipeline.getVariables().putAll(settings); } pipeline.getVariables().putAll(pipelineVariables); LOG.debug("Effective variables in the pipeline {}", pipeline.getVariables()); reader = createReaderInstance(pipeline.getReader(), baseDir, pipeline.getVariables(), this); preProcessorList = createProcessorInstanceList(pipeline.getPreProcessor()); postProcessorList = createProcessorInstanceList(pipeline.getPostProcessor()); filterList = createFilterInstanceList(); createFilterInstanceList(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } private List<FilterIF> createFilterInstanceList() { List<FilterIF> filterInstanceList = new ArrayList<>(); if(pipeline.getFilter() == null) { return filterInstanceList; } FilterIF lastFilter = null; FilterIF filterInstance = null; for(Filter filter : pipeline.getFilter()) { if(filter.getDisabled() != null && filter.getDisabled()) { continue; } filterInstance = createFilterInstance(filter); filterInstance.setBaseDir(baseDir); filterInstance.setVariables(pipeline.getVariables()); filterInstance.setPipelineExecuter(this); if(lastFilter == null) { lastFilter = filterInstance; continue; } lastFilter.setNextFilter(filterInstance); filterInstanceList.add(lastFilter); lastFilter = filterInstance; } filterInstance.setNextFilter(new LastFilter()); filterInstanceList.add(filterInstance); return filterInstanceList; } public static ReaderIF createReaderInstance(Reader reader, String baseDir, Map<String, String> variables, PipelineExecuter pipelineExecuter) throws ClassNotFoundException, IllegalAccessException, InstantiationException { if(reader == null) { return null; } ReaderIF readerInstance = (ReaderIF) getInstance(reader.getClazz()); readerInstance.setPipelineExecuter(pipelineExecuter); readerInstance.setReader(reader); readerInstance.setBaseDir(baseDir); readerInstance.setVariables(variables); return readerInstance; } private List<ProcessorIF> createProcessorInstanceList(List<Processor> processorList) throws ClassNotFoundException, IllegalAccessException, InstantiationException { List<ProcessorIF> processorInstanceList = new ArrayList<>(); if(processorList == null) { return processorInstanceList; } for(Processor processor : processorList) { if(processor.getDisabled()) { continue; } ProcessorIF processorInstance = (ProcessorIF) getInstance(processor.getClazz()); processorInstance.setProcessor(processor); processorInstance.setVariables(pipeline.getVariables()); processorInstance.setBaseDir(baseDir); processorInstanceList.add(processorInstance); } return processorInstanceList; } public static Object getInstance(String clazz) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class clazzClass = classRegestriy.get(clazz); if(clazzClass != null) { return Class.forName(clazzClass.getName()).newInstance(); } return Class.forName(clazz).newInstance(); } public static FilterIF createFilterInstance(Filter filter) { try { String filterClazz = filter.getClazz(); FilterIF filterInstance = (FilterIF) getInstance(filterClazz); filterInstance.setFilterConfig(filter); return filterInstance; } catch (Exception e) { throw new RuntimeException(e); } } public static void execute(String yamlFileName) { PipelineExecuter pipelineExecuter = new PipelineExecuter(yamlFileName); pipelineExecuter.execute(); } public void execute() { try { LOG.debug("Start the initialization."); init(); LOG.debug("Process the pre processors."); for (ProcessorIF processorIF : preProcessorList) { processorIF.process(); } if (reader != null) { LOG.debug("Start the initialization for all filters."); if (filterList.size() > 0) { filterList.get(0).init(); } LOG.debug("Read the input from the configured reader."); reader.read(); LOG.debug("Finalize the pipeline."); end(); } LOG.debug("Process the post processors."); for (ProcessorIF processorIF : postProcessorList) { processorIF.process(); } HTTPHelper.webHook(webHookEnd, "status", "end", "processId", processId); } catch (Exception e) { onWebhookError(e); throw e; } } private void onWebhookError(Exception exception) { if(!Strings.isNullOrEmpty(webHookError)) { try { String exceptionString = ExceptionUtils.getStackTrace(exception); HTTPHelper.post(webHookError, exceptionString); } catch (Exception e) { LOG.error("Could not call the error webHookError {} because {}", webHookError, e.getMessage(), e ); // fail silent } } } //public void field(String name, String value) { // filterList.get(0).field(name, value); //} public void document(Document document) { filterList.get(0).document(document); } public void end() { reader.end(); filterList.get(0).end(); } /** * Use readPipelinesFromYamlFile. It is possible to define multiple pipeline in one file. * @param fileName the fileName of the pipeline * @return the first pipeline. */ @Deprecated public static Pipeline readPipelineFromYamlFile(String fileName) { try { List<Pipeline> pipelines = readPipelinesFromYamlFile(fileName); if(pipelines == null || pipelines.size() == 0) { return null; } return pipelines.get(0); } catch (Exception e) { throw new RuntimeException(e); } } public static List<Pipeline> readPipelinesFromYamlFile(String fileName) { try { Yaml yaml = new Yaml(new Constructor(Pipeline.class)); String pipelineString = IOUtils.getString(fileName); LOG.info("pipeline:\n" + pipelineString); Iterable<Object> pipelines = yaml.loadAll(pipelineString); List<Pipeline> ret = new ArrayList<>(); for(Object obj : pipelines) { ret.add((Pipeline) obj); } return ret; } catch (Exception e) { throw new RuntimeException(e); } } public List<FilterIF> getFilterList() { return filterList; } public FilterIF getFilterById(String filterId) { for(FilterIF filter : getFilterList()) { if(filterId.equals(filter.getId())) { return filter; } } throw new IllegalArgumentException("The filter with the id: " + filterId + " does not exists."); } public ReaderIF getReader() { return this.reader; } public Map<String, String> getPipelineVariables() { return pipelineVariables; } public void setPipelineVariables(Map<String, String> pipelineVariables) { this.pipelineVariables = pipelineVariables; } public void addPipelineVariable(String name, String value) { this.pipelineVariables.put(name, value); } public String getProcessId() { return processId; } public void setProcessId(String processId) { this.processId = processId; } /** * Getter for property 'expectedDocumentCount'. * * @return Value for property 'expectedDocumentCount'. */ public Long getExpectedDocumentCount() { return expectedDocumentCount; } /** * Setter for property 'expectedDocumentCount'. * * @param expectedDocumentCount Value to set for property 'expectedDocumentCount'. */ public void setExpectedDocumentCount(Long expectedDocumentCount) { this.expectedDocumentCount = expectedDocumentCount; } public Pipeline getPipeline(String id) { return pipelineMap.get(id); } }
/* * Copyright (C) 2009 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 edu.ccggt.cogphone; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; /** * This class does all the work for setting up and managing Bluetooth * connections with other devices. It has a thread that listens for * incoming connections, a thread for connecting with a device, and a * thread for performing data transmissions when connected. */ public class BluetoothChatService { // Debugging private static final String TAG = "BluetoothChatService"; private static final boolean D = true; // Name for the SDP record when creating server socket private static final String NAME_SECURE = "BluetoothChatSecure"; private static final String NAME_INSECURE = "BluetoothChatInsecure"; // Unique UUID for this application private static final UUID MY_UUID_SECURE = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); // Member fields private final BluetoothAdapter mAdapter; private final Handler mHandler; private AcceptThread mSecureAcceptThread; private AcceptThread mInsecureAcceptThread; private ConnectThread mConnectThread; private ConnectedThread mConnectedThread; private int mState; // Constants that indicate the current connection state public static final int STATE_NONE = 0; // we're doing nothing public static final int STATE_LISTEN = 1; // now listening for incoming connections public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection public static final int STATE_CONNECTED = 3; // now connected to a remote device /** * Constructor. Prepares a new BluetoothChat session. * @param context The UI Activity Context * @param handler A Handler to send messages back to the UI Activity */ public BluetoothChatService(Context context, Handler handler) { mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; mHandler = handler; } /** * Set the current state of the chat connection * @param state An integer defining the current connection state */ private synchronized void setState(int state) { if (D) Log.d(TAG, "setState() " + mState + " -> " + state); mState = state; // Give the new state to the Handler so the UI Activity can update mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget(); } /** * Return the current connection state. */ public synchronized int getState() { return mState; } /** * Start the chat service. Specifically start AcceptThread to begin a * session in listening (server) mode. Called by the Activity onResume() */ public synchronized void start() { if (D) Log.d(TAG, "start"); // Cancel any thread attempting to make a connection if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} // Cancel any thread currently running a connection if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // setState(STATE_LISTEN); // // // Start the thread to listen on a BluetoothServerSocket // if (mSecureAcceptThread == null) { // mSecureAcceptThread = new AcceptThread(true); // mSecureAcceptThread.start(); // } // if (mInsecureAcceptThread == null) { // mInsecureAcceptThread = new AcceptThread(false); // mInsecureAcceptThread.start(); // } } /** * Start the ConnectThread to initiate a connection to a remote device. * @param device The BluetoothDevice to connect * @param secure Socket Security type - Secure (true) , Insecure (false) */ public synchronized void connect(BluetoothDevice device, boolean secure) { if (D) Log.d(TAG, "connect to: " + device); // Cancel any thread attempting to make a connection if (mState == STATE_CONNECTING) { if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} } // Cancel any thread currently running a connection if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // Start the thread to connect with the given device mConnectThread = new ConnectThread(device, secure); mConnectThread.start(); setState(STATE_CONNECTING); } /** * Start the ConnectedThread to begin managing a Bluetooth connection * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) { if (D) Log.d(TAG, "connected, Socket Type:" + socketType); // Cancel the thread that completed the connection if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;} // Cancel any thread currently running a connection if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;} // Cancel the accept thread because we only want to connect to one device if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket, socketType); mConnectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(BluetoothChat.DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); } /** * Stop all threads */ public synchronized void stop() { if (D) Log.d(TAG, "stop"); if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } setState(STATE_NONE); } /** * Write to the ConnectedThread in an unsynchronized manner * @param out The bytes to write * @see ConnectedThread#write(byte[]) */ public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (mState != STATE_CONNECTED) return; r = mConnectedThread; } // Perform the write unsynchronized r.write(out); } /** * Indicate that the connection attempt failed and notify the UI Activity. */ private void connectionFailed() { // Send a failure message back to the Activity Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(BluetoothChat.TOAST, "Unable to connect device"); msg.setData(bundle); mHandler.sendMessage(msg); // Start the service over to restart listening mode BluetoothChatService.this.start(); } /** * Indicate that the connection was lost and notify the UI Activity. */ private void connectionLost() { // Send a failure message back to the Activity Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(BluetoothChat.TOAST, "Device connection was lost"); msg.setData(bundle); mHandler.sendMessage(msg); // Start the service over to restart listening mode BluetoothChatService.this.start(); } /** * This thread runs while listening for incoming connections. It behaves * like a server-side client. It runs until a connection is accepted * (or until cancelled). */ private class AcceptThread extends Thread { // The local server socket private final BluetoothServerSocket mmServerSocket; private String mSocketType; public AcceptThread(boolean secure) { BluetoothServerSocket tmp = null; mSocketType = secure ? "Secure":"Insecure"; // Create a new listening server socket try { if (secure) { tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE); } else { tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord( NAME_INSECURE, MY_UUID_INSECURE); } } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e); } mmServerSocket = tmp; } public void run() { if (D) Log.d(TAG, "Socket Type: " + mSocketType + "BEGIN mAcceptThread" + this); setName("AcceptThread" + mSocketType); BluetoothSocket socket = null; // Listen to the server socket if we're not connected while (mState != STATE_CONNECTED) { try { // This is a blocking call and will only return on a // successful connection or an exception socket = mmServerSocket.accept(); } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e); break; } // If a connection was accepted if (socket != null) { synchronized (BluetoothChatService.this) { switch (mState) { case STATE_LISTEN: case STATE_CONNECTING: // Situation normal. Start the connected thread. connected(socket, socket.getRemoteDevice(), mSocketType); break; case STATE_NONE: case STATE_CONNECTED: // Either not ready or already connected. Terminate new socket. try { socket.close(); } catch (IOException e) { Log.e(TAG, "Could not close unwanted socket", e); } break; } } } } if (D) Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType); } public void cancel() { if (D) Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this); try { mmServerSocket.close(); } catch (IOException e) { Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e); } } } /** * This thread runs while attempting to make an outgoing connection * with a device. It runs straight through; the connection either * succeeds or fails. */ private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; private String mSocketType; public ConnectThread(BluetoothDevice device, boolean secure) { mmDevice = device; BluetoothSocket tmp = null; mSocketType = secure ? "Secure" : "Insecure"; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try { if (secure) { tmp = device.createRfcommSocketToServiceRecord( MY_UUID_SECURE); } else { tmp = device.createInsecureRfcommSocketToServiceRecord( MY_UUID_INSECURE); } } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e); } mmSocket = tmp; } public void run() { Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType); setName("ConnectThread" + mSocketType); // Always cancel discovery because it will slow down a connection mAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception mmSocket.connect(); } catch (IOException e) { // Close the socket try { mmSocket.close(); } catch (IOException e2) { Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e2); } connectionFailed(); return; } // Reset the ConnectThread because we're done synchronized (BluetoothChatService.this) { mConnectThread = null; } // Start the connected thread connected(mmSocket, mmDevice, mSocketType); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e); } } } /** * This thread runs during a connection with a remote device. * It handles all incoming and outgoing transmissions. */ private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket, String socketType) { Log.d(TAG, "create ConnectedThread: " + socketType); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); // Start the service over to restart listening mode BluetoothChatService.this.start(); break; } } } /** * Write to the connected OutStream. * @param buffer The bytes to write */ public void write(byte[] buffer) { try { mmOutStream.write(buffer); // Share the sent message back to the UI Activity mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } }
/** * 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.tools.rumen; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hadoop.mapred.TaskStatus; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskType; import org.apache.hadoop.mapreduce.jobhistory.AMStartedEvent; import org.apache.hadoop.mapreduce.jobhistory.HistoryEvent; import org.apache.hadoop.mapreduce.jobhistory.JobFinished; import org.apache.hadoop.mapreduce.jobhistory.JobFinishedEvent; import org.apache.hadoop.mapreduce.jobhistory.JobInfoChangeEvent; import org.apache.hadoop.mapreduce.jobhistory.JobInitedEvent; import org.apache.hadoop.mapreduce.jobhistory.JobPriorityChangeEvent; import org.apache.hadoop.mapreduce.jobhistory.JobStatusChangedEvent; import org.apache.hadoop.mapreduce.jobhistory.JobSubmittedEvent; import org.apache.hadoop.mapreduce.jobhistory.JobUnsuccessfulCompletionEvent; import org.apache.hadoop.mapreduce.jobhistory.MapAttemptFinished; import org.apache.hadoop.mapreduce.jobhistory.MapAttemptFinishedEvent; import org.apache.hadoop.mapreduce.jobhistory.ReduceAttemptFinished; import org.apache.hadoop.mapreduce.jobhistory.ReduceAttemptFinishedEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskAttemptFinished; import org.apache.hadoop.mapreduce.jobhistory.TaskAttemptFinishedEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskAttemptStartedEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskAttemptUnsuccessfulCompletion; import org.apache.hadoop.mapreduce.jobhistory.TaskAttemptUnsuccessfulCompletionEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskFailed; import org.apache.hadoop.mapreduce.jobhistory.TaskFailedEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskFinished; import org.apache.hadoop.mapreduce.jobhistory.TaskFinishedEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskStartedEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskUpdatedEvent; import org.apache.hadoop.tools.rumen.Pre21JobHistoryConstants.Values; import org.apache.hadoop.util.StringUtils; /** * {@link JobBuilder} builds one job. It processes a sequence of * {@link HistoryEvent}s. */ public class JobBuilder { private static final long BYTES_IN_MEG = StringUtils.TraditionalBinaryPrefix.string2long("1m"); private String jobID; private boolean finalized = false; private ParsedJob result = new ParsedJob(); private Map<String, ParsedTask> mapTasks = new HashMap<String, ParsedTask>(); private Map<String, ParsedTask> reduceTasks = new HashMap<String, ParsedTask>(); private Map<String, ParsedTask> otherTasks = new HashMap<String, ParsedTask>(); private Map<String, ParsedTaskAttempt> attempts = new HashMap<String, ParsedTaskAttempt>(); private Map<ParsedHost, ParsedHost> allHosts = new HashMap<ParsedHost, ParsedHost>(); /** * The number of splits a task can have, before we ignore them all. */ private final static int MAXIMUM_PREFERRED_LOCATIONS = 25; private int[] attemptTimesPercentiles = null; // Use this to search within the java options to get heap sizes. // The heap size number is in Capturing Group 1. // The heap size order-of-magnitude suffix is in Capturing Group 2 private static final Pattern heapPattern = Pattern.compile("-Xmx([0-9]+[kKmMgGtT])"); private Properties jobConfigurationParameters = null; public JobBuilder(String jobID) { this.jobID = jobID; } public String getJobID() { return jobID; } { if (attemptTimesPercentiles == null) { attemptTimesPercentiles = new int[19]; for (int i = 0; i < 19; ++i) { attemptTimesPercentiles[i] = (i + 1) * 5; } } } /** * Process one {@link HistoryEvent} * * @param event * The {@link HistoryEvent} to be processed. */ public void process(HistoryEvent event) { if (finalized) { throw new IllegalStateException( "JobBuilder.process(HistoryEvent event) called after ParsedJob built"); } // these are in lexicographical order by class name. if (event instanceof AMStartedEvent) { // ignore this event as Rumen currently doesnt need this event //TODO Enhance Rumen to process this event and capture restarts return; } else if (event instanceof JobFinishedEvent) { processJobFinishedEvent((JobFinishedEvent) event); } else if (event instanceof JobInfoChangeEvent) { processJobInfoChangeEvent((JobInfoChangeEvent) event); } else if (event instanceof JobInitedEvent) { processJobInitedEvent((JobInitedEvent) event); } else if (event instanceof JobPriorityChangeEvent) { processJobPriorityChangeEvent((JobPriorityChangeEvent) event); } else if (event instanceof JobStatusChangedEvent) { processJobStatusChangedEvent((JobStatusChangedEvent) event); } else if (event instanceof JobSubmittedEvent) { processJobSubmittedEvent((JobSubmittedEvent) event); } else if (event instanceof JobUnsuccessfulCompletionEvent) { processJobUnsuccessfulCompletionEvent((JobUnsuccessfulCompletionEvent) event); } else if (event instanceof MapAttemptFinishedEvent) { processMapAttemptFinishedEvent((MapAttemptFinishedEvent) event); } else if (event instanceof ReduceAttemptFinishedEvent) { processReduceAttemptFinishedEvent((ReduceAttemptFinishedEvent) event); } else if (event instanceof TaskAttemptFinishedEvent) { processTaskAttemptFinishedEvent((TaskAttemptFinishedEvent) event); } else if (event instanceof TaskAttemptStartedEvent) { processTaskAttemptStartedEvent((TaskAttemptStartedEvent) event); } else if (event instanceof TaskAttemptUnsuccessfulCompletionEvent) { processTaskAttemptUnsuccessfulCompletionEvent((TaskAttemptUnsuccessfulCompletionEvent) event); } else if (event instanceof TaskFailedEvent) { processTaskFailedEvent((TaskFailedEvent) event); } else if (event instanceof TaskFinishedEvent) { processTaskFinishedEvent((TaskFinishedEvent) event); } else if (event instanceof TaskStartedEvent) { processTaskStartedEvent((TaskStartedEvent) event); } else if (event instanceof TaskUpdatedEvent) { processTaskUpdatedEvent((TaskUpdatedEvent) event); } else throw new IllegalArgumentException( "JobBuilder.process(HistoryEvent): unknown event type"); } static String extract(Properties conf, String[] names, String defaultValue) { for (String name : names) { String result = conf.getProperty(name); if (result != null) { return result; } } return defaultValue; } private Integer extractMegabytes(Properties conf, String[] names) { String javaOptions = extract(conf, names, null); if (javaOptions == null) { return null; } Matcher matcher = heapPattern.matcher(javaOptions); Integer heapMegabytes = null; while (matcher.find()) { String heapSize = matcher.group(1); heapMegabytes = ((int) (StringUtils.TraditionalBinaryPrefix.string2long(heapSize) / BYTES_IN_MEG)); } return heapMegabytes; } private void maybeSetHeapMegabytes(Integer megabytes) { if (megabytes != null) { result.setHeapMegabytes(megabytes); } } private void maybeSetJobMapMB(Integer megabytes) { if (megabytes != null) { result.setJobMapMB(megabytes); } } private void maybeSetJobReduceMB(Integer megabytes) { if (megabytes != null) { result.setJobReduceMB(megabytes); } } /** * Process a collection of JobConf {@link Properties}. We do not restrict it * to be called once. It is okay to process a conf before, during or after the * events. * * @param conf * The job conf properties to be added. */ public void process(Properties conf) { if (finalized) { throw new IllegalStateException( "JobBuilder.process(Properties conf) called after ParsedJob built"); } //TODO remove this once the deprecate APIs in LoggedJob are removed String queue = extract(conf, JobConfPropertyNames.QUEUE_NAMES .getCandidates(), null); // set the queue name if existing if (queue != null) { result.setQueue(queue); } result.setJobName(extract(conf, JobConfPropertyNames.JOB_NAMES .getCandidates(), null)); maybeSetHeapMegabytes(extractMegabytes(conf, JobConfPropertyNames.TASK_JAVA_OPTS_S.getCandidates())); maybeSetJobMapMB(extractMegabytes(conf, JobConfPropertyNames.MAP_JAVA_OPTS_S.getCandidates())); maybeSetJobReduceMB(extractMegabytes(conf, JobConfPropertyNames.REDUCE_JAVA_OPTS_S.getCandidates())); this.jobConfigurationParameters = conf; } /** * Request the builder to build the final object. Once called, the * {@link JobBuilder} would accept no more events or job-conf properties. * * @return Parsed {@link ParsedJob} object. */ public ParsedJob build() { // The main job here is to build CDFs and manage the conf finalized = true; // set the conf if (jobConfigurationParameters != null) { result.setJobProperties(jobConfigurationParameters); } // initialize all the per-job statistics gathering places Histogram[] successfulMapAttemptTimes = new Histogram[ParsedHost.numberOfDistances() + 1]; for (int i = 0; i < successfulMapAttemptTimes.length; ++i) { successfulMapAttemptTimes[i] = new Histogram(); } Histogram successfulReduceAttemptTimes = new Histogram(); Histogram[] failedMapAttemptTimes = new Histogram[ParsedHost.numberOfDistances() + 1]; for (int i = 0; i < failedMapAttemptTimes.length; ++i) { failedMapAttemptTimes[i] = new Histogram(); } Histogram failedReduceAttemptTimes = new Histogram(); Histogram successfulNthMapperAttempts = new Histogram(); // Histogram successfulNthReducerAttempts = new Histogram(); // Histogram mapperLocality = new Histogram(); for (LoggedTask task : result.getMapTasks()) { for (LoggedTaskAttempt attempt : task.getAttempts()) { int distance = successfulMapAttemptTimes.length - 1; Long runtime = null; if (attempt.getFinishTime() > 0 && attempt.getStartTime() > 0) { runtime = attempt.getFinishTime() - attempt.getStartTime(); if (attempt.getResult() == Values.SUCCESS) { LoggedLocation host = attempt.getLocation(); List<LoggedLocation> locs = task.getPreferredLocations(); if (host != null && locs != null) { for (LoggedLocation loc : locs) { ParsedHost preferedLoc = new ParsedHost(loc); distance = Math.min(distance, preferedLoc .distance(new ParsedHost(host))); } // mapperLocality.enter(distance); } if (attempt.getStartTime() > 0 && attempt.getFinishTime() > 0) { if (runtime != null) { successfulMapAttemptTimes[distance].enter(runtime); } } TaskAttemptID attemptID = attempt.getAttemptID(); if (attemptID != null) { successfulNthMapperAttempts.enter(attemptID.getId()); } } else { if (attempt.getResult() == Pre21JobHistoryConstants.Values.FAILED) { if (runtime != null) { failedMapAttemptTimes[distance].enter(runtime); } } } } } } for (LoggedTask task : result.getReduceTasks()) { for (LoggedTaskAttempt attempt : task.getAttempts()) { Long runtime = attempt.getFinishTime() - attempt.getStartTime(); if (attempt.getFinishTime() > 0 && attempt.getStartTime() > 0) { runtime = attempt.getFinishTime() - attempt.getStartTime(); } if (attempt.getResult() == Values.SUCCESS) { if (runtime != null) { successfulReduceAttemptTimes.enter(runtime); } } else if (attempt.getResult() == Pre21JobHistoryConstants.Values.FAILED) { failedReduceAttemptTimes.enter(runtime); } } } result.setFailedMapAttemptCDFs(mapCDFArrayList(failedMapAttemptTimes)); LoggedDiscreteCDF failedReduce = new LoggedDiscreteCDF(); failedReduce.setCDF(failedReduceAttemptTimes, attemptTimesPercentiles, 100); result.setFailedReduceAttemptCDF(failedReduce); result .setSuccessfulMapAttemptCDFs(mapCDFArrayList(successfulMapAttemptTimes)); LoggedDiscreteCDF succReduce = new LoggedDiscreteCDF(); succReduce.setCDF(successfulReduceAttemptTimes, attemptTimesPercentiles, 100); result.setSuccessfulReduceAttemptCDF(succReduce); long totalSuccessfulAttempts = 0L; long maxTriesToSucceed = 0L; for (Map.Entry<Long, Long> ent : successfulNthMapperAttempts) { totalSuccessfulAttempts += ent.getValue(); maxTriesToSucceed = Math.max(maxTriesToSucceed, ent.getKey()); } if (totalSuccessfulAttempts > 0L) { double[] successAfterI = new double[(int) maxTriesToSucceed + 1]; for (int i = 0; i < successAfterI.length; ++i) { successAfterI[i] = 0.0D; } for (Map.Entry<Long, Long> ent : successfulNthMapperAttempts) { successAfterI[ent.getKey().intValue()] = ((double) ent.getValue()) / totalSuccessfulAttempts; } result.setMapperTriesToSucceed(successAfterI); } else { result.setMapperTriesToSucceed(null); } return result; } private ArrayList<LoggedDiscreteCDF> mapCDFArrayList(Histogram[] data) { ArrayList<LoggedDiscreteCDF> result = new ArrayList<LoggedDiscreteCDF>(); for (Histogram hist : data) { LoggedDiscreteCDF discCDF = new LoggedDiscreteCDF(); discCDF.setCDF(hist, attemptTimesPercentiles, 100); result.add(discCDF); } return result; } private static Values getPre21Value(String name) { if (name.equalsIgnoreCase("JOB_CLEANUP")) { return Values.CLEANUP; } if (name.equalsIgnoreCase("JOB_SETUP")) { return Values.SETUP; } // Note that pre-21, the task state of a successful task was logged as // SUCCESS while from 21 onwards, its logged as SUCCEEDED. if (name.equalsIgnoreCase(TaskStatus.State.SUCCEEDED.toString())) { return Values.SUCCESS; } return Values.valueOf(name.toUpperCase()); } private void processTaskUpdatedEvent(TaskUpdatedEvent event) { ParsedTask task = getTask(event.getTaskId().toString()); if (task == null) { return; } task.setFinishTime(event.getFinishTime()); } private void processTaskStartedEvent(TaskStartedEvent event) { ParsedTask task = getOrMakeTask(event.getTaskType(), event.getTaskId().toString(), true); task.setStartTime(event.getStartTime()); task.setPreferredLocations(preferredLocationForSplits(event .getSplitLocations())); } private void processTaskFinishedEvent(TaskFinishedEvent event) { ParsedTask task = getOrMakeTask(event.getTaskType(), event.getTaskId().toString(), false); if (task == null) { return; } task.setFinishTime(event.getFinishTime()); task.setTaskStatus(getPre21Value(event.getTaskStatus())); task.incorporateCounters(((TaskFinished) event.getDatum()).counters); } private void processTaskFailedEvent(TaskFailedEvent event) { ParsedTask task = getOrMakeTask(event.getTaskType(), event.getTaskId().toString(), false); if (task == null) { return; } task.setFinishTime(event.getFinishTime()); task.setTaskStatus(getPre21Value(event.getTaskStatus())); TaskFailed t = (TaskFailed)(event.getDatum()); task.putDiagnosticInfo(t.error.toString()); task.putFailedDueToAttemptId(t.failedDueToAttempt.toString()); // No counters in TaskFailedEvent } private void processTaskAttemptUnsuccessfulCompletionEvent( TaskAttemptUnsuccessfulCompletionEvent event) { ParsedTaskAttempt attempt = getOrMakeTaskAttempt(event.getTaskType(), event.getTaskId().toString(), event.getTaskAttemptId().toString()); if (attempt == null) { return; } attempt.setResult(getPre21Value(event.getTaskStatus())); attempt.setHostName(event.getHostname(), event.getRackName()); ParsedHost pHost = getAndRecordParsedHost(event.getRackName(), event.getHostname()); if (pHost != null) { attempt.setLocation(pHost.makeLoggedLocation()); } attempt.setFinishTime(event.getFinishTime()); attempt.arraySetClockSplits(event.getClockSplits()); attempt.arraySetCpuUsages(event.getCpuUsages()); attempt.arraySetVMemKbytes(event.getVMemKbytes()); attempt.arraySetPhysMemKbytes(event.getPhysMemKbytes()); TaskAttemptUnsuccessfulCompletion t = (TaskAttemptUnsuccessfulCompletion) (event.getDatum()); attempt.putDiagnosticInfo(t.error.toString()); // No counters in TaskAttemptUnsuccessfulCompletionEvent } private void processTaskAttemptStartedEvent(TaskAttemptStartedEvent event) { ParsedTaskAttempt attempt = getOrMakeTaskAttempt(event.getTaskType(), event.getTaskId().toString(), event.getTaskAttemptId().toString()); if (attempt == null) { return; } attempt.setStartTime(event.getStartTime()); attempt.putTrackerName(event.getTrackerName()); attempt.putHttpPort(event.getHttpPort()); attempt.putShufflePort(event.getShufflePort()); } private void processTaskAttemptFinishedEvent(TaskAttemptFinishedEvent event) { ParsedTaskAttempt attempt = getOrMakeTaskAttempt(event.getTaskType(), event.getTaskId().toString(), event.getAttemptId().toString()); if (attempt == null) { return; } attempt.setResult(getPre21Value(event.getTaskStatus())); ParsedHost pHost = getAndRecordParsedHost(event.getRackName(), event.getHostname()); if (pHost != null) { attempt.setLocation(pHost.makeLoggedLocation()); } attempt.setFinishTime(event.getFinishTime()); attempt .incorporateCounters(((TaskAttemptFinished) event.getDatum()).counters); } private void processReduceAttemptFinishedEvent( ReduceAttemptFinishedEvent event) { ParsedTaskAttempt attempt = getOrMakeTaskAttempt(event.getTaskType(), event.getTaskId().toString(), event.getAttemptId().toString()); if (attempt == null) { return; } attempt.setResult(getPre21Value(event.getTaskStatus())); attempt.setHostName(event.getHostname(), event.getRackName()); ParsedHost pHost = getAndRecordParsedHost(event.getRackName(), event.getHostname()); if (pHost != null) { attempt.setLocation(pHost.makeLoggedLocation()); } // XXX There may be redundant location info available in the event. // We might consider extracting it from this event. Currently this // is redundant, but making this will add future-proofing. attempt.setFinishTime(event.getFinishTime()); attempt.setShuffleFinished(event.getShuffleFinishTime()); attempt.setSortFinished(event.getSortFinishTime()); attempt .incorporateCounters(((ReduceAttemptFinished) event.getDatum()).counters); attempt.arraySetClockSplits(event.getClockSplits()); attempt.arraySetCpuUsages(event.getCpuUsages()); attempt.arraySetVMemKbytes(event.getVMemKbytes()); attempt.arraySetPhysMemKbytes(event.getPhysMemKbytes()); } private void processMapAttemptFinishedEvent(MapAttemptFinishedEvent event) { ParsedTaskAttempt attempt = getOrMakeTaskAttempt(event.getTaskType(), event.getTaskId().toString(), event.getAttemptId().toString()); if (attempt == null) { return; } attempt.setResult(getPre21Value(event.getTaskStatus())); attempt.setHostName(event.getHostname(), event.getRackName()); ParsedHost pHost = getAndRecordParsedHost(event.getRackName(), event.getHostname()); if (pHost != null) { attempt.setLocation(pHost.makeLoggedLocation()); } // XXX There may be redundant location info available in the event. // We might consider extracting it from this event. Currently this // is redundant, but making this will add future-proofing. attempt.setFinishTime(event.getFinishTime()); attempt .incorporateCounters(((MapAttemptFinished) event.getDatum()).counters); attempt.arraySetClockSplits(event.getClockSplits()); attempt.arraySetCpuUsages(event.getCpuUsages()); attempt.arraySetVMemKbytes(event.getVMemKbytes()); attempt.arraySetPhysMemKbytes(event.getPhysMemKbytes()); } private void processJobUnsuccessfulCompletionEvent( JobUnsuccessfulCompletionEvent event) { result.setOutcome(Pre21JobHistoryConstants.Values .valueOf(event.getStatus())); result.setFinishTime(event.getFinishTime()); // No counters in JobUnsuccessfulCompletionEvent } private void processJobSubmittedEvent(JobSubmittedEvent event) { result.setJobID(event.getJobId().toString()); result.setJobName(event.getJobName()); result.setUser(event.getUserName()); result.setSubmitTime(event.getSubmitTime()); result.putJobConfPath(event.getJobConfPath()); result.putJobAcls(event.getJobAcls()); // set the queue name if existing String queue = event.getJobQueueName(); if (queue != null) { result.setQueue(queue); } } private void processJobStatusChangedEvent(JobStatusChangedEvent event) { result.setOutcome(Pre21JobHistoryConstants.Values .valueOf(event.getStatus())); } private void processJobPriorityChangeEvent(JobPriorityChangeEvent event) { result.setPriority(LoggedJob.JobPriority.valueOf(event.getPriority() .toString())); } private void processJobInitedEvent(JobInitedEvent event) { result.setLaunchTime(event.getLaunchTime()); result.setTotalMaps(event.getTotalMaps()); result.setTotalReduces(event.getTotalReduces()); } private void processJobInfoChangeEvent(JobInfoChangeEvent event) { result.setLaunchTime(event.getLaunchTime()); } private void processJobFinishedEvent(JobFinishedEvent event) { result.setFinishTime(event.getFinishTime()); result.setJobID(jobID); result.setOutcome(Values.SUCCESS); JobFinished job = (JobFinished)event.getDatum(); Map<String, Long> countersMap = JobHistoryUtils.extractCounters(job.totalCounters); result.putTotalCounters(countersMap); countersMap = JobHistoryUtils.extractCounters(job.mapCounters); result.putMapCounters(countersMap); countersMap = JobHistoryUtils.extractCounters(job.reduceCounters); result.putReduceCounters(countersMap); } private ParsedTask getTask(String taskIDname) { ParsedTask result = mapTasks.get(taskIDname); if (result != null) { return result; } result = reduceTasks.get(taskIDname); if (result != null) { return result; } return otherTasks.get(taskIDname); } /** * @param type * the task type * @param taskIDname * the task ID name, as a string * @param allowCreate * if true, we can create a task. * @return */ private ParsedTask getOrMakeTask(TaskType type, String taskIDname, boolean allowCreate) { Map<String, ParsedTask> taskMap = otherTasks; List<LoggedTask> tasks = this.result.getOtherTasks(); switch (type) { case MAP: taskMap = mapTasks; tasks = this.result.getMapTasks(); break; case REDUCE: taskMap = reduceTasks; tasks = this.result.getReduceTasks(); break; default: // no code } ParsedTask result = taskMap.get(taskIDname); if (result == null && allowCreate) { result = new ParsedTask(); result.setTaskType(getPre21Value(type.toString())); result.setTaskID(taskIDname); taskMap.put(taskIDname, result); tasks.add(result); } return result; } private ParsedTaskAttempt getOrMakeTaskAttempt(TaskType type, String taskIDName, String taskAttemptName) { ParsedTask task = getOrMakeTask(type, taskIDName, false); ParsedTaskAttempt result = attempts.get(taskAttemptName); if (result == null && task != null) { result = new ParsedTaskAttempt(); result.setAttemptID(taskAttemptName); attempts.put(taskAttemptName, result); task.getAttempts().add(result); } return result; } private ParsedHost getAndRecordParsedHost(String hostName) { return getAndRecordParsedHost(null, hostName); } private ParsedHost getAndRecordParsedHost(String rackName, String hostName) { ParsedHost result = null; if (rackName == null) { // for old (pre-23) job history files where hostname was represented as // /rackname/hostname result = ParsedHost.parse(hostName); } else { // for new (post-23) job history files result = new ParsedHost(rackName, hostName); } if (result != null) { ParsedHost canonicalResult = allHosts.get(result); if (canonicalResult != null) { return canonicalResult; } allHosts.put(result, result); return result; } return null; } private ArrayList<LoggedLocation> preferredLocationForSplits(String splits) { if (splits != null) { ArrayList<LoggedLocation> locations = null; StringTokenizer tok = new StringTokenizer(splits, ",", false); if (tok.countTokens() <= MAXIMUM_PREFERRED_LOCATIONS) { locations = new ArrayList<LoggedLocation>(); while (tok.hasMoreTokens()) { String nextSplit = tok.nextToken(); ParsedHost node = getAndRecordParsedHost(nextSplit); if (locations != null && node != null) { locations.add(node.makeLoggedLocation()); } } return locations; } } return null; } }
/* * 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.joshua.metrics; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; // Changed PROCore.java (text normalization function) and EvaluationMetric too import java.util.Map; import java.util.logging.Logger; /*** * Implementation of the SARI metric for text-to-text correction. * * \@article{xu2016optimizing, * title={Optimizing statistical machine translation for text simplification}, * author={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, * journal={Transactions of the Association for Computational Linguistics}, * volume={4}, * year={2016}} * * @author Wei Xu */ public class SARI extends EvaluationMetric { private static final Logger logger = Logger.getLogger(SARI.class.getName()); // The maximum n-gram we care about protected int maxGramLength; protected String[] srcSentences; protected double[] weights; protected HashMap<String, Integer>[][] refNgramCounts; protected HashMap<String, Integer>[][] srcNgramCounts; /* * You already have access to these data members of the parent class (EvaluationMetric): int * numSentences; number of sentences in the MERT set int refsPerSen; number of references per * sentence String[][] refSentences; refSentences[i][r] stores the r'th reference of the i'th * source sentence (both indices are 0-based) */ public SARI(String[] Metric_options) { int mxGrmLn = Integer.parseInt(Metric_options[0]); if (mxGrmLn >= 1) { maxGramLength = mxGrmLn; } else { logger.severe("Maximum gram length must be positive"); System.exit(1); } try { loadSources(Metric_options[1]); } catch (IOException e) { logger.severe("Error loading the source sentences from " + Metric_options[1]); System.exit(1); } initialize(); // set the data members of the metric } @Override protected void initialize() { metricName = "SARI"; toBeMinimized = false; suffStatsCount = StatIndex.values().length * maxGramLength + 1; set_weightsArray(); set_refNgramCounts(); set_srcNgramCounts(); } @Override public double bestPossibleScore() { return 1.0; } @Override public double worstPossibleScore() { return 0.0; } /** * Sets the BLEU weights for each n-gram level to uniform. */ protected void set_weightsArray() { weights = new double[1 + maxGramLength]; for (int n = 1; n <= maxGramLength; ++n) { weights[n] = 1.0 / maxGramLength; } } /** * Computes the sum of ngram counts in references for each sentence (storing them in * <code>refNgramCounts</code>), which are used for clipping n-gram counts. */ protected void set_refNgramCounts() { @SuppressWarnings("unchecked") HashMap<String, Integer>[][] temp_HMA = new HashMap[numSentences][maxGramLength]; refNgramCounts = temp_HMA; String gram; int oldCount, nextCount; for (int i = 0; i < numSentences; ++i) { refNgramCounts[i] = getNgramCountsArray(refSentences[i][0]); // initialize to ngramCounts[n] of the first reference translation... // ...and update as necessary from the other reference translations for (int r = 1; r < refsPerSen; ++r) { HashMap<String, Integer>[] nextNgramCounts = getNgramCountsArray(refSentences[i][r]); for (int n = 1; n <= maxGramLength; ++n) { for (String s : (nextNgramCounts[n].keySet())) { gram = s; nextCount = nextNgramCounts[n].get(gram); if (refNgramCounts[i][n].containsKey(gram)) { // update if necessary oldCount = refNgramCounts[i][n].get(gram); refNgramCounts[i][n].put(gram, oldCount + nextCount); } else { // add it refNgramCounts[i][n].put(gram, nextCount); } } } // for (n) } // for (r) } // for (i) } protected void set_srcNgramCounts() { @SuppressWarnings("unchecked") HashMap<String, Integer>[][] temp_HMA = new HashMap[numSentences][maxGramLength]; srcNgramCounts = temp_HMA; for (int i = 0; i < numSentences; ++i) { srcNgramCounts[i] = getNgramCountsArray(srcSentences[i]); } // for (i) } // set contents of stats[] here! @Override public int[] suffStats(String cand_str, int i) { int[] stats = new int[suffStatsCount]; HashMap<String, Integer>[] candNgramCounts = getNgramCountsArray(cand_str); for (int n = 1; n <= maxGramLength; ++n) { // ADD OPERATIONS HashMap<String, Integer> cand_sub_src = substractHashMap(candNgramCounts[n], srcNgramCounts[i][n]); HashMap<String, Integer> cand_and_ref_sub_src = intersectHashMap(cand_sub_src, refNgramCounts[i][n]); HashMap<String, Integer> ref_sub_src = substractHashMap(refNgramCounts[i][n], srcNgramCounts[i][n]); stats[StatIndex.values().length * (n - 1) + StatIndex.ADDBOTH.ordinal()] = cand_and_ref_sub_src.keySet().size(); stats[StatIndex.values().length * (n - 1) + StatIndex.ADDCAND.ordinal()] = cand_sub_src .keySet().size(); stats[StatIndex.values().length * (n - 1) + StatIndex.ADDREF.ordinal()] = ref_sub_src.keySet() .size(); // System.out.println("src_and_cand_sub_ref" + cand_and_ref_sub_src + // cand_and_ref_sub_src.keySet().size()); // System.out.println("cand_sub_src" + cand_sub_src + cand_sub_src.keySet().size()); // System.out.println("ref_sub_src" + ref_sub_src + ref_sub_src.keySet().size()); // DELETION OPERATIONS HashMap<String, Integer> src_sub_cand = substractHashMap(srcNgramCounts[i][n], candNgramCounts[n], refsPerSen, refsPerSen); HashMap<String, Integer> src_sub_ref = substractHashMap(srcNgramCounts[i][n], refNgramCounts[i][n], refsPerSen, 1); HashMap<String, Integer> src_sub_cand_sub_ref = intersectHashMap(src_sub_cand, src_sub_ref, 1, 1); stats[StatIndex.values().length * (n - 1) + StatIndex.DELBOTH.ordinal()] = sumHashMapByValues( src_sub_cand_sub_ref); stats[StatIndex.values().length * (n - 1) + StatIndex.DELCAND.ordinal()] = sumHashMapByValues( src_sub_cand); stats[StatIndex.values().length * (n - 1) + StatIndex.DELREF.ordinal()] = sumHashMapByValues( src_sub_ref); // System.out.println("src_sub_cand_sub_ref" + src_sub_cand_sub_ref + // sumHashMapByValues(src_sub_cand_sub_ref)); // System.out.println("src_sub_cand" + src_sub_cand + sumHashMapByValues(src_sub_cand)); // System.out.println("src_sub_ref" + src_sub_ref + sumHashMapByValues(src_sub_ref)); stats[StatIndex.values().length * (n - 1) + StatIndex.DELREF.ordinal()] = src_sub_ref.keySet() .size() * refsPerSen; // KEEP OPERATIONS HashMap<String, Integer> src_and_cand = intersectHashMap(srcNgramCounts[i][n], candNgramCounts[n], refsPerSen, refsPerSen); HashMap<String, Integer> src_and_ref = intersectHashMap(srcNgramCounts[i][n], refNgramCounts[i][n], refsPerSen, 1); HashMap<String, Integer> src_and_cand_and_ref = intersectHashMap(src_and_cand, src_and_ref, 1, 1); stats[StatIndex.values().length * (n - 1) + StatIndex.KEEPBOTH.ordinal()] = sumHashMapByValues(src_and_cand_and_ref); stats[StatIndex.values().length * (n - 1) + StatIndex.KEEPCAND.ordinal()] = sumHashMapByValues(src_and_cand); stats[StatIndex.values().length * (n - 1) + StatIndex.KEEPREF.ordinal()] = sumHashMapByValues( src_and_ref); stats[StatIndex.values().length * (n - 1) + StatIndex.KEEPBOTH.ordinal()] = (int) (1000000 * sumHashMapByDoubleValues(divideHashMap(src_and_cand_and_ref, src_and_cand))); stats[StatIndex.values().length * (n - 1) + StatIndex.KEEPCAND.ordinal()] = (int) sumHashMapByDoubleValues( divideHashMap(src_and_cand_and_ref, src_and_ref)); stats[StatIndex.values().length * (n - 1) + StatIndex.KEEPREF.ordinal()] = src_and_ref .keySet().size(); } return stats; } @Override public double score(int[] stats) { if (stats.length != suffStatsCount) { System.out.println("Mismatch between stats.length and suffStatsCount (" + stats.length + " vs. " + suffStatsCount + ") in NewMetric.score(int[])"); System.exit(1); } double sc = 0.0; for (int n = 1; n <= maxGramLength; ++n) { int addCandCorrectNgram = stats[StatIndex.values().length * (n - 1) + StatIndex.ADDBOTH.ordinal()]; int addCandTotalNgram = stats[StatIndex.values().length * (n - 1) + StatIndex.ADDCAND.ordinal()]; int addRefTotalNgram = stats[StatIndex.values().length * (n - 1) + StatIndex.ADDREF.ordinal()]; double prec_add_n = 0.0; if (addCandTotalNgram > 0) { prec_add_n = addCandCorrectNgram / (double) addCandTotalNgram; } double recall_add_n = 0.0; if (addRefTotalNgram > 0) { recall_add_n = addCandCorrectNgram / (double) addRefTotalNgram; } // System.out.println("\nDEBUG-SARI:" + addCandCorrectNgram + " " + addCandTotalNgram + " " + // addRefTotalNgram); double f1_add_n = meanHarmonic(prec_add_n, recall_add_n); sc += weights[n] * f1_add_n; int delCandCorrectNgram = stats[StatIndex.values().length * (n - 1) + StatIndex.DELBOTH.ordinal()]; int delCandTotalNgram = stats[StatIndex.values().length * (n - 1) + StatIndex.DELCAND.ordinal()]; double prec_del_n = 0.0; if (delCandTotalNgram > 0) { prec_del_n = delCandCorrectNgram / (double) delCandTotalNgram; } // System.out.println("\nDEBUG-SARI:" + delCandCorrectNgram + " " + delRefTotalNgram); // sc += weights[n] * f1_del_n; sc += weights[n] * prec_del_n; int keepCandCorrectNgram = stats[StatIndex.values().length * (n - 1) + StatIndex.KEEPBOTH.ordinal()]; // int keepCandCorrectNgram2 = stats[StatIndex.values().length * (n - 1) + // StatIndex.KEEPBOTH2.ordinal()]; int keepCandTotalNgram = stats[StatIndex.values().length * (n - 1) + StatIndex.KEEPCAND.ordinal()]; int keepRefTotalNgram = stats[StatIndex.values().length * (n - 1) + StatIndex.KEEPREF.ordinal()]; double prec_keep_n = 0.0; if (keepCandTotalNgram > 0) { prec_keep_n = keepCandCorrectNgram / (double) (1000000 * keepCandTotalNgram); } double recall_keep_n = 0.0; if (keepRefTotalNgram > 0) { recall_keep_n = keepCandTotalNgram / (double) keepRefTotalNgram; } // System.out.println("\nDEBUG-SARI-KEEP: " + n + " " + keepCandCorrectNgram + " " + // keepCandTotalNgram + " " + keepRefTotalNgram); double f1_keep_n = meanHarmonic(prec_keep_n, recall_keep_n); sc += weights[n] * f1_keep_n; // System.out.println("\nDEBUG-SARI: " + n + " " + prec_add_n + " " + recall_add_n + " " + // prec_del_n + " " + recall_del_n + " " + prec_keep_n + " " + recall_keep_n); // System.out.println("\nDEBUG-SARI-KEEP: " + n + " " + keepCandCorrectNgram + " " + // keepCandTotalNgram + " " + keepRefTotalNgram); } sc = sc / 3.0; // // // set sc here! // // return sc; } public double meanHarmonic(double precision, double recall) { if (precision > 0 && recall > 0) { return (2.0 * precision * recall) / (precision + recall); } return 0.0; } public void loadSources(String filepath) throws IOException { srcSentences = new String[numSentences]; // BufferedReader br = new BufferedReader(new FileReader(filepath)); InputStream inStream = new FileInputStream(new File(filepath)); BufferedReader br = new BufferedReader(new InputStreamReader(inStream, "utf8")); String line; int i = 0; while (i < numSentences && (line = br.readLine()) != null) { srcSentences[i] = line.trim(); i++; } br.close(); } public double sumHashMapByDoubleValues(HashMap<String, Double> counter) { double sumcounts = 0; for (Map.Entry<String, Double> e : counter.entrySet()) { sumcounts += e.getValue(); } return sumcounts; } public int sumHashMapByValues(HashMap<String, Integer> counter) { int sumcounts = 0; for (Map.Entry<String, Integer> e : counter.entrySet()) { sumcounts += e.getValue(); } return sumcounts; } public HashMap<String, Integer> substractHashMap(HashMap<String, Integer> counter1, HashMap<String, Integer> counter2) { HashMap<String, Integer> newcounter = new HashMap<>(); for (Map.Entry<String, Integer> e : counter1.entrySet()) { String ngram = e.getKey(); int count2 = counter2.containsKey(ngram) ? counter2.get(ngram) : 0; if (count2 == 0) { newcounter.put(ngram, 1); } } return newcounter; } // HashMap result = counter1*ratio1 - counter2*ratio2 public HashMap<String, Integer> substractHashMap(HashMap<String, Integer> counter1, HashMap<String, Integer> counter2, int ratio1, int ratio2) { HashMap<String, Integer> newcounter = new HashMap<>(); for (Map.Entry<String, Integer> e : counter1.entrySet()) { String ngram = e.getKey(); int count1 = e.getValue(); int count2 = counter2.containsKey(ngram) ? counter2.get(ngram) : 0; int newcount = count1 * ratio1 - count2 * ratio2; if (newcount > 0) { newcounter.put(ngram, newcount); } } return newcounter; } public HashMap<String, Double> divideHashMap(HashMap<String, Integer> counter1, HashMap<String, Integer> counter2) { HashMap<String, Double> newcounter = new HashMap<>(); for (Map.Entry<String, Integer> e : counter1.entrySet()) { String ngram = e.getKey(); int count1 = e.getValue(); int count2 = counter2.containsKey(ngram) ? counter2.get(ngram) : 0; if (count2 != 0) { newcounter.put(ngram, (double) count1 / (double) count2); } } return newcounter; } public HashMap<String, Integer> intersectHashMap(HashMap<String, Integer> counter1, HashMap<String, Integer> counter2) { HashMap<String, Integer> newcounter = new HashMap<>(); for (Map.Entry<String, Integer> e : counter1.entrySet()) { String ngram = e.getKey(); int count2 = counter2.containsKey(ngram) ? counter2.get(ngram) : 0; if (count2 > 0) { newcounter.put(ngram, 1); } } return newcounter; } // HashMap result = (counter1*ratio1) & (counter2*ratio2) public HashMap<String, Integer> intersectHashMap(HashMap<String, Integer> counter1, HashMap<String, Integer> counter2, int ratio1, int ratio2) { HashMap<String, Integer> newcounter = new HashMap<>(); for (Map.Entry<String, Integer> e : counter1.entrySet()) { String ngram = e.getKey(); int count1 = e.getValue(); int count2 = counter2.containsKey(ngram) ? counter2.get(ngram) : 0; int newcount = Math.min(count1 * ratio1, count2 * ratio2); if (newcount > 0) { newcounter.put(ngram, newcount); } } return newcounter; } protected int wordCount(String cand_str) { if (!cand_str.equals("")) { return cand_str.split("\\s+").length; } else { return 0; } } public HashMap<String, Integer>[] getNgramCountsArray(String cand_str) { if (!cand_str.equals("")) { return getNgramCountsArray(cand_str.split("\\s+")); } else { return getNgramCountsArray(new String[0]); } } public HashMap<String, Integer>[] getNgramCountsArray(String[] words) { @SuppressWarnings("unchecked") HashMap<String, Integer>[] ngramCountsArray = new HashMap[1 + maxGramLength]; ngramCountsArray[0] = null; for (int n = 1; n <= maxGramLength; ++n) { ngramCountsArray[n] = new HashMap<>(); } int len = words.length; String gram; int st = 0; for (; st <= len - maxGramLength; ++st) { gram = words[st]; if (ngramCountsArray[1].containsKey(gram)) { int oldCount = ngramCountsArray[1].get(gram); ngramCountsArray[1].put(gram, oldCount + 1); } else { ngramCountsArray[1].put(gram, 1); } for (int n = 2; n <= maxGramLength; ++n) { gram = gram + " " + words[st + n - 1]; if (ngramCountsArray[n].containsKey(gram)) { int oldCount = ngramCountsArray[n].get(gram); ngramCountsArray[n].put(gram, oldCount + 1); } else { ngramCountsArray[n].put(gram, 1); } } // for (n) } // for (st) // now st is either len-maxGramLength+1 or zero (if above loop never entered, which // happens with sentences that have fewer than maxGramLength words) for (; st < len; ++st) { gram = words[st]; if (ngramCountsArray[1].containsKey(gram)) { int oldCount = ngramCountsArray[1].get(gram); ngramCountsArray[1].put(gram, oldCount + 1); } else { ngramCountsArray[1].put(gram, 1); } int n = 2; for (int fin = st + 1; fin < len; ++fin) { gram = gram + " " + words[st + n - 1]; if (ngramCountsArray[n].containsKey(gram)) { int oldCount = ngramCountsArray[n].get(gram); ngramCountsArray[n].put(gram, oldCount + 1); } else { ngramCountsArray[n].put(gram, 1); } ++n; } // for (fin) } // for (st) return ngramCountsArray; } public HashMap<String, Integer> getNgramCountsAll(String cand_str) { if (!cand_str.equals("")) { return getNgramCountsAll(cand_str.split("\\s+")); } else { return getNgramCountsAll(new String[0]); } } public HashMap<String, Integer> getNgramCountsAll(String[] words) { HashMap<String, Integer> ngramCountsAll = new HashMap<>(); int len = words.length; String gram; int st = 0; for (; st <= len - maxGramLength; ++st) { gram = words[st]; if (ngramCountsAll.containsKey(gram)) { int oldCount = ngramCountsAll.get(gram); ngramCountsAll.put(gram, oldCount + 1); } else { ngramCountsAll.put(gram, 1); } for (int n = 2; n <= maxGramLength; ++n) { gram = gram + " " + words[st + n - 1]; if (ngramCountsAll.containsKey(gram)) { int oldCount = ngramCountsAll.get(gram); ngramCountsAll.put(gram, oldCount + 1); } else { ngramCountsAll.put(gram, 1); } } // for (n) } // for (st) // now st is either len-maxGramLength+1 or zero (if above loop never entered, which // happens with sentences that have fewer than maxGramLength words) for (; st < len; ++st) { gram = words[st]; if (ngramCountsAll.containsKey(gram)) { int oldCount = ngramCountsAll.get(gram); ngramCountsAll.put(gram, oldCount + 1); } else { ngramCountsAll.put(gram, 1); } int n = 2; for (int fin = st + 1; fin < len; ++fin) { gram = gram + " " + words[st + n - 1]; if (ngramCountsAll.containsKey(gram)) { int oldCount = ngramCountsAll.get(gram); ngramCountsAll.put(gram, oldCount + 1); } else { ngramCountsAll.put(gram, 1); } ++n; } // for (fin) } // for (st) return ngramCountsAll; } @Override public void printDetailedScore_fromStats(int[] stats, boolean oneLiner) { System.out.println(metricName + " = " + score(stats)); // for (Map.Entry<String, Integer> entry : refNgramCounts.) { // System.out.println(entry.getKey()+" : "+ entry.getValue()); // } // // // optional (for debugging purposes) // // } private enum StatIndex { KEEPBOTH, KEEPCAND, KEEPREF, DELBOTH, DELCAND, DELREF, ADDBOTH, ADDCAND, ADDREF, KEEPBOTH2 } }
/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.spanner; import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static com.google.common.truth.Truth.assertThat; import com.google.cloud.ByteArray; import com.google.cloud.Date; import com.google.cloud.Timestamp; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.testing.EqualsTester; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link com.google.cloud.spanner.Mutation}. */ @RunWith(JUnit4.class) public class MutationTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void insertEmpty() { Mutation m = Mutation.newInsertBuilder("T1").build(); assertThat(m.getTable()).isEqualTo("T1"); assertThat(m.getOperation()).isEqualTo(Mutation.Op.INSERT); assertThat(m.getColumns()).isEmpty(); assertThat(m.getValues()).isEmpty(); assertThat(m.toString()).isEqualTo("insert(T1{})"); } @Test public void insert() { Mutation m = Mutation.newInsertBuilder("T1").set("C1").to(true).set("C2").to(1234).build(); assertThat(m.getTable()).isEqualTo("T1"); assertThat(m.getOperation()).isEqualTo(Mutation.Op.INSERT); assertThat(m.getColumns()).containsExactly("C1", "C2").inOrder(); assertThat(m.getValues()).containsExactly(Value.bool(true), Value.int64(1234)).inOrder(); assertThat(m.toString()).isEqualTo("insert(T1{C1=true,C2=1234})"); } @Test public void insertOrUpdateEmpty() { Mutation m = Mutation.newInsertOrUpdateBuilder("T2").build(); assertThat(m.getTable()).isEqualTo("T2"); assertThat(m.getOperation()).isEqualTo(Mutation.Op.INSERT_OR_UPDATE); assertThat(m.getColumns()).isEmpty(); assertThat(m.getValues()).isEmpty(); assertThat(m.toString()).isEqualTo("insert_or_update(T2{})"); } @Test public void insertOrUpdate() { Mutation m = Mutation.newInsertOrUpdateBuilder("T1").set("C1").to(true).build(); assertThat(m.getTable()).isEqualTo("T1"); assertThat(m.getOperation()).isEqualTo(Mutation.Op.INSERT_OR_UPDATE); assertThat(m.getColumns()).containsExactly("C1"); assertThat(m.getValues()).containsExactly(Value.bool(true)); assertThat(m.toString()).isEqualTo("insert_or_update(T1{C1=true})"); } @Test public void updateEmpty() { Mutation m = Mutation.newUpdateBuilder("T2").build(); assertThat(m.getTable()).isEqualTo("T2"); assertThat(m.getOperation()).isEqualTo(Mutation.Op.UPDATE); assertThat(m.getColumns()).isEmpty(); assertThat(m.getValues()).isEmpty(); assertThat(m.toString()).isEqualTo("update(T2{})"); } @Test public void update() { Mutation m = Mutation.newUpdateBuilder("T1").set("C1").to(true).set("C2").to(1234).build(); assertThat(m.getTable()).isEqualTo("T1"); assertThat(m.getOperation()).isEqualTo(Mutation.Op.UPDATE); assertThat(m.getColumns()).containsExactly("C1", "C2").inOrder(); assertThat(m.getValues()).containsExactly(Value.bool(true), Value.int64(1234)).inOrder(); assertThat(m.toString()).isEqualTo("update(T1{C1=true,C2=1234})"); } @Test public void replaceEmpty() { Mutation m = Mutation.newReplaceBuilder("T2").build(); assertThat(m.getTable()).isEqualTo("T2"); assertThat(m.getOperation()).isEqualTo(Mutation.Op.REPLACE); assertThat(m.getColumns()).isEmpty(); assertThat(m.getValues()).isEmpty(); assertThat(m.toString()).isEqualTo("replace(T2{})"); } @Test public void replace() { Mutation m = Mutation.newReplaceBuilder("T1").set("C1").to(true).set("C2").to(1234).build(); assertThat(m.getTable()).isEqualTo("T1"); assertThat(m.getOperation()).isEqualTo(Mutation.Op.REPLACE); assertThat(m.getColumns()).containsExactly("C1", "C2").inOrder(); assertThat(m.getValues()).containsExactly(Value.bool(true), Value.int64(1234)).inOrder(); assertThat(m.toString()).isEqualTo("replace(T1{C1=true,C2=1234})"); } @Test public void duplicateColumn() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Duplicate column"); Mutation.newInsertBuilder("T1").set("C1").to(true).set("C1").to(false).build(); } @Test public void duplicateColumnCaseInsensitive() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Duplicate column"); Mutation.newInsertBuilder("T1").set("C1").to(true).set("c1").to(false).build(); } @Test public void asMap() { Mutation m = Mutation.newInsertBuilder("T").build(); assertThat(m.asMap()).isEqualTo(ImmutableMap.of()); m = Mutation.newInsertBuilder("T").set("C1").to(true).set("C2").to(1234).build(); assertThat(m.asMap()) .isEqualTo(ImmutableMap.of("C1", Value.bool(true), "C2", Value.int64(1234))); } @Test public void unfinishedBindingV1() { Mutation.WriteBuilder b = Mutation.newInsertBuilder("T1"); b.set("C1"); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Incomplete binding for column C1"); b.build(); } @Test public void unfinishedBindingV2() { Mutation.WriteBuilder b = Mutation.newInsertBuilder("T1"); b.set("C1"); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Incomplete binding for column C1"); b.set("C2"); } @Test public void notInBinding() { ValueBinder<Mutation.WriteBuilder> binder = Mutation.newInsertBuilder("T1").set("C1"); binder.to(1234); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("No binding currently active"); binder.to(5678); } @Test public void delete() { KeySet keySet = KeySet.singleKey(Key.of("k1")); Mutation m = Mutation.delete("T1", keySet); assertThat(m.getOperation()).isEqualTo(Mutation.Op.DELETE); assertThat(m.getKeySet()).isEqualTo(keySet); assertThat(m.toString()).isEqualTo("delete(T1{[k1]})"); } @Test public void equalsAndHashCode() { EqualsTester tester = new EqualsTester(); // Equality, not identity. tester.addEqualityGroup( Mutation.newInsertBuilder("T1").build(), Mutation.newInsertBuilder("T1").build()); // Operation types are distinguished. tester.addEqualityGroup(Mutation.newInsertOrUpdateBuilder("T1").build()); tester.addEqualityGroup(Mutation.newUpdateBuilder("T1").build()); tester.addEqualityGroup(Mutation.newReplaceBuilder("T1").build()); // Table is distinguished. tester.addEqualityGroup(Mutation.newInsertBuilder("T2").build()); // Columns/values are distinguished (but by equality, not identity). tester.addEqualityGroup( Mutation.newInsertBuilder("T1").set("C").to("V").build(), Mutation.newInsertBuilder("T1").set("C").to("V").build()); // Deletes consider the key set. tester.addEqualityGroup(Mutation.delete("T1", KeySet.all())); tester.addEqualityGroup( Mutation.delete("T1", KeySet.singleKey(Key.of("k"))), Mutation.delete("T1", Key.of("k"))); tester.testEquals(); } @Test public void serializationBasic() { List<Mutation> mutations = Arrays.asList( Mutation.newInsertBuilder("T").set("C").to("V").build(), Mutation.newUpdateBuilder("T").set("C").to("V").build(), Mutation.newInsertOrUpdateBuilder("T").set("C").to("V").build(), Mutation.newReplaceBuilder("T").set("C").to("V").build(), Mutation.delete("T", KeySet.singleKey(Key.of("k")))); List<com.google.spanner.v1.Mutation> proto = new ArrayList<>(); // Include an existing element so that we know toProto() do not clear the list. com.google.spanner.v1.Mutation existingProto = com.google.spanner.v1.Mutation.getDefaultInstance(); proto.add(existingProto); Mutation.toProto(mutations, proto); assertThat(proto.size()).isAtLeast(1); assertThat(proto.get(0)).isSameAs(existingProto); proto.remove(0); assertThat(proto.size()).isEqualTo(5); MatcherAssert.assertThat( proto.get(0), matchesProto("insert { table: 'T' columns: 'C' values { values { string_value: 'V' } } }")); MatcherAssert.assertThat( proto.get(1), matchesProto("update { table: 'T' columns: 'C' values { values { string_value: 'V' } } }")); MatcherAssert.assertThat( proto.get(2), matchesProto( "insert_or_update { table: 'T' columns: 'C'" + " values { values { string_value: 'V' } } }")); MatcherAssert.assertThat( proto.get(3), matchesProto( "replace { table: 'T' columns: 'C' values { values { string_value: 'V' } } }")); MatcherAssert.assertThat( proto.get(4), matchesProto("delete { table: 'T' key_set { keys { values { string_value: 'k' } } } }")); } @Test public void toProtoCoalescingChangeOfTable() { List<Mutation> mutations = Arrays.asList( Mutation.newInsertBuilder("T1").set("C").to("V1").build(), Mutation.newInsertBuilder("T1").set("C").to("V2").build(), Mutation.newInsertBuilder("T1").set("C").to("V3").build(), Mutation.newInsertBuilder("T2").set("C").to("V4").build(), Mutation.newInsertBuilder("T2").set("C").to("V5").build()); List<com.google.spanner.v1.Mutation> proto = new ArrayList<>(); Mutation.toProto(mutations, proto); assertThat(proto.size()).isEqualTo(2); MatcherAssert.assertThat( proto.get(0), matchesProto( "insert { table: 'T1' columns: 'C' values { values { string_value: 'V1' } }" + " values { values { string_value: 'V2' } }" + " values { values { string_value: 'V3' } } }")); MatcherAssert.assertThat( proto.get(1), matchesProto( "insert { table: 'T2' columns: 'C' values { values { string_value: 'V4' } }" + " values { values { string_value: 'V5' } } }")); } @Test public void toProtoCoalescingChangeOfOperation() { List<Mutation> mutations = Arrays.asList( Mutation.newInsertBuilder("T").set("C").to("V1").build(), Mutation.newInsertBuilder("T").set("C").to("V2").build(), Mutation.newInsertBuilder("T").set("C").to("V3").build(), Mutation.newUpdateBuilder("T").set("C").to("V4").build(), Mutation.newUpdateBuilder("T").set("C").to("V5").build()); List<com.google.spanner.v1.Mutation> proto = new ArrayList<>(); Mutation.toProto(mutations, proto); assertThat(proto.size()).isEqualTo(2); MatcherAssert.assertThat( proto.get(0), matchesProto( "insert { table: 'T' columns: 'C' values { values { string_value: 'V1' } }" + " values { values { string_value: 'V2' } }" + " values { values { string_value: 'V3' } } }")); MatcherAssert.assertThat( proto.get(1), matchesProto( "update { table: 'T' columns: 'C' values { values { string_value: 'V4' } }" + " values { values { string_value: 'V5' } } }")); } @Test public void toProtoCoalescingChangeOfColumn() { List<Mutation> mutations = Arrays.asList( Mutation.newInsertBuilder("T").set("C1").to("V1").build(), Mutation.newInsertBuilder("T").set("C1").to("V2").build(), Mutation.newInsertBuilder("T").set("C1").to("V3").build(), Mutation.newInsertBuilder("T").set("C2").to("V4").build(), Mutation.newInsertBuilder("T").set("C2").to("V5").build()); List<com.google.spanner.v1.Mutation> proto = new ArrayList<>(); Mutation.toProto(mutations, proto); assertThat(proto.size()).isEqualTo(2); MatcherAssert.assertThat( proto.get(0), matchesProto( "insert { table: 'T' columns: 'C1' values { values { string_value: 'V1' } }" + " values { values { string_value: 'V2' } }" + " values { values { string_value: 'V3' } } }")); MatcherAssert.assertThat( proto.get(1), matchesProto( "insert { table: 'T' columns: 'C2' values { values { string_value: 'V4' } }" + " values { values { string_value: 'V5' } } }")); } @Test public void toProtoCoalescingDelete() { List<Mutation> mutations = Arrays.asList( Mutation.delete("T", Key.of("k1")), Mutation.delete("T", Key.of("k2")), Mutation.delete("T", KeySet.range(KeyRange.closedOpen(Key.of("ka"), Key.of("kb")))), Mutation.delete("T", KeySet.range(KeyRange.closedClosed(Key.of("kc"), Key.of("kd"))))); List<com.google.spanner.v1.Mutation> proto = new ArrayList<>(); Mutation.toProto(mutations, proto); assertThat(proto.size()).isEqualTo(1); MatcherAssert.assertThat( proto.get(0), matchesProto( "delete {" + " table: 'T'" + " key_set {" + " keys { values { string_value: 'k1' } }" + " keys { values { string_value: 'k2' } }" + " ranges { start_closed { values { string_value: 'ka' } } " + " end_open { values { string_value: 'kb' } } }" + " ranges { start_closed { values { string_value: 'kc' } } " + " end_closed { values { string_value: 'kd' } } }" + " }" + "} ")); } @Test public void toProtoCoalescingDeleteChanges() { List<Mutation> mutations = Arrays.asList( Mutation.newInsertBuilder("T1").set("C").to("V1").build(), Mutation.delete("T1", Key.of("k1")), Mutation.delete("T1", Key.of("k2")), Mutation.delete("T2", Key.of("k3")), Mutation.delete("T2", Key.of("k4")), Mutation.newInsertBuilder("T2").set("C").to("V1").build()); List<com.google.spanner.v1.Mutation> proto = new ArrayList<>(); Mutation.toProto(mutations, proto); assertThat(proto.size()).isEqualTo(4); MatcherAssert.assertThat( proto.get(0), matchesProto( "insert { table: 'T1' columns: 'C' values { values { string_value: 'V1' } } }")); MatcherAssert.assertThat( proto.get(1), matchesProto( "delete { table: 'T1' key_set { keys { values { string_value: 'k1' } } " + "keys { values { string_value: 'k2' } } } }")); MatcherAssert.assertThat( proto.get(2), matchesProto( "delete { table: 'T2' key_set { keys { values { string_value: 'k3' } } " + "keys { values { string_value: 'k4' } } } }")); MatcherAssert.assertThat( proto.get(3), matchesProto( "insert { table: 'T2', columns: 'C', values { values { string_value: 'V1' } } }")); } @Test public void javaSerialization() throws Exception { reserializeAndAssert(appendAllTypes(Mutation.newInsertBuilder("test")).build()); reserializeAndAssert(appendAllTypes(Mutation.newUpdateBuilder("test")).build()); reserializeAndAssert(appendAllTypes(Mutation.newReplaceBuilder("test")).build()); reserializeAndAssert(appendAllTypes(Mutation.newInsertOrUpdateBuilder("test")).build()); reserializeAndAssert( Mutation.delete( "test", Key.of( "one", 2, null, true, 2.3, ByteArray.fromBase64("abcd"), Timestamp.ofTimeSecondsAndNanos(1, 2), Date.fromYearMonthDay(2017, 04, 17)))); reserializeAndAssert(Mutation.delete("test", KeySet.all())); reserializeAndAssert( Mutation.delete( "test", KeySet.newBuilder() .addRange(KeyRange.closedClosed(Key.of("one", 2, null), Key.of("two", 3, null))) .build())); reserializeAndAssert( Mutation.delete( "test", KeySet.newBuilder() .addRange(KeyRange.closedOpen(Key.of("one", 2, null), Key.of("two", 3, null))) .build())); reserializeAndAssert( Mutation.delete( "test", KeySet.newBuilder() .addRange(KeyRange.openClosed(Key.of("one", 2, null), Key.of("two", 3, null))) .build())); reserializeAndAssert( Mutation.delete( "test", KeySet.newBuilder() .addRange(KeyRange.openOpen(Key.of("one", 2, null), Key.of("two", 3, null))) .build())); } private Mutation.WriteBuilder appendAllTypes(Mutation.WriteBuilder builder) { return builder .set("bool") .to(true) .set("boolNull") .to((Boolean) null) .set("int") .to(42) .set("intNull") .to((Long) null) .set("float") .to(42.1) .set("floatNull") .to((Double) null) .set("string") .to("str") .set("stringNull") .to((String) null) .set("boolArr") .toBoolArray(new boolean[] {true, false}) .set("boolArrNull") .toBoolArray((boolean[]) null) .set("intArr") .toInt64Array(new long[] {1, 2, 3}) .set("intArrNull") .toInt64Array((long[]) null) .set("floatArr") .toFloat64Array(new double[] {1.1, 2.2, 3.3}) .set("floatArrNull") .toFloat64Array((double[]) null) .set("nullStr") .to((String) null) .set("timestamp") .to(Timestamp.MAX_VALUE) .set("timestampNull") .to((Timestamp) null) .set("date") .to(Date.fromYearMonthDay(2017, 04, 17)) .set("dateNull") .to((Date) null) .set("stringArr") .toStringArray(ImmutableList.of("one", "two")) .set("stringArrNull") .toStringArray(null) .set("timestampArr") .toTimestampArray(ImmutableList.of(Timestamp.MAX_VALUE, Timestamp.MAX_VALUE)) .set("timestampArrNull") .toTimestampArray(null) .set("dateArr") .toDateArray( ImmutableList.of( Date.fromYearMonthDay(2017, 04, 17), Date.fromYearMonthDay(2017, 04, 18))) .set("dateArrNull") .toDateArray(null); } static Matcher<com.google.spanner.v1.Mutation> matchesProto(String expected) { return SpannerMatchers.matchesProto(com.google.spanner.v1.Mutation.class, expected); } }
/* * Copyright 2014-2018 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.agrona.concurrent; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collection; import java.util.NoSuchElementException; import java.util.Queue; import java.util.function.Consumer; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(Theories.class) public class QueuedPipeTest { private static final int QUEUE_CAPACITY = 8; interface Fixture { QueuedPipe<Integer> newInstance(); } @DataPoint public static final Fixture ONE_TO_ONE_QUEUE = () -> new OneToOneConcurrentArrayQueue<>(QUEUE_CAPACITY); @DataPoint public static final Fixture MANY_TO_ONE_QUEUE = () -> new ManyToOneConcurrentArrayQueue<>(QUEUE_CAPACITY); @DataPoint public static final Fixture MANY_TO_MANY_QUEUE = () -> new ManyToManyConcurrentArrayQueue<>(QUEUE_CAPACITY); @Theory public void shouldGetSizeWhenEmpty(final Fixture fixture) { final Queue<Integer> queue = fixture.newInstance(); assertThat(queue.size(), is(0)); } @Theory @Test(expected = NullPointerException.class) public void shouldThrowExceptionWhenNullOffered(final Fixture fixture) { final Queue<Integer> queue = fixture.newInstance(); queue.offer(null); } @Theory @Test(expected = NullPointerException.class) public void shouldThrowExceptionWhenNullAdded(final Fixture fixture) { final Queue<Integer> queue = fixture.newInstance(); queue.add(null); } @Theory public void shouldOfferAndPollToEmptyQueue(final Fixture fixture) { final Queue<Integer> queue = fixture.newInstance(); final Integer testValue = 7; final boolean success = queue.offer(testValue); assertTrue(success); assertThat(queue.size(), is(1)); final Integer polledValue = queue.poll(); Assert.assertEquals(testValue, polledValue); assertThat(polledValue, is(testValue)); assertThat(queue.size(), is(0)); } @Theory public void shouldAddAndRemoveFromEmptyQueue(final Fixture fixture) { final Queue<Integer> queue = fixture.newInstance(); final Integer testValue = 7; final boolean success = queue.add(testValue); assertTrue(success); assertThat(queue.size(), is(1)); final Integer removedValue = queue.remove(); assertThat(removedValue, is(testValue)); assertThat(queue.size(), is(0)); } @Theory public void shouldFailToOfferToFullQueue(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); fillQueue(queue); assertThat(queue.size(), is(queue.capacity())); final boolean success = queue.offer(0); Assert.assertFalse(success); } @Theory public void shouldPollSingleElementFromFullQueue(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); fillQueue(queue); final Integer polledValue = queue.poll(); assertThat(polledValue, is(0)); assertThat(queue.size(), is(queue.capacity() - 1)); } @Theory public void shouldPollNullFromEmptyQueue(final Fixture fixture) { final Queue<Integer> queue = fixture.newInstance(); final Integer polledValue = queue.poll(); Assert.assertNull(polledValue); } @Theory public void shouldPeakQueueHead(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); fillQueue(queue); final Integer headValue = queue.peek(); assertThat(headValue, is(0)); assertThat(queue.size(), is(queue.capacity())); } @Theory public void shouldReturnNullForPeekOnEmptyQueue(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); final Integer value = queue.peek(); Assert.assertNull(value); } @Theory public void shouldReturnElementQueueHead(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); fillQueue(queue); final Integer headValue = queue.element(); assertThat(headValue, is(0)); assertThat(queue.size(), is(queue.capacity())); } @Theory @Test(expected = NoSuchElementException.class) public void shouldThrowExceptionForElementOnEmptyQueue(final Fixture fixture) { final Queue<Integer> queue = fixture.newInstance(); queue.element(); } @Theory public void shouldRemoveSingleElementFromFullQueue(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); fillQueue(queue); Assert.assertEquals(queue.capacity(), queue.size()); final Integer removedValue = queue.remove(); assertThat(removedValue, is(0)); assertThat(queue.size(), is(queue.capacity() - 1)); } @Theory @Test(expected = NoSuchElementException.class) public void shouldThrowExceptionForRemoveOnEmptyQueue(final Fixture fixture) { final Queue<Integer> queue = fixture.newInstance(); queue.remove(); } @Theory public void shouldClearFullQueue(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); fillQueue(queue); queue.clear(); assertThat(queue.size(), is(0)); } @Theory public void shouldDrainFullQueue(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); fillQueue(queue); final int[] counter = new int[1]; final Consumer<Integer> elementHandler = (e) -> ++counter[0]; final int elementsDrained = queue.drain(elementHandler); assertThat(elementsDrained, is(queue.capacity())); assertThat(counter[0], is(queue.capacity())); assertThat(queue.size(), is(0)); } @Theory public void shouldHandleExceptionWhenDraining(final Fixture fixture) { final String testMessage = "Test Exception"; final QueuedPipe<Integer> queue = fixture.newInstance(); fillQueue(queue); final int[] counter = new int[1]; final int exceptionTrigger = 3; final Consumer<Integer> elementHandler = (e) -> { ++counter[0]; if (exceptionTrigger == counter[0]) { throw new RuntimeException(testMessage); } }; RuntimeException exception = null; try { queue.drain(elementHandler); } catch (final RuntimeException ex) { exception = ex; } Assert.assertNotNull(exception); assertThat(queue.size(), is(queue.capacity() - exceptionTrigger)); } @Theory public void shouldDrainFullQueueToCollection(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); final Collection<Integer> target = new ArrayList<>(); fillQueue(queue); final int elementsDrained = queue.drainTo(target, Integer.MAX_VALUE); assertThat(elementsDrained, is(queue.capacity())); assertThat(target.size(), is(queue.capacity())); assertThat(queue.size(), is(0)); } @Theory public void shouldDrainQueueWithCountToCollection(final Fixture fixture) { final QueuedPipe<Integer> queue = fixture.newInstance(); final Collection<Integer> target = new ArrayList<>(); final int count = 3; fillQueue(queue); final int elementsDrained = queue.drainTo(target, count); assertThat(elementsDrained, is(count)); assertThat(target.size(), is(count)); assertThat(queue.size(), is(queue.capacity() - count)); } private void fillQueue(final QueuedPipe<Integer> queue) { for (int i = 0, size = queue.capacity(); i < size; i++) { final boolean success = queue.offer(i); assertTrue(success); } } }
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved. */ package org.pentaho.platform.dataaccess.datasource.beans; import org.pentaho.agilebi.modeler.ModelerException; import org.pentaho.metadata.model.Domain; import org.pentaho.metadata.model.LogicalColumn; import org.pentaho.metadata.model.LogicalModel; import org.pentaho.metadata.model.LogicalRelationship; import org.pentaho.metadata.model.LogicalTable; import org.pentaho.metadata.model.concept.security.RowLevelSecurity; import org.pentaho.metadata.model.concept.security.Security; import org.pentaho.metadata.model.concept.security.SecurityOwner; import org.pentaho.metadata.model.concept.types.AggregationType; import org.pentaho.metadata.model.concept.types.Alignment; import org.pentaho.metadata.model.concept.types.Color; import org.pentaho.metadata.model.concept.types.ColumnWidth; import org.pentaho.metadata.model.concept.types.DataType; import org.pentaho.metadata.model.concept.types.FieldType; import org.pentaho.metadata.model.concept.types.Font; import org.pentaho.metadata.model.concept.types.JoinType; import org.pentaho.metadata.model.concept.types.LocaleType; import org.pentaho.metadata.model.concept.types.LocalizedString; import org.pentaho.metadata.model.concept.types.RelationshipType; import org.pentaho.metadata.model.concept.types.TableType; import org.pentaho.metadata.model.concept.types.TargetColumnType; import org.pentaho.metadata.model.concept.types.TargetTableType; import org.pentaho.platform.dataaccess.datasource.wizard.models.CsvParseException; import org.pentaho.platform.dataaccess.datasource.wizard.sources.query.QueryDatasourceSummary; import java.io.Serializable; /* * This class is a workaround for GWT. GWT is not able to compile these classes are they have been used in a map * http://code.google.com/p/google-web-toolkit/issues/detail?id=3521 */ public class BogoPojo extends org.pentaho.agilebi.modeler.gwt.BogoPojo implements Serializable { private static final long serialVersionUID = 7542132543385685472L; TargetTableType targetTableType; LocalizedString localizedString; DataType dataType; AggregationType aggType; TargetColumnType targetColumnType; LocaleType localeType; RowLevelSecurity rowLevelSecurity; SecurityOwner securityOwner; Security security; FieldType fieldType; Font font; TableType tableType; RelationshipType relationshipType; JoinType joinType; Alignment alignment; Color color; ColumnWidth columnWidth; Boolean booleanValue; CsvParseException csvParseException; LogicalTable lTable; LogicalModel lModel; LogicalColumn lColumn; LogicalRelationship lRelationship; ModelerException modelerException; Domain domain; QueryDatasourceSummary querySummary; public Domain getDomain() { return domain; } public void setDomain( Domain domain ) { this.domain = domain; } public LogicalColumn getlColumn() { return lColumn; } public void setlColumn( LogicalColumn lColumn ) { this.lColumn = lColumn; } public LogicalModel getlModel() { return lModel; } public void setlModel( LogicalModel lModel ) { this.lModel = lModel; } public LogicalTable getlTable() { return lTable; } public void setlTable( LogicalTable lTable ) { this.lTable = lTable; } public Boolean getBooleanValue() { return booleanValue; } public void setBooleanValue( Boolean booleanValue ) { this.booleanValue = booleanValue; } public Alignment getAlignment() { return alignment; } public void setAlignment( Alignment alignment ) { this.alignment = alignment; } public Color getColor() { return color; } public void setColor( Color color ) { this.color = color; } public ColumnWidth getColumnWidth() { return columnWidth; } public void setColumnWidth( ColumnWidth columnWidth ) { this.columnWidth = columnWidth; } public JoinType getJoinType() { return joinType; } public void setJoinType( JoinType joinType ) { this.joinType = joinType; } public RelationshipType getRelationshipType() { return relationshipType; } public void setRelationshipType( RelationshipType relationshipType ) { this.relationshipType = relationshipType; } public TableType getTableType() { return tableType; } public void setTableType( TableType tableType ) { this.tableType = tableType; } public Font getFont() { return font; } public void setFont( Font font ) { this.font = font; } public TargetTableType getTargetTableType() { return targetTableType; } public void setTargetTableType( TargetTableType targetTableType ) { this.targetTableType = targetTableType; } public LocalizedString getLocalizedString() { return localizedString; } public void setLocalizedString( LocalizedString localizedString ) { this.localizedString = localizedString; } public DataType getDataType() { return dataType; } public void setDataType( DataType dataType ) { this.dataType = dataType; } public AggregationType getAggType() { return aggType; } public void setAggType( AggregationType aggType ) { this.aggType = aggType; } public TargetColumnType getTargetColumnType() { return targetColumnType; } public void setTargetColumnType( TargetColumnType targetColumnType ) { this.targetColumnType = targetColumnType; } public void setLocaleType( LocaleType localeType ) { this.localeType = localeType; } public LocaleType getLocaleType() { return localeType; } public void setRowLevelSecurity( RowLevelSecurity rowLevelSecurity ) { this.rowLevelSecurity = rowLevelSecurity; } public RowLevelSecurity getRowLevelSecurity() { return rowLevelSecurity; } public void setSecurityOwner( SecurityOwner securityOwner ) { this.securityOwner = securityOwner; } public SecurityOwner getSecurityOwner() { return securityOwner; } public void setSecurity( Security security ) { this.security = security; } public Security getSecurity() { return security; } public void setFieldType( FieldType fieldType ) { this.fieldType = fieldType; } public FieldType getFieldType() { return fieldType; } public CsvParseException getCsvParseException() { return csvParseException; } public void setCsvParseException( CsvParseException csvParseException ) { this.csvParseException = csvParseException; } public ModelerException getModelerException() { return modelerException; } public void setModelerException( ModelerException modelerException ) { this.modelerException = modelerException; } public LogicalRelationship getlRelationship() { return lRelationship; } public void setlRelationship( LogicalRelationship lRelationship ) { this.lRelationship = lRelationship; } public QueryDatasourceSummary getQuerySummary() { return querySummary; } public void setQuerySummary( QueryDatasourceSummary querySummary ) { this.querySummary = querySummary; } }