text
stringlengths
7
1.01M
/* * Maintained by brightSPARK Labs. * www.brightsparklabs.com * * Refer to LICENSE at repository root for license details. */ package com.brightsparklabs.asanti.validator.rule; import static com.google.common.base.Preconditions.checkNotNull; import com.brightsparklabs.asanti.data.AsnData; import com.brightsparklabs.asanti.exception.DecodeException; import com.brightsparklabs.asanti.validator.FailureType; import com.brightsparklabs.asanti.validator.ValidationFailure; import com.brightsparklabs.asanti.validator.ValidationRule; import com.brightsparklabs.asanti.validator.failure.DecodedTagValidationFailure; import com.google.common.collect.ImmutableSet; import java.util.Optional; /** * Validates that the value of a given tag is equal to a particular value. Equality is tested via * {@link Object#equals(Object)}. * * @param <T> the expected type of the data as returned by {@link AsnData#getDecodedObject} * @author brightSPARK Labs */ public class IsEqualValidationRule<T> implements ValidationRule { // ------------------------------------------------------------------------- // INSTANCE VARIABLES // ------------------------------------------------------------------------- /** the expected value the tag should have */ private final T expectedValue; /** adds a bit of type safety */ private final Class<T> classOfT; // ------------------------------------------------------------------------- // CONSTRUCTION // ------------------------------------------------------------------------- /** * Default constructor. * * @param expectedValue the value to test against * @param classOfT the class of the T the class of the T * @throws NullPointerException if {@code expectedValue} is {@code null} */ public IsEqualValidationRule(T expectedValue, Class<T> classOfT) { checkNotNull(expectedValue); this.expectedValue = expectedValue; this.classOfT = classOfT; } // ------------------------------------------------------------------------- // IMPLEMENTATION: ValidationRule // ------------------------------------------------------------------------- @Override public ImmutableSet<ValidationFailure> validate(final String tag, final AsnData asnData) throws DecodeException { final ImmutableSet.Builder<ValidationFailure> builder = ImmutableSet.builder(); try { final Optional<T> actualValue = asnData.getDecodedObject(tag, classOfT); final boolean actualValuePresent = actualValue.isPresent(); if (!actualValuePresent || !expectedValue.equals(actualValue.get())) { final String reason = actualValuePresent ? "Found value: [" + actualValue.get().toString() + "] but expected value: [" + expectedValue.toString() + "]" : "No value found when expecting value: [" + expectedValue.toString() + "]"; final ValidationFailure failure = new DecodedTagValidationFailure( tag, FailureType.CustomValidationFailed, reason); builder.add(failure); } } catch (ClassCastException ex) { final ValidationFailure failure = new DecodedTagValidationFailure( tag, FailureType.CustomValidationFailed, "Data was not in the expected format: " + ex.getMessage()); builder.add(failure); } return builder.build(); } }
package com.synopsys.integration.alert.channel; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.transaction.annotation.Transactional; import com.google.gson.Gson; import com.synopsys.integration.alert.common.ContentConverter; import com.synopsys.integration.alert.common.action.TestAction; import com.synopsys.integration.alert.common.channel.DistributionChannelTestAction; import com.synopsys.integration.alert.common.descriptor.ChannelDescriptor; import com.synopsys.integration.alert.common.descriptor.DescriptorProcessor; import com.synopsys.integration.alert.common.descriptor.config.field.ConfigField; import com.synopsys.integration.alert.common.descriptor.config.field.errors.AlertFieldStatus; import com.synopsys.integration.alert.common.descriptor.config.field.validation.FieldValidationUtility; import com.synopsys.integration.alert.common.enumeration.ConfigContextEnum; import com.synopsys.integration.alert.common.enumeration.FrequencyType; import com.synopsys.integration.alert.common.enumeration.ProcessingType; import com.synopsys.integration.alert.common.exception.AlertRuntimeException; import com.synopsys.integration.alert.common.persistence.accessor.FieldUtility; import com.synopsys.integration.alert.common.persistence.accessor.JobAccessor; import com.synopsys.integration.alert.common.persistence.model.ConfigurationFieldModel; import com.synopsys.integration.alert.common.persistence.model.ConfigurationModel; import com.synopsys.integration.alert.common.persistence.model.DefinedFieldModel; import com.synopsys.integration.alert.common.persistence.model.job.DistributionJobModel; import com.synopsys.integration.alert.common.persistence.model.job.DistributionJobRequestModel; import com.synopsys.integration.alert.common.persistence.model.job.details.DistributionJobDetailsModel; import com.synopsys.integration.alert.common.rest.model.FieldModel; import com.synopsys.integration.alert.common.rest.model.FieldValueModel; import com.synopsys.integration.alert.common.rest.model.JobFieldModel; import com.synopsys.integration.alert.common.util.DataStructureUtils; import com.synopsys.integration.alert.database.api.DefaultConfigurationAccessor; import com.synopsys.integration.alert.database.api.DefaultDescriptorAccessor; import com.synopsys.integration.alert.database.configuration.repository.RegisteredDescriptorRepository; import com.synopsys.integration.alert.descriptor.api.model.ProviderKey; import com.synopsys.integration.alert.test.common.TestProperties; import com.synopsys.integration.alert.util.AlertIntegrationTest; import com.synopsys.integration.alert.web.api.job.JobFieldModelPopulationUtils; import com.synopsys.integration.exception.IntegrationException; @Transactional @AlertIntegrationTest public abstract class ChannelDescriptorTestIT { protected Gson gson; protected ContentConverter contentConverter; protected TestProperties testProperties; @Autowired protected ProviderKey providerKey; @Autowired protected JobAccessor jobAccessor; @Autowired protected DefaultConfigurationAccessor configurationAccessor; @Autowired protected DefaultDescriptorAccessor descriptorAccessor; @Autowired protected DescriptorProcessor descriptorProcessor; @Autowired protected RegisteredDescriptorRepository registeredDescriptorRepository; protected ConfigurationModel providerGlobalConfig; protected Optional<ConfigurationModel> optionalChannelGlobalConfig = Optional.empty(); protected DistributionJobModel distributionJobModel; protected String eventDestinationName; @BeforeEach public void init() throws Exception { gson = new Gson(); contentConverter = new ContentConverter(gson, new DefaultConversionService()); testProperties = new TestProperties(); providerGlobalConfig = saveProviderGlobalConfig(); optionalChannelGlobalConfig = saveGlobalConfiguration(); eventDestinationName = getEventDestinationName(); distributionJobModel = saveDistributionJob(); } @AfterEach public void cleanupTest() { if (null != configurationAccessor) { optionalChannelGlobalConfig.ifPresent(configurationAccessor::deleteConfiguration); if (null != providerGlobalConfig) { configurationAccessor.deleteConfiguration(providerGlobalConfig); } } if (null != jobAccessor && null != distributionJobModel && null != distributionJobModel.getJobId()) { jobAccessor.deleteJob(distributionJobModel.getJobId()); } } public Map<String, FieldValueModel> createFieldModelMap(List<ConfigurationFieldModel> configFieldModels) { Map<String, FieldValueModel> fieldModelMap = new HashMap<>(); for (ConfigurationFieldModel model : configFieldModels) { String key = model.getFieldKey(); Collection<String> values = List.of(); if (!model.isSensitive()) { values = model.getFieldValues(); } FieldValueModel fieldValueModel = new FieldValueModel(values, model.isSet()); fieldModelMap.put(key, fieldValueModel); } return fieldModelMap; } private FieldModel createValidFieldModel(ConfigurationModel configurationModel, ConfigContextEnum context) { Map<String, FieldValueModel> fieldValueMap = createFieldModelMap(configurationModel.getCopyOfFieldList()); if (ConfigContextEnum.DISTRIBUTION == context) { optionalChannelGlobalConfig.ifPresent(globalConfig -> fieldValueMap.putAll(createFieldModelMap(globalConfig.getCopyOfFieldList()))); } FieldModel model = new FieldModel(String.valueOf(configurationModel.getConfigurationId()), eventDestinationName, context.name(), fieldValueMap); return model; } public FieldUtility createValidGlobalFieldUtility(ConfigurationModel configurationModel) { Map<String, ConfigurationFieldModel> fieldMap = new HashMap<>(); fieldMap.putAll(configurationModel.getCopyOfKeyToFieldMap()); optionalChannelGlobalConfig.ifPresent(globalConfig -> fieldMap.putAll(globalConfig.getCopyOfKeyToFieldMap())); return new FieldUtility(fieldMap); } public FieldModel createInvalidGlobalFieldModel() { Map<String, String> invalidValuesMap = createInvalidGlobalFieldMap(); Map<String, FieldValueModel> fieldModelMap = createFieldValueModelMap(invalidValuesMap); FieldModel model = new FieldModel("1L", eventDestinationName, ConfigContextEnum.GLOBAL.name(), fieldModelMap); return model; } public Map<String, FieldValueModel> createFieldValueModelMap(Map<String, String> fieldValueMap) { Map<String, FieldValueModel> fieldModelMap = new HashMap<>(); for (Map.Entry<String, String> fieldValue : fieldValueMap.entrySet()) { String key = fieldValue.getKey(); String value = fieldValue.getValue(); FieldValueModel fieldValueModel = new FieldValueModel(List.of(value), StringUtils.isNotBlank(value)); fieldModelMap.put(key, fieldValueModel); } return fieldModelMap; } public FieldModel createFieldModel(String descriptorName, String emailAddress) { String context = ConfigContextEnum.DISTRIBUTION.name(); Map<String, FieldValueModel> keyToValues = new HashMap<>(); keyToValues.put(TestAction.KEY_DESTINATION_NAME, new FieldValueModel(List.of(emailAddress), false)); return new FieldModel(descriptorName, context, keyToValues); } public abstract Optional<ConfigurationModel> saveGlobalConfiguration() throws Exception; public abstract DistributionJobDetailsModel createDistributionJobDetails(); public abstract ChannelDescriptor getDescriptor(); public abstract boolean assertGlobalFields(Set<DefinedFieldModel> globalFields); public abstract boolean assertDistributionFields(Set<DefinedFieldModel> distributionFields); public abstract FieldModel createTestConfigDestination(); public abstract Map<String, String> createInvalidGlobalFieldMap(); public abstract String getEventDestinationName(); public abstract TestAction getGlobalTestAction(); public abstract DistributionChannelTestAction getDistributionChannelTestAction(); protected ConfigurationModel saveProviderGlobalConfig() { return configurationAccessor.createConfiguration(providerKey, ConfigContextEnum.GLOBAL, List.of()); } private DistributionJobModel saveDistributionJob() { DistributionJobRequestModel requestModel = new DistributionJobRequestModel( true, getClass().getSimpleName(), FrequencyType.REAL_TIME, ProcessingType.DEFAULT, eventDestinationName, providerGlobalConfig.getConfigurationId(), false, null, List.of("VULNERABILITY"), List.of(), List.of(), List.of(), createDistributionJobDetails() ); return jobAccessor.createJob(requestModel); } private Map<String, ConfigField> createFieldMap(ConfigContextEnum context) { return getDescriptor().getUIConfig(context) .map(uiConfig -> DataStructureUtils.mapToValues(uiConfig.getFields(), ConfigField::getKey)) .orElse(Map.of()); } @Test public void testDistributionConfig() { try { DistributionChannelTestAction descriptorActionApi = getDistributionChannelTestAction(); descriptorActionApi.testConfig(distributionJobModel, "Topic - Channel Descriptor Test IT", "Message - Channel Descriptor Test IT"); } catch (IntegrationException e) { e.printStackTrace(); fail(); } } @Test public void testDistributionValidate() { JobFieldModel jobFieldModel = JobFieldModelPopulationUtils.createJobFieldModelWithDefaultProviderProjectState(distributionJobModel); Map<String, ConfigField> configFields = new HashMap<>(); for (FieldModel singleFieldModelFromJob : jobFieldModel.getFieldModels()) { List<ConfigField> fieldsFromModel = descriptorProcessor.retrieveUIConfigFields(singleFieldModelFromJob.getContext(), singleFieldModelFromJob.getDescriptorName()); for (ConfigField fieldFromModel : fieldsFromModel) { String fieldKey = fieldFromModel.getKey(); if (!configFields.containsKey(fieldKey)) { configFields.put(fieldKey, fieldFromModel); } } } FieldValidationUtility fieldValidationAction = new FieldValidationUtility(); List<AlertFieldStatus> fieldErrors = fieldValidationAction.validateConfig(configFields, jobFieldModel.getFieldModels()); assertTrue(fieldErrors.isEmpty()); } @Test public void testDistributionValidateWithFieldErrors() { ConfigContextEnum context = ConfigContextEnum.DISTRIBUTION; FieldModel restModel = new FieldModel(eventDestinationName, context.name(), Map.of()); Map<String, ConfigField> configFieldMap = createFieldMap(context); FieldValidationUtility fieldValidationAction = new FieldValidationUtility(); List<AlertFieldStatus> fieldErrors = fieldValidationAction.validateConfig(configFieldMap, restModel); if (restModel.getKeyToValues().size() > 0) { assertEquals(restModel.getKeyToValues().size(), fieldErrors.size()); } } @Test public void testGlobalValidate() { ConfigurationModel globalChannelConfig = optionalChannelGlobalConfig .orElseThrow(() -> new AlertRuntimeException("Missing global channel config")); FieldModel restModel = createValidFieldModel(globalChannelConfig, ConfigContextEnum.GLOBAL); Map<String, ConfigField> configFieldMap = createFieldMap(ConfigContextEnum.GLOBAL); FieldValidationUtility fieldValidationAction = new FieldValidationUtility(); List<AlertFieldStatus> fieldErrors = fieldValidationAction.validateConfig(configFieldMap, restModel); assertTrue(fieldErrors.isEmpty(), StringUtils.join(fieldErrors, "; ")); } @Test public void testGlobalValidateWithFieldErrors() { // descriptor has a global configuration therefore continue testing FieldModel restModel = createInvalidGlobalFieldModel(); Map<String, ConfigField> configFieldMap = createFieldMap(ConfigContextEnum.GLOBAL); FieldValidationUtility fieldValidationAction = new FieldValidationUtility(); List<AlertFieldStatus> fieldErrors = fieldValidationAction.validateConfig(configFieldMap, restModel); assertEquals(restModel.getKeyToValues().size(), fieldErrors.size()); } @Test public void testDefinedFields() { assertTrue(assertGlobalFields(getDescriptor().getAllDefinedFields(ConfigContextEnum.GLOBAL))); assertTrue(assertDistributionFields(getDescriptor().getAllDefinedFields(ConfigContextEnum.DISTRIBUTION))); assertTrue(getDescriptor().getAllDefinedFields(null).isEmpty()); } }
/** * Copyright 2018 Smartrplace UG * * 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.smartrplace.logging.fendodb.grafana; import org.ogema.core.application.Application; import org.ogema.core.application.ApplicationManager; import org.ogema.core.security.WebAccessManager; import org.osgi.service.component.annotations.Component; @Component(service=Application.class) public class FendodbGrafanaConfig implements Application { private static final String WEB_PATH = "/org/smartrplace/logging/fendodb/grafana"; private ApplicationManager appMan; @Override public void start(ApplicationManager appManager) { this.appMan = appManager; final WebAccessManager wam = appManager.getWebAccessManager(); wam.registerWebResource(WEB_PATH + "/config", "webresources"); wam.registerStartUrl(WEB_PATH + "/config/config.html"); } @Override public void stop(AppStopReason reason) { try { appMan.getWebAccessManager().unregisterWebResource(WEB_PATH + "/config"); } catch (Exception e) { e.printStackTrace(); } } }
package org.andengine.engine.options.resolutionpolicy; import org.andengine.engine.options.resolutionpolicy.BaseResolutionPolicy; import android.view.View.MeasureSpec; /** * Based on CroppedResolutionPolicy by jgibbs, added methods to get corners coordinates * http://www.andengine.org/forums/gles2/targeting-multiple-display-resolutions-t6794.html#p29955 * * @author jgibbs, Martin Varga * */ public class CropResolutionPolicy extends BaseResolutionPolicy { private final float desiredWidth; private final float desiredHeight; private float userWidth; private float userHeight; private float left; private float right; private float top; private float bottom; public CropResolutionPolicy(float pWidth, float pHeight) { desiredWidth = pWidth; desiredHeight = pHeight; } @Override public void onMeasure(Callback pResolutionPolicyCallback, int pWidthMeasureSpec, int pHeightMeasureSpec) { BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec); final int measuredWidth = MeasureSpec.getSize(pWidthMeasureSpec); final int measuredHeight = MeasureSpec.getSize(pHeightMeasureSpec); final float desiredRatio = (float) desiredWidth / (float) desiredHeight; float scaleRatio; float resultWidth; float resultHeight; if ((float) measuredWidth / (float) measuredHeight < desiredRatio) { // Scale to fit height, width will crop resultWidth = measuredHeight * desiredRatio; resultHeight = measuredHeight; scaleRatio = desiredHeight / resultHeight; } else { // Scale to fit width, height will crop resultHeight = measuredWidth / desiredRatio; resultWidth = measuredWidth; scaleRatio = desiredWidth / resultWidth; } userWidth = measuredWidth * scaleRatio; userHeight = measuredHeight * scaleRatio; left = (desiredWidth - userWidth) / 2f; right = userWidth + left; bottom = (desiredHeight - userHeight) / 2f; top = userHeight + bottom; pResolutionPolicyCallback.onResolutionChanged(Math.round(resultWidth), Math.round(resultHeight)); } public float getUserWidth() { return userWidth; } public float getUserHeight() { return userHeight; } public float getLeft() { return left; } public float getRight() { return right; } public float getTop() { return top; } public float getBottom() { return bottom; } }
package cgeo.geocaching.sorting; import java.util.Comparator; import cgeo.geocaching.Geocache; public interface CacheComparator extends Comparator<Geocache> { }
package com.kunal.cyclicSort; class FirstMissingPositive { // Given an unsorted array containing numbers, find the smallest missing positive number in it. public static int findNumber(int[] nums) { int i = 0; while (i < nums.length) { if (nums[i] > 0 && nums[i] <= nums.length && nums[i] != nums[nums[i] - 1]) swap(nums, i, nums[i] - 1); else i++; } for (i = 0; i < nums.length; i++) if (nums[i] != i + 1) return i + 1; return nums.length + 1; } private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { System.out.println(FirstMissingPositive.findNumber(new int[]{-3, 1, 5, 4, 2})); System.out.println(FirstMissingPositive.findNumber(new int[]{3, -2, 0, 1, 2})); System.out.println(FirstMissingPositive.findNumber(new int[]{3, 2, 5, 1})); } }
// Copyrights (c) 2018-2019 FIRST, 2020 Highlanders FRC. All Rights Reserved. package frc.robot.commands.defaults; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.MagIntake; public class MagIntakeDefault extends CommandBase { private MagIntake magIntake; public MagIntakeDefault(MagIntake magIntake) { this.magIntake = magIntake; addRequirements(this.magIntake); } @Override public void initialize() {} @Override public void execute() { magIntake.setIntakePercent(0, 0); magIntake.intakePistonUp(); magIntake.setMagPercent(0, 0); } @Override public void end(boolean interrupted) {} @Override public boolean isFinished() { return false; } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.core.graph.processing.traverse.tree; import org.kie.workbench.common.stunner.core.graph.Edge; import org.kie.workbench.common.stunner.core.graph.Graph; import org.kie.workbench.common.stunner.core.graph.Node; public interface TreeTraverseCallback<G extends Graph, N extends Node, E extends Edge> { void startGraphTraversal( G graph ); boolean startNodeTraversal( N node ); boolean startEdgeTraversal( E edge ); void endNodeTraversal( N node ); void endEdgeTraversal( E edge ); void endGraphTraversal(); }
package com.chihurumnanya.itransmit.activities; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.MenuItem; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.chihurumnanya.itransmit.R; import com.chihurumnanya.itransmit.data.FirebaseDbContract; import com.chihurumnanya.itransmit.fragments.TripFactoryFragment; import com.chihurumnanya.itransmit.models.TripModel; import com.chihurumnanya.itransmit.utils.Constants; /** * Activity that holds the trip form fragment */ public class TripFactoryActivity extends FirebaseBaseActivity implements TripFactoryFragment.OnTripFactoryListener { private static final String TAG_TRIP_FACTORY_FRAGMENT = "tag_trip_factory_fragment"; private TripFactoryFragment mTripFactoryFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_trip_factory); mFirebaseDatabase = FirebaseDatabase.getInstance(); mFirebaseAuth = FirebaseAuth.getInstance(); mCurrentUser = mFirebaseAuth.getCurrentUser(); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { Intent intent = getIntent(); if (intent != null && intent.hasExtra(Constants.Extra.EXTRA_TRIP)) { // TripModel already exists TripModel trip = intent.getParcelableExtra(Constants.Extra.EXTRA_TRIP); mTripFactoryFragment = TripFactoryFragment.newInstance(trip); } else { // New trip mTripFactoryFragment = TripFactoryFragment.newInstance(null); } getSupportFragmentManager().beginTransaction() .add(R.id.trip_factory_fragment_container, mTripFactoryFragment, TAG_TRIP_FACTORY_FRAGMENT).commit(); } else { // Fragment already exists, just get it using its TAG mTripFactoryFragment = (TripFactoryFragment) getSupportFragmentManager() .findFragmentByTag(TAG_TRIP_FACTORY_FRAGMENT); } } @Override public void changeActionBarTitle(String newTitle) { if (getSupportActionBar() != null) { getSupportActionBar().setTitle(newTitle); } } @Override public void saveTrip(TripModel trip, boolean isEditMode) { if (trip != null) { final DatabaseReference tripReference = mFirebaseDatabase.getReference().child(FirebaseDbContract.Trips.PATH_TRIPS) .child(mCurrentUser.getUid()); if (isEditMode && !TextUtils.isEmpty(trip.getId())) { DatabaseReference databaseReference = tripReference.child(trip.getId()); databaseReference.setValue(trip); } else if (!isEditMode) { DatabaseReference databaseReference = tripReference.push(); trip.setId(databaseReference.getKey()); databaseReference.setValue(trip); } else { Toast.makeText(this, getString(R.string.trip_updated_error), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, getString(R.string.trip_updated_error), Toast.LENGTH_SHORT).show(); } finish(); } @Override public void deleteTrip(TripModel trip) { final DatabaseReference tripReference = mFirebaseDatabase.getReference().child(FirebaseDbContract.Trips.PATH_TRIPS) .child(mCurrentUser.getUid()); if (trip != null) { tripReference.child(trip.getId()).removeValue(); removeOtherTripData(trip); } else { Toast.makeText(this, getString(R.string.trip_updated_error), Toast.LENGTH_SHORT).show(); } finish(); } // Remove trip attributions, expenses, budgets and places private void removeOtherTripData(TripModel trip) { // Remove Trip attributions final DatabaseReference attributionsReference = mFirebaseDatabase.getReference() .child(FirebaseDbContract.Attributions.PATH_ATTRIBUTIONS) .child(mCurrentUser.getUid()) .child(trip.getId()); attributionsReference.removeValue(); // Remove Trip expenses final DatabaseReference expensesReference = mFirebaseDatabase.getReference() .child(FirebaseDbContract.Expenses.PATH_EXPENSES) .child(mCurrentUser.getUid()) .child(trip.getId()); expensesReference.removeValue(); // Remove Trip budgets final DatabaseReference budgetsReference = mFirebaseDatabase.getReference() .child(FirebaseDbContract.Budgets.PATH_BUDGETS) .child(mCurrentUser.getUid()) .child(trip.getId()); budgetsReference.removeValue(); // Remove Trip places final DatabaseReference placesReference = mFirebaseDatabase.getReference() .child(FirebaseDbContract.Places.PATH_PLACES) .child(mCurrentUser.getUid()) .child(trip.getId()); placesReference.removeValue(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // To animate transition like back button press finish(); return true; } return super.onOptionsItemSelected(item); } }
/* * MIT License * * Copyright (c) 2017 dkzwm * Copyright (c) 2015 liaohuqiu.net * * 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 me.dkzwm.widget.srl.util; import android.os.Build; import android.view.View; import android.webkit.WebView; import android.widget.AbsListView; import android.widget.Adapter; import android.widget.ListView; import android.widget.ScrollView; import androidx.core.view.ScrollingView; import androidx.core.widget.NestedScrollView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.PagerSnapHelper; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; /** @author dkzwm */ public class ScrollCompat { public static boolean canAutoLoadMore(View view) { if (view instanceof AbsListView) { AbsListView listView = (AbsListView) view; final int lastVisiblePosition = listView.getLastVisiblePosition(); final Adapter adapter = listView.getAdapter(); return adapter != null && adapter.getCount() > 0 && lastVisiblePosition >= 0 && lastVisiblePosition >= adapter.getCount() - 1; } else if (ViewCatcherUtil.isRecyclerView(view)) { RecyclerView recyclerView = (RecyclerView) view; RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager == null) { return false; } int lastVisiblePosition = -1; if (manager instanceof LinearLayoutManager) { LinearLayoutManager linearManager = ((LinearLayoutManager) manager); if (linearManager.getOrientation() == RecyclerView.HORIZONTAL) { return false; } lastVisiblePosition = linearManager.findLastVisibleItemPosition(); } else if (manager instanceof StaggeredGridLayoutManager) { StaggeredGridLayoutManager gridLayoutManager = (StaggeredGridLayoutManager) manager; if (gridLayoutManager.getOrientation() == RecyclerView.HORIZONTAL) { return false; } int[] lastPositions = new int[gridLayoutManager.getSpanCount()]; gridLayoutManager.findLastVisibleItemPositions(lastPositions); for (int value : lastPositions) { if (value > lastVisiblePosition) { lastVisiblePosition = value; } } } RecyclerView.Adapter adapter = recyclerView.getAdapter(); return adapter != null && adapter.getItemCount() > 0 && lastVisiblePosition >= 0 && lastVisiblePosition >= adapter.getItemCount() - 1; } return false; } public static boolean canAutoRefresh(View view) { if (view instanceof AbsListView) { AbsListView listView = (AbsListView) view; final int lastVisiblePosition = listView.getLastVisiblePosition(); final Adapter adapter = listView.getAdapter(); return adapter != null && lastVisiblePosition == 0; } else if (ViewCatcherUtil.isRecyclerView(view)) { RecyclerView recyclerView = (RecyclerView) view; RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager == null) { return false; } int firstVisiblePosition = -1; if (manager instanceof LinearLayoutManager) { LinearLayoutManager linearManager = ((LinearLayoutManager) manager); if (linearManager.getOrientation() == RecyclerView.HORIZONTAL) { return false; } firstVisiblePosition = linearManager.findFirstVisibleItemPosition(); } else if (manager instanceof StaggeredGridLayoutManager) { StaggeredGridLayoutManager gridLayoutManager = (StaggeredGridLayoutManager) manager; if (gridLayoutManager.getOrientation() == RecyclerView.HORIZONTAL) { return false; } int[] firstPositions = new int[gridLayoutManager.getSpanCount()]; gridLayoutManager.findFirstVisibleItemPositions(firstPositions); for (int value : firstPositions) { if (value == 0) { firstVisiblePosition = 0; break; } } } RecyclerView.Adapter adapter = recyclerView.getAdapter(); return adapter != null && firstVisiblePosition == 0; } return false; } public static boolean scrollCompat(View view, float deltaY) { if (view != null) { if (view instanceof AbsListView) { final AbsListView absListView = (AbsListView) view; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { absListView.scrollListBy((int) deltaY); } else if (absListView instanceof ListView) { // {@link android.support.v4.widget.ListViewCompat#scrollListBy(ListView, // int)} final ListView listView = (ListView) absListView; final int firstPosition = listView.getFirstVisiblePosition(); if (firstPosition == ListView.INVALID_POSITION) { return false; } final View firstView = listView.getChildAt(0); if (firstView == null) { return false; } final int newTop = (int) (firstView.getTop() - deltaY); listView.setSelectionFromTop(firstPosition, newTop); } else { absListView.smoothScrollBy((int) deltaY, 0); } return true; } else if (view instanceof WebView || view instanceof ScrollView || view instanceof NestedScrollView) { view.scrollBy(0, (int) deltaY); return true; } else if (ViewCatcherUtil.isRecyclerView(view)) { RecyclerView recyclerView = (RecyclerView) view; if (!(recyclerView.getOnFlingListener() instanceof PagerSnapHelper)) { // Fix the problem of adding new data to RecyclerView while in Fling state, // the new items will continue to Fling if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_SETTLING) { recyclerView.stopScroll(); } view.scrollBy(0, (int) deltaY); } return true; } } return false; } public static boolean canScaleInternal(View view) { return view instanceof ScrollView && ((ScrollView) view).getChildCount() > 0 || view instanceof NestedScrollView && ((NestedScrollView) view).getChildCount() > 0; } public static boolean isScrollingView(View view) { if (view instanceof AbsListView || view instanceof ScrollView || view instanceof WebView) { return true; } if (ViewCatcherUtil.isRecyclerView(view)) { RecyclerView recyclerView = (RecyclerView) view; RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager != null) { if (manager instanceof LinearLayoutManager) { LinearLayoutManager linearManager = ((LinearLayoutManager) manager); return linearManager.getOrientation() == RecyclerView.VERTICAL; } else if (manager instanceof StaggeredGridLayoutManager) { StaggeredGridLayoutManager gridLayoutManager = (StaggeredGridLayoutManager) manager; return gridLayoutManager.getOrientation() == RecyclerView.VERTICAL; } } return true; } else { return view instanceof ScrollingView; } } public static void flingCompat(View view, int velocityY) { if (view instanceof ScrollView) { ScrollView scrollView = (ScrollView) view; scrollView.fling(velocityY); } else if (view instanceof WebView) { WebView webView = (WebView) view; webView.flingScroll(0, velocityY); } else if (view instanceof NestedScrollView) { NestedScrollView scrollView = (NestedScrollView) view; scrollView.fling(velocityY); } else if (view instanceof AbsListView) { AbsListView listView = (AbsListView) view; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { listView.fling(velocityY); } } else if (ViewCatcherUtil.isRecyclerView(view)) { RecyclerView recyclerView = (RecyclerView) view; recyclerView.fling(0, velocityY); } } public static void stopFling(View view) { if (view instanceof ScrollView) { ScrollView scrollView = (ScrollView) view; scrollView.smoothScrollBy(0, 0); } else if (view instanceof WebView) { WebView webView = (WebView) view; webView.flingScroll(0, 0); } else if (view instanceof NestedScrollView) { NestedScrollView scrollView = (NestedScrollView) view; scrollView.smoothScrollBy(0, 0); } else if (view instanceof AbsListView) { AbsListView listView = (AbsListView) view; listView.smoothScrollBy(0, 0); } else if (ViewCatcherUtil.isRecyclerView(view)) { RecyclerView recyclerView = (RecyclerView) view; recyclerView.stopScroll(); } } }
package be.renaudraas.playground.util; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import be.renaudraas.playground.business.mapper.Mapper; public class ListUtils { private ListUtils() { } @NonNull public static <To, From> List<To> convert(@Nullable Collection<From> source, Mapper<From, To> mapper) { if (source == null) { return new ArrayList<>(); } List<To> results = new ArrayList<>(source.size()); for (From object : source) { To instance = mapper.map(object); results.add(instance); } return results; } }
package hr.unidu.oop.p03; public class GreskaStatic { private int x, y; public static void main(String[] args) { // gre�ka kod prevo�enja jer se iz static metode // poku�avaju koristiti varijable i metode koje nisu static //x=3; //y=5; // System.out.println(x + " + " + y + " = "+zbroj(x,y)); } public int zbroj(int a, int b) { return a+b; } }
/* * Copyright 2014 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.spinnaker.clouddriver.model; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.netflix.spinnaker.clouddriver.documentation.Empty; import com.netflix.spinnaker.clouddriver.names.NamerRegistry; import com.netflix.spinnaker.moniker.Moniker; import java.util.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * A server group provides a relationship to many instances, and exists within a defined region and * one or more zones. */ public interface ServerGroup { /** * The name of the server group * * @return name */ String getName(); /** * This resource's moniker * * @return */ default Moniker getMoniker() { return NamerRegistry.getDefaultNamer().deriveMoniker(this); } /** * Some arbitrary identifying type for this server group. May provide vendor-specific * identification or data-center awareness to callers. * * @deprecated use #getCloudProvider * @return type */ String getType(); /** Provider-specific identifier */ String getCloudProvider(); /** * The region in which the instances of this server group are known to exist. * * @return server group region */ String getRegion(); /** * Some vendor-specific indicator that the server group is disabled * * @return true if the server group is disabled; false otherwise */ @JsonGetter Boolean isDisabled(); /** * Timestamp indicating when the server group was created * * @return the number of milliseconds after the beginning of time (1 January, 1970 UTC) when this * server group was created */ Long getCreatedTime(); /** * The zones within a region that the instances within this server group occupy. * * @return zones of a region for which this server group has presence or is capable of having * presence, or an empty set if none exist */ @Empty Set<String> getZones(); /** * The concrete instances that comprise this server group * * @return set of instances or an empty set if none exist */ @Empty Set<? extends Instance> getInstances(); /** * The names of the load balancers associated with this server group * * @return the set of load balancer names or an empty set if none exist */ @Empty Set<String> getLoadBalancers(); /** * The names of the security groups associated with this server group * * @return the set of security group names or an empty set if none exist */ @Empty Set<String> getSecurityGroups(); /** * A collection of attributes describing the launch configuration of this server group * * @return a map containing various attributes of the launch configuration */ @Empty Map<String, Object> getLaunchConfig(); /** * A collection of attributes describing the tags of this server group * * @return a map containing various tags */ @Empty default Map<String, Object> getTags() { return null; } /** * A data structure with the total number of instances, and the number of instances reporting each * status * * @return a data structure */ InstanceCounts getInstanceCounts(); /** * The capacity (in terms of number of instances) required for the server group * * @return */ Capacity getCapacity(); /** * This represents all images deployed to the server group. For most providers, this will be a * singleton. */ @JsonIgnore ImagesSummary getImagesSummary(); /** * An ImageSummary is collection of data related to the build and VM image of the server group. * This is merely a view of data from other parts of this object. * * <p>Deprecated in favor of getImagesSummary, which is a more generic getImageSummary. */ @JsonIgnore @Deprecated ImageSummary getImageSummary(); default List<ServerGroupManager.ServerGroupManagerSummary> getServerGroupManagers() { return new ArrayList<>(); } default Map<String, String> getLabels() { return new HashMap<>(); } @JsonIgnore default Map<String, Object> getExtraAttributes() { return Collections.EMPTY_MAP; } @Builder @NoArgsConstructor @AllArgsConstructor @Data static class InstanceCounts { /** Total number of instances in the server group */ private Integer total = 0; /** Total number of "Up" instances (all health indicators report "Up" or "Unknown") */ private Integer up = 0; /** Total number of "Down" instances (at least one health indicator reports "Down") */ private Integer down = 0; /** * Total number of "Unknown" instances (all health indicators report "Unknown", or no health * indicators reported) */ private Integer unknown = 0; /** * Total number of "OutOfService" instances (at least one health indicator reports * "OutOfService", none are "Down" */ private Integer outOfService = 0; /** * Total number of "Starting" instances (where any health indicator reports "Starting" and none * are "Down" or "OutOfService") */ private Integer starting = 0; } @Builder @NoArgsConstructor @AllArgsConstructor @Data public static class Capacity { /** * Minimum number of instances required in this server group. If provider specific {@code * ServerGroup} does not have a notion of min then this should be same as {@code desired} */ private Integer min; /** * Max number of instances required in this server group. If provider specific {@code * ServerGroup} does not have a notion of max then this should be same as {@code desired} */ private Integer max; /** Desired number of instances required in this server group */ private Integer desired; } /** * Cloud provider-specific data related to the build and VM image of the server group. Deprecated * in favor of Images summary */ @JsonInclude(NON_NULL) public static interface ImageSummary extends Summary { String getServerGroupName(); String getImageId(); String getImageName(); Map<String, Object> getImage(); @Empty Map<String, Object> getBuildInfo(); } /** Cloud provider-specific data related to the build and VM image of the server group. */ @JsonInclude(NON_NULL) public static interface ImagesSummary extends Summary { List<? extends ImageSummary> getSummaries(); } }
package org.company.asm; import org.company.App; import org.company.junit.JUnitTest; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import static org.company.asm.MyClassVisitor.normalizeDesc; import static org.company.junit.Const.*; public class ASMUtil { public static ClassWriter addAnnotationToClass(InputStream fis, boolean isJunit5) throws IOException { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(fis); classReader.accept(classNode, 0); String annotationToAdd = isJunit5 ? kDisabledAnnotationFQN : kIgnoreAnnotationFQN; if (classNode.invisibleAnnotations == null) classNode.invisibleAnnotations = new ArrayList<>(); if (classNode.visibleAnnotations == null) classNode.visibleAnnotations = new ArrayList<>(); boolean annotationAlreadyPresent = false; AnnotationNode testAnnotationToRemove = null; for (AnnotationNode oldAnnotation : classNode.invisibleAnnotations) { if (oldAnnotation.desc.equals(annotationToAdd)) annotationAlreadyPresent = true; if (oldAnnotation.desc.equals(kTestAnnotationFQN5) || oldAnnotation.desc.equals(kTestAnnotationFQN4)) testAnnotationToRemove = oldAnnotation; } if (!annotationAlreadyPresent) classNode.invisibleAnnotations.add(new AnnotationNode(annotationToAdd)); classNode.invisibleAnnotations.remove(testAnnotationToRemove); annotationAlreadyPresent = false; testAnnotationToRemove = null; for (AnnotationNode oldAnnotation : classNode.visibleAnnotations) { if (oldAnnotation.desc.equals(annotationToAdd)) annotationAlreadyPresent = true; if (oldAnnotation.desc.equals(kTestAnnotationFQN5) || oldAnnotation.desc.equals(kTestAnnotationFQN4)) testAnnotationToRemove = oldAnnotation; } if (!annotationAlreadyPresent) classNode.visibleAnnotations.add(new AnnotationNode(annotationToAdd)); classNode.visibleAnnotations.remove(testAnnotationToRemove); //ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); if I have the // ClassWriter.COMPUTE_FRAMES flag, I get a java.lang.TypeNotPresentException // (see https://stackoverflow.com/questions/26573945/classnotfoundexception-at-asm-objectwriter-getcommonsuperclass) // so let's try with the COMPUTE_MAXS flag //ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); //ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // https://stackoverflow.com/questions/35145997/asm-5-0-3-with-java-1-8-incorrect-maxstack-with-java-lang-verifyerror-operand-s?noredirect=1#comment58021378_35145997 ClassWriter classWriter = new ByteCodeWriter(classReader, App.class.getClassLoader(), ClassWriter.COMPUTE_FRAMES); classNode.accept(classWriter); return classWriter; } public static boolean thereAreNoMoreTests; public static ClassWriter addAnnotationToIgnoreTests(InputStream fis, ArrayList<JUnitTest> tests, boolean annotateAllMethods) throws IOException { App.logger.info("[{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", "adding annotations to tests to ignore (there are " + tests.size() + " tests to ignore)"); ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(fis); classReader.accept(classNode, 0); ArrayList<JUnitTest> testsWithNewAnnotation = new ArrayList<>(); thereAreNoMoreTests = true; for (MethodNode method : classNode.methods) { if (!method.name.equals("<init>") && !method.name.equals("<clinit>")) { String name = method.name + normalizeDesc(method.desc); boolean annotationAlreadyPresent; if (method.invisibleAnnotations == null) method.invisibleAnnotations = new ArrayList<>(); if (method.visibleAnnotations == null) method.visibleAnnotations = new ArrayList<>(); boolean thisMethodIsATest = false; for (AnnotationNode oldAnnotation : method.invisibleAnnotations) { if (oldAnnotation.desc.equals(kTestAnnotationFQN5) || oldAnnotation.desc.equals(kTestAnnotationFQN4)) { thisMethodIsATest = true; break; } } for (AnnotationNode oldAnnotation : method.visibleAnnotations) { if (oldAnnotation.desc.equals(kTestAnnotationFQN5) || oldAnnotation.desc.equals(kTestAnnotationFQN4)) { thisMethodIsATest = true; break; } } boolean thisTestWasProcessed = false; for (JUnitTest test: tests) { if (name.equals(test.getMethodName() + test.getDescWithoutReturningType()) || annotateAllMethods) { App.logger.info("[{}{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", "processing annotations of test ", name); thisTestWasProcessed = true; AnnotationNode testAnnotationToRemove = null; String annotationToAdd = test.isJunit5() ? kDisabledAnnotationFQN : kIgnoreAnnotationFQN; for (AnnotationNode oldAnnotation : method.invisibleAnnotations) { if (oldAnnotation.desc.equals(annotationToAdd)) annotationAlreadyPresent = true; if (oldAnnotation.desc.equals(kTestAnnotationFQN5) || oldAnnotation.desc.equals(kTestAnnotationFQN4)) testAnnotationToRemove = oldAnnotation; } // add annotation in visible annotations // if (!annotationAlreadyPresent) { // method.invisibleAnnotations.add(new AnnotationNode(annotationToAdd)); // App.logger.info("[{}{}{}{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", // "annotating method ", name, " with invisible annotation ", annotationToAdd); // } // else // App.logger.info("[{}{}{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", // "annotation ", annotationToAdd, " is already present in invisible annotations"); if (testAnnotationToRemove != null) { method.invisibleAnnotations.remove(testAnnotationToRemove); App.logger.info("[{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", "@Test annotation was present in invisible annotations, now removed"); } else App.logger.info("[{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", "@Test annotation was not present in invisible annotations"); testAnnotationToRemove = null; annotationAlreadyPresent = false; for (AnnotationNode oldAnnotation : method.visibleAnnotations) { if (oldAnnotation.desc.equals(annotationToAdd)) annotationAlreadyPresent = true; if (oldAnnotation.desc.equals(kTestAnnotationFQN5) || oldAnnotation.desc.equals(kTestAnnotationFQN4)) testAnnotationToRemove = oldAnnotation; } if (!annotationAlreadyPresent) { method.visibleAnnotations.add(new AnnotationNode(annotationToAdd)); App.logger.info("[{}{}{}{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", "annotating method ", name, " with visible annotation ", annotationToAdd); } else App.logger.info("[{}{}{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", "annotation ", annotationToAdd, " is already present in visible annotations"); if (testAnnotationToRemove != null) { method.visibleAnnotations.remove(testAnnotationToRemove); App.logger.info("[{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", "@Test annotation was present in visible annotations, now removed"); } else App.logger.info("[{}{}{}", "ASMUtil", " (" + "addAnnotationToIgnoreTests" + ")]: ", "@Test annotation was not present in visible annotations"); testsWithNewAnnotation.add(test); } } // if this method was a test, but we did not process it, it means that // the class will still contain at least one test if (thisMethodIsATest && !thisTestWasProcessed) thereAreNoMoreTests = false; } } tests.removeAll(testsWithNewAnnotation); //ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); if I have the // ClassWriter.COMPUTE_FRAMES flag, I get a java.lang.TypeNotPresentException // (see https://stackoverflow.com/questions/26573945/classnotfoundexception-at-asm-objectwriter-getcommonsuperclass) // so let's try with the COMPUTE_MAXS flag //ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); //ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // https://stackoverflow.com/questions/35145997/asm-5-0-3-with-java-1-8-incorrect-maxstack-with-java-lang-verifyerror-operand-s?noredirect=1#comment58021378_35145997 ClassWriter classWriter = new ByteCodeWriter(classReader, App.class.getClassLoader(), ClassWriter.COMPUTE_FRAMES); classNode.accept(classWriter); return classWriter; } }
package com.example.grpwork; import androidx.appcompat.app.AppCompatActivity; import android.app.ActivityOptions; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Pair; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static int LANCALEARN_SCREEN=5000; //Variables Animation topAmin, bottomAmin; ImageView image; TextView logo, groupname; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Animation topAmin= AnimationUtils.loadAnimation(this,R.anim.top_animation); bottomAmin= AnimationUtils.loadAnimation(this,R.anim.bottom_animation); //hooks image= findViewById(R.id.imageView); logo= findViewById(R.id.textView); groupname= findViewById(R.id.textView2); image.setAnimation(topAmin); logo.setAnimation(bottomAmin); groupname.setAnimation(bottomAmin); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent=new Intent(MainActivity.this,Dashboard.class); Pair[ ]pairs=new Pair[2]; pairs[0]=new Pair<View, String>(image,"logo_image"); pairs[1]=new Pair<View, String>(logo,"logo_text"); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this,pairs); startActivity(intent,options.toBundle()); } } }, LANCALEARN_SCREEN); } }
package com.example.moviestvshowsinfo.Utils.JSONUtils; import android.text.TextUtils; import com.example.moviestvshowsinfo.MovieTvShowsDetails; import com.example.moviestvshowsinfo.R; import com.example.moviestvshowsinfo.Utils.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public final class JSONParsing { private static URL createUrl(String string) { URL url = null; try { url = new URL(string); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } public static String makeHttpRequest(URL url) { String jsonResponse = ""; if (url == null) { return jsonResponse; } HttpURLConnection httpURLConnection = null; InputStream inputStream = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(10000); httpURLConnection.setReadTimeout(15000); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); if (httpURLConnection.getResponseCode() == 200) { inputStream = httpURLConnection.getInputStream(); Scanner scanner = new Scanner(inputStream); scanner.useDelimiter("\\A"); while (scanner.hasNext()) { jsonResponse = scanner.next(); } scanner.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return jsonResponse; } private static List<MovieTvShowsDetails> extractDataFromJsonResponse(String jsonResponse) { List<MovieTvShowsDetails> list = new ArrayList<>(); if (TextUtils.isEmpty(jsonResponse)) { return null; } try { JSONObject jsonObject = new JSONObject(jsonResponse); JSONArray results = jsonObject.optJSONArray("results"); if (results != null && results.length() != 0) { for (int i = 0; i < results.length(); i++) { JSONObject currentMovie = results.optJSONObject(i); int movieTvShowId = currentMovie.optInt("id"); String title = currentMovie.optString("title"); if (title == null || title.isEmpty()) { title = currentMovie.optString("name"); if (title == null || title.isEmpty()) { title = ""; } } String language = currentMovie.optString("original_language"); if (language == null || language.isEmpty()) { language = ""; } else { String[] languageCodes = Utils.getMainContext().getResources().getStringArray(R.array.languages_iso_639_1_codes); String[] languageNames = Utils.getMainContext().getResources().getStringArray(R.array.languages_english_names); for (int j = 0; j < languageCodes.length; j++) { if (languageCodes[j].equals(language)) { language = languageNames[j]; } } } String releaseDate = currentMovie.optString("release_date"); if (releaseDate == null || releaseDate.isEmpty()) { releaseDate = ""; } if (releaseDate == null || releaseDate.isEmpty()) { releaseDate = currentMovie.optString("first_air_date"); if (releaseDate == null || releaseDate.isEmpty()) { releaseDate = ""; } } if (releaseDate != null && !releaseDate.isEmpty()) { String year = releaseDate.substring(2, 4); String month = releaseDate.substring(5, 7); String day = releaseDate.substring(8, 10); releaseDate = day + "-" + month + "-" + year; } boolean adult = false; adult = currentMovie.optBoolean("adult"); double averageVote = currentMovie.optDouble("vote_average"); if (averageVote < 1) { averageVote = 0; } String posterPath = ""; String backgroundPath = ""; if (!currentMovie.isNull("poster_path")) { posterPath = currentMovie.optString("poster_path"); posterPath = "https://image.tmdb.org/t/p/original" + posterPath; } if (!currentMovie.isNull("backdrop_path")) { backgroundPath = currentMovie.optString("backdrop_path"); backgroundPath = "https://image.tmdb.org/t/p/original" + backgroundPath; } JSONArray genreIds = currentMovie.optJSONArray("genre_ids"); String genres = ""; if (genreIds != null) { int[] genresIntegerArray = Utils.getMainContext().getResources().getIntArray(R.array.movies_tv_shows_integer_genres_array); String[] genresStringArray = Utils.getMainContext().getResources().getStringArray(R.array.movies_tv_shows_string_genres_array); for (int j = 0; j < genreIds.length(); j++) { int id = genreIds.optInt(j); for (int k = 0; k < genresIntegerArray.length; k++) { if (id == genresIntegerArray[k]) { genres = genres + genresStringArray[k] + ", "; } } } if (genres != null && !genres.isEmpty()) { genres = genres.substring(0, genres.length() - 2); } } MovieTvShowsDetails currentMovieTvShowsDetails = new MovieTvShowsDetails(movieTvShowId, title, genres, language, releaseDate, averageVote, adult, posterPath, backgroundPath); list.add(currentMovieTvShowsDetails); } } else { list = null; } } catch (JSONException e) { e.printStackTrace(); } return list; } private static MovieTvShowsDetails extractDataFromJsonResponesForDetails(String jsonResponse) { MovieTvShowsDetails movieTvShowsDetails = null; if (TextUtils.isEmpty(jsonResponse)) { return null; } try { JSONObject jsonObject = new JSONObject(jsonResponse); int movieTvShowId = jsonObject.optInt("id"); String title = jsonObject.optString("title"); if (title == null || title.isEmpty()) { title = jsonObject.optString("name"); if (title == null || title.isEmpty()) { title = ""; } } String genres = ""; JSONArray genresArray = jsonObject.optJSONArray("genres"); if (genresArray != null) { for (int i = 0; i < genresArray.length(); i++) { JSONObject currentGenre = genresArray.getJSONObject(i); String genreName = currentGenre.optString("name"); genres = genres + genreName + ", "; } if (genres != null && !genres.isEmpty()) { genres = genres.substring(0, genres.length() - 2); } } String language = jsonObject.optString("original_language"); if (language == null || language.isEmpty()) { language = ""; }else { String[] languageCodes = Utils.getMainContext().getResources().getStringArray(R.array.languages_iso_639_1_codes); String[] languageNames = Utils.getMainContext().getResources().getStringArray(R.array.languages_english_names); for (int i = 0; i < languageCodes.length; i++) { if (languageCodes[i].equals(language)) { language = languageNames[i]; } } } String releaseDate = jsonObject.optString("release_date"); if (releaseDate == null || releaseDate.isEmpty()) { releaseDate = jsonObject.optString("first_air_date"); if (releaseDate == null || releaseDate.isEmpty()) { releaseDate = ""; } } if (releaseDate != null && !releaseDate.isEmpty()) { String year = releaseDate.substring(2, 4); String month = releaseDate.substring(5, 7); String day = releaseDate.substring(8, 10); releaseDate = day + "-" + month + "-" + year; } double averageVote = jsonObject.optDouble("vote_average"); if (averageVote < 1) { averageVote = 0; } boolean adult = false; adult = jsonObject.optBoolean("adult"); String posterPath = ""; String backgroundPath = ""; if (!jsonObject.isNull("poster_path")) { posterPath = jsonObject.optString("poster_path"); posterPath = "https://image.tmdb.org/t/p/original" + posterPath; } if (!jsonObject.isNull("backdrop_path")) { backgroundPath = jsonObject.optString("backdrop_path"); backgroundPath = "https://image.tmdb.org/t/p/original" + backgroundPath; } String overView = jsonObject.optString("overview"); if (overView == null || overView.isEmpty()) { overView = ""; } int budget = jsonObject.optInt("budget"); if (budget < 1) { budget = 0; } int revenue = jsonObject.optInt("revenue"); if (revenue < 1) { revenue = 0; } String productionCompanies = ""; JSONArray productionComapniesArray = jsonObject.optJSONArray("production_companies"); if (productionComapniesArray != null) { int companyCount = 1; for (int i = 0; i < productionComapniesArray.length(); i++) { JSONObject currentComapny = productionComapniesArray.optJSONObject(i); String companyName = companyCount + "- " + currentComapny.optString("name"); productionCompanies = productionCompanies + companyName + "\n"; companyCount++; } } movieTvShowsDetails = new MovieTvShowsDetails(movieTvShowId, title, genres, language, releaseDate, averageVote, adult, posterPath, backgroundPath, overView, budget, revenue, productionCompanies); } catch (JSONException e) { e.printStackTrace(); } return movieTvShowsDetails; } private static String extractYoutubeVideoKeyFromJsonResponse(String jsonResponse) { String youTubeVideoKey = ""; if (jsonResponse == null || jsonResponse.isEmpty()) { return null; } try { JSONObject jsonObject = new JSONObject(jsonResponse); JSONArray resultsArray = jsonObject.optJSONArray("results"); if (resultsArray != null) { for (int i = 0; i < resultsArray.length(); i++) { JSONObject currentResult = resultsArray.optJSONObject(i); String type = currentResult.optString("type"); if (type.equals("Trailer")) { youTubeVideoKey = currentResult.optString("key"); break; } else if (type.equals("Teaser")) { youTubeVideoKey = currentResult.optString("key"); } } } } catch ( JSONException e) { e.printStackTrace(); } return youTubeVideoKey; } /** * {@fetchDataForList} loads the list of Movies or Tv Shows. */ public static List<MovieTvShowsDetails> fetchDataForList(String stringUrl) { URL url = createUrl(stringUrl); String jsonResponse = makeHttpRequest(url); List<MovieTvShowsDetails> list = extractDataFromJsonResponse(jsonResponse); return list; } /** * {@fetchDataForDetails} loads the details of specific Movie or Tv Show. */ public static MovieTvShowsDetails fetchDataForDetails(String stringUrl) { URL url = createUrl(stringUrl); String jsonResponse = makeHttpRequest(url); MovieTvShowsDetails movieTvShowsDetails = extractDataFromJsonResponesForDetails(jsonResponse); return movieTvShowsDetails; } /** * {@fetchYoutubeVideoKey} loads the Youtube Video Key of specific Movie or Tv Show. */ public static String fetchYoutubeVideoKey(String stringUrl) { URL url = createUrl(stringUrl); String jsonResponse = makeHttpRequest(url); String youTubeVideoKey = extractYoutubeVideoKeyFromJsonResponse(jsonResponse); return youTubeVideoKey; } }
package br.com.zupacademy.rayllanderson.ecommerce.products.questions.requests; import br.com.zupacademy.rayllanderson.ecommerce.products.model.Product; import br.com.zupacademy.rayllanderson.ecommerce.products.questions.model.Question; import br.com.zupacademy.rayllanderson.ecommerce.users.model.User; import com.fasterxml.jackson.annotation.JsonCreator; import javax.validation.constraints.NotBlank; public class QuestionPostRequest { @NotBlank private final String title; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public QuestionPostRequest(@NotBlank String title) { this.title = title; } public Question toModel(User user, Product product){ return new Question(title, user, product); } }
package com.bsu.sed.controller; import com.bsu.sed.dto.ContactDto; import com.bsu.sed.model.SystemAttributeKey; import com.bsu.sed.model.TextKey; import com.bsu.sed.model.Tiles; import com.bsu.sed.service.MailService; import com.bsu.sed.service.SystemAttributeService; import com.bsu.sed.service.TextService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.transaction.Transactional; /** * @author gbondarchuk */ @Controller @RequestMapping("/contact") public class ContactController { @Autowired private MailService mailService; @Autowired private TextService textService; @Autowired private SystemAttributeService systemAttributeService; @RequestMapping public ModelAndView getContactPage() { ModelAndView modelAndView = new ModelAndView(Tiles.CONTACT_PAGE.getTileName()); modelAndView.addObject("contactDetails", textService.get(TextKey.CONTACT_DETAILS)); modelAndView.addObject("mapURL", systemAttributeService.get(SystemAttributeKey.MAP_URL)); return modelAndView; } @RequestMapping(value = "", method = RequestMethod.POST) public ModelAndView sendMessage(@ModelAttribute ContactDto dto) { ModelAndView modelAndView = new ModelAndView(Tiles.CONTACT_PAGE.getTileName()); mailService.sendContactMessage(dto); modelAndView.addObject("success", "Successfully sent"); return modelAndView; } }
package search.ex1.screen.event; import io.jmix.ui.screen.*; import search.ex1.entity.Event; @UiController("sample_Event.browse") @UiDescriptor("event-browse.xml") @LookupComponent("eventsTable") public class EventBrowse extends StandardLookup<Event> { }
package p03_CardsWithPower; public enum Rank { ACE (14), TWO (2), THREE (3), FOUR (4), FIVE (5), SIX (6), SEVEN (7), EIGHT (8), NINE (9), TEN (10), JACK (11), QUEEN (12), KING (13); private int rankPower; Rank(int rankPower) { this.rankPower = rankPower; } public int getRankPower() { return rankPower; } @Override public String toString() { return this.name(); } }
package com.nanosai.streamops.storage.file; public class StreamStorageBlockFS { private String fileName = null; private long firstOffset = 0; protected long fileLength = 0; public StreamStorageBlockFS(String fileName, long fileLength, long firstOffset) { this.fileName = fileName; this.fileLength = fileLength; this.firstOffset = firstOffset; } public String getFileName() { return this.fileName; } public long getFirstOffset() { return firstOffset; } public long getFileLength() { return this.fileLength; } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.completion; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtilBase; import javax.annotation.Nonnull; /** * @author yole */ class CompletionInitializationContextImpl extends CompletionInitializationContext { private final OffsetsInFile myHostOffsets; CompletionInitializationContextImpl(Editor editor, @Nonnull Caret caret, PsiFile file, CompletionType completionType, int invocationCount) { super(editor, caret, PsiUtilBase.getLanguageInEditor(editor, file.getProject()), file, completionType, invocationCount); myHostOffsets = new OffsetsInFile(file, getOffsetMap()).toTopLevelFile(); } @Nonnull OffsetsInFile getHostOffsets() { return myHostOffsets; } }
/* TallerTower: An RPG Copyright (C) 2011-2012 Eric Ahnell Any questions should be directed to the author via email at: products@puttysoftware.com */ package com.puttysoftware.tallertower.creatures.castes.predefined; import com.puttysoftware.tallertower.creatures.castes.Caste; import com.puttysoftware.tallertower.creatures.castes.CasteConstants; public class Buffer extends Caste { public Buffer() { super(CasteConstants.CASTE_BUFFER); } }
/* * Copyright 2015 Akyruu (akyruu@hotmail.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.avaryuon.commons.reflect; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.avaryuon.commons.LogUtils; /** * Contains utility methods for reflection. Don't instantiate. * * @author Akyruu (akyruu@hotmail.com) * @version 0.1 */ public final class ReflectionUtils { /* STATIC FIELDS ======================================================= */ /* Logging ------------------------------------------------------------- */ private static final Logger LOGGER = LoggerFactory .getLogger( ReflectionUtils.class ); /* FIELDS ============================================================== */ // Nothing here /* CONSTRUCTORS ======================================================== */ private ReflectionUtils() { // Nothing to do } /* METHODS ============================================================= */ /* Package ------------------------------------------------------------- */ public static String getPackageName( Class< ? > objClass ) { return objClass.getPackage().getName(); } /* Field --------------------------------------------------------------- */ /* Finding */ public static Field findField( Class< ? > objClass, String fieldName ) { Field field = null; if( objClass != null && !Object.class.equals( objClass ) ) { try { field = objClass.getDeclaredField( fieldName ); } catch( NoSuchFieldException ex ) { Class< ? > superclass = objClass.getSuperclass(); LogUtils.logTrace( LOGGER, "Field \"{}\" is not found for class {}. Continue to search with superclass of {}.", ex, fieldName, objClass.getCanonicalName(), superclass.getCanonicalName() ); field = findField( superclass, fieldName ); } catch( SecurityException ex ) { LogUtils.logError( LOGGER, "Field \"{}\" is not accessible.", ex, fieldName ); } } return field; } public static Collection< Field > findFields( Class< ? > objClass, Class< ? extends Annotation > annotationType ) { Collection< Field > annotedFields = new ArrayList<>(); if( objClass != null && !Object.class.equals( objClass ) ) { for( Field field : objClass.getDeclaredFields() ) { Annotation annotation = field .getDeclaredAnnotation( annotationType ); if( annotation != null ) { annotedFields.add( field ); } } annotedFields.addAll( findFields( objClass.getSuperclass(), annotationType ) ); } return annotedFields; } /* Value */ public static Object getValue( Object obj, Field field ) { Object value = null; if( field != null ) { field.setAccessible( true ); try { value = field.get( obj ); } catch( IllegalArgumentException | IllegalAccessException ex ) { LOGGER.error( "", ex ); } } return value; } public static void setValue( Object obj, Field field, Object value ) { if( field != null ) { field.setAccessible( true ); try { field.set( obj, value ); } catch( IllegalArgumentException | IllegalAccessException ex ) { LOGGER.error( "", ex ); } } } }
package abi39_0_0.expo.modules.camera; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Color; import android.media.CamcorderProfile; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.View; import com.google.android.cameraview.CameraView; import com.google.android.cameraview.Size; import abi39_0_0.org.unimodules.core.ModuleRegistry; import abi39_0_0.org.unimodules.core.Promise; import abi39_0_0.org.unimodules.core.interfaces.LifecycleEventListener; import abi39_0_0.org.unimodules.core.interfaces.services.EventEmitter; import abi39_0_0.org.unimodules.core.interfaces.services.UIManager; import abi39_0_0.org.unimodules.interfaces.barcodescanner.BarCodeScanner; import abi39_0_0.org.unimodules.interfaces.barcodescanner.BarCodeScannerProvider; import abi39_0_0.org.unimodules.interfaces.barcodescanner.BarCodeScannerResult; import abi39_0_0.org.unimodules.interfaces.barcodescanner.BarCodeScannerSettings; import abi39_0_0.org.unimodules.interfaces.camera.CameraViewInterface; import abi39_0_0.org.unimodules.interfaces.facedetector.FaceDetector; import abi39_0_0.org.unimodules.interfaces.facedetector.FaceDetectorProvider; import abi39_0_0.org.unimodules.interfaces.permissions.Permissions; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import abi39_0_0.expo.modules.camera.tasks.BarCodeScannerAsyncTask; import abi39_0_0.expo.modules.camera.tasks.BarCodeScannerAsyncTaskDelegate; import abi39_0_0.expo.modules.camera.tasks.FaceDetectorAsyncTaskDelegate; import abi39_0_0.expo.modules.camera.tasks.FaceDetectorTask; import abi39_0_0.expo.modules.camera.tasks.PictureSavedDelegate; import abi39_0_0.expo.modules.camera.tasks.ResolveTakenPictureAsyncTask; import abi39_0_0.expo.modules.camera.utils.FileSystemUtils; import abi39_0_0.expo.modules.camera.utils.ImageDimensions; public class ExpoCameraView extends CameraView implements LifecycleEventListener, BarCodeScannerAsyncTaskDelegate, FaceDetectorAsyncTaskDelegate, PictureSavedDelegate, CameraViewInterface { private static final String MUTE_KEY = "mute"; private static final String QUALITY_KEY = "quality"; private static final String FAST_MODE_KEY = "fastMode"; private static final String MAX_DURATION_KEY = "maxDuration"; private static final String MAX_FILE_SIZE_KEY = "maxFileSize"; private Queue<Promise> mPictureTakenPromises = new ConcurrentLinkedQueue<>(); private Map<Promise, Map<String, Object>> mPictureTakenOptions = new ConcurrentHashMap<>(); private Map<Promise, File> mPictureTakenDirectories = new ConcurrentHashMap<>(); private Promise mVideoRecordedPromise; private boolean mIsPaused = false; private boolean mIsNew = true; // Concurrency lock for scanners to avoid flooding the runtime public volatile boolean barCodeScannerTaskLock = false; public volatile boolean faceDetectorTaskLock = false; // Scanning-related properties private BarCodeScanner mBarCodeScanner; private FaceDetector mFaceDetector; private Map<String, Object> mPendingFaceDetectorSettings; private boolean mShouldDetectFaces = false; private boolean mShouldScanBarCodes = false; private ModuleRegistry mModuleRegistry; public ExpoCameraView(Context themedReactContext, ModuleRegistry moduleRegistry) { super(themedReactContext, true); mModuleRegistry = moduleRegistry; initBarCodeScanner(); setChildrenDrawingOrderEnabled(true); mModuleRegistry.getModule(UIManager.class).registerLifecycleEventListener(this); addCallback(new Callback() { @Override public void onCameraOpened(CameraView cameraView) { CameraViewHelper.emitCameraReadyEvent(mModuleRegistry.getModule(EventEmitter.class), cameraView); } @Override public void onMountError(CameraView cameraView) { CameraViewHelper.emitMountErrorEvent(mModuleRegistry.getModule(EventEmitter.class), cameraView, "Camera component could not be rendered - is there any other instance running?"); } @Override public void onPictureTaken(CameraView cameraView, final byte[] data) { Promise promise = mPictureTakenPromises.poll(); final File cacheDirectory = mPictureTakenDirectories.remove(promise); Map<String, Object> options = mPictureTakenOptions.remove(promise); if (options.containsKey(FAST_MODE_KEY) && (Boolean) options.get(FAST_MODE_KEY)) { promise.resolve(null); } new ResolveTakenPictureAsyncTask(data, promise, options, cacheDirectory, ExpoCameraView.this).execute(); } @Override public void onVideoRecorded(CameraView cameraView, String path) { if (mVideoRecordedPromise != null) { if (path != null) { Bundle result = new Bundle(); result.putString("uri", Uri.fromFile(new File(path)).toString()); mVideoRecordedPromise.resolve(result); } else { mVideoRecordedPromise.reject("E_RECORDING", "Couldn't stop recording - there is none in progress"); } mVideoRecordedPromise = null; } } @Override public void onFramePreview(CameraView cameraView, byte[] data, int width, int height, int rotation) { int correctRotation = CameraViewHelper.getCorrectCameraRotation(rotation, getFacing()); if (mShouldScanBarCodes && !barCodeScannerTaskLock && cameraView instanceof BarCodeScannerAsyncTaskDelegate) { barCodeScannerTaskLock = true; BarCodeScannerAsyncTaskDelegate delegate = (BarCodeScannerAsyncTaskDelegate) cameraView; new BarCodeScannerAsyncTask(delegate, mBarCodeScanner, data, width, height, rotation).execute(); } if (mShouldDetectFaces && !faceDetectorTaskLock && cameraView instanceof FaceDetectorAsyncTaskDelegate) { faceDetectorTaskLock = true; float density = cameraView.getResources().getDisplayMetrics().density; ImageDimensions dimensions = new ImageDimensions(width, height, correctRotation, getFacing()); double scaleX = (double) cameraView.getWidth() / (dimensions.getWidth() * density); double scaleY = (double) cameraView.getHeight() / (dimensions.getHeight() * density); FaceDetectorAsyncTaskDelegate delegate = (FaceDetectorAsyncTaskDelegate) cameraView; FaceDetectorTask task = new FaceDetectorTask(delegate, mFaceDetector, data, width, height, correctRotation, getFacing() == CameraView.FACING_FRONT, scaleX, scaleY); task.execute(); } } }); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { View preview = getView(); if (null == preview) { return; } this.setBackgroundColor(Color.BLACK); int width = right - left; int height = bottom - top; preview.layout(0, 0, width, height); } @Override public void requestLayout() { // React handles this for us, so we don't need to call super.requestLayout(); } @Override public void onViewAdded(View child) { // react adds children to containers at the beginning of children list and that moves pre-react added preview to the end of that list // above would cause preview (TextureView that covers all available space) to be rendered at the top of children stack // while we need this preview to be rendered last beneath all other children // child is not preview if (this.getView() == child || this.getView() == null) { return; } // bring to front all non-preview children List<View> childrenToBeReordered = new ArrayList<>(); for (int i = 0; i < this.getChildCount(); i++) { View childView = this.getChildAt(i); if (i == 0 && childView == this.getView()) { // preview is already first in children list - do not reorder anything return; } if (childView != this.getView()) { childrenToBeReordered.add(childView); } } for (View childView : childrenToBeReordered) { bringChildToFront(childView); } requestLayout(); invalidate(); } public void takePicture(Map<String, Object> options, final Promise promise, File cacheDirectory) { mPictureTakenPromises.add(promise); mPictureTakenOptions.put(promise, options); mPictureTakenDirectories.put(promise, cacheDirectory); try { super.takePicture(); } catch (Exception e) { mPictureTakenPromises.remove(promise); mPictureTakenOptions.remove(promise); mPictureTakenDirectories.remove(promise); throw e; } } @Override public void onPictureSaved(Bundle response) { CameraViewHelper.emitPictureSavedEvent(mModuleRegistry.getModule(EventEmitter.class), this, response); } public void record(Map<String, Object> options, final Promise promise, File cacheDirectory) { try { String path = FileSystemUtils.generateOutputPath(cacheDirectory, "Camera", ".mp4"); double maxDuration = -1; if (options.get(MAX_DURATION_KEY) != null) { maxDuration = (double) options.get(MAX_DURATION_KEY); } double maxFileSize = -1; if (options.get(MAX_FILE_SIZE_KEY) != null) { maxFileSize = (double) options.get(MAX_FILE_SIZE_KEY); } CamcorderProfile profile = CamcorderProfile.get(getCameraId(), CamcorderProfile.QUALITY_HIGH); if (options.get(QUALITY_KEY) != null) { profile = CameraViewHelper.getCamcorderProfile(getCameraId(), ((Double) options.get(QUALITY_KEY)).intValue()); } Boolean muteValue = (Boolean) options.get(MUTE_KEY); boolean recordAudio = muteValue == null || !muteValue; if (super.record(path, (int) maxDuration * 1000, (int) maxFileSize, recordAudio, profile)) { mVideoRecordedPromise = promise; } else { promise.reject("E_RECORDING_FAILED", "Starting video recording failed. Another recording might be in progress."); } } catch (IOException e) { promise.reject("E_RECORDING_FAILED", "Starting video recording failed - could not create video file."); } } /** * Initialize the barcode scanner. * Supports all iOS codes except [code138, code39mod43, itf14] * Additionally supports [codabar, code128, maxicode, rss14, rssexpanded, upc_a, upc_ean] */ private void initBarCodeScanner() { BarCodeScannerProvider barCodeScannerProvider = mModuleRegistry.getModule(BarCodeScannerProvider.class); if (barCodeScannerProvider != null) { mBarCodeScanner = barCodeScannerProvider.createBarCodeDetectorWithContext(getContext()); } } public void setShouldScanBarCodes(boolean shouldScanBarCodes) { this.mShouldScanBarCodes = shouldScanBarCodes; setScanning(mShouldScanBarCodes || mShouldDetectFaces); } public void setBarCodeScannerSettings(BarCodeScannerSettings settings) { if (mBarCodeScanner != null) { mBarCodeScanner.setSettings(settings); } } @Override public void onBarCodeScanned(BarCodeScannerResult barCode) { if (!mShouldScanBarCodes) { return; } CameraViewHelper.emitBarCodeReadEvent(mModuleRegistry.getModule(EventEmitter.class), this, barCode); } public void onBarCodeScanningTaskCompleted() { barCodeScannerTaskLock = false; } public int[] getPreviewSizeAsArray() { Size previewSize = getPreviewSize(); return new int[]{previewSize.getWidth(), previewSize.getHeight()}; } @Override public void onHostResume() { if (hasCameraPermissions()) { if ((mIsPaused && !isCameraOpened()) || mIsNew) { mIsPaused = false; mIsNew = false; if (!Build.FINGERPRINT.contains("generic")) { start(); FaceDetectorProvider faceDetectorProvider = mModuleRegistry.getModule(FaceDetectorProvider.class); if (faceDetectorProvider != null) { mFaceDetector = faceDetectorProvider.createFaceDetectorWithContext(getContext()); if (mPendingFaceDetectorSettings != null) { mFaceDetector.setSettings(mPendingFaceDetectorSettings); mPendingFaceDetectorSettings = null; } } } } } else { CameraViewHelper.emitMountErrorEvent(mModuleRegistry.getModule(EventEmitter.class), this, "Camera permissions not granted - component could not be rendered."); } } @Override public void onHostPause() { if (!mIsPaused && isCameraOpened()) { if (mFaceDetector != null) { mFaceDetector.release(); } mIsPaused = true; stop(); } } @Override public void onHostDestroy() { if (mFaceDetector != null) { mFaceDetector.release(); } stop(); } private boolean hasCameraPermissions() { return mModuleRegistry.getModule(Permissions.class).hasGrantedPermissions(Manifest.permission.CAMERA); } public void setShouldDetectFaces(boolean shouldDetectFaces) { mShouldDetectFaces = shouldDetectFaces; setScanning(mShouldScanBarCodes || mShouldDetectFaces); } public void setFaceDetectorSettings(Map<String, Object> settings) { if (mFaceDetector == null) { mPendingFaceDetectorSettings = settings; } else { mFaceDetector.setSettings(settings); } } @Override public void onFacesDetected(List<Bundle> facesReported) { if (!mShouldDetectFaces) { return; } List<Bundle> facesDetected = facesReported == null ? new ArrayList<Bundle>() : facesReported; CameraViewHelper.emitFacesDetectedEvent(mModuleRegistry.getModule(EventEmitter.class), this, facesDetected); } @Override public void onFaceDetectionError(FaceDetector faceDetector) { faceDetectorTaskLock = false; if (!mShouldDetectFaces) { return; } CameraViewHelper.emitFaceDetectionErrorEvent(mModuleRegistry.getModule(EventEmitter.class), this, faceDetector); } @Override public void onFaceDetectingTaskCompleted() { faceDetectorTaskLock = false; } }
/* * Copyright 2016-2021 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.ecs.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ListTaskDefinitions" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListTaskDefinitionsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The full family name with which to filter the <code>ListTaskDefinitions</code> results. Specifying a * <code>familyPrefix</code> limits the listed task definitions to task definition revisions that belong to that * family. * </p> */ private String familyPrefix; /** * <p> * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, only * <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, you can view * task definitions that are <code>INACTIVE</code> as long as an active task or service still references them. If * you paginate the resulting output, be sure to keep the <code>status</code> value constant in each subsequent * request. * </p> */ private String status; /** * <p> * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By default ( * <code>ASC</code>), task definitions are listed lexicographically by family name and in ascending numerical order * by revision so that the newest task definitions in a family are listed last. Setting this parameter to * <code>DESC</code> reverses the sort order on family name and revision so that the newest task definitions in a * family are listed first. * </p> */ private String sort; /** * <p> * The <code>nextToken</code> value returned from a <code>ListTaskDefinitions</code> request indicating that more * results are available to fulfill the request and further calls will be needed. If <code>maxResults</code> was * provided, it is possible the number of results to be fewer than <code>maxResults</code>. * </p> * <note> * <p> * This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and * not for other programmatic purposes. * </p> * </note> */ private String nextToken; /** * <p> * The maximum number of task definition results returned by <code>ListTaskDefinitions</code> in paginated output. * When this parameter is used, <code>ListTaskDefinitions</code> only returns <code>maxResults</code> results in a * single page along with a <code>nextToken</code> response element. The remaining results of the initial request * can be seen by sending another <code>ListTaskDefinitions</code> request with the returned <code>nextToken</code> * value. This value can be between 1 and 100. If this parameter is not used, then <code>ListTaskDefinitions</code> * returns up to 100 results and a <code>nextToken</code> value if applicable. * </p> */ private Integer maxResults; /** * <p> * The full family name with which to filter the <code>ListTaskDefinitions</code> results. Specifying a * <code>familyPrefix</code> limits the listed task definitions to task definition revisions that belong to that * family. * </p> * * @param familyPrefix * The full family name with which to filter the <code>ListTaskDefinitions</code> results. Specifying a * <code>familyPrefix</code> limits the listed task definitions to task definition revisions that belong to * that family. */ public void setFamilyPrefix(String familyPrefix) { this.familyPrefix = familyPrefix; } /** * <p> * The full family name with which to filter the <code>ListTaskDefinitions</code> results. Specifying a * <code>familyPrefix</code> limits the listed task definitions to task definition revisions that belong to that * family. * </p> * * @return The full family name with which to filter the <code>ListTaskDefinitions</code> results. Specifying a * <code>familyPrefix</code> limits the listed task definitions to task definition revisions that belong to * that family. */ public String getFamilyPrefix() { return this.familyPrefix; } /** * <p> * The full family name with which to filter the <code>ListTaskDefinitions</code> results. Specifying a * <code>familyPrefix</code> limits the listed task definitions to task definition revisions that belong to that * family. * </p> * * @param familyPrefix * The full family name with which to filter the <code>ListTaskDefinitions</code> results. Specifying a * <code>familyPrefix</code> limits the listed task definitions to task definition revisions that belong to * that family. * @return Returns a reference to this object so that method calls can be chained together. */ public ListTaskDefinitionsRequest withFamilyPrefix(String familyPrefix) { setFamilyPrefix(familyPrefix); return this; } /** * <p> * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, only * <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, you can view * task definitions that are <code>INACTIVE</code> as long as an active task or service still references them. If * you paginate the resulting output, be sure to keep the <code>status</code> value constant in each subsequent * request. * </p> * * @param status * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, * only <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, * you can view task definitions that are <code>INACTIVE</code> as long as an active task or service still * references them. If you paginate the resulting output, be sure to keep the <code>status</code> value * constant in each subsequent request. * @see TaskDefinitionStatus */ public void setStatus(String status) { this.status = status; } /** * <p> * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, only * <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, you can view * task definitions that are <code>INACTIVE</code> as long as an active task or service still references them. If * you paginate the resulting output, be sure to keep the <code>status</code> value constant in each subsequent * request. * </p> * * @return The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, * only <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, * you can view task definitions that are <code>INACTIVE</code> as long as an active task or service still * references them. If you paginate the resulting output, be sure to keep the <code>status</code> value * constant in each subsequent request. * @see TaskDefinitionStatus */ public String getStatus() { return this.status; } /** * <p> * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, only * <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, you can view * task definitions that are <code>INACTIVE</code> as long as an active task or service still references them. If * you paginate the resulting output, be sure to keep the <code>status</code> value constant in each subsequent * request. * </p> * * @param status * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, * only <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, * you can view task definitions that are <code>INACTIVE</code> as long as an active task or service still * references them. If you paginate the resulting output, be sure to keep the <code>status</code> value * constant in each subsequent request. * @return Returns a reference to this object so that method calls can be chained together. * @see TaskDefinitionStatus */ public ListTaskDefinitionsRequest withStatus(String status) { setStatus(status); return this; } /** * <p> * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, only * <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, you can view * task definitions that are <code>INACTIVE</code> as long as an active task or service still references them. If * you paginate the resulting output, be sure to keep the <code>status</code> value constant in each subsequent * request. * </p> * * @param status * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, * only <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, * you can view task definitions that are <code>INACTIVE</code> as long as an active task or service still * references them. If you paginate the resulting output, be sure to keep the <code>status</code> value * constant in each subsequent request. * @see TaskDefinitionStatus */ public void setStatus(TaskDefinitionStatus status) { withStatus(status); } /** * <p> * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, only * <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, you can view * task definitions that are <code>INACTIVE</code> as long as an active task or service still references them. If * you paginate the resulting output, be sure to keep the <code>status</code> value constant in each subsequent * request. * </p> * * @param status * The task definition status with which to filter the <code>ListTaskDefinitions</code> results. By default, * only <code>ACTIVE</code> task definitions are listed. By setting this parameter to <code>INACTIVE</code>, * you can view task definitions that are <code>INACTIVE</code> as long as an active task or service still * references them. If you paginate the resulting output, be sure to keep the <code>status</code> value * constant in each subsequent request. * @return Returns a reference to this object so that method calls can be chained together. * @see TaskDefinitionStatus */ public ListTaskDefinitionsRequest withStatus(TaskDefinitionStatus status) { this.status = status.toString(); return this; } /** * <p> * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By default ( * <code>ASC</code>), task definitions are listed lexicographically by family name and in ascending numerical order * by revision so that the newest task definitions in a family are listed last. Setting this parameter to * <code>DESC</code> reverses the sort order on family name and revision so that the newest task definitions in a * family are listed first. * </p> * * @param sort * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By * default (<code>ASC</code>), task definitions are listed lexicographically by family name and in ascending * numerical order by revision so that the newest task definitions in a family are listed last. Setting this * parameter to <code>DESC</code> reverses the sort order on family name and revision so that the newest task * definitions in a family are listed first. * @see SortOrder */ public void setSort(String sort) { this.sort = sort; } /** * <p> * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By default ( * <code>ASC</code>), task definitions are listed lexicographically by family name and in ascending numerical order * by revision so that the newest task definitions in a family are listed last. Setting this parameter to * <code>DESC</code> reverses the sort order on family name and revision so that the newest task definitions in a * family are listed first. * </p> * * @return The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By * default (<code>ASC</code>), task definitions are listed lexicographically by family name and in ascending * numerical order by revision so that the newest task definitions in a family are listed last. Setting this * parameter to <code>DESC</code> reverses the sort order on family name and revision so that the newest * task definitions in a family are listed first. * @see SortOrder */ public String getSort() { return this.sort; } /** * <p> * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By default ( * <code>ASC</code>), task definitions are listed lexicographically by family name and in ascending numerical order * by revision so that the newest task definitions in a family are listed last. Setting this parameter to * <code>DESC</code> reverses the sort order on family name and revision so that the newest task definitions in a * family are listed first. * </p> * * @param sort * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By * default (<code>ASC</code>), task definitions are listed lexicographically by family name and in ascending * numerical order by revision so that the newest task definitions in a family are listed last. Setting this * parameter to <code>DESC</code> reverses the sort order on family name and revision so that the newest task * definitions in a family are listed first. * @return Returns a reference to this object so that method calls can be chained together. * @see SortOrder */ public ListTaskDefinitionsRequest withSort(String sort) { setSort(sort); return this; } /** * <p> * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By default ( * <code>ASC</code>), task definitions are listed lexicographically by family name and in ascending numerical order * by revision so that the newest task definitions in a family are listed last. Setting this parameter to * <code>DESC</code> reverses the sort order on family name and revision so that the newest task definitions in a * family are listed first. * </p> * * @param sort * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By * default (<code>ASC</code>), task definitions are listed lexicographically by family name and in ascending * numerical order by revision so that the newest task definitions in a family are listed last. Setting this * parameter to <code>DESC</code> reverses the sort order on family name and revision so that the newest task * definitions in a family are listed first. * @see SortOrder */ public void setSort(SortOrder sort) { withSort(sort); } /** * <p> * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By default ( * <code>ASC</code>), task definitions are listed lexicographically by family name and in ascending numerical order * by revision so that the newest task definitions in a family are listed last. Setting this parameter to * <code>DESC</code> reverses the sort order on family name and revision so that the newest task definitions in a * family are listed first. * </p> * * @param sort * The order in which to sort the results. Valid values are <code>ASC</code> and <code>DESC</code>. By * default (<code>ASC</code>), task definitions are listed lexicographically by family name and in ascending * numerical order by revision so that the newest task definitions in a family are listed last. Setting this * parameter to <code>DESC</code> reverses the sort order on family name and revision so that the newest task * definitions in a family are listed first. * @return Returns a reference to this object so that method calls can be chained together. * @see SortOrder */ public ListTaskDefinitionsRequest withSort(SortOrder sort) { this.sort = sort.toString(); return this; } /** * <p> * The <code>nextToken</code> value returned from a <code>ListTaskDefinitions</code> request indicating that more * results are available to fulfill the request and further calls will be needed. If <code>maxResults</code> was * provided, it is possible the number of results to be fewer than <code>maxResults</code>. * </p> * <note> * <p> * This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and * not for other programmatic purposes. * </p> * </note> * * @param nextToken * The <code>nextToken</code> value returned from a <code>ListTaskDefinitions</code> request indicating that * more results are available to fulfill the request and further calls will be needed. If * <code>maxResults</code> was provided, it is possible the number of results to be fewer than * <code>maxResults</code>.</p> <note> * <p> * This token should be treated as an opaque identifier that is only used to retrieve the next items in a * list and not for other programmatic purposes. * </p> */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The <code>nextToken</code> value returned from a <code>ListTaskDefinitions</code> request indicating that more * results are available to fulfill the request and further calls will be needed. If <code>maxResults</code> was * provided, it is possible the number of results to be fewer than <code>maxResults</code>. * </p> * <note> * <p> * This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and * not for other programmatic purposes. * </p> * </note> * * @return The <code>nextToken</code> value returned from a <code>ListTaskDefinitions</code> request indicating that * more results are available to fulfill the request and further calls will be needed. If * <code>maxResults</code> was provided, it is possible the number of results to be fewer than * <code>maxResults</code>.</p> <note> * <p> * This token should be treated as an opaque identifier that is only used to retrieve the next items in a * list and not for other programmatic purposes. * </p> */ public String getNextToken() { return this.nextToken; } /** * <p> * The <code>nextToken</code> value returned from a <code>ListTaskDefinitions</code> request indicating that more * results are available to fulfill the request and further calls will be needed. If <code>maxResults</code> was * provided, it is possible the number of results to be fewer than <code>maxResults</code>. * </p> * <note> * <p> * This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and * not for other programmatic purposes. * </p> * </note> * * @param nextToken * The <code>nextToken</code> value returned from a <code>ListTaskDefinitions</code> request indicating that * more results are available to fulfill the request and further calls will be needed. If * <code>maxResults</code> was provided, it is possible the number of results to be fewer than * <code>maxResults</code>.</p> <note> * <p> * This token should be treated as an opaque identifier that is only used to retrieve the next items in a * list and not for other programmatic purposes. * </p> * @return Returns a reference to this object so that method calls can be chained together. */ public ListTaskDefinitionsRequest withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * The maximum number of task definition results returned by <code>ListTaskDefinitions</code> in paginated output. * When this parameter is used, <code>ListTaskDefinitions</code> only returns <code>maxResults</code> results in a * single page along with a <code>nextToken</code> response element. The remaining results of the initial request * can be seen by sending another <code>ListTaskDefinitions</code> request with the returned <code>nextToken</code> * value. This value can be between 1 and 100. If this parameter is not used, then <code>ListTaskDefinitions</code> * returns up to 100 results and a <code>nextToken</code> value if applicable. * </p> * * @param maxResults * The maximum number of task definition results returned by <code>ListTaskDefinitions</code> in paginated * output. When this parameter is used, <code>ListTaskDefinitions</code> only returns <code>maxResults</code> * results in a single page along with a <code>nextToken</code> response element. The remaining results of * the initial request can be seen by sending another <code>ListTaskDefinitions</code> request with the * returned <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is not used, * then <code>ListTaskDefinitions</code> returns up to 100 results and a <code>nextToken</code> value if * applicable. */ public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } /** * <p> * The maximum number of task definition results returned by <code>ListTaskDefinitions</code> in paginated output. * When this parameter is used, <code>ListTaskDefinitions</code> only returns <code>maxResults</code> results in a * single page along with a <code>nextToken</code> response element. The remaining results of the initial request * can be seen by sending another <code>ListTaskDefinitions</code> request with the returned <code>nextToken</code> * value. This value can be between 1 and 100. If this parameter is not used, then <code>ListTaskDefinitions</code> * returns up to 100 results and a <code>nextToken</code> value if applicable. * </p> * * @return The maximum number of task definition results returned by <code>ListTaskDefinitions</code> in paginated * output. When this parameter is used, <code>ListTaskDefinitions</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> response element. * The remaining results of the initial request can be seen by sending another * <code>ListTaskDefinitions</code> request with the returned <code>nextToken</code> value. This value can * be between 1 and 100. If this parameter is not used, then <code>ListTaskDefinitions</code> returns up to * 100 results and a <code>nextToken</code> value if applicable. */ public Integer getMaxResults() { return this.maxResults; } /** * <p> * The maximum number of task definition results returned by <code>ListTaskDefinitions</code> in paginated output. * When this parameter is used, <code>ListTaskDefinitions</code> only returns <code>maxResults</code> results in a * single page along with a <code>nextToken</code> response element. The remaining results of the initial request * can be seen by sending another <code>ListTaskDefinitions</code> request with the returned <code>nextToken</code> * value. This value can be between 1 and 100. If this parameter is not used, then <code>ListTaskDefinitions</code> * returns up to 100 results and a <code>nextToken</code> value if applicable. * </p> * * @param maxResults * The maximum number of task definition results returned by <code>ListTaskDefinitions</code> in paginated * output. When this parameter is used, <code>ListTaskDefinitions</code> only returns <code>maxResults</code> * results in a single page along with a <code>nextToken</code> response element. The remaining results of * the initial request can be seen by sending another <code>ListTaskDefinitions</code> request with the * returned <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is not used, * then <code>ListTaskDefinitions</code> returns up to 100 results and a <code>nextToken</code> value if * applicable. * @return Returns a reference to this object so that method calls can be chained together. */ public ListTaskDefinitionsRequest withMaxResults(Integer maxResults) { setMaxResults(maxResults); return this; } /** * 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 (getFamilyPrefix() != null) sb.append("FamilyPrefix: ").append(getFamilyPrefix()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()).append(","); if (getSort() != null) sb.append("Sort: ").append(getSort()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getMaxResults() != null) sb.append("MaxResults: ").append(getMaxResults()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListTaskDefinitionsRequest == false) return false; ListTaskDefinitionsRequest other = (ListTaskDefinitionsRequest) obj; if (other.getFamilyPrefix() == null ^ this.getFamilyPrefix() == null) return false; if (other.getFamilyPrefix() != null && other.getFamilyPrefix().equals(this.getFamilyPrefix()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getSort() == null ^ this.getSort() == null) return false; if (other.getSort() != null && other.getSort().equals(this.getSort()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getMaxResults() == null ^ this.getMaxResults() == null) return false; if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFamilyPrefix() == null) ? 0 : getFamilyPrefix().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getSort() == null) ? 0 : getSort().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode()); return hashCode; } @Override public ListTaskDefinitionsRequest clone() { return (ListTaskDefinitionsRequest) super.clone(); } }
package com.flechow.pinboard.security; import com.flechow.pinboard.domain.User; import com.flechow.pinboard.repository.UserRepository; import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors; /** * Authenticate a user from the database. */ @Component("userDetailsService") public class DomainUserDetailsService implements UserDetailsService { private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class); private final UserRepository userRepository; public DomainUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override @Transactional public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); if (new EmailValidator().isValid(login, null)) { return userRepository.findOneWithAuthoritiesByEmailIgnoreCase(login) .map(user -> createSpringSecurityUser(login, user)) .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); } String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin) .map(user -> createSpringSecurityUser(lowercaseLogin, user)) .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); } private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { if (!user.getActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream() .map(authority -> new SimpleGrantedAuthority(authority.getName())) .collect(Collectors.toList()); return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities); } }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.github.vo; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import static com.android.example.github.vo.Status.ERROR; import static com.android.example.github.vo.Status.LOADING; import static com.android.example.github.vo.Status.SUCCESS; /** * A generic class that holds a value with its loading status. * @param <T> */ public class Resource<T> { @NonNull public final Status status; @Nullable public final String message; @Nullable public final T data; public Resource(@NonNull Status status, @Nullable T data, @Nullable String message) { this.status = status; this.data = data; this.message = message; } public static <T> Resource<T> success(@Nullable T data) { return new Resource<>(SUCCESS, data, null); } public static <T> Resource<T> error(String msg, @Nullable T data) { return new Resource<>(ERROR, data, msg); } public static <T> Resource<T> loading(@Nullable T data) { return new Resource<>(LOADING, data, null); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Resource<?> resource = (Resource<?>) o; if (status != resource.status) { return false; } if (message != null ? !message.equals(resource.message) : resource.message != null) { return false; } return data != null ? data.equals(resource.data) : resource.data == null; } @Override public int hashCode() { int result = status.hashCode(); result = 31 * result + (message != null ? message.hashCode() : 0); result = 31 * result + (data != null ? data.hashCode() : 0); return result; } @Override public String toString() { return "Resource{" + "status=" + status + ", message='" + message + '\'' + ", data=" + data + '}'; } }
/* * ==================================================================== * 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.xslf.util; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import javax.imageio.ImageIO; import org.apache.poi.sl.draw.DrawFactory; import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; /** * An utility to convert slides of a .pptx slide show to a PNG image * * @author Yegor Kozlov */ public class PPTX2PNG { static void usage(String error){ String msg = "Usage: PPTX2PNG [options] <ppt or pptx file>\n" + (error == null ? "" : ("Error: "+error+"\n")) + "Options:\n" + " -scale <float> scale factor\n" + " -slide <integer> 1-based index of a slide to render\n" + " -format <type> png,gif,jpg (,null for testing)" + " -outdir <dir> output directory, defaults to origin of the ppt/pptx file" + " -quiet do not write to console (for normal processing)"; System.out.println(msg); // no System.exit here, as we also run in junit tests! } public static void main(String[] args) throws Exception { if (args.length == 0) { usage(null); return; } String slidenumStr = "-1"; float scale = 1; File file = null; String format = "png"; File outdir = null; boolean quiet = false; for (int i = 0; i < args.length; i++) { if (args[i].startsWith("-")) { if ("-scale".equals(args[i])) { scale = Float.parseFloat(args[++i]); } else if ("-slide".equals(args[i])) { slidenumStr = args[++i]; } else if ("-format".equals(args[i])) { format = args[++i]; } else if ("-outdir".equals(args[i])) { outdir = new File(args[++i]); } else if ("-quiet".equals(args[i])) { quiet = true; } } else { file = new File(args[i]); } } if (file == null || !file.exists()) { usage("File not specified or it doesn't exist"); return; } if (format == null || !format.matches("^(png|gif|jpg|null)$")) { usage("Invalid format given"); return; } if (outdir == null) { outdir = file.getParentFile(); } if (!"null".equals(format) && (outdir == null || !outdir.exists() || !outdir.isDirectory())) { usage("Output directory doesn't exist"); return; } if (scale < 0) { usage("Invalid scale given"); return; } if (!quiet) { System.out.println("Processing " + file); } try (SlideShow<?, ?> ss = SlideShowFactory.create(file, null, true)) { List<? extends Slide<?, ?>> slides = ss.getSlides(); Set<Integer> slidenum = slideIndexes(slides.size(), slidenumStr); if (slidenum.isEmpty()) { usage("slidenum must be either -1 (for all) or within range: [1.." + slides.size() + "] for " + file); return; } Dimension pgsize = ss.getPageSize(); int width = (int) (pgsize.width * scale); int height = (int) (pgsize.height * scale); for (Integer slideNo : slidenum) { Slide<?, ?> slide = slides.get(slideNo); String title = slide.getTitle(); if (!quiet) { System.out.println("Rendering slide " + slideNo + (title == null ? "" : ": " + title)); } BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = img.createGraphics(); DrawFactory.getInstance(graphics).fixFonts(graphics); // default rendering options graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); graphics.scale(scale, scale); // draw stuff slide.draw(graphics); // save the result if (!"null".equals(format)) { String outname = file.getName().replaceFirst(".pptx?", ""); outname = String.format(Locale.ROOT, "%1$s-%2$04d.%3$s", outname, slideNo, format); File outfile = new File(outdir, outname); ImageIO.write(img, format, outfile); } graphics.dispose(); img.flush(); } } if (!quiet) { System.out.println("Done"); } } private static Set<Integer> slideIndexes(final int slideCount, String range) { Set<Integer> slideIdx = new TreeSet<>(); if ("-1".equals(range)) { for (int i=0; i<slideCount; i++) { slideIdx.add(i); } } else { for (String subrange : range.split(",")) { String idx[] = subrange.split("-"); switch (idx.length) { default: case 0: break; case 1: { int subidx = Integer.parseInt(idx[0]); if (subrange.contains("-")) { int startIdx = subrange.startsWith("-") ? 0 : subidx; int endIdx = subrange.endsWith("-") ? slideCount : Math.min(subidx,slideCount); for (int i=Math.max(startIdx,1); i<endIdx; i++) { slideIdx.add(i-1); } } else { slideIdx.add(Math.max(subidx,1)-1); } break; } case 2: { int startIdx = Math.min(Integer.parseInt(idx[0]), slideCount); int endIdx = Math.min(Integer.parseInt(idx[1]), slideCount); for (int i=Math.max(startIdx,1); i<endIdx; i++) { slideIdx.add(i-1); } break; } } } } return slideIdx; } }
package com.example.macaron.mobile_project.Activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.NavigationView; import android.support.v4.app.FragmentActivity; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.example.macaron.mobile_project.Adapter.ListViewAdapter; import com.example.macaron.mobile_project.Class.Knewledge; import com.example.macaron.mobile_project.Method.ChangeModule; import com.example.macaron.mobile_project.Method.DBModule; import com.example.macaron.mobile_project.R; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; public class HumanitiesActivity extends FragmentActivity implements NavigationView.OnNavigationItemSelectedListener{ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.drawer_humanities_layout); NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override protected void onResume() { super.onResume(); final ListView listView; final ListViewAdapter adapter; final ArrayList<Knewledge> knewledges = new ArrayList<>(); adapter = new ListViewAdapter(); listView = (ListView)findViewById(R.id.listView_humanities); listView.setAdapter(adapter); final DBModule dbModule = new DBModule(); dbModule.openReadDB(this); final FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference reference = database.getReference().child("지식").child("인문학"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot snapshot : dataSnapshot.getChildren()){ Knewledge knewledge = snapshot.getValue(Knewledge.class); knewledges.add(knewledge); boolean is_read = dbModule.executeRawQuery_Read("인문학", knewledge.gettitle()); adapter.addItem(knewledge.gettitle(), is_read); } adapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { adapter.changeItem(knewledges.get(position).gettitle(), true); adapter.notifyDataSetChanged(); if(!dbModule.executeRawQuery_Read("인문학", knewledges.get(position).gettitle())) { dbModule.insert_Read("인문학", knewledges.get(position).gettitle()); } ChangeModule changeModule = new ChangeModule(); changeModule.chActi(HumanitiesActivity.this, KnewledgeActivity.class, "지식", "인문학", knewledges.get(position).gettitle(), knewledges.get(position).getcontent()); } }); } public void clickMenuHum(View view){ DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_humanities_layout); drawer.openDrawer(GravityCompat.START); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { ChangeModule ca = new ChangeModule(); int id = item.getItemId(); Activity preActivity = HumanitiesActivity.this; Class curActivity = HumanitiesActivity.class; Class nextActivity = null; DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_humanities_layout); if(id == R.id.today_knew){ nextActivity = MainActivity.class; }else if(id == R.id.philosophy){ nextActivity = PhilosophyActivity.class; }else if(id == R.id.humanities){ nextActivity = HumanitiesActivity.class; }else if(id == R.id.history){ nextActivity = HistoryActivity.class; }else if(id == R.id.economy){ nextActivity = EconomyActivity.class; }else if(id == R.id.music){ nextActivity = MusicActivity.class; }else if(id == R.id.bookmark){ nextActivity = BookMarkActivity.class; }else if(id == R.id.settings){ nextActivity = SettingActivity.class; }else if(id == R.id.info){ nextActivity = InformActivity.class; } ca.chActi(preActivity, nextActivity, curActivity, drawer); finish(); return false; } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_humanities_layout); if(drawer.isDrawerOpen(GravityCompat.START)){ drawer.closeDrawer(GravityCompat.START); }else { super.onBackPressed(); } } }
package com.github.jitwxs.sample.netty.example6; import com.github.jitwxs.nettystudy.example6.BaseMessageProto; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * @author jitwxs * @date 2021-08-08 14:36 */ public class TestProtoServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .localAddress(8899) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(BaseMessageProto.Student.getDefaultInstance())); pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new ProtobufEncoder()); pipeline.addLast(new TestProtoServerHandler()); } }); ChannelFuture channelFuture = bootstrap.bind().sync(); channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } }
package com.example.tests; import java.io.File; import java.io.IOException; import java.util.Iterator; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static com.example.tests.ContactDataGenerator.loadContactsFromXmlFile; import static org.junit.Assert.assertThat; import static org.hamcrest.Matchers.*; import com.example.utils.SortedListOf; public class ContactCreationTests extends TestBase { @DataProvider public Iterator<Object[]> contactsFromFile() throws IOException { return wrapContactsForDataProvider(loadContactsFromXmlFile(new File("contacts.xml"))).iterator(); } @Test(dataProvider = "contactsFromFile") public void testContactCreationWithValidData(ContactData contact) throws Exception { //save state SortedListOf<ContactData> oldList = app.getContactHelper().getUiContacts(); //action app.getContactHelper().createContact(contact); //save new state SortedListOf<ContactData> newList = new SortedListOf<ContactData>(app.getHibernateHelper().listContacts()); //compare states assertThat(newList, equalTo(oldList.withAdded(contact))); //compare model to implementation // if (wantToCheck()) { // if ("yes".equals(app.getProperty("check.db"))) { // // assertThat(app.getModel().getContacts(), equalTo(app.getHibernateHelper().listContacts())); // } // if ("yes".equals(app.getProperty("check.ui"))) { // assertThat(app.getModel().getContacts(), equalTo(app.getContactHelper().getUiContacts())); // } // } } }
/* * * This file is part of the iText (R) project. Copyright (c) 1998-2019 iText Group NV * Authors: Bruno Lowagie, Paulo Soares, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, * a covered work must retain the producer line in every PDF that is created * or manipulated using iText. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the iText software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * serving PDFs on the fly in a web application, shipping iText with a closed * source product. * * For more information, please contact iText Software Corp. at this * address: sales@itextpdf.com */ package com.itextpdf.text; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.HashMap; import java.util.List; import com.itextpdf.text.api.Indentable; import com.itextpdf.text.error_messages.MessageLocalization; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfObject; import com.itextpdf.text.pdf.interfaces.IAccessibleElement; /** * A <CODE>Section</CODE> is a part of a <CODE>Document</CODE> containing * other <CODE>Section</CODE>s, <CODE>Paragraph</CODE>s, <CODE>List</CODE> * and/or <CODE>Table</CODE>s. * <P> * Remark: you can not construct a <CODE>Section</CODE> yourself. * You will have to ask an instance of <CODE>Section</CODE> to the * <CODE>Chapter</CODE> or <CODE>Section</CODE> to which you want to * add the new <CODE>Section</CODE>. * <P> * Example: * <BLOCKQUOTE><PRE> * Paragraph title2 = new Paragraph("This is Chapter 2", FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 255))); * Chapter chapter2 = new Chapter(title2, 2); * Paragraph someText = new Paragraph("This is some text"); * chapter2.add(someText); * Paragraph title21 = new Paragraph("This is Section 1 in Chapter 2", FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0))); * <STRONG>Section section1 = chapter2.addSection(title21);</STRONG> * Paragraph someSectionText = new Paragraph("This is some silly paragraph in a chapter and/or section. It contains some text to test the functionality of Chapters and Section."); * <STRONG>section1.add(someSectionText);</STRONG> * Paragraph title211 = new Paragraph("This is SubSection 1 in Section 1 in Chapter 2", FontFactory.getFont(FontFactory.HELVETICA, 14, Font.BOLD, new Color(255, 0, 0))); * <STRONG>Section section11 = section1.addSection(40, title211, 2);</STRONG> * <STRONG>section11.add(someSectionText);</STRONG> * </PRE></BLOCKQUOTE> */ public class Section extends ArrayList<Element> implements TextElementArray, LargeElement, Indentable, IAccessibleElement { // constant /** * A possible number style. The default number style: "1.2.3." * @since iText 2.0.8 */ public static final int NUMBERSTYLE_DOTTED = 0; /** * A possible number style. For instance: "1.2.3" * @since iText 2.0.8 */ public static final int NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT = 1; /** A serial version uid. */ private static final long serialVersionUID = 3324172577544748043L; // member variables /** The title of this section. */ protected Paragraph title; /** The bookmark title if different from the content title */ protected String bookmarkTitle; /** The number of sectionnumbers that has to be shown before the section title. */ protected int numberDepth; /** * The style for sectionnumbers. * @since iText 2.0.8 */ protected int numberStyle = NUMBERSTYLE_DOTTED; /** The indentation of this section on the left side. */ protected float indentationLeft; /** The indentation of this section on the right side. */ protected float indentationRight; /** The additional indentation of the content of this section. */ protected float indentation; /** false if the bookmark children are not visible */ protected boolean bookmarkOpen = true; /** true if the section has to trigger a new page */ protected boolean triggerNewPage = false; /** This is the number of subsections. */ protected int subsections = 0; /** This is the complete list of sectionnumbers of this section and the parents of this section. */ protected ArrayList<Integer> numbers = null; /** * Indicates if the Section will be complete once added to the document. * @since iText 2.0.8 */ protected boolean complete = true; /** * Indicates if the Section was added completely to the document. * @since iText 2.0.8 */ protected boolean addedCompletely = false; /** * Indicates if this is the first time the section was added. * @since iText 2.0.8 */ protected boolean notAddedYet = true; // constructors /** * Constructs a new <CODE>Section</CODE>. */ protected Section() { title = new Paragraph(); numberDepth = 1; title.setRole(new PdfName("H" + numberDepth)); } /** * Constructs a new <CODE>Section</CODE>. * * @param title a <CODE>Paragraph</CODE> * @param numberDepth the numberDepth */ protected Section(final Paragraph title, final int numberDepth) { this.numberDepth = numberDepth; this.title = title; if (title != null) title.setRole(new PdfName("H" + numberDepth)); } // implementation of the Element-methods /** * Processes the element by adding it (or the different parts) to an * <CODE>ElementListener</CODE>. * * @param listener the <CODE>ElementListener</CODE> * @return <CODE>true</CODE> if the element was processed successfully */ public boolean process(final ElementListener listener) { try { Element element; for (Object element2 : this) { element = (Element)element2; listener.add(element); } return true; } catch(DocumentException de) { return false; } } /** * Gets the type of the text element. * * @return a type */ public int type() { return Element.SECTION; } /** * Checks if this object is a <CODE>Chapter</CODE>. * * @return <CODE>true</CODE> if it is a <CODE>Chapter</CODE>, * <CODE>false</CODE> if it is a <CODE>Section</CODE>. */ public boolean isChapter() { return type() == Element.CHAPTER; } /** * Checks if this object is a <CODE>Section</CODE>. * * @return <CODE>true</CODE> if it is a <CODE>Section</CODE>, * <CODE>false</CODE> if it is a <CODE>Chapter</CODE>. */ public boolean isSection() { return type() == Element.SECTION; } /** * Gets all the chunks in this element. * * @return an <CODE>ArrayList</CODE> */ public List<Chunk> getChunks() { List<Chunk> tmp = new ArrayList<Chunk>(); for (Object element : this) { tmp.addAll(((Element) element).getChunks()); } return tmp; } /** * @see com.itextpdf.text.Element#isContent() * @since iText 2.0.8 */ public boolean isContent() { return true; } /** * @see com.itextpdf.text.Element#isNestable() * @since iText 2.0.8 */ public boolean isNestable() { return false; } // overriding some of the ArrayList-methods /** * Adds a <CODE>Paragraph</CODE>, <CODE>List</CODE> or <CODE>Table</CODE> * to this <CODE>Section</CODE>. * * @param index index at which the specified element is to be inserted * @param element an element of type <CODE>Paragraph</CODE>, <CODE>List</CODE> or <CODE>Table</CODE>= * @throws ClassCastException if the object is not a <CODE>Paragraph</CODE>, <CODE>List</CODE> or <CODE>Table</CODE> * @since 5.0.1 (signature changed to use Element) */ @Override public void add(final int index, final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.isNestable()) { super.add(index, element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } } /** * Adds a <CODE>Paragraph</CODE>, <CODE>List</CODE>, <CODE>Table</CODE> or another <CODE>Section</CODE> * to this <CODE>Section</CODE>. * * @param element an element of type <CODE>Paragraph</CODE>, <CODE>List</CODE>, <CODE>Table</CODE> or another <CODE>Section</CODE> * @return a boolean * @throws ClassCastException if the object is not a <CODE>Paragraph</CODE>, <CODE>List</CODE>, <CODE>Table</CODE> or <CODE>Section</CODE> * @since 5.0.1 (signature changed to use Element) */ @Override public boolean add(final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.type() == Element.SECTION) { Section section = (Section) element; section.setNumbers(++subsections, numbers); return super.add(section); } else if (element instanceof MarkedSection && ((MarkedObject)element).element.type() == Element.SECTION) { MarkedSection mo = (MarkedSection)element; Section section = (Section)mo.element; section.setNumbers(++subsections, numbers); return super.add(mo); } else if (element.isNestable()) { return super.add(element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } } /** * Adds a collection of <CODE>Element</CODE>s * to this <CODE>Section</CODE>. * * @param collection a collection of <CODE>Paragraph</CODE>s, <CODE>List</CODE>s and/or <CODE>Table</CODE>s * @return <CODE>true</CODE> if the action succeeded, <CODE>false</CODE> if not. * @throws ClassCastException if one of the objects isn't a <CODE>Paragraph</CODE>, <CODE>List</CODE>, <CODE>Table</CODE> */ @Override public boolean addAll(final Collection<? extends Element> collection) { if (collection.size() == 0) return false; for (Element element : collection) { this.add(element); } return true; } // methods that return a Section /** * Creates a <CODE>Section</CODE>, adds it to this <CODE>Section</CODE> and returns it. * * @param indentation the indentation of the new section * @param title the title of the new section * @param numberDepth the numberDepth of the section * @return a new Section object */ public Section addSection(final float indentation, final Paragraph title, final int numberDepth) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } Section section = new Section(title, numberDepth); section.setIndentation(indentation); add(section); return section; } /** * Creates a <CODE>Section</CODE>, adds it to this <CODE>Section</CODE> and returns it. * * @param indentation the indentation of the new section * @param title the title of the new section * @return a new Section object */ public Section addSection(final float indentation, final Paragraph title) { return addSection(indentation, title, numberDepth + 1); } /** * Creates a <CODE>Section</CODE>, add it to this <CODE>Section</CODE> and returns it. * * @param title the title of the new section * @param numberDepth the numberDepth of the section * @return a new Section object */ public Section addSection(final Paragraph title, final int numberDepth) { return addSection(0, title, numberDepth); } /** * Adds a marked section. For use in class MarkedSection only! * @return the MarkedSection */ protected MarkedSection addMarkedSection() { MarkedSection section = new MarkedSection(new Section(null, numberDepth + 1)); add(section); return section; } /** * Creates a <CODE>Section</CODE>, adds it to this <CODE>Section</CODE> and returns it. * * @param title the title of the new section * @return a new Section object */ public Section addSection(final Paragraph title) { return addSection(0, title, numberDepth + 1); } /** * Adds a <CODE>Section</CODE> to this <CODE>Section</CODE> and returns it. * * @param indentation the indentation of the new section * @param title the title of the new section * @param numberDepth the numberDepth of the section * @return a new Section object */ public Section addSection(final float indentation, final String title, final int numberDepth) { return addSection(indentation, new Paragraph(title), numberDepth); } /** * Adds a <CODE>Section</CODE> to this <CODE>Section</CODE> and returns it. * * @param title the title of the new section * @param numberDepth the numberDepth of the section * @return a new Section object */ public Section addSection(final String title, final int numberDepth) { return addSection(new Paragraph(title), numberDepth); } /** * Adds a <CODE>Section</CODE> to this <CODE>Section</CODE> and returns it. * * @param indentation the indentation of the new section * @param title the title of the new section * @return a new Section object */ public Section addSection(final float indentation, final String title) { return addSection(indentation, new Paragraph(title)); } /** * Adds a <CODE>Section</CODE> to this <CODE>Section</CODE> and returns it. * * @param title the title of the new section * @return a new Section object */ public Section addSection(final String title) { return addSection(new Paragraph(title)); } // public methods /** * Sets the title of this section. * * @param title the new title */ public void setTitle(final Paragraph title) { this.title = title; } /** * Returns the title, preceded by a certain number of sectionnumbers. * * @return a <CODE>Paragraph</CODE> */ public Paragraph getTitle() { return constructTitle(title, numbers, numberDepth, numberStyle); } /** * Constructs a Paragraph that will be used as title for a Section or Chapter. * @param title the title of the section * @param numbers a list of sectionnumbers * @param numberDepth how many numbers have to be shown * @param numberStyle the numbering style * @return a Paragraph object * @since iText 2.0.8 */ public static Paragraph constructTitle(final Paragraph title, final ArrayList<Integer> numbers, final int numberDepth, final int numberStyle) { if (title == null) { return null; } int depth = Math.min(numbers.size(), numberDepth); if (depth < 1) { return title; } StringBuffer buf = new StringBuffer(" "); for (int i = 0; i < depth; i++) { buf.insert(0, "."); buf.insert(0, numbers.get(i).intValue()); } if (numberStyle == NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT) { buf.deleteCharAt(buf.length() - 2); } Paragraph result = new Paragraph(title); result.add(0, new Chunk(buf.toString(), title.getFont())); return result; } /** * Sets the depth of the sectionnumbers that will be shown preceding the title. * <P> * If the numberdepth is 0, the sections will not be numbered. If the numberdepth * is 1, the section will be numbered with their own number. If the numberdepth is * higher (for instance x > 1), the numbers of x - 1 parents will be shown. * * @param numberDepth the new numberDepth */ public void setNumberDepth(final int numberDepth) { this.numberDepth = numberDepth; } /** * Returns the numberdepth of this <CODE>Section</CODE>. * * @return the numberdepth */ public int getNumberDepth() { return numberDepth; } /** * Sets the style for numbering sections. * Possible values are {@link Section#NUMBERSTYLE_DOTTED}: 1.2.3. (the default) * or {@link Section#NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT}: 1.2.3 * @param numberStyle the style to use * @since iText 2.0.8 */ public void setNumberStyle(final int numberStyle) { this.numberStyle = numberStyle; } /** * Gets the style used for numbering sections. * @since iText 2.0.8 * @return a value corresponding with a numbering style */ public int getNumberStyle() { return numberStyle; } /** * Sets the indentation of this <CODE>Section</CODE> on the left side. * * @param indentation the indentation */ public void setIndentationLeft(final float indentation) { indentationLeft = indentation; } /** * Returns the indentation of this <CODE>Section</CODE> on the left side. * * @return the indentation */ public float getIndentationLeft() { return indentationLeft; } /** * Sets the indentation of this <CODE>Section</CODE> on the right side. * * @param indentation the indentation */ public void setIndentationRight(final float indentation) { indentationRight = indentation; } /** * Returns the indentation of this <CODE>Section</CODE> on the right side. * * @return the indentation */ public float getIndentationRight() { return indentationRight; } /** * Sets the indentation of the content of this <CODE>Section</CODE>. * * @param indentation the indentation */ public void setIndentation(final float indentation) { this.indentation = indentation; } /** * Returns the indentation of the content of this <CODE>Section</CODE>. * * @return the indentation */ public float getIndentation() { return indentation; } /** Setter for property bookmarkOpen. * @param bookmarkOpen false if the bookmark children are not * visible. */ public void setBookmarkOpen(final boolean bookmarkOpen) { this.bookmarkOpen = bookmarkOpen; } /** * Getter for property bookmarkOpen. * @return Value of property bookmarkOpen. */ public boolean isBookmarkOpen() { return bookmarkOpen; } /** * Setter for property triggerNewPage. * @param triggerNewPage true if a new page has to be triggered. */ public void setTriggerNewPage(final boolean triggerNewPage) { this.triggerNewPage = triggerNewPage; } /** * Getter for property bookmarkOpen. * @return Value of property triggerNewPage. */ public boolean isTriggerNewPage() { return triggerNewPage && notAddedYet; } /** * Sets the bookmark title. The bookmark title is the same as the section title but * can be changed with this method. * @param bookmarkTitle the bookmark title */ public void setBookmarkTitle(final String bookmarkTitle) { this.bookmarkTitle = bookmarkTitle; } /** * Gets the bookmark title. * @return the bookmark title */ public Paragraph getBookmarkTitle() { if (bookmarkTitle == null) return getTitle(); else return new Paragraph(bookmarkTitle); } /** * Changes the Chapter number. * @param number the new number */ public void setChapterNumber(final int number) { numbers.set(numbers.size() - 1, Integer.valueOf(number)); Object s; for (Iterator<Element> i = iterator(); i.hasNext(); ) { s = i.next(); if (s instanceof Section) { ((Section)s).setChapterNumber(number); } } } /** * Returns the depth of this section. * * @return the depth */ public int getDepth() { return numbers.size(); } // private methods /** * Sets the number of this section. * * @param number the number of this section * @param numbers an <CODE>ArrayList<Integer></CODE>, containing the numbers of the Parent */ private void setNumbers(final int number, final ArrayList<Integer> numbers) { this.numbers = new ArrayList<Integer>(); this.numbers.add(Integer.valueOf(number)); this.numbers.addAll(numbers); } /** * Indicates if this is the first time the section is added. * @since iText2.0.8 * @return true if the section wasn't added yet */ public boolean isNotAddedYet() { return notAddedYet; } /** * Sets the indication if the section was already added to * the document. * @since iText2.0.8 * @param notAddedYet */ public void setNotAddedYet(final boolean notAddedYet) { this.notAddedYet = notAddedYet; } /** * @return return the addedCompletely value * @since iText 2.0.8 */ protected boolean isAddedCompletely() { return addedCompletely; } /** * @param addedCompletely true if section was completely added, false otherwise * @since iText 2.0.8 */ protected void setAddedCompletely(final boolean addedCompletely) { this.addedCompletely = addedCompletely; } /** * @since iText 2.0.8 * @see com.itextpdf.text.LargeElement#flushContent() */ public void flushContent() { setNotAddedYet(false); title = null; Element element; for (Iterator<Element> i = iterator(); i.hasNext(); ) { element = i.next(); if (element instanceof Section) { Section s = (Section)element; if (!s.isComplete() && size() == 1) { s.flushContent(); return; } else { s.setAddedCompletely(true); } } i.remove(); } } /** * @since iText 2.0.8 * @see com.itextpdf.text.LargeElement#isComplete() */ public boolean isComplete() { return complete; } /** * @since iText 2.0.8 * @see com.itextpdf.text.LargeElement#setComplete(boolean) */ public void setComplete(final boolean complete) { this.complete = complete; } /** * Adds a new page to the section. * @since 2.1.1 */ public void newPage() { this.add(Chunk.NEXTPAGE); } public PdfObject getAccessibleAttribute(final PdfName key) { return title.getAccessibleAttribute(key); } public void setAccessibleAttribute(final PdfName key, final PdfObject value) { title.setAccessibleAttribute(key, value); } public HashMap<PdfName, PdfObject> getAccessibleAttributes() { return title.getAccessibleAttributes(); } public PdfName getRole() { return title.getRole(); } public void setRole(final PdfName role) { title.setRole(role); } public AccessibleElementId getId() { return title.getId(); } public void setId(final AccessibleElementId id) { title.setId(id); } public boolean isInline() { return false; } }
class Solution { private int size; private List<List<String>> solutions = new ArrayList<List<String>>(); public List<List<String>> solveNQueens(int n) { size = n; char emptyBoard[][] = new char[size][size]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { emptyBoard[i][j] = '.'; } } backtrack(0, new HashSet<>(), new HashSet<>(), new HashSet<>(), emptyBoard); return solutions; } // Making use of a helper function to get the // solutions in the correct output format private List<String> createBoard(char[][] state) { List<String> board = new ArrayList<String>(); for (int row = 0; row < size; row++) { String current_row = new String(state[row]); board.add(current_row); } return board; } private void backtrack(int row, Set<Integer> diagonals, Set<Integer> antiDiagonals, Set<Integer> cols, char[][] state) { // Base case - N queens have been placed if (row == size) { solutions.add(createBoard(state)); return; } for (int col = 0; col < size; col++) { int currDiagonal = row - col; int currAntiDiagonal = row + col; // If the queen is not placeable if (cols.contains(col) || diagonals.contains(currDiagonal) || antiDiagonals.contains(currAntiDiagonal)) { continue; } // "Add" the queen to the board cols.add(col); diagonals.add(currDiagonal); antiDiagonals.add(currAntiDiagonal); state[row][col] = 'Q'; // Move on to the next row with the updated board state backtrack(row + 1, diagonals, antiDiagonals, cols, state); // "Remove" the queen from the board since we have already // explored all valid paths using the above function call cols.remove(col); diagonals.remove(currDiagonal); antiDiagonals.remove(currAntiDiagonal); state[row][col] = '.'; } } }
// Copyright 2018 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.location.suplclient.asn1.supl2.rrlp_components; // Copyright 2008 Google Inc. All Rights Reserved. /* * This class is AUTOMATICALLY GENERATED. Do NOT EDIT. */ // // import com.google.location.suplclient.asn1.base.Asn1Integer; import com.google.location.suplclient.asn1.base.Asn1Tag; import com.google.location.suplclient.asn1.base.BitStream; import com.google.location.suplclient.asn1.base.BitStreamReader; import com.google.common.collect.ImmutableList; import java.util.Collection; import javax.annotation.Nullable; /** * */ public class SVID extends Asn1Integer { // private static final Asn1Tag TAG_SVID = Asn1Tag.fromClassAndNumber(-1, -1); public SVID() { super(); setValueRange(new java.math.BigInteger("0"), new java.math.BigInteger("63")); } @Override @Nullable protected Asn1Tag getTag() { return TAG_SVID; } @Override protected boolean isTagImplicit() { return true; } public static Collection<Asn1Tag> getPossibleFirstTags() { if (TAG_SVID != null) { return ImmutableList.of(TAG_SVID); } else { return Asn1Integer.getPossibleFirstTags(); } } /** * Creates a new SVID from encoded stream. */ public static SVID fromPerUnaligned(byte[] encodedBytes) { SVID result = new SVID(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; } /** * Creates a new SVID from encoded stream. */ public static SVID fromPerAligned(byte[] encodedBytes) { SVID result = new SVID(); result.decodePerAligned(new BitStreamReader(encodedBytes)); return result; } @Override public Iterable<BitStream> encodePerUnaligned() { return super.encodePerUnaligned(); } @Override public Iterable<BitStream> encodePerAligned() { return super.encodePerAligned(); } @Override public void decodePerUnaligned(BitStreamReader reader) { super.decodePerUnaligned(reader); } @Override public void decodePerAligned(BitStreamReader reader) { super.decodePerAligned(reader); } @Override public String toString() { return toIndentedString(""); } public String toIndentedString(String indent) { return "SVID = " + getInteger() + ";\n"; } }
public class TestaWhile { public static void main(String args[]) { int contador = 0; while (contador <= 10) { System.out.println(contador); contador = contador + 1; } } }
package com.flanks255.simplybackpacks.items; import com.flanks255.simplybackpacks.SimplyBackpacks; import net.minecraft.item.Rarity; import net.minecraft.util.ResourceLocation; /** * Represents a singleton instance of a backpack. Sets up each backpack in it's own way */ public enum Backpack { COMMON(Rarity.COMMON, 18, "common_gui.png", 176, 150, 7, 67), UNCOMMON(Rarity.UNCOMMON, 33, "uncommon_gui.png", 212, 168, 25, 85), RARE(Rarity.RARE, 66, "rare_gui.png", 212, 222, 25, 139), EPIC(Rarity.EPIC, 99, "epic_gui.png", 212, 276, 25, 193); public Rarity rarity; public int slots; public ResourceLocation location; public int xSize; public int ySize; public int slotXOffset; public int slotYOffset; Backpack(Rarity rarity, int slots, String location, int xSize, int ySize, int slotXOffset, int slotYOffset) { this.rarity = rarity; this.slots = slots; this.location = new ResourceLocation(SimplyBackpacks.MODID, "textures/gui/" + location); this.xSize = xSize; this.ySize = ySize; this.slotXOffset = slotXOffset; this.slotYOffset = slotYOffset; } }
package org.hl7.fhir.dstu3.model.codesystems; /* Copyright (c) 2011+, HL7, Inc. 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 HL7 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 HOLDER 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. */ // Generated on Sat, Mar 25, 2017 21:03-0400 for FHIR v3.0.0 import org.hl7.fhir.exceptions.FHIRException; public enum ObservationCategory { /** * The Social History Observations define the patient's occupational, personal (e.g. lifestyle), social, and environmental history and health risk factors, as well as administrative data such as marital status, race, ethnicity and religious affiliation. */ SOCIALHISTORY, /** * Clinical observations measure the body's basic functions such as such as blood pressure, heart rate, respiratory rate, height, weight, body mass index, head circumference, pulse oximetry, temperature, and body surface area. */ VITALSIGNS, /** * Observations generated by imaging. The scope includes observations, plain x-ray, ultrasound, CT, MRI, angiography, echocardiography, nuclear medicine. */ IMAGING, /** * The results of observations generated by laboratories. Laboratory results are typically generated by laboratories providing analytic services in areas such as chemistry, hematology, serology, histology, cytology, anatomic pathology, microbiology, and/or virology. These observations are based on analysis of specimens obtained from the patient and submitted to the laboratory. */ LABORATORY, /** * Observations generated by other procedures. This category includes observations resulting from interventional and non-interventional procedures excluding lab and imaging (e.g. cardiology catheterization, endoscopy, electrodiagnostics, etc.). Procedure results are typically generated by a clinician to provide more granular information about component observations made during a procedure, such as where a gastroenterologist reports the size of a polyp observed during a colonoscopy. */ PROCEDURE, /** * Assessment tool/survey instrument observations (e.g. Apgar Scores, Montreal Cognitive Assessment (MoCA)) */ SURVEY, /** * Observations generated by physical exam findings including direct observations made by a clinician and use of simple instruments and the result of simple maneuvers performed directly on the patient's body. */ EXAM, /** * Observations generated by non-interventional treatment protocols (e.g. occupational, physical, radiation, nutritional and medication therapy) */ THERAPY, /** * added to help the parsers */ NULL; public static ObservationCategory fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("social-history".equals(codeString)) return SOCIALHISTORY; if ("vital-signs".equals(codeString)) return VITALSIGNS; if ("imaging".equals(codeString)) return IMAGING; if ("laboratory".equals(codeString)) return LABORATORY; if ("procedure".equals(codeString)) return PROCEDURE; if ("survey".equals(codeString)) return SURVEY; if ("exam".equals(codeString)) return EXAM; if ("therapy".equals(codeString)) return THERAPY; throw new FHIRException("Unknown ObservationCategory code '"+codeString+"'"); } public String toCode() { switch (this) { case SOCIALHISTORY: return "social-history"; case VITALSIGNS: return "vital-signs"; case IMAGING: return "imaging"; case LABORATORY: return "laboratory"; case PROCEDURE: return "procedure"; case SURVEY: return "survey"; case EXAM: return "exam"; case THERAPY: return "therapy"; case NULL: return null; default: return "?"; } } public String getSystem() { return "http://hl7.org/fhir/observation-category"; } public String getDefinition() { switch (this) { case SOCIALHISTORY: return "The Social History Observations define the patient's occupational, personal (e.g. lifestyle), social, and environmental history and health risk factors, as well as administrative data such as marital status, race, ethnicity and religious affiliation."; case VITALSIGNS: return " Clinical observations measure the body's basic functions such as such as blood pressure, heart rate, respiratory rate, height, weight, body mass index, head circumference, pulse oximetry, temperature, and body surface area."; case IMAGING: return "Observations generated by imaging. The scope includes observations, plain x-ray, ultrasound, CT, MRI, angiography, echocardiography, nuclear medicine."; case LABORATORY: return "The results of observations generated by laboratories. Laboratory results are typically generated by laboratories providing analytic services in areas such as chemistry, hematology, serology, histology, cytology, anatomic pathology, microbiology, and/or virology. These observations are based on analysis of specimens obtained from the patient and submitted to the laboratory."; case PROCEDURE: return "Observations generated by other procedures. This category includes observations resulting from interventional and non-interventional procedures excluding lab and imaging (e.g. cardiology catheterization, endoscopy, electrodiagnostics, etc.). Procedure results are typically generated by a clinician to provide more granular information about component observations made during a procedure, such as where a gastroenterologist reports the size of a polyp observed during a colonoscopy."; case SURVEY: return "Assessment tool/survey instrument observations (e.g. Apgar Scores, Montreal Cognitive Assessment (MoCA))"; case EXAM: return "Observations generated by physical exam findings including direct observations made by a clinician and use of simple instruments and the result of simple maneuvers performed directly on the patient's body."; case THERAPY: return "Observations generated by non-interventional treatment protocols (e.g. occupational, physical, radiation, nutritional and medication therapy)"; case NULL: return null; default: return "?"; } } public String getDisplay() { switch (this) { case SOCIALHISTORY: return "Social History"; case VITALSIGNS: return "Vital Signs"; case IMAGING: return "Imaging"; case LABORATORY: return "Laboratory"; case PROCEDURE: return "Procedure"; case SURVEY: return "Survey"; case EXAM: return "Exam"; case THERAPY: return "Therapy"; case NULL: return null; default: return "?"; } } }
/* * Copyright (C) 2015 andrewj * * 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 net.sourceforge.argparse4j.impl.type; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.Locale; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.mock.MockArgument; import org.junit.Test; public class CaseInsensitiveEnumStringArgumentTypeTest { enum Lang { PYTHON, JAVA, CPP { @Override public String toString() { return "C++"; } }, INTERLISP { @Override public String toString() { return "Interlisp"; } } } @Test public void testConvert() throws ArgumentParserException { ArgumentParser ap = ArgumentParsers.newFor("argparse4j") .locale(Locale.US).build(); CaseInsensitiveEnumStringArgumentType<Lang> type = CaseInsensitiveEnumStringArgumentType .forEnum(Lang.class); assertEquals(Lang.PYTHON, type.convert(ap, null, "PYTHON")); assertEquals(Lang.PYTHON, type.convert(ap, null, "Python")); assertEquals(Lang.PYTHON, type.convert(ap, null, "pYTHON")); assertEquals(Lang.JAVA, type.convert(ap, null, "JAVA")); assertEquals(Lang.CPP, type.convert(ap, null, "C++")); assertEquals(Lang.INTERLISP, type.convert(ap, null, "INTERLISP")); } @Test public void testConvertErrorsWithUnknownMember() throws ArgumentParserException { ArgumentParser ap = ArgumentParsers.newFor("argparse4j") .locale(Locale.US).build(); CaseInsensitiveEnumStringArgumentType<Lang> type = CaseInsensitiveEnumStringArgumentType .forEnum(Lang.class); try { type.convert(ap, new MockArgument(), "CPP"); fail("Expected ArgumentParserException to be thrown"); } catch (ArgumentParserException e) { assertEquals( "argument null: could not convert 'CPP' (choose from {PYTHON,JAVA,C++,Interlisp})", e.getMessage()); } } @Test public void testIgnoresLocaleOfParserForCaseInsensitivity() throws ArgumentParserException { ArgumentParser ap = ArgumentParsers.newFor("argparse4j") .locale(new Locale("tr")).build(); CaseInsensitiveEnumStringArgumentType<Lang> type = CaseInsensitiveEnumStringArgumentType .forEnum(Lang.class); try { type.convert(ap, new MockArgument(), "ınterlisp"); fail("Expected ArgumentParserException to be thrown"); } catch (ArgumentParserException e) { assertEquals( "argument null: could not convert 'ınterlisp' (choose from {PYTHON,JAVA,C++,Interlisp})", e.getMessage()); } } }
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.server.services.impl; import java.io.PrintStream; import org.kie.api.KieServices; import org.kie.api.builder.Message; import org.kie.api.builder.Message.Level; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.Results; import org.kie.api.runtime.KieContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Runs container verification against a given release. */ public class KieServerContainerVerifier { private static final Logger logger = LoggerFactory.getLogger(KieServerContainerVerifier.class); public boolean verify(String releaseId) { boolean verified; try { String[] gav = releaseId.split(":"); verified = verify(gav[0], gav[1], gav[2]); } catch (Throwable t) { logger.error(t.getMessage(), t); verified = false; } return verified; } public boolean verify(String groupId, String artifactId, String version) { boolean verified; KieServices services = KieServices.Factory.get(); try { ReleaseId releaseId = services.newReleaseId(groupId, artifactId, version); verified = verify(releaseId); } catch (Throwable t) { logger.error(t.getMessage(), t); verified = false; } return verified; } public boolean verify(ReleaseId releaseId) { boolean verified; KieServices services = KieServices.Factory.get(); try { KieContainer container = services.newKieContainer(releaseId); verified = verify(container); } catch (Throwable t) { logger.error(t.getMessage(), t); verified = false; } return verified; } public boolean verify(KieContainer container) { boolean verified = true; try { Results results = container.verify(); for (Message message : results.getMessages()) { Level level = message.getLevel(); switch (level) { case INFO: logger.info(message.toString()); break; case WARNING: logger.warn(message.toString()); break; case ERROR: logger.error(message.toString()); verified = false; break; } } } catch (Throwable t) { logger.error(t.getMessage(), t); verified = false; } return verified; } public static void main(String[] args) { boolean verified = main(args, System.out, System.err); if (!verified) { System.exit(1); } } // package-protected for JUnit testing static final String USAGE = "Usage: java " + KieServerContainerVerifier.class.getName() + " <gav1> <gav2> ...\n"; static boolean main(String[] args, PrintStream out, PrintStream err) { boolean triggered = false; boolean verified = true; if (args != null && args.length > 0) { KieServerContainerVerifier verifier = new KieServerContainerVerifier(); for (String arg : args) { if (arg != null) { arg = arg.trim(); if (!arg.isEmpty()) { triggered = true; if (verifier.verify(arg)) { logger.info(arg + " verified."); } else { logger.error(arg + " not verified."); verified = false; } } } } } if (!triggered) { err.print(USAGE); } return verified; } }
/* ==================================================================== 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.xddf.usermodel.text; import java.util.HashMap; import org.openxmlformats.schemas.drawingml.x2006.main.STTextFontAlignType; public enum FontAlignment { AUTOMATIC(STTextFontAlignType.AUTO), BOTTOM(STTextFontAlignType.B), BASELINE(STTextFontAlignType.BASE), CENTER(STTextFontAlignType.CTR), TOP(STTextFontAlignType.T); final STTextFontAlignType.Enum underlying; FontAlignment(STTextFontAlignType.Enum align) { this.underlying = align; } private static final HashMap<STTextFontAlignType.Enum, FontAlignment> reverse = new HashMap<>(); static { for (FontAlignment value : values()) { reverse.put(value.underlying, value); } } static FontAlignment valueOf(STTextFontAlignType.Enum align) { return reverse.get(align); } }
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package test.fixtures.inheritance; import java.util.*; public class MyLeafAsyncReactiveWrapper extends test.fixtures.inheritance.MyNodeAsyncReactiveWrapper implements MyLeaf.Reactive { private final MyLeaf.Async _delegate; public MyLeafAsyncReactiveWrapper(MyLeaf.Async _delegate) { super(_delegate); this._delegate = _delegate; } @java.lang.Override public void dispose() { _delegate.close(); } @java.lang.Override public reactor.core.publisher.Mono<Void> doLeaf() { return com.facebook.swift.transport.util.FutureUtil.toMono(_delegate.doLeaf()); } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core; import java.lang.annotation.Annotation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; /** * A common delegate for detecting Kotlin's presence and for identifying Kotlin types. * * @author Juergen Hoeller * @author Sebastien Deleuze * @since 5.0 */ @SuppressWarnings("unchecked") public abstract class KotlinDetector { private static final Log logger = LogFactory.getLog(KotlinDetector.class); @Nullable private static final Class<? extends Annotation> kotlinMetadata; private static final boolean kotlinReflectPresent; static { Class<?> metadata; ClassLoader classLoader = KotlinDetector.class.getClassLoader(); try { metadata = ClassUtils.forName("kotlin.Metadata", classLoader); } catch (ClassNotFoundException ex) { // Kotlin API not available - no Kotlin support metadata = null; } kotlinMetadata = (Class<? extends Annotation>) metadata; kotlinReflectPresent = ClassUtils.isPresent("kotlin.reflect.full.KClasses", classLoader); if (kotlinMetadata != null && !kotlinReflectPresent) { logger.info("Kotlin reflection implementation not found at runtime, related features won't be available."); } } /** * Determine whether Kotlin is present in general. */ public static boolean isKotlinPresent() { return (kotlinMetadata != null); } /** * Determine whether Kotlin reflection is present. * @since 5.1 */ public static boolean isKotlinReflectPresent() { return kotlinReflectPresent; } /** * Determine whether the given {@code Class} is a Kotlin type * (with Kotlin metadata present on it). */ public static boolean isKotlinType(Class<?> clazz) { return (kotlinMetadata != null && clazz.getDeclaredAnnotation(kotlinMetadata) != null); } }
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.version; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sourceforge.plantuml.AbstractPSystem; import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.command.PSystemSingleLineFactory; import net.sourceforge.plantuml.core.UmlSource; import net.sourceforge.plantuml.security.SecurityProfile; import net.sourceforge.plantuml.security.SecurityUtils; public class PSystemVersionFactory extends PSystemSingleLineFactory { @Override protected AbstractPSystem executeLine(UmlSource source, String line) { try { if (line.matches("(?i)^(authors?|about)\\s*$")) { return PSystemVersion.createShowAuthors2(source); } if (line.matches("(?i)^version\\s*$")) { return PSystemVersion.createShowVersion2(source); } if (line.matches("(?i)^stdlib\\s*$")) { return PSystemVersion.createStdLib(source); } // if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE && line.matches("(?i)^path\\s*$")) { // return PSystemVersion.createPath(source); // } if (line.matches("(?i)^testdot\\s*$")) { return PSystemVersion.createTestDot(source); } // if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE // && line.matches("(?i)^dumpstacktrace\\s*$")) { // return PSystemVersion.createDumpStackTrace(); // } if (line.matches("(?i)^keydistributor\\s*$")) { return PSystemVersion.createKeyDistributor(source); } if (line.matches("(?i)^keygen\\s*$")) { line = line.trim(); return new PSystemKeygen(source, ""); } if (line.matches("(?i)^keyimport(\\s+[0-9a-z]+)?\\s*$")) { line = line.trim(); final String key = line.substring("keyimport".length()).trim(); return new PSystemKeygen(source, key); } if (line.matches("(?i)^keycheck\\s+([0-9a-z]+)\\s+([0-9a-z]+)\\s*$")) { final Pattern p = Pattern.compile("(?i)^keycheck\\s+([0-9a-z]+)\\s+([0-9a-z]+)\\s*$"); final Matcher m = p.matcher(line); if (m.find()) { return new PSystemKeycheck(source, m.group(1), m.group(2)); } } } catch (IOException e) { Log.error("Error " + e); } return null; } }
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.onap.sdc.ci.tests.datatypes; public enum UserRoleEnum { ADMIN("jh0003", "Jimmy", "Hendrix"), DESIGNER("cs0008", "Carlos", "Santana"), DESIGNER2("me0009", "Melissa","Etheridge"), TESTER("jm0007", "Joni", "Mitchell"), ADMIN4("km2000", "Kot", "May"), GOVERNOR("gv0001","David", "Shadmi"), OPS("op0001", "Steve", "Regev"), PRODUCT_STRATEGIST1("ps0001", "Eden","Rozin"), PRODUCT_STRATEGIST2("ps0002", "Ella", "Kvetny"), PRODUCT_STRATEGIST3("ps0003", "Geva", "Alon"), PRODUCT_MANAGER1("pm0001", "Teddy", "Isashar"), PRODUCT_MANAGER2("pm0002", "Sarah", "Bettens"); private String userId; private String firstName; private String lastName; private String userName; private UserRoleEnum(String userId, String userName) { this.userId = userId; this.userName = userName; } private UserRoleEnum(String userId, String firstName, String lastName) { this.userId = userId; this.firstName = firstName; this.lastName = lastName; this.userName = firstName + " " + lastName; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
package ng.com.stemcoders.campusspace.utils; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.content.FileProvider; import java.io.File; import ng.com.stemcoders.campusspace.R; public class NotificationUtil { public static final String NOTIFICATION_CHANNEL_ID = "Campus Space Notification Channel ID"; public static final String NOTIFICATION_CHANNEL_NAME = "Campus Space Notifications"; public static final String NOTIFICATION_CHANNEL_DESC = "Notifications from Campus Space Application"; public static final int REQUEST_CODE_VIEW_RESOURCE = 1002; public static NotificationCompat.Builder buildNotification (Context context) { NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context); NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID) .setPriority(NotificationCompat.PRIORITY_HIGH); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notificationManagerCompat.getNotificationChannel(NOTIFICATION_CHANNEL_ID) == null) { NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH); channel.setDescription(NOTIFICATION_CHANNEL_DESC); notificationManagerCompat.createNotificationChannel(channel); } return builder; } public static NotificationCompat.Builder buildProgressNotification(Context context, String title, String text) { return buildNotification(context) .setContentTitle(title) .setContentText(text) .setOnlyAlertOnce(true) .setOngoing(true) .setSmallIcon(android.R.drawable.stat_sys_download); } public static NotificationCompat.Builder buildResourceDownloadingNotification(Context context, String fileName) { return buildProgressNotification(context, context.getString(R.string.downloading_resource), fileName); } public static NotificationCompat.Builder buildResourceDownloadedNotification(Context context, File resourceFile) { Intent intent = FileUtil.buildViewFileIntent(context, resourceFile); PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_CODE_VIEW_RESOURCE, intent, PendingIntent.FLAG_UPDATE_CURRENT); return buildNotification(context) .setContentTitle(context.getString(R.string.downloaded)) .setContentText(resourceFile.getName()) .setSmallIcon(android.R.drawable.stat_sys_download_done) .setContentIntent(pendingIntent) .setAutoCancel(true); } }
package com.js.amoeba.config; import java.util.HashSet; import java.util.Set; import org.springframework.context.annotation.Bean; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import org.thymeleaf.templateresolver.ITemplateResolver; public class ThymeLeafConfig { @Bean ClassLoaderTemplateResolver emailTemplateResolver() { final ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); resolver.setPrefix("mail/"); resolver.setSuffix(".html"); resolver.setTemplateMode("HTML5"); resolver.setCharacterEncoding("UTF-8"); resolver.setOrder(1); return resolver; } @Bean public SpringTemplateEngine templateEngine() { final SpringTemplateEngine engine = new SpringTemplateEngine(); final Set<ITemplateResolver> templateResolvers = new HashSet<ITemplateResolver>(); templateResolvers.add(emailTemplateResolver()); engine.setTemplateResolvers(templateResolvers); return engine; } }
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.find.actions; import com.intellij.CommonBundle; import com.intellij.codeInsight.hint.HintManager; import com.intellij.find.FindBundle; import com.intellij.find.usages.api.SearchTarget; import com.intellij.lang.Language; import com.intellij.lang.findUsages.EmptyFindUsagesProvider; import com.intellij.lang.findUsages.LanguageFindUsages; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorGutter; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.project.PossiblyDumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.registry.Registry; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtilBase; import com.intellij.usages.UsageTarget; import com.intellij.usages.UsageView; import org.jetbrains.annotations.NotNull; import java.util.List; import static com.intellij.openapi.actionSystem.IdeActions.ACTION_HIGHLIGHT_USAGES_IN_FILE; public class FindUsagesInFileAction extends AnAction implements PossiblyDumbAware { public FindUsagesInFileAction() { setInjectedContext(true); } @Override public boolean isDumbAware() { return Registry.is("ide.find.in.file.highlight.usages"); } @Override public void actionPerformed(@NotNull AnActionEvent e) { if (Registry.is("ide.find.in.file.highlight.usages")) { ActionManager.getInstance().getAction(ACTION_HIGHLIGHT_USAGES_IN_FILE).actionPerformed(e); return; } DataContext dataContext = e.getDataContext(); final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) return; PsiDocumentManager.getInstance(project).commitAllDocuments(); Editor editor = CommonDataKeys.EDITOR.getData(dataContext); UsageTarget[] usageTargets = UsageView.USAGE_TARGETS_KEY.getData(dataContext); if (usageTargets != null) { FileEditor fileEditor = PlatformDataKeys.FILE_EDITOR.getData(dataContext); if (fileEditor != null) { usageTargets[0].findUsagesInEditor(fileEditor); } } else if (editor == null) { Messages.showMessageDialog( project, FindBundle.message("find.no.usages.at.cursor.error"), CommonBundle.getErrorTitle(), Messages.getErrorIcon() ); } else { HintManager.getInstance().showErrorHint(editor, FindBundle.message("find.no.usages.at.cursor.error")); } } @Override public void update(@NotNull AnActionEvent event) { if (Registry.is("ide.find.in.file.highlight.usages")) { ActionManager.getInstance().getAction(ACTION_HIGHLIGHT_USAGES_IN_FILE).update(event); return; } updateFindUsagesAction(event); } private static boolean isEnabled(DataContext dataContext) { Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null || EditorGutter.KEY.getData(dataContext) != null || Boolean.TRUE.equals(dataContext.getData(CommonDataKeys.EDITOR_VIRTUAL_SPACE))) { return false; } List<SearchTarget> searchTargets = dataContext.getData(FindUsagesAction.SEARCH_TARGETS); if (searchTargets != null && !searchTargets.isEmpty()) { return true; } Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (editor == null) { UsageTarget[] target = UsageView.USAGE_TARGETS_KEY.getData(dataContext); return target != null && target.length > 0; } else { PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) { return false; } Language language = PsiUtilBase.getLanguageInEditor(editor, project); if (language == null) { language = file.getLanguage(); } return !(LanguageFindUsages.INSTANCE.forLanguage(language) instanceof EmptyFindUsagesProvider); } } public static void updateFindUsagesAction(@NotNull AnActionEvent event) { Presentation presentation = event.getPresentation(); DataContext dataContext = event.getDataContext(); boolean enabled = isEnabled(dataContext); presentation.setVisible(enabled || !ActionPlaces.isPopupPlace(event.getPlace())); presentation.setEnabled(enabled); } }
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tightblog.rendering.service; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.PageRequest; import org.tightblog.domain.User; import org.tightblog.domain.Weblog; import org.tightblog.rendering.service.WeblogListGenerator.WeblogListData; import org.tightblog.dao.WeblogDao; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class WeblogListGeneratorTest { private WeblogListGenerator weblogListGenerator; private List<Weblog> weblogList; private Instant now = Instant.now(); private Instant twoDaysAgo = now.minus(2, ChronoUnit.DAYS); private WeblogDao mockWeblogDao; @Before public void initialize() { mockWeblogDao = mock(WeblogDao.class); weblogListGenerator = new WeblogListGenerator(mockWeblogDao); User user1 = new User(); user1.setScreenName("user1"); User user2 = new User(); user2.setScreenName("user2"); weblogList = new ArrayList<>(); Weblog weblog1 = new Weblog(); weblog1.setName("Most Popular Blog"); weblog1.setHandle("mostpop1"); weblog1.setAbout("About most popular 1"); weblog1.setCreator(user1); weblog1.setLastModified(now); weblog1.setHitsToday(200); weblogList.add(weblog1); Weblog weblog2 = new Weblog(); weblog2.setName("Second-Most Popular Blog"); weblog2.setHandle("mostpop2"); weblog2.setAbout("About most popular 2"); weblog2.setCreator(user2); weblog2.setLastModified(twoDaysAgo); weblog2.setHitsToday(150); weblogList.add(weblog2); } @Test public void testGetHotWeblogs() { when(mockWeblogDao.findByVisibleTrueAndHitsTodayGreaterThanOrderByHitsTodayDesc(eq(0), any())) .thenReturn(weblogList); List<WeblogListGenerator.WeblogData> weblogDataList = weblogListGenerator.getHotWeblogs(12); assertEquals(2, weblogDataList.size()); WeblogListGenerator.WeblogData firstBlog = weblogDataList.get(0); assertEquals("Most Popular Blog", firstBlog.getName()); assertEquals("mostpop1", firstBlog.getHandle()); assertEquals("About most popular 1", firstBlog.getAbout()); assertEquals("user1", firstBlog.getCreatorScreenName()); assertEquals(now, firstBlog.getLastModified()); assertEquals(200, firstBlog.getHitsToday()); assertEquals("Second-Most Popular Blog", weblogDataList.get(1).getName()); } @Test public void testGetWeblogsByLetter() { List<Weblog> oneWeblogList = new ArrayList<>(); oneWeblogList.add(weblogList.get(0)); when(mockWeblogDao.findByLetterOrderByHandle('M', PageRequest.of(30, 11))) .thenReturn(oneWeblogList); when(mockWeblogDao.findByVisibleTrueOrderByHandle(any())).thenReturn(weblogList); // test if letter and pageNum > 0 get one weblog and prev link WeblogListData data = weblogListGenerator.getWeblogsByLetter("http://www.foo.com", 'M', 3, 10); assertEquals(1, data.getWeblogs().size()); assertEquals("mostpop1", data.getWeblogs().get(0).getHandle()); assertEquals("http://www.foo.com?letter=M&page=2", data.getPrevLink()); assertNull(data.getNextLink()); // test if no letter get two weblogs with no next or previous data = weblogListGenerator.getWeblogsByLetter("http://www.foo.com", null, 0, 10); assertEquals(2, data.getWeblogs().size()); assertEquals("mostpop2", data.getWeblogs().get(1).getHandle()); assertNull(data.getPrevLink()); assertNull(data.getNextLink()); // test if no letter & length 1 get just one back (first page - no prev link) data = weblogListGenerator.getWeblogsByLetter("http://www.foo.com", null, 0, 1); assertEquals(1, data.getWeblogs().size()); assertEquals("mostpop1", data.getWeblogs().get(0).getHandle()); assertNull(data.getPrevLink()); assertEquals("http://www.foo.com?page=1", data.getNextLink()); // test if no letter & length 1 get just one back (non-first page) data = weblogListGenerator.getWeblogsByLetter("http://www.foo.com", null, 2, 1); assertEquals(1, data.getWeblogs().size()); assertEquals("mostpop1", data.getWeblogs().get(0).getHandle()); assertEquals("http://www.foo.com?page=1", data.getPrevLink()); assertEquals("http://www.foo.com?page=3", data.getNextLink()); } }
/* * Copyright 2000-2021 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.fusion.typeconversion; import org.junit.Test; public class MapConversionTest extends BaseTypeConversionTest { @Test public void should_ConvertToMapOfString_When_ReceiveMapOfString() { String inputValue = "{\"key\": \"value\", \"second_key\":\"2\"}"; String expectedValue = "{\"key\":\"value-foo\",\"second_key\":\"2-foo\"}"; assertEqualExpectedValueWhenCallingMethod("getFooMapStringString", inputValue, expectedValue); } @Test public void should_ConvertToMapOfString_When_ReceiveMapWithNonStringValue() { String inputValue = "{\"key\": 1, \"second_key\": 2.0}"; String expectedValue = "{\"key\":\"1-foo\",\"second_key\":\"2.0-foo\"}"; assertEqualExpectedValueWhenCallingMethod("getFooMapStringString", inputValue, expectedValue); } @Test public void should_ConvertToMapOfInteger_When_ReceiveMapOfInteger() { String inputValue = "{\"key\":2,\"second_key\":3}"; String expectedValue = "{\"key\":3,\"second_key\":4}"; assertEqualExpectedValueWhenCallingMethod("getAddOneMapStringInteger", inputValue, expectedValue); } @Test public void should_ConvertToMapOfInteger_When_ReceiveMapOfNonInteger() { String inputValue = "{\"key\":\"2\"}"; String expectedValue = "{\"key\":3}"; assertEqualExpectedValueWhenCallingMethod("getAddOneMapStringInteger", inputValue, expectedValue); } @Test public void should_ConvertToMapOfInteger_When_ReceiveMapOfDecimal() { String inputValue = "{\"key\": 2.0}"; String expectedValue = "{\"key\":3}"; assertEqualExpectedValueWhenCallingMethod("getAddOneMapStringInteger", inputValue, expectedValue); inputValue = "{\"key\":2.9}"; assertEqualExpectedValueWhenCallingMethod("getAddOneMapStringInteger", inputValue, expectedValue); } @Test public void should_ConvertToMapOfDouble_When_ReceiveMapOfDecimal() { String inputValue = "{\"key\": 2.0}"; String expectedValue = "{\"key\":3.0}"; assertEqualExpectedValueWhenCallingMethod("getAddOneMapStringDouble", inputValue, expectedValue); } @Test public void should_FailToConvertToMapOfDouble_When_ReceiveMapOfInteger() { String inputValue = "{\"key\": 2}"; String expectedValue = "{\"key\":3.0}"; assertEqualExpectedValueWhenCallingMethod("getAddOneMapStringDouble", inputValue, expectedValue); } @Test public void should_FailToConvertToMapOfStringEnum_When_ReceiveMapOfStringEnum() { String inputValue = "{\"first_key\": \"FIRST\", \"second_key\": \"SECOND\"}"; String expectedValue = "{\"first_key\":\"SECOND\",\"second_key\":\"THIRD\"}"; assertEqualExpectedValueWhenCallingMethod("getNextEnumMapStringEnum", inputValue, expectedValue); } @Test public void should_ConvertToMapOfEnumInteger_When_ReceiveMapOfEnumInteger() { String inputValue = "{\"FIRST\": \"1\"}"; String expectedValue = "{\"FIRST\":2}"; assertEqualExpectedValueWhenCallingMethod("getAddOneMapEnumInteger", inputValue, expectedValue); } }
package com.wang.guava.reference; import java.lang.ref.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * @description: Reference示例 * @author: wei·man cui * @date: 2020/8/21 9:29 */ public class ReferenceExample { /** * 设置 VM Options:-Xmx128M -Xms64M -XX:+PrintGCDetails */ public static void main(String[] args) throws InterruptedException { // strongRef(); // softReference(); // weakReference(); softWeakPhantomRef(); } /** * 强引用:即便抛出 OutOfMemory ,强引用也不会被GC */ public static void strongRef() throws InterruptedException { int current = 1; List<Ref> contianer = new ArrayList<>(); for (; ; ) { contianer.add(new Ref(current)); current++; System.out.println("The [" + current + "] Ref will be insert into container"); TimeUnit.MILLISECONDS.sleep(500); } } /** * 软引用:new SoftReference<>(new Object()); 创建软引用对象 * SoftReference 可以检测到JVM内存空间是否足够,不足时就GC掉软引用 * 因为这个特性,适合用于开发 缓存Cache(适度放大休眠时间,给JVM充足时间执行GC) */ public static void softReference() throws InterruptedException { int current = 1; List<SoftReference> contianer = new ArrayList<>(); for (; ; ) { contianer.add(new SoftReference<>(new Ref(current))); current++; System.out.println("The [" + current + "] Ref will be insert into container"); TimeUnit.SECONDS.sleep(1); } } /** * 弱引用:只要被扫描标记,就会被GC,不论是 Minor GC还是Full GC。 * <p> * 年轻代回收内存:Minor GC; * 老年代回收内存:Major GC; * 整个堆回收内存:Full GC。 * </P> */ public static void weakReference() throws InterruptedException { int current = 1; List<WeakReference<Ref>> contianer = new ArrayList<>(); for (; ; ) { contianer.add(new WeakReference<>(new Ref(current))); current++; System.out.println("The [" + current + "] Ref will be insert into container"); TimeUnit.MILLISECONDS.sleep(200); } } /** * 软/弱/虚引用的比较. * System.gc()需要时间,因此休眠 */ public static void softWeakPhantomRef() throws InterruptedException { /*Ref softRef = new Ref(10); SoftReference<Ref> soft = new SoftReference<>(softRef); softRef = null; System.gc(); TimeUnit.SECONDS.sleep(1); System.out.println(softRef); System.out.println("【软引用】" + soft.get().index);*/ /*Ref weakRef = new Ref(8); WeakReference<Ref> weak = new WeakReference<>(weakRef); weakRef = null; System.gc(); TimeUnit.SECONDS.sleep(1); System.out.println(weakRef); System.out.println("【弱引用】被GC掉,空指针异常:" + weak.get().index);*/ ReferenceQueue<Ref> queue = new ReferenceQueue<>(); PhantomReference<Ref> phantom = new PhantomReference<>(new Ref(5), queue); System.out.println("【虚引用】:" + phantom.get()); System.gc(); // TimeUnit.SECONDS.sleep(1); Reference<? extends Ref> object = queue.remove(); System.out.println(object); } /** * GC时,会扫描两次。 * 首次标记:判断是否需要执行finalize()方法,判定是否需要执行的标准——对象是否重写了finalize(), * 或者虚拟机已经调用了finalize()方法,若是,则判定为不执行。 * 第二次标记:虚拟机执行finalize()方法,对象被放置F-Queue队列,若在finalize()方法中 对象被重新引用则存活 * 否则被标记回收。 */ private static class Ref { // 1M private byte[] data = new byte[1024 * 1024]; private final int index; public Ref(int index) { this.index = index; } @Override protected void finalize() throws Throwable { System.out.println("The index [" + index + "] will be GC."); } } }
package org.egov.fsm.calculator.web.models.demand; import java.util.ArrayList; import java.util.List; import org.egov.common.contract.response.ResponseInfo; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @Builder public class DemandResponse { @JsonProperty("ResponseInfo") private ResponseInfo responseInfo; @JsonProperty("Demands") private List<Demand> demands = new ArrayList<>(); }
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.test.autoconfigure; import java.util.LinkedHashSet; import java.util.Set; import org.springframework.boot.autoconfigure.condition.ConditionEvaluationReport; import org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportMessage; import org.springframework.boot.test.context.DefaultTestExecutionListenersPostProcessor; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.TestContext; import org.springframework.test.context.TestExecutionListener; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; /** * Alternative {@link DependencyInjectionTestExecutionListener} prints the * {@link ConditionEvaluationReport} when the context cannot be prepared. * * @author Phillip Webb * @since 1.4.1 */ public class SpringBootDependencyInjectionTestExecutionListener extends DependencyInjectionTestExecutionListener { @Override public void prepareTestInstance(TestContext testContext) throws Exception { try { super.prepareTestInstance(testContext); } catch (Exception ex) { outputConditionEvaluationReport(testContext); throw ex; } } private void outputConditionEvaluationReport(TestContext testContext) { try { ApplicationContext context = testContext.getApplicationContext(); if (context instanceof ConfigurableApplicationContext) { ConditionEvaluationReport report = ConditionEvaluationReport .get(((ConfigurableApplicationContext) context).getBeanFactory()); System.err.println(new ConditionEvaluationReportMessage(report)); } } catch (Exception ex) { // Allow original failure to be reported } } static class PostProcessor implements DefaultTestExecutionListenersPostProcessor { @Override public Set<Class<? extends TestExecutionListener>> postProcessDefaultTestExecutionListeners( Set<Class<? extends TestExecutionListener>> listeners) { Set<Class<? extends TestExecutionListener>> updated = new LinkedHashSet<>( listeners.size()); for (Class<? extends TestExecutionListener> listener : listeners) { updated.add( listener.equals(DependencyInjectionTestExecutionListener.class) ? SpringBootDependencyInjectionTestExecutionListener.class : listener); } return updated; } } }
// ============================================================================ // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // https://github.com/Talend/data-prep/blob/master/LICENSE // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dataprep.api.service.api; import java.io.Serializable; import java.util.List; import java.util.Objects; import org.talend.dataprep.api.action.ActionForm; import org.talend.dataprep.api.dataset.DataSetMetadata; import org.talend.dataprep.api.dataset.RowMetadata; import org.talend.dataprep.api.folder.Folder; import org.talend.dataprep.api.preparation.Action; import org.talend.dataprep.api.preparation.StepDiff; import org.talend.dataprep.api.share.Owner; import com.fasterxml.jackson.annotation.JsonProperty; /** * Simple bean used to display a preparation and a summary of its related dataset and its location. */ public class EnrichedPreparation { private String id; private String dataSetId; /** Metadata on which the preparation is based. **/ private RowMetadata rowMetadata; private String author; private String name; private long creationDate; private long lastModificationDate; private String headId; private List<String> steps; /** List of action metadata (description) */ private List<ActionForm> metadata; private List<Action> actions; /** This preparation owner. */ private Owner owner; private boolean allowFullRun; private List<StepDiff> diff; /** The dataset metadata to summarize. */ @JsonProperty("dataset") private DataSetMetadataSummary summary; /** Where the preparation is stored. */ private Folder folder; public void setSummary(DataSetMetadataSummary summary) { this.summary = summary; } public void setFolder(Folder folder) { this.folder = folder; } public DataSetMetadataSummary getSummary() { return summary; } public Folder getFolder() { return folder; } public List<String> getSteps() { return steps; } public void setSteps(List<String> steps) { this.steps = steps; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getCreationDate() { return creationDate; } public void setCreationDate(long creationDate) { this.creationDate = creationDate; } public long getLastModificationDate() { return lastModificationDate; } public void setLastModificationDate(long lastModificationDate) { this.lastModificationDate = lastModificationDate; } public String getHeadId() { return headId; } public void setHeadId(String headId) { this.headId = headId; } public Owner getOwner() { return owner; } public void setOwner(Owner owner) { this.owner = owner; } public boolean isAllowFullRun() { return allowFullRun; } public void setAllowFullRun(boolean allowFullRun) { this.allowFullRun = allowFullRun; } public String getDataSetId() { return dataSetId; } public void setDataSetId(String dataSetId) { this.dataSetId = dataSetId; } public List<Action> getActions() { return actions; } public void setActions(List<Action> actions) { this.actions = actions; } public List<StepDiff> getDiff() { return diff; } public void setDiff(List<StepDiff> diff) { this.diff = diff; } public RowMetadata getRowMetadata() { return rowMetadata; } public void setRowMetadata(RowMetadata rowMetadata) { this.rowMetadata = rowMetadata; } public List<ActionForm> getMetadata() { return metadata; } public void setMetadata(List<ActionForm> metadata) { this.metadata = metadata; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } EnrichedPreparation that = (EnrichedPreparation) o; return Objects.equals(summary, that.summary) && Objects.equals(folder, this.folder); } @Override public int hashCode() { return Objects.hash(super.hashCode(), summary, folder); } @Override public String toString() { return "EnrichedPreparation{" + "preparation id=" + getId() + '\'' + ", summary=" + summary + ", folder=" + folder + '}'; } /** * Inner class that summarize a dataset metadata. */ public static class DataSetMetadataSummary implements Serializable { /** The dataset id. */ private String dataSetId = null; /** The dataset name. */ private String dataSetName = null; /** the number of rows in the dataset. */ private long dataSetNbRow; // For deserialization purposes only public DataSetMetadataSummary() { } /** * Constructor. * * @param metadata the dataset metadata to create the summary from. */ public DataSetMetadataSummary(DataSetMetadata metadata) { if (metadata != null) { this.dataSetId = metadata.getId(); this.dataSetName = metadata.getName(); this.dataSetNbRow = metadata.getContent().getNbRecords(); } } public String getDataSetId() { return dataSetId; } public String getDataSetName() { return dataSetName; } public long getDataSetNbRow() { return dataSetNbRow; } @Override public String toString() { return "DataSetMetadataSummary{" + "dataSetId='" + dataSetId + '\'' + ", dataSetName='" + dataSetName + '\'' + ", dataSetNbRow=" + dataSetNbRow + '}'; } } }
// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.retrace.internal; import com.android.tools.r8.references.Reference; import com.android.tools.r8.references.TypeReference; import com.android.tools.r8.retrace.RetraceClassResult; import com.android.tools.r8.retrace.RetraceFieldResult; import com.android.tools.r8.retrace.RetraceFrameResult; import com.android.tools.r8.retrace.RetraceStackTraceProxy; import com.android.tools.r8.retrace.RetraceTypeResult; import com.android.tools.r8.retrace.RetracedClassReference; import com.android.tools.r8.retrace.RetracedFieldReference; import com.android.tools.r8.retrace.RetracedMethodReference; import com.android.tools.r8.retrace.RetracedTypeReference; import com.android.tools.r8.retrace.Retracer; import com.android.tools.r8.retrace.StackTraceElementProxy; import com.android.tools.r8.retrace.StackTraceElementProxyRetracer; import com.android.tools.r8.utils.Box; import com.android.tools.r8.utils.ListUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; public class StackTraceElementProxyRetracerImpl<T, ST extends StackTraceElementProxy<T, ST>> implements StackTraceElementProxyRetracer<T, ST> { private final Retracer retracer; public StackTraceElementProxyRetracerImpl(Retracer retracer) { this.retracer = retracer; } @Override public Stream<RetraceStackTraceProxy<T, ST>> retrace(ST element) { if (!element.hasClassName()) { RetraceStackTraceProxyImpl.Builder<T, ST> builder = RetraceStackTraceProxyImpl.builder(element); return Stream.of(builder.build()); } RetraceClassResult classResult = retracer.retraceClass(element.getClassReference()); if (element.hasMethodName()) { return retraceMethod(element, classResult); } else if (element.hasFieldName()) { return retraceField(element, classResult); } else { return retraceClassOrType(element, classResult); } } private Stream<RetraceStackTraceProxy<T, ST>> retraceClassOrType( ST element, RetraceClassResult classResult) { return classResult.stream() .flatMap( classElement -> retraceFieldOrReturnType(element) .flatMap( fieldOrReturnTypeConsumer -> retracedMethodArguments(element) .map( argumentsConsumer -> { RetraceStackTraceProxyImpl.Builder<T, ST> proxy = RetraceStackTraceProxyImpl.builder(element) .setRetracedClass(classElement.getRetracedClass()) .setAmbiguous(classResult.isAmbiguous()) .setTopFrame(true); argumentsConsumer.accept(proxy); fieldOrReturnTypeConsumer.accept(proxy); if (element.hasFileName()) { proxy.setSourceFile( classElement .retraceSourceFile(element.getFileName()) .getFilename()); } return proxy.build(); }))); } private Stream<RetraceStackTraceProxy<T, ST>> retraceMethod( ST element, RetraceClassResult classResult) { return retraceFieldOrReturnType(element) .flatMap( fieldOrReturnTypeConsumer -> retracedMethodArguments(element) .flatMap( argumentsConsumer -> { RetraceFrameResult frameResult = element.hasLineNumber() ? classResult.lookupFrame( element.getMethodName(), element.getLineNumber()) : classResult.lookupFrame(element.getMethodName()); return frameResult.stream() .flatMap( frameElement -> { List<RetraceStackTraceProxy<T, ST>> retracedProxies = new ArrayList<>(); frameElement.visitNonCompilerSynthesizedFrames( (frame, index) -> { boolean isTopFrame = retracedProxies.isEmpty(); RetraceStackTraceProxyImpl.Builder<T, ST> proxy = RetraceStackTraceProxyImpl.builder(element) .setRetracedClass(frame.getHolderClass()) .setRetracedMethod(frame) .setAmbiguous( frameResult.isAmbiguous() && isTopFrame) .setTopFrame(isTopFrame); if (element.hasLineNumber()) { proxy.setLineNumber( frame.getOriginalPositionOrDefault( element.getLineNumber())); } if (element.hasFileName()) { proxy.setSourceFile( frameElement .retraceSourceFile(frame, element.getFileName()) .getFilename()); } fieldOrReturnTypeConsumer.accept(proxy); argumentsConsumer.accept(proxy); retracedProxies.add(proxy.build()); }); return retracedProxies.stream(); }); })); } private Stream<RetraceStackTraceProxy<T, ST>> retraceField( ST element, RetraceClassResult classResult) { return retraceFieldOrReturnType(element) .flatMap( fieldOrReturnTypeConsumer -> retracedMethodArguments(element) .flatMap( argumentsConsumer -> { RetraceFieldResult retraceFieldResult = classResult.lookupField(element.getFieldName()); return retraceFieldResult.stream() .map( fieldElement -> { RetraceStackTraceProxyImpl.Builder<T, ST> proxy = RetraceStackTraceProxyImpl.builder(element) .setRetracedClass( fieldElement.getField().getHolderClass()) .setRetracedField(fieldElement.getField()) .setAmbiguous(retraceFieldResult.isAmbiguous()) .setTopFrame(true); if (element.hasFileName()) { proxy.setSourceFile( fieldElement .retraceSourceFile(element.getFileName()) .getFilename()); } fieldOrReturnTypeConsumer.accept(proxy); argumentsConsumer.accept(proxy); return proxy.build(); }); })); } private Stream<Consumer<RetraceStackTraceProxyImpl.Builder<T, ST>>> retraceFieldOrReturnType( ST element) { if (!element.hasFieldOrReturnType()) { return Stream.of(noEffect -> {}); } String elementOrReturnType = element.getFieldOrReturnType(); if (elementOrReturnType.equals("void")) { return Stream.of( proxy -> proxy.setRetracedFieldOrReturnType(RetracedTypeReferenceImpl.createVoid())); } else { TypeReference typeReference = Reference.typeFromTypeName(elementOrReturnType); RetraceTypeResult retraceTypeResult = retracer.retraceType(typeReference); return retraceTypeResult.stream() .map( type -> (proxy -> { proxy.setRetracedFieldOrReturnType(type.getType()); if (retraceTypeResult.isAmbiguous()) { proxy.setAmbiguous(true); } })); } } private Stream<Consumer<RetraceStackTraceProxyImpl.Builder<T, ST>>> retracedMethodArguments( ST element) { if (!element.hasMethodArguments()) { return Stream.of(noEffect -> {}); } List<RetraceTypeResult> retracedResults = Arrays.stream(element.getMethodArguments().split(",")) .map(typeName -> retracer.retraceType(Reference.typeFromTypeName(typeName))) .collect(Collectors.toList()); List<List<RetracedTypeReference>> initial = new ArrayList<>(); initial.add(new ArrayList<>()); Box<Boolean> isAmbiguous = new Box<>(false); List<List<RetracedTypeReference>> retracedArguments = ListUtils.fold( retracedResults, initial, (acc, retracedTypeResult) -> { if (retracedTypeResult.isAmbiguous()) { isAmbiguous.set(true); } List<List<RetracedTypeReference>> newResult = new ArrayList<>(); retracedTypeResult.forEach( retracedElement -> { acc.forEach( oldResult -> { List<RetracedTypeReference> newList = new ArrayList<>(oldResult); newList.add(retracedElement.getType()); newResult.add(newList); }); }); return newResult; }); return retracedArguments.stream() .map( arguments -> proxy -> { proxy.setRetracedMethodArguments(arguments); if (isAmbiguous.get()) { proxy.setAmbiguous(true); } }); } public static class RetraceStackTraceProxyImpl<T, ST extends StackTraceElementProxy<T, ST>> implements RetraceStackTraceProxy<T, ST> { private final ST originalItem; private final RetracedClassReference retracedClass; private final RetracedMethodReference retracedMethod; private final RetracedFieldReference retracedField; private final RetracedTypeReference fieldOrReturnType; private final List<RetracedTypeReference> methodArguments; private final String sourceFile; private final int lineNumber; private final boolean isAmbiguous; private final boolean isTopFrame; private RetraceStackTraceProxyImpl( ST originalItem, RetracedClassReference retracedClass, RetracedMethodReference retracedMethod, RetracedFieldReference retracedField, RetracedTypeReference fieldOrReturnType, List<RetracedTypeReference> methodArguments, String sourceFile, int lineNumber, boolean isAmbiguous, boolean isTopFrame) { assert originalItem != null; this.originalItem = originalItem; this.retracedClass = retracedClass; this.retracedMethod = retracedMethod; this.retracedField = retracedField; this.fieldOrReturnType = fieldOrReturnType; this.methodArguments = methodArguments; this.sourceFile = sourceFile; this.lineNumber = lineNumber; this.isAmbiguous = isAmbiguous; this.isTopFrame = isTopFrame; } @Override public boolean isAmbiguous() { return isAmbiguous; } @Override public boolean isTopFrame() { return isTopFrame; } @Override public boolean hasRetracedClass() { return retracedClass != null; } @Override public boolean hasRetracedMethod() { return retracedMethod != null; } @Override public boolean hasRetracedField() { return retracedField != null; } @Override public boolean hasSourceFile() { return sourceFile != null; } @Override public boolean hasLineNumber() { return lineNumber != -1; } @Override public boolean hasFieldOrReturnType() { return fieldOrReturnType != null; } @Override public boolean hasMethodArguments() { return methodArguments != null; } @Override public ST getOriginalItem() { return originalItem; } @Override public RetracedClassReference getRetracedClass() { return retracedClass; } @Override public RetracedMethodReference getRetracedMethod() { return retracedMethod; } @Override public RetracedFieldReference getRetracedField() { return retracedField; } @Override public RetracedTypeReference getRetracedFieldOrReturnType() { return fieldOrReturnType; } @Override public List<RetracedTypeReference> getMethodArguments() { return methodArguments; } @Override public String getSourceFile() { return sourceFile; } private static <T, ST extends StackTraceElementProxy<T, ST>> Builder<T, ST> builder( ST originalElement) { return new Builder<>(originalElement); } @Override public int getLineNumber() { return lineNumber; } @Override public int compareTo(RetraceStackTraceProxy<T, ST> other) { int classCompare = Boolean.compare(hasRetracedClass(), other.hasRetracedClass()); if (classCompare != 0) { return classCompare; } if (hasRetracedClass()) { classCompare = getRetracedClass().getTypeName().compareTo(other.getRetracedClass().getTypeName()); if (classCompare != 0) { return classCompare; } } int methodCompare = Boolean.compare(hasRetracedMethod(), other.hasRetracedMethod()); if (methodCompare != 0) { return methodCompare; } if (hasRetracedMethod()) { methodCompare = getRetracedMethod().compareTo(other.getRetracedMethod()); if (methodCompare != 0) { return methodCompare; } } int sourceFileCompare = Boolean.compare(hasSourceFile(), other.hasSourceFile()); if (sourceFileCompare != 0) { return sourceFileCompare; } if (hasSourceFile()) { sourceFileCompare = getSourceFile().compareTo(other.getSourceFile()); if (sourceFileCompare != 0) { return sourceFileCompare; } } int lineNumberCompare = Boolean.compare(hasLineNumber(), other.hasLineNumber()); if (lineNumberCompare != 0) { return lineNumberCompare; } if (hasLineNumber()) { return Integer.compare(lineNumber, other.getLineNumber()); } return 0; } private static class Builder<T, ST extends StackTraceElementProxy<T, ST>> { private final ST originalElement; private RetracedClassReference classContext; private RetracedMethodReference methodContext; private RetracedFieldReference retracedField; private RetracedTypeReference fieldOrReturnType; private List<RetracedTypeReference> methodArguments; private String sourceFile; private int lineNumber = -1; private boolean isAmbiguous; private boolean isTopFrame; private Builder(ST originalElement) { this.originalElement = originalElement; } private Builder<T, ST> setRetracedClass(RetracedClassReference retracedClass) { this.classContext = retracedClass; return this; } private Builder<T, ST> setRetracedMethod(RetracedMethodReference methodElement) { this.methodContext = methodElement; return this; } private Builder<T, ST> setRetracedField(RetracedFieldReference retracedField) { this.retracedField = retracedField; return this; } private Builder<T, ST> setRetracedFieldOrReturnType(RetracedTypeReference retracedType) { this.fieldOrReturnType = retracedType; return this; } private Builder<T, ST> setRetracedMethodArguments(List<RetracedTypeReference> arguments) { this.methodArguments = arguments; return this; } private Builder<T, ST> setSourceFile(String sourceFile) { this.sourceFile = sourceFile; return this; } private Builder<T, ST> setLineNumber(int lineNumber) { this.lineNumber = lineNumber; return this; } private Builder<T, ST> setAmbiguous(boolean ambiguous) { this.isAmbiguous = ambiguous; return this; } private Builder<T, ST> setTopFrame(boolean topFrame) { isTopFrame = topFrame; return this; } private RetraceStackTraceProxy<T, ST> build() { RetracedClassReference retracedClass = classContext; if (methodContext != null) { retracedClass = methodContext.getHolderClass(); } return new RetraceStackTraceProxyImpl<>( originalElement, retracedClass, methodContext, retracedField, fieldOrReturnType, methodArguments, sourceFile, lineNumber, isAmbiguous, isTopFrame); } } } }
/* * 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.engine; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.document.StoredField; import org.apache.lucene.document.StringField; import org.apache.lucene.index.CodecReader; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.MergePolicy; import org.apache.lucene.index.NumericDocValues; import org.apache.lucene.index.SegmentCommitInfo; import org.apache.lucene.index.SegmentInfos; import org.apache.lucene.index.StandardDirectoryReader; import org.apache.lucene.index.Term; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.MatchNoDocsQuery; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.util.InfoStream; import org.apache.lucene.util.NullInfoStream; import org.elasticsearch.test.ESTestCase; import java.io.IOException; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; public class RecoverySourcePruneMergePolicyTests extends ESTestCase { public void testPruneAll() throws IOException { try (Directory dir = newDirectory()) { IndexWriterConfig iwc = newIndexWriterConfig(); RecoverySourcePruneMergePolicy mp = new RecoverySourcePruneMergePolicy("extra_source", MatchNoDocsQuery::new, newLogMergePolicy()); iwc.setMergePolicy(mp); try (IndexWriter writer = new IndexWriter(dir, iwc)) { for (int i = 0; i < 20; i++) { if (i > 0 && randomBoolean()) { writer.flush(); } Document doc = new Document(); doc.add(new StoredField("source", "hello world")); doc.add(new StoredField("extra_source", "hello world")); doc.add(new NumericDocValuesField("extra_source", 1)); writer.addDocument(doc); } writer.forceMerge(1); writer.commit(); try (DirectoryReader reader = DirectoryReader.open(writer)) { for (int i = 0; i < reader.maxDoc(); i++) { Document document = reader.document(i); assertEquals(1, document.getFields().size()); assertEquals("source", document.getFields().get(0).name()); } assertEquals(1, reader.leaves().size()); LeafReader leafReader = reader.leaves().get(0).reader(); NumericDocValues extra_source = leafReader.getNumericDocValues("extra_source"); if (extra_source != null) { assertEquals(DocIdSetIterator.NO_MORE_DOCS, extra_source.nextDoc()); } if (leafReader instanceof CodecReader && reader instanceof StandardDirectoryReader) { CodecReader codecReader = (CodecReader) leafReader; StandardDirectoryReader sdr = (StandardDirectoryReader) reader; SegmentInfos segmentInfos = sdr.getSegmentInfos(); MergePolicy.MergeSpecification forcedMerges = mp.findForcedDeletesMerges( segmentInfos, new MergePolicy.MergeContext() { @Override public int numDeletesToMerge(SegmentCommitInfo info) { return info.info.maxDoc() - 1; } @Override public int numDeletedDocs(SegmentCommitInfo info) { return info.info.maxDoc() - 1; } @Override public InfoStream getInfoStream() { return new NullInfoStream(); } @Override public Set<SegmentCommitInfo> getMergingSegments() { return Collections.emptySet(); } }); // don't wrap if there is nothing to do assertSame(codecReader, forcedMerges.merges.get(0).wrapForMerge(codecReader)); } } } } } public void testPruneSome() throws IOException { try (Directory dir = newDirectory()) { IndexWriterConfig iwc = newIndexWriterConfig(); iwc.setMergePolicy(new RecoverySourcePruneMergePolicy("extra_source", () -> new TermQuery(new Term("even", "true")), iwc.getMergePolicy())); try (IndexWriter writer = new IndexWriter(dir, iwc)) { for (int i = 0; i < 20; i++) { if (i > 0 && randomBoolean()) { writer.flush(); } Document doc = new Document(); doc.add(new StringField("even", Boolean.toString(i % 2 == 0), Field.Store.YES)); doc.add(new StoredField("source", "hello world")); doc.add(new StoredField("extra_source", "hello world")); doc.add(new NumericDocValuesField("extra_source", 1)); writer.addDocument(doc); } writer.forceMerge(1); writer.commit(); try (DirectoryReader reader = DirectoryReader.open(writer)) { assertEquals(1, reader.leaves().size()); NumericDocValues extra_source = reader.leaves().get(0).reader().getNumericDocValues("extra_source"); assertNotNull(extra_source); for (int i = 0; i < reader.maxDoc(); i++) { Document document = reader.document(i); Set<String> collect = document.getFields().stream().map(IndexableField::name).collect(Collectors.toSet()); assertTrue(collect.contains("source")); assertTrue(collect.contains("even")); if (collect.size() == 3) { assertTrue(collect.contains("extra_source")); assertEquals("true", document.getField("even").stringValue()); assertEquals(i, extra_source.nextDoc()); } else { assertEquals(2, document.getFields().size()); } } assertEquals(DocIdSetIterator.NO_MORE_DOCS, extra_source.nextDoc()); } } } } public void testPruneNone() throws IOException { try (Directory dir = newDirectory()) { IndexWriterConfig iwc = newIndexWriterConfig(); iwc.setMergePolicy(new RecoverySourcePruneMergePolicy("extra_source", () -> new MatchAllDocsQuery(), iwc.getMergePolicy())); try (IndexWriter writer = new IndexWriter(dir, iwc)) { for (int i = 0; i < 20; i++) { if (i > 0 && randomBoolean()) { writer.flush(); } Document doc = new Document(); doc.add(new StoredField("source", "hello world")); doc.add(new StoredField("extra_source", "hello world")); doc.add(new NumericDocValuesField("extra_source", 1)); writer.addDocument(doc); } writer.forceMerge(1); writer.commit(); try (DirectoryReader reader = DirectoryReader.open(writer)) { assertEquals(1, reader.leaves().size()); NumericDocValues extra_source = reader.leaves().get(0).reader().getNumericDocValues("extra_source"); assertNotNull(extra_source); for (int i = 0; i < reader.maxDoc(); i++) { Document document = reader.document(i); Set<String> collect = document.getFields().stream().map(IndexableField::name).collect(Collectors.toSet()); assertTrue(collect.contains("source")); assertTrue(collect.contains("extra_source")); assertEquals(i, extra_source.nextDoc()); } assertEquals(DocIdSetIterator.NO_MORE_DOCS, extra_source.nextDoc()); } } } } }
package com.wildbeeslabs.sensiblemetrics.diffy.validator.service; import com.wildbeeslabs.sensiblemetrics.diffy.validator.utils.DecimalNumberComparatorHelper; import com.wildbeeslabs.sensiblemetrics.diffy.validator.utils.InfinityNumberComparatorHelper; /** * Check that the number being validated is greater than or equal to the minimum * value specified. */ public class DecimalMinValidatorForDouble extends AbstractDecimalMinValidator<Double> { public DecimalMinValidatorForDouble(final String minValue, final boolean inclusive) { super(minValue, inclusive); } @Override protected int compare(final Double number) { return DecimalNumberComparatorHelper.compare(number, this.getMinValue(), InfinityNumberComparatorHelper.LESS_THAN); } }
/* * Copyright (c) 2008-2022, 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.cache.eviction; import com.hazelcast.config.Config; import com.hazelcast.config.EvictionConfig; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.spi.properties.ClusterProperty; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.TestHazelcastInstanceFactory; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import javax.cache.spi.CachingProvider; import java.util.concurrent.ConcurrentMap; import static com.hazelcast.cache.CacheTestSupport.createServerCachingProvider; import static com.hazelcast.cache.impl.maxsize.impl.EntryCountCacheEvictionChecker.calculateMaxPartitionSize; import static com.hazelcast.config.EvictionConfig.DEFAULT_MAX_ENTRY_COUNT; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class CacheEvictionPolicyComparatorTest extends AbstractCacheEvictionPolicyComparatorTest { @Override protected CachingProvider createCachingProvider(HazelcastInstance instance) { return createServerCachingProvider(instance); } @Override protected HazelcastInstance createInstance(Config config) { TestHazelcastInstanceFactory instanceFactory = createHazelcastInstanceFactory(); return instanceFactory.newHazelcastInstance(config); } @Override protected ConcurrentMap getUserContext(HazelcastInstance hazelcastInstance) { return hazelcastInstance.getUserContext(); } @Test public void test_evictionPolicyComparator_with_comparatorClassName_when_maxSizePolicy_is_entryCount() { int partitionCount = Integer.parseInt(ClusterProperty.PARTITION_COUNT.getDefaultValue()); int iterationCount = (calculateMaxPartitionSize(DEFAULT_MAX_ENTRY_COUNT, partitionCount) * partitionCount) * 2; EvictionConfig evictionConfig = new EvictionConfig().setComparatorClassName(MyEvictionPolicyComparator.class.getName()); testEvictionPolicyComparator(evictionConfig, iterationCount); } @Test public void test_evictionPolicyComparator_with_comparatorInstance_when_maxSizePolicy_is_entryCount() { int partitionCount = Integer.parseInt(ClusterProperty.PARTITION_COUNT.getDefaultValue()); int iterationCount = (calculateMaxPartitionSize(DEFAULT_MAX_ENTRY_COUNT, partitionCount) * partitionCount) * 2; EvictionConfig evictionConfig = new EvictionConfig().setComparator(new MyEvictionPolicyComparator()); testEvictionPolicyComparator(evictionConfig, iterationCount); } }
package calc5.calc; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Calculator11111111111111111111111111111111111111111 { public static Object debug() {return util.Util.get();} private static void sort(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort2(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort3(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort4(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort5(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort6(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort7(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort8(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort9(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort10(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort11(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort12(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort13(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort14(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort15(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort16(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort17(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort18(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort19(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } private static void sort20(List<Object> list) { Collections.sort(list, new Comparator<Object>() { public int compare(Object o1, Object o2) { return o2.hashCode() - o2.hashCode(); } }); } }
package com.unascribed.yttr.crafting; import java.util.Collection; import java.util.Collections; import org.jetbrains.annotations.Nullable; import com.google.gson.JsonObject; import com.unascribed.yttr.init.YItems; import com.google.common.base.Ascii; import net.minecraft.entity.EntityType; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtList; import net.minecraft.nbt.NbtString; import net.minecraft.recipe.Ingredient.Entry; import net.minecraft.util.Arm; import net.minecraft.util.registry.Registry; public class EntityIngredientEntry implements Entry { public final EntityType<?> entityType; public final @Nullable Arm mainHand; public EntityIngredientEntry(EntityType<?> entityType, @Nullable Arm mainHand) { this.entityType = entityType; this.mainHand = mainHand; } @Override public Collection<ItemStack> getStacks() { ItemStack is = new ItemStack(YItems.SNARE); is.getOrCreateSubTag("Contents").putString("id", Registry.ENTITY_TYPE.getId(entityType).toString()); if (mainHand != null) { NbtList lore = new NbtList(); lore.add(NbtString.of("\"§7"+(mainHand == Arm.LEFT ? "Left" : "Right")+"-Handed\"")); is.getOrCreateSubTag("display").put("Lore", lore); } return Collections.singleton(is); } @Override public JsonObject toJson() { JsonObject obj = new JsonObject(); obj.addProperty("yttr:entity", Registry.ENTITY_TYPE.getId(entityType).toString()); if (mainHand != null) { obj.addProperty("yttr:main_hand", Ascii.toLowerCase(mainHand.name())); } return obj; } }
package com.opyung.controller; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.opyung.biz.AdminBiz; import com.opyung.dao.ReportDao; import com.opyung.dto.DealBoardDto; import com.opyung.dto.MemberDto; import com.opyung.dto.ReportBoardDto; @WebServlet("/AdminController") public class AdminConrtoller extends HttpServlet { private static final long serialVersionUID = 1L; public AdminConrtoller() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //인코딩 처리 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); HttpSession session = request.getSession(); //command 출력 String command = request.getParameter("command"); System.out.println("[command:"+command+"]"); AdminBiz biz = new AdminBiz(); ///////////////////admin_main///////////////////// //검수대기만보이게 '검수신청' if(command.equals("admin")){ List<DealBoardDto> list = biz.dealAll(); List<ReportBoardDto> relist = biz.reportAll(); int countnull1 = relist.size(); List<ReportBoardDto> count = biz.count(); int count1 = count.size(); List<DealBoardDto> countready = biz.countready(); int countready1 = countready.size(); List<DealBoardDto> counting = biz.counting(); int counting1 = counting.size(); List<DealBoardDto> countgo = biz.countgo(); int countgo1 = countgo.size(); request.setAttribute("countnull", countnull1); request.setAttribute("count", count1); request.setAttribute("list", relist); request.setAttribute("countready", countready1); request.setAttribute("counting", counting1); request.setAttribute("countgo", countgo1); request.setAttribute("deal", list); dispatch("admin.jsp", request, response); } ///////////////////admin_user///////////////////// //유저 정보 전체 출력 else if(command.equals("userInfo")) { List<MemberDto> list = biz.selectAll(); request.setAttribute("list", list); dispatch("admin_user.jsp", request, response); //블랙 처리 }else if(command.equals("black")) { String mb_id = request.getParameter("mb_id"); String blackStatus = request.getParameter("blackStatus"); MemberDto dto = biz.selectOne(mb_id); if(blackStatus.equals("black")) { boolean res = biz.black(dto); if(res) { jsResponse("블랙처리되었습니다.", "admin.do?command=userInfo", response); }else { dispatch("admin.do?command=userInfo", request, response); } }else { int res = biz.blackCancel(dto); if(res>0) { jsResponse("블랙해지 처리되었습니다.", "admin.do?command=userInfo", response); }else { dispatch("admin.do?command=userInfo", request, response); } } //검색창 통한 정렬 및 검색 }else if(command.equals("search")){ String keyword = request.getParameter("keyword"); String keyField = request.getParameter("keyField"); List<MemberDto> list = biz.search(keyword,keyField); request.setAttribute("list", list); dispatch("admin_user.jsp", request, response); } ////////////////////admin_deal///////////////////////////// else if(command.equals("deal")) { List<DealBoardDto> list = biz.dealAll(); List<DealBoardDto> countready = biz.countready(); int countready1 = countready.size(); List<DealBoardDto> counting = biz.counting(); int counting1 = counting.size(); List<DealBoardDto> countgo = biz.countgo(); int countgo1 = countgo.size(); request.setAttribute("ingAll", counting); request.setAttribute("goAll", countgo); request.setAttribute("countready", countready1); request.setAttribute("counting", counting1); request.setAttribute("countgo", countgo1); request.setAttribute("deal", list); dispatch("admin_deal.jsp", request, response); } else if(command.equals("dealInfo")) { int sche_no = Integer.parseInt(request.getParameter("dealno")); String dealselect = request.getParameter("dealselect"); String start = request.getParameter("start"); String end = request.getParameter("end"); DealBoardDto dto = biz.dealselect(sche_no); boolean res = biz.dealupdate(dealselect,start,end,sche_no); if(res) { jsResponse("입력이 완료되었습니다.", "admin.do?command=deal", response); }else { dispatch("admin.do?command=deal", request, response); } } ///////////////////admin_report///////////////////// /*전체를 보내지말고 완료 날짜에 null값인 데이터들만 불러온다.(처리완료)*/ else if(command.equals("report")) { List<ReportBoardDto> list = biz.reportAll(); int countnull1 = list.size(); List<ReportBoardDto> count = biz.count(); int count1 = count.size(); request.setAttribute("countnull", countnull1); request.setAttribute("count", count1); request.setAttribute("count1", count); request.setAttribute("list", list); dispatch("admin_report.jsp", request, response); /*처리버튼를 하면 완료날짜업데이트하고 score에 점수를 -1 한다.*/ }else if(command.equals("treat")) { int report_no = Integer.parseInt(request.getParameter("report_no")); String report_tid = request.getParameter("report_tid"); String report_treat = request.getParameter("report_treat"); ReportBoardDto dto = biz.reselect(report_no); boolean res = biz.edate(report_no); if(report_treat.equals("yes")) if(res) { response.sendRedirect("admin.do?command=minus&report_tid="+report_tid); }else { dispatch("admin.do?command=report", request, response); }else { dispatch("admin.do?command=report", request, response); } }else if(command.equals("minus")) { String mb_id = request.getParameter("report_tid"); MemberDto dto = biz.selectOne(mb_id); boolean res = biz.minus(mb_id); if(res) { jsResponse("점수 차감 처리되었습니다.", "admin.do?command=report", response); }else { dispatch("admin.do?command=report", request, response); } } } private void jsResponse(String msg, String url, HttpServletResponse response) throws IOException { String s = "<script type='text/javascript'>" +"alert('"+msg+"');" +"location.href='"+url+"';" +"</script>"; PrintWriter out = response.getWriter(); out.print(s); } //dispatch private void dispatch(String url, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatch = request.getRequestDispatcher(url); dispatch.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.atguigu.gulimall.ums.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 会员收藏的商品 * * @author zoucj * @email 1095768010@qq.com * @date 2019-08-01 21:21:44 */ @ApiModel @Data @TableName("ums_member_collect_spu") public class MemberCollectSpuEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId @ApiModelProperty(name = "id",value = "id") private Long id; /** * 会员id */ @ApiModelProperty(name = "memberId",value = "会员id") private Long memberId; /** * spu_id */ @ApiModelProperty(name = "spuId",value = "spu_id") private Long spuId; /** * spu_name */ @ApiModelProperty(name = "spuName",value = "spu_name") private String spuName; /** * spu_img */ @ApiModelProperty(name = "spuImg",value = "spu_img") private String spuImg; /** * create_time */ @ApiModelProperty(name = "createTime",value = "create_time") private Date createTime; }
/* * 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.cql3.statements; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.exceptions.SyntaxException; public class PropertyDefinitions { protected static final Logger logger = LoggerFactory.getLogger(PropertyDefinitions.class); protected final Map<String, Object> properties = new HashMap<String, Object>(); public void addProperty(String name, String value) throws SyntaxException { if (properties.put(name, value) != null) throw new SyntaxException(String.format("Multiple definition for property '%s'", name)); } public void addProperty(String name, Map<String, String> value) throws SyntaxException { if (properties.put(name, value) != null) throw new SyntaxException(String.format("Multiple definition for property '%s'", name)); } public void validate(Set<String> keywords, Set<String> obsolete) throws SyntaxException { for (String name : properties.keySet()) { if (keywords.contains(name)) continue; if (obsolete.contains(name)) logger.warn("Ignoring obsolete property {}", name); else throw new SyntaxException(String.format("Unknown property '%s'", name)); } } protected String getSimple(String name) throws SyntaxException { Object val = properties.get(name); if (val == null) return null; if (!(val instanceof String)) throw new SyntaxException(String.format("Invalid value for property '%s'. It should be a string", name)); return (String)val; } protected Map<String, String> getMap(String name) throws SyntaxException { Object val = properties.get(name); if (val == null) return null; if (!(val instanceof Map)) throw new SyntaxException(String.format("Invalid value for property '%s'. It should be a map.", name)); return (Map<String, String>)val; } public Boolean hasProperty(String name) { return properties.containsKey(name); } public String getString(String key, String defaultValue) throws SyntaxException { String value = getSimple(key); return value != null ? value : defaultValue; } // Return a property value, typed as a Boolean public Boolean getBoolean(String key, Boolean defaultValue) throws SyntaxException { String value = getSimple(key); return (value == null) ? defaultValue : value.toLowerCase().matches("(1|true|yes)"); } // Return a property value, typed as a double public double getDouble(String key, double defaultValue) throws SyntaxException { String value = getSimple(key); if (value == null) { return defaultValue; } else { try { return Double.parseDouble(value); } catch (NumberFormatException e) { throw new SyntaxException(String.format("Invalid double value %s for '%s'", value, key)); } } } // Return a property value, typed as an Integer public Integer getInt(String key, Integer defaultValue) throws SyntaxException { String value = getSimple(key); return toInt(key, value, defaultValue); } public static Integer toInt(String key, String value, Integer defaultValue) throws SyntaxException { if (value == null) { return defaultValue; } else { try { return Integer.valueOf(value); } catch (NumberFormatException e) { throw new SyntaxException(String.format("Invalid integer value %s for '%s'", value, key)); } } } }
package com.reactcalculator; import android.app.Application; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage() ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
/* * 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 groovy.lang; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Interceptor that registers the timestamp of each method call * before and after invocation. The timestamps are stored internally * and can be retrieved through the with the <pre>getCalls()</pre> * and <pre>statistic()</pre> API. * <p> * Example usage: * <pre> * def proxy = ProxyMetaClass.getInstance(ArrayList.class) * proxy.interceptor = new BenchmarkInterceptor() * proxy.use { * def list = (0..10000).collect{ it } * 4.times { list.size() } * 4000.times { list.set(it, it+1) } * } * proxy.interceptor.statistic() * </pre> * Which produces the following output: * <pre> * [[size, 4, 0], [set, 4000, 21]] * </pre> */ public class BenchmarkInterceptor implements Interceptor { protected Map calls = new LinkedHashMap(); // keys to list of invocation times and before and after /** * Returns the raw data associated with the current benchmark run. */ public Map getCalls() { return calls; } /** * Resets all the benchmark data on this object. */ public void reset() { calls = new HashMap(); } /** * This code is executed before the method is called. * @param object receiver object for the method call * @param methodName name of the method to call * @param arguments arguments to the method call * @return null * relays this result. */ public Object beforeInvoke(Object object, String methodName, Object[] arguments) { if (!calls.containsKey(methodName)) calls.put(methodName, new LinkedList()); ((List) calls.get(methodName)).add(System.currentTimeMillis()); return null; } /** * This code is executed after the method is called. * @param object receiver object for the called method * @param methodName name of the called method * @param arguments arguments to the called method * @param result result of the executed method call or result of beforeInvoke if method was not called * @return result */ public Object afterInvoke(Object object, String methodName, Object[] arguments, Object result) { ((List) calls.get(methodName)).add(System.currentTimeMillis()); return result; } /** * The call should be invoked separately * @return true */ public boolean doInvoke() { return true; } /** * Returns benchmark statistics as a List&lt;Object[]&gt;. * AccumulateTime is measured in milliseconds and is as accurate as * System.currentTimeMillis() allows it to be. * @return a list of lines, each item is [methodname, numberOfCalls, accumulatedTime] */ public List statistic() { List result = new LinkedList(); for (Iterator iter = calls.keySet().iterator(); iter.hasNext();) { Object[] line = new Object[3]; result.add(line); line[0] = iter.next(); List times = (List) calls.get(line[0]); line[1] = times.size() / 2; int accTime = 0; for (Iterator it = times.iterator(); it.hasNext();) { Long start = (Long) it.next(); Long end = (Long) it.next(); accTime += end - start; } line[2] = (long) accTime; } return result; } }
package com.fmi.design.patterns; public abstract class Observer { public abstract void update(); }
package com.joseduarte.dwssurviveallyoucan; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; import com.joseduarte.dwssurviveallyoucan.adapters.TopListViewAdapter; import com.joseduarte.dwssurviveallyoucan.models.User; import com.joseduarte.dwssurviveallyoucan.util.GlobalInformation; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class TopActivity extends AppCompatActivity { private RecyclerView recyclerView; private TopListViewAdapter adapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ); GlobalInformation.context = this; setContentView(R.layout.activity_top); ArrayList<User> list = new ArrayList<>(GlobalInformation.TOP_LIST); List<User> top = new ArrayList<>(); if(list.size() == 1) top.add(list.get(0)); else if (list.size() > 1) { int maxUsers = (list.size() > 50) ? 50 : list.size(); Collections.sort(list); for (int i = 0; i < maxUsers; i++) { top.add(list.get(i)); } } adapter = new TopListViewAdapter(top); recyclerView = findViewById(R.id.tops_recyclerview); recyclerView.setAdapter(adapter); findViewById(R.id.back_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); GlobalInformation.topActivity = this; } public void update() { ArrayList<User> list = new ArrayList<>(GlobalInformation.TOP_LIST); List<User> top = list.subList( 0, (list.size() > 50) ? 50 : list.size() - 1 ); Collections.sort(top); adapter.update(top); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.aggregation; import com.facebook.presto.bytecode.DynamicClassLoader; import com.facebook.presto.metadata.BoundVariables; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.SqlAggregationFunction; import com.facebook.presto.operator.aggregation.state.MinMaxByNState; import com.facebook.presto.operator.aggregation.state.MinMaxByNStateFactory; import com.facebook.presto.operator.aggregation.state.MinMaxByNStateSerializer; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.BlockBuilderStatus; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.facebook.presto.type.ArrayType; import com.google.common.collect.ImmutableList; import java.lang.invoke.MethodHandle; import java.util.List; import java.util.function.Function; import static com.facebook.presto.metadata.Signature.orderableTypeParameter; import static com.facebook.presto.metadata.Signature.typeVariable; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INDEX; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INPUT_CHANNEL; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.INPUT_CHANNEL; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.NULLABLE_BLOCK_INPUT_CHANNEL; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.STATE; import static com.facebook.presto.operator.aggregation.AggregationUtils.generateAggregationName; import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.util.Reflection.methodHandle; import static com.google.common.collect.ImmutableList.toImmutableList; import static java.lang.Math.toIntExact; import static java.util.Objects.requireNonNull; public abstract class AbstractMinMaxByNAggregationFunction extends SqlAggregationFunction { private static final MethodHandle INPUT_FUNCTION = methodHandle(AbstractMinMaxByNAggregationFunction.class, "input", BlockComparator.class, Type.class, Type.class, MinMaxByNState.class, Block.class, Block.class, int.class, long.class); private static final MethodHandle COMBINE_FUNCTION = methodHandle(AbstractMinMaxByNAggregationFunction.class, "combine", MinMaxByNState.class, MinMaxByNState.class); private static final MethodHandle OUTPUT_FUNCTION = methodHandle(AbstractMinMaxByNAggregationFunction.class, "output", ArrayType.class, MinMaxByNState.class, BlockBuilder.class); private final String name; private final Function<Type, BlockComparator> typeToComparator; protected AbstractMinMaxByNAggregationFunction(String name, Function<Type, BlockComparator> typeToComparator) { super(name, ImmutableList.of(typeVariable("V"), orderableTypeParameter("K")), ImmutableList.of(), parseTypeSignature("array(V)"), ImmutableList.of(parseTypeSignature("V"), parseTypeSignature("K"), parseTypeSignature(StandardTypes.BIGINT))); this.name = requireNonNull(name, "name is null"); this.typeToComparator = requireNonNull(typeToComparator, "typeToComparator is null"); } @Override public InternalAggregationFunction specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { Type keyType = boundVariables.getTypeVariable("K"); Type valueType = boundVariables.getTypeVariable("V"); return generateAggregation(valueType, keyType); } public static void input(BlockComparator comparator, Type valueType, Type keyType, MinMaxByNState state, Block value, Block key, int blockIndex, long n) { TypedKeyValueHeap heap = state.getTypedKeyValueHeap(); if (heap == null) { if (n <= 0) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "third argument of max_by/min_by must be a positive integer"); } heap = new TypedKeyValueHeap(comparator, keyType, valueType, toIntExact(n)); state.setTypedKeyValueHeap(heap); } long startSize = heap.getEstimatedSize(); if (!key.isNull(blockIndex)) { heap.add(key, value, blockIndex); } state.addMemoryUsage(heap.getEstimatedSize() - startSize); } public static void combine(MinMaxByNState state, MinMaxByNState otherState) { TypedKeyValueHeap otherHeap = otherState.getTypedKeyValueHeap(); if (otherHeap == null) { return; } TypedKeyValueHeap heap = state.getTypedKeyValueHeap(); if (heap == null) { state.setTypedKeyValueHeap(otherHeap); return; } long startSize = heap.getEstimatedSize(); heap.addAll(otherHeap); state.addMemoryUsage(heap.getEstimatedSize() - startSize); } public static void output(ArrayType outputType, MinMaxByNState state, BlockBuilder out) { TypedKeyValueHeap heap = state.getTypedKeyValueHeap(); if (heap == null || heap.isEmpty()) { out.appendNull(); return; } Type elementType = outputType.getElementType(); BlockBuilder arrayBlockBuilder = out.beginBlockEntry(); BlockBuilder reversedBlockBuilder = elementType.createBlockBuilder(new BlockBuilderStatus(), heap.getCapacity()); long startSize = heap.getEstimatedSize(); heap.popAll(reversedBlockBuilder); state.addMemoryUsage(heap.getEstimatedSize() - startSize); for (int i = reversedBlockBuilder.getPositionCount() - 1; i >= 0; i--) { elementType.appendTo(reversedBlockBuilder, i, arrayBlockBuilder); } out.closeEntry(); } protected InternalAggregationFunction generateAggregation(Type valueType, Type keyType) { DynamicClassLoader classLoader = new DynamicClassLoader(AbstractMinMaxNAggregationFunction.class.getClassLoader()); BlockComparator comparator = typeToComparator.apply(keyType); List<Type> inputTypes = ImmutableList.of(valueType, keyType, BIGINT); MinMaxByNStateSerializer stateSerializer = new MinMaxByNStateSerializer(comparator, keyType, valueType); Type intermediateType = stateSerializer.getSerializedType(); ArrayType outputType = new ArrayType(valueType); List<AggregationMetadata.ParameterMetadata> inputParameterMetadata = ImmutableList.of( new AggregationMetadata.ParameterMetadata(STATE), new AggregationMetadata.ParameterMetadata(NULLABLE_BLOCK_INPUT_CHANNEL, valueType), new AggregationMetadata.ParameterMetadata(BLOCK_INPUT_CHANNEL, keyType), new AggregationMetadata.ParameterMetadata(BLOCK_INDEX), new AggregationMetadata.ParameterMetadata(INPUT_CHANNEL, BIGINT)); AggregationMetadata metadata = new AggregationMetadata( generateAggregationName(name, valueType.getTypeSignature(), inputTypes.stream().map(Type::getTypeSignature).collect(toImmutableList())), inputParameterMetadata, INPUT_FUNCTION.bindTo(comparator).bindTo(valueType).bindTo(keyType), COMBINE_FUNCTION, OUTPUT_FUNCTION.bindTo(outputType), MinMaxByNState.class, stateSerializer, new MinMaxByNStateFactory(), outputType); GenericAccumulatorFactoryBinder factory = AccumulatorCompiler.generateAccumulatorFactoryBinder(metadata, classLoader); return new InternalAggregationFunction(name, inputTypes, intermediateType, outputType, true, factory); } }
/* * Copyright 2013-2018 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.pinpoint.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * Default Push Notification Message. * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/DefaultPushNotificationMessage" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DefaultPushNotificationMessage implements Serializable, Cloneable, StructuredPojo { /** * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default action. * DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a designated user interface * within the app. URL - The default mobile browser on the user's device launches and opens a web page at the URL you * specify. Possible values include: OPEN_APP | DEEP_LINK | URL */ private String action; /** The message body of the notification. */ private String body; /** * The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' * object */ private java.util.Map<String, String> data; /** * Indicates if the message should display on the recipient's device. You can use silent pushes for remote * configuration or to deliver messages to in-app notification centers. */ private Boolean silentPush; /** Default message substitutions. Can be overridden by individual address substitutions. */ private java.util.Map<String, java.util.List<String>> substitutions; /** The message title that displays above the message on the user's device. */ private String title; /** The URL to open in the user's mobile browser. Used if the value for Action is URL. */ private String url; /** * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default action. * DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a designated user interface * within the app. URL - The default mobile browser on the user's device launches and opens a web page at the URL you * specify. Possible values include: OPEN_APP | DEEP_LINK | URL * * @param action * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default * action. DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a * designated user interface within the app. URL - The default mobile browser on the user's device launches * and opens a web page at the URL you specify. Possible values include: OPEN_APP | DEEP_LINK | URL * @see Action */ public void setAction(String action) { this.action = action; } /** * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default action. * DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a designated user interface * within the app. URL - The default mobile browser on the user's device launches and opens a web page at the URL you * specify. Possible values include: OPEN_APP | DEEP_LINK | URL * * @return The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your * app launches, or it becomes the foreground app if it has been sent to the background. This is the default * action. DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a * designated user interface within the app. URL - The default mobile browser on the user's device launches * and opens a web page at the URL you specify. Possible values include: OPEN_APP | DEEP_LINK | URL * @see Action */ public String getAction() { return this.action; } /** * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default action. * DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a designated user interface * within the app. URL - The default mobile browser on the user's device launches and opens a web page at the URL you * specify. Possible values include: OPEN_APP | DEEP_LINK | URL * * @param action * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default * action. DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a * designated user interface within the app. URL - The default mobile browser on the user's device launches * and opens a web page at the URL you specify. Possible values include: OPEN_APP | DEEP_LINK | URL * @return Returns a reference to this object so that method calls can be chained together. * @see Action */ public DefaultPushNotificationMessage withAction(String action) { setAction(action); return this; } /** * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default action. * DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a designated user interface * within the app. URL - The default mobile browser on the user's device launches and opens a web page at the URL you * specify. Possible values include: OPEN_APP | DEEP_LINK | URL * * @param action * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default * action. DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a * designated user interface within the app. URL - The default mobile browser on the user's device launches * and opens a web page at the URL you specify. Possible values include: OPEN_APP | DEEP_LINK | URL * @see Action */ public void setAction(Action action) { withAction(action); } /** * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default action. * DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a designated user interface * within the app. URL - The default mobile browser on the user's device launches and opens a web page at the URL you * specify. Possible values include: OPEN_APP | DEEP_LINK | URL * * @param action * The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP - Your app * launches, or it becomes the foreground app if it has been sent to the background. This is the default * action. DEEP_LINK - Uses deep linking features in iOS and Android to open your app and display a * designated user interface within the app. URL - The default mobile browser on the user's device launches * and opens a web page at the URL you specify. Possible values include: OPEN_APP | DEEP_LINK | URL * @return Returns a reference to this object so that method calls can be chained together. * @see Action */ public DefaultPushNotificationMessage withAction(Action action) { this.action = action.toString(); return this; } /** * The message body of the notification. * * @param body * The message body of the notification. */ public void setBody(String body) { this.body = body; } /** * The message body of the notification. * * @return The message body of the notification. */ public String getBody() { return this.body; } /** * The message body of the notification. * * @param body * The message body of the notification. * @return Returns a reference to this object so that method calls can be chained together. */ public DefaultPushNotificationMessage withBody(String body) { setBody(body); return this; } /** * The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' * object * * @return The data payload used for a silent push. This payload is added to the notifications' * data.pinpoint.jsonBody' object */ public java.util.Map<String, String> getData() { return data; } /** * The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' * object * * @param data * The data payload used for a silent push. This payload is added to the notifications' * data.pinpoint.jsonBody' object */ public void setData(java.util.Map<String, String> data) { this.data = data; } /** * The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' * object * * @param data * The data payload used for a silent push. This payload is added to the notifications' * data.pinpoint.jsonBody' object * @return Returns a reference to this object so that method calls can be chained together. */ public DefaultPushNotificationMessage withData(java.util.Map<String, String> data) { setData(data); return this; } public DefaultPushNotificationMessage addDataEntry(String key, String value) { if (null == this.data) { this.data = new java.util.HashMap<String, String>(); } if (this.data.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.data.put(key, value); return this; } /** * Removes all the entries added into Data. * * @return Returns a reference to this object so that method calls can be chained together. */ public DefaultPushNotificationMessage clearDataEntries() { this.data = null; return this; } /** * Indicates if the message should display on the recipient's device. You can use silent pushes for remote * configuration or to deliver messages to in-app notification centers. * * @param silentPush * Indicates if the message should display on the recipient's device. You can use silent pushes for remote * configuration or to deliver messages to in-app notification centers. */ public void setSilentPush(Boolean silentPush) { this.silentPush = silentPush; } /** * Indicates if the message should display on the recipient's device. You can use silent pushes for remote * configuration or to deliver messages to in-app notification centers. * * @return Indicates if the message should display on the recipient's device. You can use silent pushes for remote * configuration or to deliver messages to in-app notification centers. */ public Boolean getSilentPush() { return this.silentPush; } /** * Indicates if the message should display on the recipient's device. You can use silent pushes for remote * configuration or to deliver messages to in-app notification centers. * * @param silentPush * Indicates if the message should display on the recipient's device. You can use silent pushes for remote * configuration or to deliver messages to in-app notification centers. * @return Returns a reference to this object so that method calls can be chained together. */ public DefaultPushNotificationMessage withSilentPush(Boolean silentPush) { setSilentPush(silentPush); return this; } /** * Indicates if the message should display on the recipient's device. You can use silent pushes for remote * configuration or to deliver messages to in-app notification centers. * * @return Indicates if the message should display on the recipient's device. You can use silent pushes for remote * configuration or to deliver messages to in-app notification centers. */ public Boolean isSilentPush() { return this.silentPush; } /** * Default message substitutions. Can be overridden by individual address substitutions. * * @return Default message substitutions. Can be overridden by individual address substitutions. */ public java.util.Map<String, java.util.List<String>> getSubstitutions() { return substitutions; } /** * Default message substitutions. Can be overridden by individual address substitutions. * * @param substitutions * Default message substitutions. Can be overridden by individual address substitutions. */ public void setSubstitutions(java.util.Map<String, java.util.List<String>> substitutions) { this.substitutions = substitutions; } /** * Default message substitutions. Can be overridden by individual address substitutions. * * @param substitutions * Default message substitutions. Can be overridden by individual address substitutions. * @return Returns a reference to this object so that method calls can be chained together. */ public DefaultPushNotificationMessage withSubstitutions(java.util.Map<String, java.util.List<String>> substitutions) { setSubstitutions(substitutions); return this; } public DefaultPushNotificationMessage addSubstitutionsEntry(String key, java.util.List<String> value) { if (null == this.substitutions) { this.substitutions = new java.util.HashMap<String, java.util.List<String>>(); } if (this.substitutions.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.substitutions.put(key, value); return this; } /** * Removes all the entries added into Substitutions. * * @return Returns a reference to this object so that method calls can be chained together. */ public DefaultPushNotificationMessage clearSubstitutionsEntries() { this.substitutions = null; return this; } /** * The message title that displays above the message on the user's device. * * @param title * The message title that displays above the message on the user's device. */ public void setTitle(String title) { this.title = title; } /** * The message title that displays above the message on the user's device. * * @return The message title that displays above the message on the user's device. */ public String getTitle() { return this.title; } /** * The message title that displays above the message on the user's device. * * @param title * The message title that displays above the message on the user's device. * @return Returns a reference to this object so that method calls can be chained together. */ public DefaultPushNotificationMessage withTitle(String title) { setTitle(title); return this; } /** * The URL to open in the user's mobile browser. Used if the value for Action is URL. * * @param url * The URL to open in the user's mobile browser. Used if the value for Action is URL. */ public void setUrl(String url) { this.url = url; } /** * The URL to open in the user's mobile browser. Used if the value for Action is URL. * * @return The URL to open in the user's mobile browser. Used if the value for Action is URL. */ public String getUrl() { return this.url; } /** * The URL to open in the user's mobile browser. Used if the value for Action is URL. * * @param url * The URL to open in the user's mobile browser. Used if the value for Action is URL. * @return Returns a reference to this object so that method calls can be chained together. */ public DefaultPushNotificationMessage withUrl(String url) { setUrl(url); 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 (getAction() != null) sb.append("Action: ").append(getAction()).append(","); if (getBody() != null) sb.append("Body: ").append(getBody()).append(","); if (getData() != null) sb.append("Data: ").append(getData()).append(","); if (getSilentPush() != null) sb.append("SilentPush: ").append(getSilentPush()).append(","); if (getSubstitutions() != null) sb.append("Substitutions: ").append(getSubstitutions()).append(","); if (getTitle() != null) sb.append("Title: ").append(getTitle()).append(","); if (getUrl() != null) sb.append("Url: ").append(getUrl()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DefaultPushNotificationMessage == false) return false; DefaultPushNotificationMessage other = (DefaultPushNotificationMessage) obj; if (other.getAction() == null ^ this.getAction() == null) return false; if (other.getAction() != null && other.getAction().equals(this.getAction()) == false) return false; if (other.getBody() == null ^ this.getBody() == null) return false; if (other.getBody() != null && other.getBody().equals(this.getBody()) == false) return false; if (other.getData() == null ^ this.getData() == null) return false; if (other.getData() != null && other.getData().equals(this.getData()) == false) return false; if (other.getSilentPush() == null ^ this.getSilentPush() == null) return false; if (other.getSilentPush() != null && other.getSilentPush().equals(this.getSilentPush()) == false) return false; if (other.getSubstitutions() == null ^ this.getSubstitutions() == null) return false; if (other.getSubstitutions() != null && other.getSubstitutions().equals(this.getSubstitutions()) == false) return false; if (other.getTitle() == null ^ this.getTitle() == null) return false; if (other.getTitle() != null && other.getTitle().equals(this.getTitle()) == false) return false; if (other.getUrl() == null ^ this.getUrl() == null) return false; if (other.getUrl() != null && other.getUrl().equals(this.getUrl()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAction() == null) ? 0 : getAction().hashCode()); hashCode = prime * hashCode + ((getBody() == null) ? 0 : getBody().hashCode()); hashCode = prime * hashCode + ((getData() == null) ? 0 : getData().hashCode()); hashCode = prime * hashCode + ((getSilentPush() == null) ? 0 : getSilentPush().hashCode()); hashCode = prime * hashCode + ((getSubstitutions() == null) ? 0 : getSubstitutions().hashCode()); hashCode = prime * hashCode + ((getTitle() == null) ? 0 : getTitle().hashCode()); hashCode = prime * hashCode + ((getUrl() == null) ? 0 : getUrl().hashCode()); return hashCode; } @Override public DefaultPushNotificationMessage clone() { try { return (DefaultPushNotificationMessage) 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.pinpoint.model.transform.DefaultPushNotificationMessageMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package io.kubernetes.client.openapi.models; import io.kubernetes.client.fluent.VisitableBuilder; import com.google.gson.annotations.SerializedName; import io.kubernetes.client.fluent.Fluent; import io.kubernetes.client.fluent.Nested; import java.util.ArrayList; import java.lang.String; import java.util.function.Predicate; import java.lang.Integer; import java.lang.Deprecated; import java.util.Iterator; import java.util.Collection; import java.util.List; import java.lang.Boolean; /** * Generated */ public interface V1IngressListFluent<A extends io.kubernetes.client.openapi.models.V1IngressListFluent<A>> extends io.kubernetes.client.fluent.Fluent<A>{ public java.lang.String getApiVersion(); public A withApiVersion(java.lang.String apiVersion); public java.lang.Boolean hasApiVersion(); /** * Method is deprecated. use withApiVersion instead. */ @java.lang.Deprecated public A withNewApiVersion(java.lang.String original); public A addToItems(java.lang.Integer index,io.kubernetes.client.openapi.models.V1Ingress item); public A setToItems(java.lang.Integer index,io.kubernetes.client.openapi.models.V1Ingress item); public A addToItems(io.kubernetes.client.openapi.models.V1Ingress... items); public A addAllToItems(java.util.Collection<io.kubernetes.client.openapi.models.V1Ingress> items); public A removeFromItems(io.kubernetes.client.openapi.models.V1Ingress... items); public A removeAllFromItems(java.util.Collection<io.kubernetes.client.openapi.models.V1Ingress> items); public A removeMatchingFromItems(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressBuilder> predicate); /** * This method has been deprecated, please use method buildItems instead. * @return The buildable object. */ @java.lang.Deprecated public java.util.List<io.kubernetes.client.openapi.models.V1Ingress> getItems(); public java.util.List<io.kubernetes.client.openapi.models.V1Ingress> buildItems(); public io.kubernetes.client.openapi.models.V1Ingress buildItem(java.lang.Integer index); public io.kubernetes.client.openapi.models.V1Ingress buildFirstItem(); public io.kubernetes.client.openapi.models.V1Ingress buildLastItem(); public io.kubernetes.client.openapi.models.V1Ingress buildMatchingItem(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressBuilder> predicate); public java.lang.Boolean hasMatchingItem(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressBuilder> predicate); public A withItems(java.util.List<io.kubernetes.client.openapi.models.V1Ingress> items); public A withItems(io.kubernetes.client.openapi.models.V1Ingress... items); public java.lang.Boolean hasItems(); public io.kubernetes.client.openapi.models.V1IngressListFluent.ItemsNested<A> addNewItem(); public io.kubernetes.client.openapi.models.V1IngressListFluent.ItemsNested<A> addNewItemLike(io.kubernetes.client.openapi.models.V1Ingress item); public io.kubernetes.client.openapi.models.V1IngressListFluent.ItemsNested<A> setNewItemLike(java.lang.Integer index,io.kubernetes.client.openapi.models.V1Ingress item); public io.kubernetes.client.openapi.models.V1IngressListFluent.ItemsNested<A> editItem(java.lang.Integer index); public io.kubernetes.client.openapi.models.V1IngressListFluent.ItemsNested<A> editFirstItem(); public io.kubernetes.client.openapi.models.V1IngressListFluent.ItemsNested<A> editLastItem(); public io.kubernetes.client.openapi.models.V1IngressListFluent.ItemsNested<A> editMatchingItem(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1IngressBuilder> predicate); public java.lang.String getKind(); public A withKind(java.lang.String kind); public java.lang.Boolean hasKind(); /** * Method is deprecated. use withKind instead. */ @java.lang.Deprecated public A withNewKind(java.lang.String original); /** * This method has been deprecated, please use method buildMetadata instead. * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V1ListMeta getMetadata(); public io.kubernetes.client.openapi.models.V1ListMeta buildMetadata(); public A withMetadata(io.kubernetes.client.openapi.models.V1ListMeta metadata); public java.lang.Boolean hasMetadata(); public io.kubernetes.client.openapi.models.V1IngressListFluent.MetadataNested<A> withNewMetadata(); public io.kubernetes.client.openapi.models.V1IngressListFluent.MetadataNested<A> withNewMetadataLike(io.kubernetes.client.openapi.models.V1ListMeta item); public io.kubernetes.client.openapi.models.V1IngressListFluent.MetadataNested<A> editMetadata(); public io.kubernetes.client.openapi.models.V1IngressListFluent.MetadataNested<A> editOrNewMetadata(); public io.kubernetes.client.openapi.models.V1IngressListFluent.MetadataNested<A> editOrNewMetadataLike(io.kubernetes.client.openapi.models.V1ListMeta item); public interface ItemsNested<N> extends io.kubernetes.client.fluent.Nested<N>,io.kubernetes.client.openapi.models.V1IngressFluent<io.kubernetes.client.openapi.models.V1IngressListFluent.ItemsNested<N>>{ public N and(); public N endItem(); } public interface MetadataNested<N> extends io.kubernetes.client.fluent.Nested<N>,io.kubernetes.client.openapi.models.V1ListMetaFluent<io.kubernetes.client.openapi.models.V1IngressListFluent.MetadataNested<N>>{ public N and(); public N endMetadata(); } }
package io.muun.apollo.presentation.ui.signup; import io.muun.apollo.domain.model.SignupStep; import io.muun.apollo.presentation.ui.base.SingleFragmentView; public interface SignupView extends SingleFragmentView { void changeStep(SignupStep step, SignupStep previousStep); }
package com.brentcroft.util.templates; import static java.lang.String.format; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.el.ELContext; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import org.apache.log4j.Level; import org.apache.log4j.Logger; import com.brentcroft.util.templates.el.ELContextFactory; import com.brentcroft.util.templates.el.ELFilter; import com.brentcroft.util.templates.el.SimpleELContextFactory; import com.brentcroft.util.templates.el.StandardELFilter; import com.brentcroft.util.tools.StreamTools; /** * Maintains a set of ELTemplates (i.e. text containing EL expressions) and * provides two methods: <code>expandText( text, context )</code>, and * <code>expandUri( uri, context )</code>, to expand ELTemplates within the * context of a map of objects provided at expansion time. * <p/> * * ELTemplates are either anonymous (and not cached), or are loaded from a uri, * compiled and cached (using the uri as a key). * <p/> * * NB: non-standard el-expressions of the form ${*green} are expanded as though * "green" (or "green.tpl") is the name of a template. * <p/> * * By default, the implementation obtains an instance of an ExpressionFactory by * calling <code>javax.el.ExpressionFactory.newInstance()</code>. * <p/> * The default provider mechanism can be overridden by setting the * <code>expressionFactoryClass</code> property to the fully qualified name of a * class that extends <code>javax.el.ExpressionFactory.newInstance()</code> * <br/> * (immediately clearing any existing ExpressionFactory instance). * <p/> * * @author ADobson * * @see <a href="http://en.wikipedia.org/wiki/Unified_Expression_Language" > * Unified_Expression_Language</a> * @see <a href="http://docs.oracle.com/cd/E19226-01/820-7627/gjddd/">The Java * EE 6 Tutorial, Volume I: Chapter 6 Unified Expression Language</a> * @see <a href="http://juel.sourceforge.net/" >JUEL</a> * */ public class ELTemplateManager { private static Logger logger = Logger.getLogger( ELTemplateManager.class.getCanonicalName() ); private static ExpressionFactory expressionFactory = null; private static final ELContextFactory elContextFactory = new SimpleELContextFactory(); public static final String DEFAULT_TEMPLATE_EXTENSION = ".tpl"; public static final Pattern EL_EXPRESSION_PATTERN = Pattern.compile( "\\$\\{[^}]+\\}" ); private final Map<String, ELTemplate> templates = new HashMap<>(); // 2013-06-01: ACD: this is what I now would expect by default private ELFilter valueExpressionFilter = null; // default load mechanism fails if ELTemplateManager is not loaded by the // common class-loader private String expressionFactoryClass = null; public ELTemplateManager withELFilter(ELFilter elFilter) { this.setValueExpressionFilter( elFilter ); return this; } public void setExpressionFactoryClass( String expressionFactoryClass ) { this.expressionFactoryClass = expressionFactoryClass; // reset expressionFactory = null; } public ELContextFactory getELContextFactory() { return elContextFactory; } public ELContext getELContext( Map<?, ?> rootObjects ) { return elContextFactory.getELContext( rootObjects ); } public ValueExpression getValueExpression( String expression, Map<?, ?> rootObjects, Class<?> clazz ) { return getExpressionFactory().createValueExpression( getELContext( rootObjects ), expression, clazz ); } private ExpressionFactory getExpressionFactory() { if ( expressionFactory != null ) { return expressionFactory; } else if ( expressionFactoryClass == null ) { expressionFactory = ExpressionFactory.newInstance(); { final Level level = Level.DEBUG; if ( logger.isEnabledFor( level ) ) { logger.log( level, "Loaded default ExpressionFactory: " + expressionFactory ); } } } else { try { expressionFactory = (ExpressionFactory) getClass().getClassLoader().loadClass( expressionFactoryClass ) .newInstance(); { final Level level = Level.DEBUG; if ( logger.isEnabledFor( level ) ) { logger.log( level, "Loaded named ExpressionFactory: " + expressionFactory ); } } } catch ( Exception e ) { throw new RuntimeException( "Unable to instantiate ExpressionFactory using classname: " + expressionFactoryClass, e ); } } return expressionFactory; } /** * Set an ELFilter to apply to the results of ValueExpressions. * * @param valueExpressionFilter */ public void setValueExpressionFilter( ELFilter valueExpressionFilter ) { this.valueExpressionFilter = valueExpressionFilter; } /** * Set a StandardELFilter to apply to the results of ValueExpressions. * * @param standardFilter */ public void setValueExpressionStandardFilter( StandardELFilter standardFilter ) { setValueExpressionFilter( standardFilter ); } /** * Find a template and return it's rendering of a Map by the template. * <p/> * If a template is not already cached (with the key * <code>templateUri</code>) then a new template is built (and cached) by * opening, and parsing the stream from <code>templateUri</code>. * <p/> * Return the rendering of the Map <code>rootObjects</code> by the template. * <p/> * * * @param uri * identifies a template * @param rootObjects * a Map of root objects (to make accessible in EL expressions in * the template) * @return the rendering of the Map <code>rootObjects</code> by the * specified template <code>templateUri</code> */ public String expandUri( final String uri, Map<String, ? super Object> rootObjects ) { // if no period then tack a default extension on the end final int lastIndexOfPeriod = uri.lastIndexOf( '.' ); final String newUri = ( lastIndexOfPeriod > -1 ) ? uri : ( uri + DEFAULT_TEMPLATE_EXTENSION ); // find if ( !templates.containsKey( newUri ) ) { loadTemplate( newUri ); } // render return templates.get( newUri ).render( rootObjects ); } /** * Only allow one thread to load a template at any one time. * <p/> * If the desired template has already been loaded then just return * otherwise load and cache the template. * * @param uri * the uri of the template to load. */ private synchronized void loadTemplate( final String uri ) { // find if ( templates.containsKey( uri ) ) { return; } // build and cache templates.put( uri, new ELTemplateBuilder().build( uri ) ); { final Level level = Level.INFO; if ( logger.isEnabledFor( level ) ) { logger.log( level, "Loaded template: " + uri ); } } } /** * Expands the supplied <code>elText</code> so that all EL tags are replaced * with their values calculated with respect to the supplied map of root * objects. * * @param elText * the elText to be expanded * @return the expanded elText */ public String expandText( String elText, Map<String, Object> rootObjects ) { return buildTemplate( elText ).render( rootObjects ); } /** * Builds an anonymous <code>ELTemplate</code> from the supplied text. * <p/> * The template is not cached (it has no uri). * * @param elText * the text to be decomposed into an ELTemplate * @return the new ELTemplate */ public ELTemplate buildTemplate( String elText ) { return new ELTemplateBuilder().parse( elText ); } /** * Test if the candidate text contains any EL template expressions. * * @param candidate the text to detect EL expressions in * @return true if the candidate text has at least one EL expression otherwise false. */ public static boolean hasTemplate(String candidate) { return EL_EXPRESSION_PATTERN.matcher( candidate ).find(); } final ELContext context = elContextFactory.getELConfigContext(); /** * A decomposition of a text stream into a list of * <code>ELTemplateElement</code> elements. * <p/> * Each <code>ELTemplateElement</code> has a type that is either:<br/> * * LITERAL, VALUE_EXPRESSION or TEMPLATE_REF. */ public class ELTemplate implements Renderable { private final List<ELTemplateElement> elements = new ArrayList<>(); private String localUri; public ELTemplate withUri( String uri ) { this.localUri = uri; return this; } @Override public String toString() { StringBuilder b = new StringBuilder(); if ( !elements.isEmpty() ) { elements.forEach( b::append ); } return b.toString(); } /** * The key function of a template is to render itself (using a Map of * objects providing the EL namespace). * * @param rootObjects * a Map of named objects * @return a String containing the rendering of the template */ public String render( Map<String, ? super Object> rootObjects ) { final ELContext context = elContextFactory.getELContext( rootObjects ); final StringBuilder out = new StringBuilder(); for ( ELTemplateElement element : elements ) { switch ( element.type ) { case LITERAL: out.append( element.element ); break; case TEMPLATE_REF: // mess with the template reference if necessary // if no period then tack a ".tpl" on the end final int lastIndexOfPeriod = element.element.lastIndexOf( '.' ); final String newFilename = ( lastIndexOfPeriod > -1 ) ? element.element : ( element.element + ".tpl" ); if ( localUri == null ) { // recurse out.append( expandUri( newFilename, rootObjects ) ); } else { // if have last slash in local uri then replace // filename with newFilename final int lastIndexOfSlash = localUri.lastIndexOf( '/' ); final String newUri = ( ( lastIndexOfSlash > -1 ) ? localUri.substring( 0, lastIndexOfSlash ) : localUri ) + "/" + newFilename; out.append( expandUri( newUri, rootObjects ) ); } break; case VALUE_EXPRESSION: if ( element.valueExpression == null ) { element.valueExpression = getExpressionFactory().createValueExpression( context, element.element, Object.class ); } try { final Object value = element.valueExpression.getValue( context ); // maybe filter value expression final Object filteredValue = ( valueExpressionFilter == null || value == null ) ? value : valueExpressionFilter.filter( value ); out.append( filteredValue == null ? "" : filteredValue ); } catch ( RuntimeException e ) { throw new ELTemplateException( format( "Failed to evaluate EL Expression [%s]: %s", element.valueExpression, e.getMessage() ), e ); } break; default: throw new ELTemplateException( "Unexpected ELType: " + element.type ); } } return out.toString(); } void addLiteral( String text ) { if ( text != null && text.length() > 0 ) { elements.add( new ELTemplateElement( text, ELType.LITERAL ) ); } } void addValueExpression( String text ) { elements.add( new ELTemplateElement( text.trim(), ELType.VALUE_EXPRESSION ) ); } void addTemplateRef( String text ) { elements.add( new ELTemplateElement( text.trim(), ELType.TEMPLATE_REF ) ); } class ELTemplateElement { private final String element; private final ELType type; private ValueExpression valueExpression; ELTemplateElement( String element, ELType type ) { this.element = element; this.type = type; valueExpression = getExpressionFactory().createValueExpression( context, element, Object.class ); } @Override public String toString() { return element; } } } class ELTemplateBuilder { public ELTemplate build( String uri ) { try { return parse( StreamTools.readUrl( StreamTools.getLocalFileURL( getClass(), uri ) ) ).withUri( uri ); } catch ( Exception e ) { throw (RuntimeException) e; } } /* * Is the choice of the state numbers constrained? * * Yes it is! * * Try [OUTSIDE = 87] and [ENTERING = 0] and see the compiler errors. */ private static final int OUTSIDE = 0; private static final int ENTERING = 0x10000; private static final int INSIDE = 0x2000; // 36 private static final char PILOT = '$'; // 35 private static final char PILOT2 = '#'; // 123 private static final char START = '{'; // 125 private static final char END = '}'; /* * Copied (and modified from MrTemplate - thanks Frank) */ private ELTemplate parse( String elText ) { final ELTemplate elTemplate = new ELTemplate(); int state = OUTSIDE; boolean pilot2 = false; final StringBuilder token = new StringBuilder(); final StringBuilder literal = new StringBuilder(); final CharacterIterator it = new StringCharacterIterator( elText ); for ( char c = it.first() ; c != CharacterIterator.DONE ; c = it.next() ) { switch ( state + c ) { case OUTSIDE + PILOT2: pilot2 = true; state = ENTERING; break; case OUTSIDE + PILOT: pilot2 = false; state = ENTERING; break; case ENTERING + START: state = INSIDE; break; case INSIDE + END: state = OUTSIDE; elTemplate.addLiteral( literal.toString() ); literal.setLength( 0 ); final String tokenText = token.toString().trim(); if ( tokenText.length() < 1 ) { throw new ELTemplateException( "EL Template has no tokenText!" ); } switch ( tokenText.charAt( 0 ) ) { case '*': // frank's original feature for // including // another template elTemplate.addTemplateRef( tokenText.substring( 1 ) ); break; default: elTemplate.addValueExpression( ( pilot2 ? "#{" : "${" ) + tokenText + "}" ); break; } token.setLength( 0 ); pilot2 = false; break; default: switch ( state ) { case ENTERING: // got $ or # without { - treat it as // a // literal state = OUTSIDE; literal.append( pilot2 ? PILOT2 : PILOT ); literal.append( c ); break; case INSIDE: token.append( c ); break; default: literal.append( c ); } } } if ( state == ENTERING ) { // catch the odd case of $ at EOF literal.append( ( pilot2 ? PILOT2 : PILOT ) ); } else if ( state == INSIDE ) { // catch the even odder case of unclosed // ${ at EOF literal.append( ( pilot2 ? PILOT2 : PILOT ) ); literal.append( START ); literal.append( token.toString() ); } if ( literal.length() > 0 ) { elTemplate.addLiteral( literal.toString() ); } literal.setLength( 0 ); return elTemplate; } } /** * We are free to add new types (e.g. like TEMPLATE_REF) as long as we can * justify (and implement) their purpose. * * @author ADobson * */ enum ELType { /** * A literal segment of text that contains no expressions. * */ LITERAL, /** * An EL expression. * <p/> * * E.g. ${request.id} */ VALUE_EXPRESSION, /** * A template reference. * <p/> * * E.g. ${*header} or ${*header.tpl} */ TEMPLATE_REF, } }
package org.meizhuo.concurrency.example.aqs; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; @Slf4j public class FutureTaskExample { public static void main(String[] args) throws Exception { FutureTask<String> futureTask = new FutureTask<String>(new Callable<String>() { @Override public String call() throws Exception { log.info("do something in callable"); Thread.sleep(5000); return "Done"; } }); new Thread(futureTask).start(); log.info("do something in main"); Thread.sleep(1000); String result = futureTask.get(); log.info("result:{}", result); } }
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.lang.reflect.Method; import org.springframework.core.Ordered; import org.springframework.lang.Nullable; /** * {@link BeanInfoFactory} implementation that evaluates whether bean classes have * "non-standard" JavaBeans setter methods and are thus candidates for introspection * by Spring's (package-visible) {@code ExtendedBeanInfo} implementation. * * <p>Ordered at {@link Ordered#LOWEST_PRECEDENCE} to allow other user-defined * {@link BeanInfoFactory} types to take precedence. * * @author Chris Beams * @see BeanInfoFactory * @see CachedIntrospectionResults * @since 3.2 */ public class ExtendedBeanInfoFactory implements BeanInfoFactory, Ordered { /** * Return an {@link ExtendedBeanInfo} for the given bean class, if applicable. */ @Override @Nullable public BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException { return (supports(beanClass) ? new ExtendedBeanInfo(Introspector.getBeanInfo(beanClass)) : null); } /** * Return whether the given bean class declares or inherits any non-void * returning bean property or indexed property setter methods. */ private boolean supports(Class<?> beanClass) { for (Method method : beanClass.getMethods()) { if (ExtendedBeanInfo.isCandidateWriteMethod(method)) { return true; } } return false; } @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } }
/* * 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.deltaspike.test.testcontrol.mock.uc015; import javax.interceptor.InterceptorBinding; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; @InterceptorBinding @Target({ METHOD, TYPE }) @Retention(RUNTIME) public @interface TestInterceptor { }
/* Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.getcapacitor; import android.content.Context; import android.net.Uri; import android.webkit.CookieManager; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Helper class meant to be used with the android.webkit.WebView class to enable hosting assets, * resources and other data on 'virtual' https:// URL. * Hosting assets and resources on https:// URLs is desirable as it is compatible with the * Same-Origin policy. * <p> * This class is intended to be used from within the * {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, String)} and * {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, * android.webkit.WebResourceRequest)} * methods. */ public class WebViewLocalServer { private final static String capacitorFileStart = Bridge.CAPACITOR_FILE_START; private final static String capacitorContentStart = Bridge.CAPACITOR_CONTENT_START; private String basePath; private final UriMatcher uriMatcher; private final AndroidProtocolHandler protocolHandler; private final ArrayList<String> authorities; private boolean isAsset; // Whether to route all requests to paths without extensions back to `index.html` private final boolean html5mode; private final JSInjector jsInjector; private final Bridge bridge; /** * A handler that produces responses for paths on the virtual asset server. * <p> * Methods of this handler will be invoked on a background thread and care must be taken to * correctly synchronize access to any shared state. * <p> * On Android KitKat and above these methods may be called on more than one thread. This thread * may be different than the thread on which the shouldInterceptRequest method was invoke. * This means that on Android KitKat and above it is possible to block in this method without * blocking other resources from loading. The number of threads used to parallelize loading * is an internal implementation detail of the WebView and may change between updates which * means that the amount of time spend blocking in this method should be kept to an absolute * minimum. */ public abstract static class PathHandler { protected String mimeType; private String encoding; private String charset; private int statusCode; private String reasonPhrase; private Map<String, String> responseHeaders; public PathHandler() { this(null, null, 200, "OK", null); } public PathHandler(String encoding, String charset, int statusCode, String reasonPhrase, Map<String, String> responseHeaders) { this.encoding = encoding; this.charset = charset; this.statusCode = statusCode; this.reasonPhrase = reasonPhrase; Map<String, String> tempResponseHeaders; if (responseHeaders == null) { tempResponseHeaders = new HashMap<>(); } else { tempResponseHeaders = responseHeaders; } tempResponseHeaders.put("Cache-Control", "no-cache"); this.responseHeaders = tempResponseHeaders; } public InputStream handle(WebResourceRequest request) { return handle(request.getUrl()); } abstract public InputStream handle(Uri url); public String getEncoding() { return encoding; } public String getCharset() { return charset; } public int getStatusCode() { return statusCode; } public String getReasonPhrase() { return reasonPhrase; } public Map<String, String> getResponseHeaders() { return responseHeaders; } } WebViewLocalServer(Context context, Bridge bridge, JSInjector jsInjector, ArrayList<String> authorities, boolean html5mode) { uriMatcher = new UriMatcher(null); this.html5mode = html5mode; this.protocolHandler = new AndroidProtocolHandler(context.getApplicationContext()); this.authorities = authorities; this.bridge = bridge; this.jsInjector = jsInjector; } private static Uri parseAndVerifyUrl(String url) { if (url == null) { return null; } Uri uri = Uri.parse(url); if (uri == null) { Logger.error("Malformed URL: " + url); return null; } String path = uri.getPath(); if (path == null || path.length() == 0) { Logger.error("URL does not have a path: " + url); return null; } return uri; } /** * Attempt to retrieve the WebResourceResponse associated with the given <code>request</code>. * This method should be invoked from within * {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, * android.webkit.WebResourceRequest)}. * * @param request the request to process. * @return a response if the request URL had a matching handler, null if no handler was found. */ public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) { Uri loadingUrl = request.getUrl(); PathHandler handler; synchronized (uriMatcher) { handler = (PathHandler) uriMatcher.match(request.getUrl()); } if (handler == null) { return null; } if (isLocalFile(loadingUrl) || isMainUrl(loadingUrl) || !isAllowedUrl(loadingUrl)) { Logger.debug("Handling local request: " + request.getUrl().toString()); return handleLocalRequest(request, handler); } else { return handleProxyRequest(request, handler); } } private boolean isLocalFile(Uri uri) { String path = uri.getPath(); if (path.startsWith(capacitorContentStart) || path.startsWith(capacitorFileStart)) { return true; } return false; } private boolean isMainUrl(Uri loadingUrl) { return (bridge.getServerUrl() == null && loadingUrl.getHost().equalsIgnoreCase(bridge.getHost())); } private boolean isAllowedUrl(Uri loadingUrl) { return !(bridge.getServerUrl() == null && !bridge.getAppAllowNavigationMask().matches(loadingUrl.getHost())); } private WebResourceResponse handleLocalRequest(WebResourceRequest request, PathHandler handler) { String path = request.getUrl().getPath(); if (request.getRequestHeaders().get("Range") != null) { InputStream responseStream = new LollipopLazyInputStream(handler, request); String mimeType = getMimeType(path, responseStream); Map<String, String> tempResponseHeaders = handler.getResponseHeaders(); int statusCode = 206; try { int totalRange = responseStream.available(); String rangeString = request.getRequestHeaders().get("Range"); String[] parts = rangeString.split("="); String[] streamParts = parts[1].split("-"); String fromRange = streamParts[0]; int range = totalRange-1; if (streamParts.length > 1) { range = Integer.parseInt(streamParts[1]); } tempResponseHeaders.put("Accept-Ranges", "bytes"); tempResponseHeaders.put("Content-Range", "bytes " + fromRange + "-" + range + "/" + totalRange); } catch (IOException e) { statusCode = 404; } return new WebResourceResponse(mimeType, handler.getEncoding(), statusCode, handler.getReasonPhrase(), tempResponseHeaders, responseStream); } if (isLocalFile(request.getUrl())) { InputStream responseStream = new LollipopLazyInputStream(handler, request); String mimeType = getMimeType(request.getUrl().getPath(), responseStream); int statusCode = getStatusCode(responseStream, handler.getStatusCode()); return new WebResourceResponse(mimeType, handler.getEncoding(), statusCode, handler.getReasonPhrase(), handler.getResponseHeaders(), responseStream); } if (path.equals("/cordova.js")) { return new WebResourceResponse("application/javascript", handler.getEncoding(), handler.getStatusCode(), handler.getReasonPhrase(), handler.getResponseHeaders(), null); } if (path.equals("/") || (!request.getUrl().getLastPathSegment().contains(".") && html5mode)) { InputStream responseStream; try { String startPath = this.basePath + "/index.html"; if (isAsset) { responseStream = protocolHandler.openAsset(startPath); } else { responseStream = protocolHandler.openFile(startPath); } } catch (IOException e) { Logger.error("Unable to open index.html", e); return null; } responseStream = jsInjector.getInjectedStream(responseStream); bridge.reset(); int statusCode = getStatusCode(responseStream, handler.getStatusCode()); return new WebResourceResponse("text/html", handler.getEncoding(), statusCode, handler.getReasonPhrase(), handler.getResponseHeaders(), responseStream); } if ("/favicon.ico".equalsIgnoreCase(path)) { try { return new WebResourceResponse("image/png", null, null); } catch (Exception e) { Logger.error("favicon handling failed", e); } } int periodIndex = path.lastIndexOf("."); if (periodIndex >= 0) { String ext = path.substring(path.lastIndexOf("."), path.length()); InputStream responseStream = new LollipopLazyInputStream(handler, request); // TODO: Conjure up a bit more subtlety than this if (ext.equals(".html")) { responseStream = jsInjector.getInjectedStream(responseStream); bridge.reset(); } String mimeType = getMimeType(path, responseStream); int statusCode = getStatusCode(responseStream, handler.getStatusCode()); return new WebResourceResponse(mimeType, handler.getEncoding(), statusCode, handler.getReasonPhrase(), handler.getResponseHeaders(), responseStream); } return null; } /** * Instead of reading files from the filesystem/assets, proxy through to the URL * and let an external server handle it. * @param request * @param handler * @return */ private WebResourceResponse handleProxyRequest(WebResourceRequest request, PathHandler handler) { final String method = request.getMethod(); if (method.equals("GET")) { try { String url = request.getUrl().toString(); Map<String, String> headers = request.getRequestHeaders(); boolean isHtmlText = false; for (Map.Entry<String, String> header : headers.entrySet()) { if (header.getKey().equalsIgnoreCase("Accept") && header.getValue().toLowerCase().contains("text/html")) { isHtmlText = true; break; } } if (isHtmlText) { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); for (Map.Entry<String, String> header : headers.entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } String getCookie = CookieManager.getInstance().getCookie(url); if (getCookie != null) { conn.setRequestProperty("Cookie", getCookie); } conn.setRequestMethod(method); conn.setReadTimeout(30 * 1000); conn.setConnectTimeout(30 * 1000); String cookie = conn.getHeaderField("Set-Cookie"); if (cookie != null) { CookieManager.getInstance().setCookie(url, cookie); } InputStream responseStream = conn.getInputStream(); responseStream = jsInjector.getInjectedStream(responseStream); bridge.reset(); return new WebResourceResponse("text/html", handler.getEncoding(), handler.getStatusCode(), handler.getReasonPhrase(), handler.getResponseHeaders(), responseStream); } } catch (SocketTimeoutException ex) { bridge.handleAppUrlLoadError(ex); } catch (Exception ex) { bridge.handleAppUrlLoadError(ex); } } return null; } private String getMimeType(String path, InputStream stream) { String mimeType = null; try { mimeType = URLConnection.guessContentTypeFromName(path); // Does not recognize *.js if (mimeType != null && path.endsWith(".js") && mimeType.equals("image/x-icon")) { Logger.debug("We shouldn't be here"); } if (mimeType == null) { if (path.endsWith(".js") || path.endsWith(".mjs")) { // Make sure JS files get the proper mimetype to support ES modules mimeType = "application/javascript"; } else if (path.endsWith(".wasm")) { mimeType = "application/wasm"; } else { mimeType = URLConnection.guessContentTypeFromStream(stream); } } } catch (Exception ex) { Logger.error("Unable to get mime type" + path, ex); } return mimeType; } private int getStatusCode(InputStream stream, int defaultCode) { int finalStatusCode = defaultCode; try { if (stream.available() == -1) { finalStatusCode = 404; } } catch (IOException e) { finalStatusCode = 500; } return finalStatusCode; } /** * Registers a handler for the given <code>uri</code>. The <code>handler</code> will be invoked * every time the <code>shouldInterceptRequest</code> method of the instance is called with * a matching <code>uri</code>. * * @param uri the uri to use the handler for. The scheme and authority (domain) will be matched * exactly. The path may contain a '*' element which will match a single element of * a path (so a handler registered for /a/* will be invoked for /a/b and /a/c.html * but not for /a/b/b) or the '**' element which will match any number of path * elements. * @param handler the handler to use for the uri. */ void register(Uri uri, PathHandler handler) { synchronized (uriMatcher) { uriMatcher.addURI(uri.getScheme(), uri.getAuthority(), uri.getPath(), handler); } } /** * Hosts the application's assets on an https:// URL. Assets from the local path * <code>assetPath/...</code> will be available under * <code>https://{uuid}.androidplatform.net/assets/...</code>. * * @param assetPath the local path in the application's asset folder which will be made * available by the server (for example "/www"). * @return prefixes under which the assets are hosted. */ public void hostAssets(String assetPath) { this.isAsset = true; this.basePath = assetPath; createHostingDetails(); } /** * Hosts the application's files on an https:// URL. Files from the basePath * <code>basePath/...</code> will be available under * <code>https://{uuid}.androidplatform.net/...</code>. * * @param basePath the local path in the application's data folder which will be made * available by the server (for example "/www"). * @return prefixes under which the assets are hosted. */ public void hostFiles(final String basePath) { this.isAsset = false; this.basePath = basePath; createHostingDetails(); } private void createHostingDetails() { final String assetPath = this.basePath; if (assetPath.indexOf('*') != -1) { throw new IllegalArgumentException("assetPath cannot contain the '*' character."); } PathHandler handler = new PathHandler() { @Override public InputStream handle(Uri url) { InputStream stream = null; String path = url.getPath(); try { if (path.startsWith(capacitorContentStart)) { stream = protocolHandler.openContentUrl(url); } else if (path.startsWith(capacitorFileStart) || !isAsset) { if (!path.startsWith(capacitorFileStart)) { path = basePath + url.getPath(); } stream = protocolHandler.openFile(path); } else { stream = protocolHandler.openAsset(assetPath + path); } } catch (IOException e) { Logger.error("Unable to open asset URL: " + url); return null; } return stream; } }; for (String authority: authorities) { registerUriForScheme(Bridge.CAPACITOR_HTTP_SCHEME, handler, authority); registerUriForScheme(Bridge.CAPACITOR_HTTPS_SCHEME, handler, authority); String customScheme = this.bridge.getScheme(); if (!customScheme.equals(Bridge.CAPACITOR_HTTP_SCHEME) && !customScheme.equals(Bridge.CAPACITOR_HTTPS_SCHEME)) { registerUriForScheme(customScheme, handler, authority); } } } private void registerUriForScheme(String scheme, PathHandler handler, String authority) { Uri.Builder uriBuilder = new Uri.Builder(); uriBuilder.scheme(scheme); uriBuilder.authority(authority); uriBuilder.path(""); Uri uriPrefix = uriBuilder.build(); register(Uri.withAppendedPath(uriPrefix, "/"), handler); register(Uri.withAppendedPath(uriPrefix, "**"), handler); } /** * The KitKat WebView reads the InputStream on a separate threadpool. We can use that to * parallelize loading. */ private static abstract class LazyInputStream extends InputStream { protected final PathHandler handler; private InputStream is = null; public LazyInputStream(PathHandler handler) { this.handler = handler; } private InputStream getInputStream() { if (is == null) { is = handle(); } return is; } protected abstract InputStream handle(); @Override public int available() throws IOException { InputStream is = getInputStream(); return (is != null) ? is.available() : -1; } @Override public int read() throws IOException { InputStream is = getInputStream(); return (is != null) ? is.read() : -1; } @Override public int read(byte b[]) throws IOException { InputStream is = getInputStream(); return (is != null) ? is.read(b) : -1; } @Override public int read(byte b[], int off, int len) throws IOException { InputStream is = getInputStream(); return (is != null) ? is.read(b, off, len) : -1; } @Override public long skip(long n) throws IOException { InputStream is = getInputStream(); return (is != null) ? is.skip(n) : 0; } } // For L and above. private static class LollipopLazyInputStream extends LazyInputStream { private WebResourceRequest request; private InputStream is; public LollipopLazyInputStream(PathHandler handler, WebResourceRequest request) { super(handler); this.request = request; } @Override protected InputStream handle() { return handler.handle(request); } } public String getBasePath(){ return this.basePath; } }
/* Copyright 2010 WebDriver committers Copyright 2010 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 org.openqa.selenium.android.server.handler; import org.openqa.selenium.android.library.AndroidWebElement; import org.openqa.selenium.remote.server.Session; import org.openqa.selenium.remote.server.rest.ResultType; public class GetElementDisplayed extends AndroidWebElementHandler { public GetElementDisplayed(Session session) { super(session); } public ResultType call() throws Exception { AndroidWebElement element = (AndroidWebElement) getElement(); response.setValue(element.isDisplayed()); return ResultType.SUCCESS; } @Override public String toString() { return String.format("[is displayed: %s]", getElementAsString()); } }
package codeInsight.completion.variables.locals; public class TestSource4 { int aaa = 0; public static void foo(){ int abc = 0; class Inner1{ int sbe=a<caret> } } }
/* * Copyright 2021 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dataqna.v1alpha.stub; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.grpc.GrpcCallSettings; import com.google.api.gax.grpc.GrpcStubCallableFactory; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.dataqna.v1alpha.CreateQuestionRequest; import com.google.cloud.dataqna.v1alpha.ExecuteQuestionRequest; import com.google.cloud.dataqna.v1alpha.GetQuestionRequest; import com.google.cloud.dataqna.v1alpha.GetUserFeedbackRequest; import com.google.cloud.dataqna.v1alpha.Question; import com.google.cloud.dataqna.v1alpha.UpdateUserFeedbackRequest; import com.google.cloud.dataqna.v1alpha.UserFeedback; import com.google.common.collect.ImmutableMap; import com.google.longrunning.stub.GrpcOperationsStub; import io.grpc.MethodDescriptor; import io.grpc.protobuf.ProtoUtils; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * gRPC stub implementation for the QuestionService service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @BetaApi @Generated("by gapic-generator-java") public class GrpcQuestionServiceStub extends QuestionServiceStub { private static final MethodDescriptor<GetQuestionRequest, Question> getQuestionMethodDescriptor = MethodDescriptor.<GetQuestionRequest, Question>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.dataqna.v1alpha.QuestionService/GetQuestion") .setRequestMarshaller(ProtoUtils.marshaller(GetQuestionRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Question.getDefaultInstance())) .build(); private static final MethodDescriptor<CreateQuestionRequest, Question> createQuestionMethodDescriptor = MethodDescriptor.<CreateQuestionRequest, Question>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.dataqna.v1alpha.QuestionService/CreateQuestion") .setRequestMarshaller( ProtoUtils.marshaller(CreateQuestionRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Question.getDefaultInstance())) .build(); private static final MethodDescriptor<ExecuteQuestionRequest, Question> executeQuestionMethodDescriptor = MethodDescriptor.<ExecuteQuestionRequest, Question>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.dataqna.v1alpha.QuestionService/ExecuteQuestion") .setRequestMarshaller( ProtoUtils.marshaller(ExecuteQuestionRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Question.getDefaultInstance())) .build(); private static final MethodDescriptor<GetUserFeedbackRequest, UserFeedback> getUserFeedbackMethodDescriptor = MethodDescriptor.<GetUserFeedbackRequest, UserFeedback>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.dataqna.v1alpha.QuestionService/GetUserFeedback") .setRequestMarshaller( ProtoUtils.marshaller(GetUserFeedbackRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(UserFeedback.getDefaultInstance())) .build(); private static final MethodDescriptor<UpdateUserFeedbackRequest, UserFeedback> updateUserFeedbackMethodDescriptor = MethodDescriptor.<UpdateUserFeedbackRequest, UserFeedback>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.dataqna.v1alpha.QuestionService/UpdateUserFeedback") .setRequestMarshaller( ProtoUtils.marshaller(UpdateUserFeedbackRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(UserFeedback.getDefaultInstance())) .build(); private final UnaryCallable<GetQuestionRequest, Question> getQuestionCallable; private final UnaryCallable<CreateQuestionRequest, Question> createQuestionCallable; private final UnaryCallable<ExecuteQuestionRequest, Question> executeQuestionCallable; private final UnaryCallable<GetUserFeedbackRequest, UserFeedback> getUserFeedbackCallable; private final UnaryCallable<UpdateUserFeedbackRequest, UserFeedback> updateUserFeedbackCallable; private final BackgroundResource backgroundResources; private final GrpcOperationsStub operationsStub; private final GrpcStubCallableFactory callableFactory; public static final GrpcQuestionServiceStub create(QuestionServiceStubSettings settings) throws IOException { return new GrpcQuestionServiceStub(settings, ClientContext.create(settings)); } public static final GrpcQuestionServiceStub create(ClientContext clientContext) throws IOException { return new GrpcQuestionServiceStub( QuestionServiceStubSettings.newBuilder().build(), clientContext); } public static final GrpcQuestionServiceStub create( ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { return new GrpcQuestionServiceStub( QuestionServiceStubSettings.newBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of GrpcQuestionServiceStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected GrpcQuestionServiceStub( QuestionServiceStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new GrpcQuestionServiceCallableFactory()); } /** * Constructs an instance of GrpcQuestionServiceStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected GrpcQuestionServiceStub( QuestionServiceStubSettings settings, ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); GrpcCallSettings<GetQuestionRequest, Question> getQuestionTransportSettings = GrpcCallSettings.<GetQuestionRequest, Question>newBuilder() .setMethodDescriptor(getQuestionMethodDescriptor) .setParamsExtractor( request -> { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("name", String.valueOf(request.getName())); return params.build(); }) .build(); GrpcCallSettings<CreateQuestionRequest, Question> createQuestionTransportSettings = GrpcCallSettings.<CreateQuestionRequest, Question>newBuilder() .setMethodDescriptor(createQuestionMethodDescriptor) .setParamsExtractor( request -> { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("parent", String.valueOf(request.getParent())); return params.build(); }) .build(); GrpcCallSettings<ExecuteQuestionRequest, Question> executeQuestionTransportSettings = GrpcCallSettings.<ExecuteQuestionRequest, Question>newBuilder() .setMethodDescriptor(executeQuestionMethodDescriptor) .setParamsExtractor( request -> { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("name", String.valueOf(request.getName())); return params.build(); }) .build(); GrpcCallSettings<GetUserFeedbackRequest, UserFeedback> getUserFeedbackTransportSettings = GrpcCallSettings.<GetUserFeedbackRequest, UserFeedback>newBuilder() .setMethodDescriptor(getUserFeedbackMethodDescriptor) .setParamsExtractor( request -> { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("name", String.valueOf(request.getName())); return params.build(); }) .build(); GrpcCallSettings<UpdateUserFeedbackRequest, UserFeedback> updateUserFeedbackTransportSettings = GrpcCallSettings.<UpdateUserFeedbackRequest, UserFeedback>newBuilder() .setMethodDescriptor(updateUserFeedbackMethodDescriptor) .setParamsExtractor( request -> { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put( "user_feedback.name", String.valueOf(request.getUserFeedback().getName())); return params.build(); }) .build(); this.getQuestionCallable = callableFactory.createUnaryCallable( getQuestionTransportSettings, settings.getQuestionSettings(), clientContext); this.createQuestionCallable = callableFactory.createUnaryCallable( createQuestionTransportSettings, settings.createQuestionSettings(), clientContext); this.executeQuestionCallable = callableFactory.createUnaryCallable( executeQuestionTransportSettings, settings.executeQuestionSettings(), clientContext); this.getUserFeedbackCallable = callableFactory.createUnaryCallable( getUserFeedbackTransportSettings, settings.getUserFeedbackSettings(), clientContext); this.updateUserFeedbackCallable = callableFactory.createUnaryCallable( updateUserFeedbackTransportSettings, settings.updateUserFeedbackSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } public GrpcOperationsStub getOperationsStub() { return operationsStub; } @Override public UnaryCallable<GetQuestionRequest, Question> getQuestionCallable() { return getQuestionCallable; } @Override public UnaryCallable<CreateQuestionRequest, Question> createQuestionCallable() { return createQuestionCallable; } @Override public UnaryCallable<ExecuteQuestionRequest, Question> executeQuestionCallable() { return executeQuestionCallable; } @Override public UnaryCallable<GetUserFeedbackRequest, UserFeedback> getUserFeedbackCallable() { return getUserFeedbackCallable; } @Override public UnaryCallable<UpdateUserFeedbackRequest, UserFeedback> updateUserFeedbackCallable() { return updateUserFeedbackCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies; import java.util.Iterator; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.gef.commands.Command; import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand; import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand; import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.ReorientRelationshipRequest; import org.eclipse.gmf.runtime.notation.Edge; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands.EsbLinkCreateCommand; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands.EsbLinkReorientCommand; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EsbLinkEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; /** * @generated */ public class EntitlementMediatorObligationsOutputConnectorItemSemanticEditPolicy extends EsbBaseItemSemanticEditPolicy { /** * @generated */ public EntitlementMediatorObligationsOutputConnectorItemSemanticEditPolicy() { super(EsbElementTypes.EntitlementMediatorObligationsOutputConnector_3751); } /** * @generated */ protected Command getDestroyElementCommand(DestroyElementRequest req) { View view = (View) getHost().getModel(); CompositeTransactionalCommand cmd = new CompositeTransactionalCommand(getEditingDomain(), null); cmd.setTransactionNestingEnabled(false); for (Iterator<?> it = view.getSourceEdges().iterator(); it.hasNext();) { Edge outgoingLink = (Edge) it.next(); if (EsbVisualIDRegistry.getVisualID(outgoingLink) == EsbLinkEditPart.VISUAL_ID) { DestroyElementRequest r = new DestroyElementRequest(outgoingLink.getElement(), false); cmd.add(new DestroyElementCommand(r)); cmd.add(new DeleteCommand(getEditingDomain(), outgoingLink)); continue; } } EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$ if (annotation == null) { // there are indirectly referenced children, need extra commands: false addDestroyShortcutsCommand(cmd, view); // delete host element cmd.add(new DestroyElementCommand(req)); } else { cmd.add(new DeleteCommand(getEditingDomain(), view)); } return getGEFWrapper(cmd.reduce()); } /** * @generated */ protected Command getCreateRelationshipCommand(CreateRelationshipRequest req) { Command command = req.getTarget() == null ? getStartCreateRelationshipCommand(req) : getCompleteCreateRelationshipCommand(req); return command != null ? command : super.getCreateRelationshipCommand(req); } /** * @generated */ protected Command getStartCreateRelationshipCommand(CreateRelationshipRequest req) { if (EsbElementTypes.EsbLink_4001 == req.getElementType()) { return getGEFWrapper(new EsbLinkCreateCommand(req, req.getSource(), req.getTarget())); } return null; } /** * @generated */ protected Command getCompleteCreateRelationshipCommand(CreateRelationshipRequest req) { if (EsbElementTypes.EsbLink_4001 == req.getElementType()) { return null; } return null; } /** * Returns command to reorient EClass based link. New link target or source * should be the domain model element associated with this node. * * @generated */ protected Command getReorientRelationshipCommand(ReorientRelationshipRequest req) { switch (getVisualID(req)) { case EsbLinkEditPart.VISUAL_ID: return getGEFWrapper(new EsbLinkReorientCommand(req)); } return super.getReorientRelationshipCommand(req); } }
/* * Copyright © 2016-2018 European Support Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openecomp.core.zusammen.db; import com.amdocs.zusammen.adaptor.inbound.api.types.item.*; import com.amdocs.zusammen.commons.health.data.HealthInfo; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.*; import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; import com.amdocs.zusammen.datatypes.itemversion.Tag; import java.util.Collection; public interface ZusammenConnector { Collection<HealthInfo> checkHealth(SessionContext sessionContext); String getVersion(SessionContext sessionContext); Collection<Item> listItems(SessionContext context); Item getItem(SessionContext context, Id itemId); Id createItem(SessionContext context, Info info); void deleteItem(SessionContext context, Id itemId); void updateItem(SessionContext context, Id itemId, Info info); Collection<ItemVersion> listPublicVersions(SessionContext context, Id itemId); ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId); Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData); void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData); ItemVersion getVersion(SessionContext context, Id itemId, Id versionId); ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId); void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag); void resetVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId); void revertVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId); ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, Id versionId); void publishVersion(SessionContext context, Id itemId, Id versionId, String message); void syncVersion(SessionContext context, Id itemId, Id versionId); void forceSyncVersion(SessionContext context, Id itemId, Id versionId); void cleanVersion(SessionContext context, Id itemId, Id versionId); ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId); Collection<ElementInfo> listElements(SessionContext context, ElementContext elementContext, Id parentElementId); ElementInfo getElementInfo(SessionContext context, ElementContext elementContext, Id elementId); Element getElement(SessionContext context, ElementContext elementContext, Id elementId); ElementConflict getElementConflict(SessionContext context, ElementContext elementContext, Id elementId); Element saveElement(SessionContext context, ElementContext elementContext, Element element, String message); void resolveElementConflict(SessionContext context, ElementContext elementContext, Element element, Resolution resolution); void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef); }
package com.actionbarsherlock.plus; import android.os.Build; import android.view.KeyEvent; import com.actionbarsherlock.app.SherlockActivity; public abstract class SherlockActivityPlus extends SherlockActivity { @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_MENU) { openOptionsMenu(); return true; } } return super.onKeyUp(keyCode, event); } }
package com.example.myapplication1.Activities; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.example.myapplication1.R; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.example.myapplication1.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class LoginActivity extends AppCompatActivity { private EditText userMail,userPassword; private Button btnLogin; private ProgressBar loginProgress; private FirebaseAuth mAuth; private Intent HomeActivity; private ImageView loginPhoto; @Override public void onBackPressed() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); userMail = findViewById(R.id.login_mail); userPassword = findViewById(R.id.login_password); btnLogin = findViewById(R.id.loginBtn); loginProgress = findViewById(R.id.login_progress); mAuth = FirebaseAuth.getInstance(); HomeActivity = new Intent(this,Money.class); loginPhoto = findViewById(R.id.login_photo); loginPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent registerActivity = new Intent(getApplicationContext(),RegisterActivity.class); startActivity(registerActivity); finish(); } }); loginProgress.setVisibility(View.INVISIBLE); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { loginProgress.setVisibility(View.VISIBLE); btnLogin.setVisibility(View.INVISIBLE); final String mail = userMail.getText().toString(); final String password = userPassword.getText().toString(); if (mail.isEmpty() || password.isEmpty()) { showMessage("Please Verify All Field"); btnLogin.setVisibility(View.VISIBLE); loginProgress.setVisibility(View.INVISIBLE); } else { signIn(mail,password); } } }); } private void signIn(String mail, String password) { mAuth.signInWithEmailAndPassword(mail,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { loginProgress.setVisibility(View.INVISIBLE); btnLogin.setVisibility(View.VISIBLE); updateUI(); } else { showMessage(task.getException().getMessage()); btnLogin.setVisibility(View.VISIBLE); loginProgress.setVisibility(View.INVISIBLE); } } }); } private void updateUI() { startActivity(HomeActivity); finish(); } private void showMessage(String text) { Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG).show(); } @Override protected void onStart() { super.onStart(); FirebaseUser user = mAuth.getCurrentUser(); if(user != null) { //user is already connected so we need to redirect him to home page updateUI(); } } }
// javac BankAccount.java // java BankAccount class BankAccountClass { int balance; public BankAccount(int balance) { this.balance = balance; } public void withdraw(int amount) { this.balance = this.balance - amount; } public static void main(String[] args) { BankAccountClass Account1 = new BankAccountClass(5000); BankAccountClass Account2 = new BankAccountClass(15000); } } class BetterBankAccountClass extends BankAccountClass { int balance; int maximumAmount; public BetterBankAccount(int balance, int maximumAmount) { this.balance = balance; this.maximumAmount = maximumAmount; } public void isBalanceAboveMaximum() { if (this.balance > this.maximumAmount) { System.out.println("Your balance is higher than the maximum amount allowed!"); } else { System.out.println("Your balance is under the maximum amount allowed!"); } } } public class BankAccount { public static void main(String[] args) { BankAccountClass Account1 = new BankAccountClass(5000); BankAccountClass Account2 = new BankAccountClass(15000); ///////////////////// BetterBankAccountClass Account3 = new BetterBankAccountClass(5000); BetterBankAccountClass Account4 = new BetterBankAccountClass(15000); } }
/* * Copyright 2014 Axiomine * * 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.axiomine.largecollections.turboutil; import com.google.common.base.Throwables; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Set; import org.iq80.leveldb.WriteBatch; import com.google.common.base.Function; import com.axiomine.largecollections.util.*; import com.axiomine.largecollections.serdes.*; import com.axiomine.largecollections.kryo.serializers.*; import org.apache.hadoop.io.*; public class TextDoubleMap extends LargeCollection implements Map<Text,Double>, Serializable{ public static final long serialVersionUID = 2l; private transient TurboSerializer<Text> keySerFunc = new WritableSerDes.TextSerFunction(); private transient TurboSerializer<Double> valSerFunc = new DoubleSerDes.SerFunction(); private transient TurboDeSerializer<Text> keyDeSerFunc = new WritableSerDes.TextDeSerFunction(); private transient TurboDeSerializer< Double> valDeSerFunc = new DoubleSerDes.DeSerFunction(); public TextDoubleMap() { super(); } public TextDoubleMap(String dbName) { super(dbName); } public TextDoubleMap(String dbPath, String dbName) { super(dbPath, dbName); } public TextDoubleMap(String dbPath, String dbName, int cacheSize) { super(dbPath, dbName, cacheSize); } public TextDoubleMap(String dbPath, String dbName, int cacheSize, int bloomFilterSize) { super(dbPath, dbName, cacheSize, bloomFilterSize); } @Override public void optimize() { MapKeySet<Text> keys = new MapKeySet<Text>(this, keyDeSerFunc); try { this.initializeBloomFilter(); for (Text entry : keys) { this.bloomFilter.put(entry); } } catch (Exception ex) { throw Throwables.propagate(ex); } finally{ if(keys!=null){ try{ keys.close(); } catch(Exception ex){ throw Throwables.propagate(ex); } } } } @Override public boolean containsKey(Object key) { byte[] valBytes = null; if (key != null) { Text ki = (Text) key; if (this.bloomFilter.mightContain(ki)) { byte[] keyBytes = keySerFunc.apply(ki); valBytes = db.get(keyBytes); } } return valBytes != null; } @Override public boolean containsValue(Object value) { // Will be very slow unless a seperate DB is maintained with values as // keys throw new UnsupportedOperationException(); } @Override public Double get(Object key) { byte[] vbytes = null; if (key == null) { return null; } Text ki = (Text) key; if (bloomFilter.mightContain((Text) key)) { vbytes = db.get(keySerFunc.apply(ki)); if (vbytes == null) { return null; } else { return valDeSerFunc.apply(vbytes); } } else { return null; } } @Override public int size() { return (int) size; } @Override public boolean isEmpty() { return size == 0; } /* Putting null values is not allowed for this map */ @Override public Double put(Text key, Double value) { if (key == null) return null; if (value == null)// Do not add null key or value return null; byte[] fullKeyArr = keySerFunc.apply(key); byte[] fullValArr = valSerFunc.apply(value); if (!this.containsKey(key)) { bloomFilter.put(key); db.put(fullKeyArr, fullValArr); size++; } else { db.put(fullKeyArr, fullValArr); } return value; } @Override public Double remove(Object key) { Double v = null; if (key == null) return v; if (this.size > 0 && this.bloomFilter.mightContain((Text) key)) { v = this.get(key); } if (v != null) { byte[] fullKeyArr = keySerFunc.apply((Text) key); db.delete(fullKeyArr); size--; } return v; } @Override public void putAll(Map<? extends Text, ? extends Double> m) { try { WriteBatch batch = db.createWriteBatch(); int counter = 0; for (Map.Entry<? extends Text, ? extends Double> e : m .entrySet()) { byte[] keyArr = keySerFunc.apply(e.getKey()); Double v = null; Text k = e.getKey(); if (this.size > 0 && this.bloomFilter.mightContain(k)) { v = this.get(k); } if (v == null) { bloomFilter.put(k); this.size++; } batch.put(keyArr, valSerFunc.apply(e.getValue())); counter++; if (counter % 1000 == 0) { db.write(batch); batch.close(); batch = db.createWriteBatch(); } } db.write(batch); batch.close(); } catch (Exception ex) { throw Throwables.propagate(ex); } } @Override public void clear() { this.clearDB(); } /* Iterators and Collections based on this Map */ @Override public Set<Text> keySet() { return new MapKeySet<Text>(this, keyDeSerFunc); } @Override public Collection<Double> values() { return new ValueCollection<Double>(this, this.getDB(), this.valDeSerFunc); } @Override public Set<java.util.Map.Entry<Text, Double>> entrySet() { return new MapEntrySet<Text, Double>(this, this.keyDeSerFunc, this.valDeSerFunc); } /* Serialization functions go here */ private void writeObject(java.io.ObjectOutputStream stream) throws IOException { this.serialize(stream); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { keySerFunc = new WritableSerDes.TextSerFunction(); valSerFunc = new DoubleSerDes.SerFunction(); keyDeSerFunc = new WritableSerDes.TextDeSerFunction(); valDeSerFunc = new DoubleSerDes.DeSerFunction(); this.deserialize(in); } /* End of Serialization functions go here */ }
/* * Copyright 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.arquillian.container; import java.io.IOException; import java.io.InputStream; import org.jboss.arquillian.container.spi.client.container.DeploymentException; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentHelper; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.exporter.ZipExporter; /** * A deployer that uses the {@link ServerDeploymentHelper}. * * <p> * The client is not closed by an instance of this and is the responsibility of the user to clean up the client instance. * </p> * * @author Thomas.Diesler@jboss.com * @since 17-Nov-2010 */ public class ArchiveDeployer { private static final Logger log = Logger.getLogger(ArchiveDeployer.class); private final ServerDeploymentHelper deployer; private final ManagementClient client; /** * Creates a new deployer for deploying archives. * <p> * Using this constructor the state of the client connection cannot be validated. This could produce unexpected * results if the client is closed and there's an attempt to use an instance of this type. * </p> * * @param modelControllerClient the model controller to use * * @deprecated use {@link #ArchiveDeployer(ManagementClient)} */ @Deprecated public ArchiveDeployer(ModelControllerClient modelControllerClient) { this.deployer = new ServerDeploymentHelper(modelControllerClient); client = null; } /** * Creates a new deployer for deploying archives. * * @param client the management client to use */ public ArchiveDeployer(ManagementClient client) { this.client = client; this.deployer = new ServerDeploymentHelper(client.getControllerClient()); } /** * Deploys the archive to a running container. * * @param archive the archive to deploy * * @return the runtime name of the deployment * * @throws DeploymentException if an error happens during deployment * @throws IllegalStateException if the client has been closed */ public String deploy(Archive<?> archive) throws DeploymentException { return deployInternal(archive); } /** * Deploys the archive to a running container. * * @param name the runtime for the deployment * @param input the input stream of a deployment archive * * @return the runtime name of the deployment * * @throws DeploymentException if an error happens during deployment * @throws IllegalStateException if the client has been closed */ public String deploy(String name, InputStream input) throws DeploymentException { return deployInternal(name, input); } /** * Removes an archive from the running container. * <p> * All exceptions are caught and logged as a warning. {@link Error Errors} will still be thrown however. * </p> * * @param runtimeName the runtime name for the deployment */ public void undeploy(String runtimeName) { try { deployer.undeploy(runtimeName); } catch (Exception ex) { log.warnf(ex, "Cannot undeploy: %s", runtimeName); } } private String deployInternal(Archive<?> archive) throws DeploymentException { checkState(); final InputStream input = archive.as(ZipExporter.class).exportAsInputStream(); try { return deployInternal(archive.getName(), input); } finally { if (input != null) try { input.close(); } catch (IOException e) { log.warnf(e, "Failed to close resource %s", input); } } } private String deployInternal(String name, InputStream input) throws DeploymentException { checkState(); try { return deployer.deploy(name, input); } catch (Exception ex) { Throwable rootCause = ex.getCause(); while (null != rootCause && rootCause.getCause() != null) { rootCause = rootCause.getCause(); } throw new DeploymentException("Cannot deploy: " + name, rootCause); } } private void checkState() { // Checks the state if (client != null && client.isClosed()) { throw new IllegalStateException("The client connection has been closed."); } } }
package net.n2oapp.framework.api.metadata.meta.control; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; /** * Клиентская модель компонента текста */ @Getter @Setter public class Text extends Field { @JsonProperty private String text; @JsonProperty private String format; }
/* * 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.knox.gateway.topology.discovery.cm; import com.cloudera.api.swagger.client.ApiClient; import com.cloudera.api.swagger.client.Pair; import com.cloudera.api.swagger.client.auth.Authentication; import com.cloudera.api.swagger.client.auth.HttpBasicAuth; import org.apache.knox.gateway.config.ConfigurationException; import org.apache.knox.gateway.config.GatewayConfig; import org.apache.knox.gateway.i18n.messages.MessagesFactory; import org.apache.knox.gateway.services.security.AliasService; import org.apache.knox.gateway.services.security.AliasServiceException; import org.apache.knox.gateway.topology.discovery.ServiceDiscoveryConfig; import org.apache.knox.gateway.topology.discovery.cm.auth.AuthUtils; import org.apache.knox.gateway.topology.discovery.cm.auth.SpnegoAuthInterceptor; import javax.security.auth.Subject; import java.util.List; import static org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscovery.API_PATH; import static org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscovery.DEFAULT_USER_ALIAS; import static org.apache.knox.gateway.topology.discovery.cm.ClouderaManagerServiceDiscovery.DEFAULT_PWD_ALIAS; /** * Cloudera Manager ApiClient extension for service discovery. */ public class DiscoveryApiClient extends ApiClient { private ClouderaManagerServiceDiscoveryMessages log = MessagesFactory.get(ClouderaManagerServiceDiscoveryMessages.class); private boolean isKerberos; private ServiceDiscoveryConfig config; public DiscoveryApiClient(ServiceDiscoveryConfig discoveryConfig, AliasService aliasService) { this.config = discoveryConfig; configure(aliasService); } boolean isKerberos() { return isKerberos; } private void configure(AliasService aliasService) { String apiAddress = config.getAddress(); apiAddress += (apiAddress.endsWith("/") ? API_PATH : "/" + API_PATH); setBasePath(apiAddress); String username = config.getUser(); String passwordAlias = config.getPasswordAlias(); String password = null; // If no configured username, then use default username alias if (username == null) { if (aliasService != null) { try { char[] defaultUser = aliasService.getPasswordFromAliasForGateway(DEFAULT_USER_ALIAS); if (defaultUser != null) { username = new String(defaultUser); } } catch (AliasServiceException e) { log.aliasServiceUserError(DEFAULT_USER_ALIAS, e.getLocalizedMessage()); } } // If username is still null if (username == null) { log.aliasServiceUserNotFound(); throw new ConfigurationException("No username is configured for Cloudera Manager service discovery."); } } if (aliasService != null) { // If no password alias is configured, then try the default alias if (passwordAlias == null) { passwordAlias = DEFAULT_PWD_ALIAS; } try { char[] pwd = aliasService.getPasswordFromAliasForGateway(passwordAlias); if (pwd != null) { password = new String(pwd); } } catch (AliasServiceException e) { log.aliasServicePasswordError(passwordAlias, e.getLocalizedMessage()); } } // If the password could not be determined if (password == null) { log.aliasServicePasswordNotFound(); isKerberos = Boolean.getBoolean(GatewayConfig.HADOOP_KERBEROS_SECURED); } setUsername(username); setPassword(password); if (isKerberos) { // If there is a Kerberos subject, then add the SPNEGO auth interceptor Subject subject = AuthUtils.getKerberosSubject(); if (subject != null) { SpnegoAuthInterceptor spnegoInterceptor = new SpnegoAuthInterceptor(subject); getHttpClient().interceptors().add(spnegoInterceptor); } } } @Override public String buildUrl(String path, List<Pair> queryParams) { // If kerberos is enabled, then for every request, we're going to include a doAs query param if (isKerberos()) { String user = getUsername(); if (user != null) { queryParams.add(new Pair("doAs", user)); } } return super.buildUrl(path, queryParams); } /** * @return The username set from the discovery configuration when this instance was initialized. */ private String getUsername() { String username = null; Authentication basicAuth = getAuthentication("basic"); if (basicAuth instanceof HttpBasicAuth) { username = ((HttpBasicAuth) basicAuth).getUsername(); } return username; } }
/* * Copyright 2017 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.priam.resources; import static org.junit.Assert.assertEquals; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Provider; import com.netflix.priam.PriamServer; import com.netflix.priam.backup.*; import com.netflix.priam.config.IConfiguration; import com.netflix.priam.defaultimpl.ICassandraProcess; import com.netflix.priam.health.InstanceState; import com.netflix.priam.identity.IPriamInstanceFactory; import com.netflix.priam.identity.config.InstanceInfo; import com.netflix.priam.restore.Restore; import com.netflix.priam.tuner.ICassandraTuner; import com.netflix.priam.utils.DateUtil; import java.util.Date; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMockit.class) public class BackupServletTest { private @Mocked PriamServer priamServer; private IConfiguration config; private @Mocked IBackupFileSystem bkpFs; private @Mocked Restore restoreObj; private @Mocked Provider<AbstractBackupPath> pathProvider; private @Mocked ICassandraTuner tuner; private @Mocked SnapshotBackup snapshotBackup; private @Mocked IPriamInstanceFactory factory; private @Mocked ICassandraProcess cassProcess; private @Mocked BackupStatusMgr bkupStatusMgr; private BackupServlet resource; private RestoreServlet restoreResource; private BackupVerification backupVerification; private InstanceInfo instanceInfo; @Before public void setUp() { Injector injector = Guice.createInjector(new BRTestModule()); config = injector.getInstance(IConfiguration.class); InstanceState instanceState = injector.getInstance(InstanceState.class); instanceInfo = injector.getInstance(InstanceInfo.class); resource = new BackupServlet(config, bkpFs, snapshotBackup, bkupStatusMgr, backupVerification); restoreResource = new RestoreServlet(restoreObj, instanceState); } @Test public void backup() throws Exception { new Expectations() { { snapshotBackup.execute(); } }; Response response = resource.backup(); assertEquals(200, response.getStatus()); assertEquals("[\"ok\"]", response.getEntity()); assertEquals( MediaType.APPLICATION_JSON_TYPE, response.getMetadata().get("Content-Type").get(0)); } @Test public void restore_minimal() throws Exception { final String dateRange = null; final String oldRegion = "us-east-1"; new Expectations() { { instanceInfo.getRegion(); result = oldRegion; restoreObj.restore((Date) any, (Date) any); // TODO: test default value } }; expectCassandraStartup(); Response response = restoreResource.restore(dateRange); assertEquals(200, response.getStatus()); assertEquals("[\"ok\"]", response.getEntity()); assertEquals( MediaType.APPLICATION_JSON_TYPE, response.getMetadata().get("Content-Type").get(0)); } @Test public void restore_withDateRange() throws Exception { final String dateRange = "201101010000,201112312359"; new Expectations() { { DateUtil.getDate(dateRange.split(",")[0]); result = new DateTime(2011, 1, 1, 0, 0).toDate(); times = 1; DateUtil.getDate(dateRange.split(",")[1]); result = new DateTime(2011, 12, 31, 23, 59).toDate(); times = 1; restoreObj.restore( DateUtil.getDate(dateRange.split(",")[0]), DateUtil.getDate(dateRange.split(",")[1])); } }; expectCassandraStartup(); Response response = restoreResource.restore(dateRange); assertEquals(200, response.getStatus()); assertEquals("[\"ok\"]", response.getEntity()); assertEquals( MediaType.APPLICATION_JSON_TYPE, response.getMetadata().get("Content-Type").get(0)); } // TODO: create CassandraController interface and inject, instead of static util method private void expectCassandraStartup() { new Expectations() { { config.getCassStartupScript(); result = "/usr/bin/false"; config.getHeapNewSize(); result = "2G"; config.getHeapSize(); result = "8G"; config.getDataFileLocation(); result = "/var/lib/cassandra/data"; config.getCommitLogLocation(); result = "/var/lib/cassandra/commitlog"; config.getBackupLocation(); result = "backup"; config.getCacheLocation(); result = "/var/lib/cassandra/saved_caches"; config.getJmxPort(); result = 7199; config.getMaxDirectMemory(); result = "50G"; } }; } }
/** * Copyright ${license.git.copyrightYears} the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.executor; import static org.apache.ibatis.executor.ExecutionPlaceholder.EXECUTION_PLACEHOLDER; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.cache.impl.PerpetualCache; import org.apache.ibatis.cursor.Cursor; import org.apache.ibatis.executor.statement.StatementUtil; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.logging.jdbc.ConnectionLogger; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.mapping.ParameterMode; import org.apache.ibatis.mapping.StatementType; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.ObjectFactory; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.LocalCacheScope; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.transaction.Transaction; import org.apache.ibatis.type.TypeHandlerRegistry; /** * @author Clinton Begin */ public abstract class BaseExecutor implements Executor { private static final Log log = LogFactory.getLog(BaseExecutor.class); protected Transaction transaction; protected Executor wrapper; protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads; protected PerpetualCache localCache; protected PerpetualCache localOutputParameterCache; protected Configuration configuration; protected int queryStack; private boolean closed; protected BaseExecutor(Configuration configuration, Transaction transaction) { this.transaction = transaction; this.deferredLoads = new ConcurrentLinkedQueue<DeferredLoad>(); this.localCache = new PerpetualCache("LocalCache"); this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache"); this.closed = false; this.configuration = configuration; this.wrapper = this; } @Override public Transaction getTransaction() { if (closed) { throw new ExecutorException("Executor was closed."); } return transaction; } @Override public void close(boolean forceRollback) { try { try { rollback(forceRollback); } finally { if (transaction != null) { transaction.close(); } } } catch (SQLException e) { // Ignore. There's nothing that can be done at this point. log.warn("Unexpected exception on closing transaction. Cause: " + e); } finally { transaction = null; deferredLoads = null; localCache = null; localOutputParameterCache = null; closed = true; } } @Override public boolean isClosed() { return closed; } @Override public int update(MappedStatement ms, Object parameter) throws SQLException { ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId()); if (closed) { throw new ExecutorException("Executor was closed."); } clearLocalCache(); return doUpdate(ms, parameter); } @Override public List<BatchResult> flushStatements() throws SQLException { return flushStatements(false); } public List<BatchResult> flushStatements(boolean isRollBack) throws SQLException { if (closed) { throw new ExecutorException("Executor was closed."); } return doFlushStatements(isRollBack); } @Override public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException { BoundSql boundSql = ms.getBoundSql(parameter); CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql); return query(ms, parameter, rowBounds, resultHandler, key, boundSql); } @SuppressWarnings("unchecked") @Override public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId()); if (closed) { throw new ExecutorException("Executor was closed."); } if (queryStack == 0 && ms.isFlushCacheRequired()) { clearLocalCache(); } List<E> list; try { queryStack++; list = resultHandler == null ? (List<E>) localCache.getObject(key) : null; if (list != null) { handleLocallyCachedOutputParameters(ms, key, parameter, boundSql); } else { list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql); } } finally { queryStack--; } if (queryStack == 0) { for (DeferredLoad deferredLoad : deferredLoads) { deferredLoad.load(); } // issue #601 deferredLoads.clear(); if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) { // issue #482 clearLocalCache(); } } return list; } @Override public <E> Cursor<E> queryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds) throws SQLException { BoundSql boundSql = ms.getBoundSql(parameter); return doQueryCursor(ms, parameter, rowBounds, boundSql); } @Override public void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class<?> targetType) { if (closed) { throw new ExecutorException("Executor was closed."); } DeferredLoad deferredLoad = new DeferredLoad(resultObject, property, key, localCache, configuration, targetType); if (deferredLoad.canLoad()) { deferredLoad.load(); } else { deferredLoads.add(new DeferredLoad(resultObject, property, key, localCache, configuration, targetType)); } } @Override public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) { if (closed) { throw new ExecutorException("Executor was closed."); } CacheKey cacheKey = new CacheKey(); cacheKey.update(ms.getId()); cacheKey.update(rowBounds.getOffset()); cacheKey.update(rowBounds.getLimit()); cacheKey.update(boundSql.getSql()); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry(); // mimic DefaultParameterHandler logic for (ParameterMapping parameterMapping : parameterMappings) { if (parameterMapping.getMode() != ParameterMode.OUT) { Object value; String propertyName = parameterMapping.getProperty(); if (boundSql.hasAdditionalParameter(propertyName)) { value = boundSql.getAdditionalParameter(propertyName); } else if (parameterObject == null) { value = null; } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { value = parameterObject; } else { MetaObject metaObject = configuration.newMetaObject(parameterObject); value = metaObject.getValue(propertyName); } cacheKey.update(value); } } if (configuration.getEnvironment() != null) { // issue #176 cacheKey.update(configuration.getEnvironment().getId()); } return cacheKey; } @Override public boolean isCached(MappedStatement ms, CacheKey key) { return localCache.getObject(key) != null; } @Override public void commit(boolean required) throws SQLException { if (closed) { throw new ExecutorException("Cannot commit, transaction is already closed"); } clearLocalCache(); flushStatements(); if (required) { transaction.commit(); } } @Override public void rollback(boolean required) throws SQLException { if (!closed) { try { clearLocalCache(); flushStatements(true); } finally { if (required) { transaction.rollback(); } } } } @Override public void clearLocalCache() { if (!closed) { localCache.clear(); localOutputParameterCache.clear(); } } protected abstract int doUpdate(MappedStatement ms, Object parameter) throws SQLException; protected abstract List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException; protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException; protected abstract <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql) throws SQLException; protected void closeStatement(Statement statement) { if (statement != null) { try { statement.close(); } catch (SQLException e) { // ignore } } } /** * Apply a transaction timeout. * @param statement a current statement * @throws SQLException if a database access error occurs, this method is called on a closed <code>Statement</code> * @since 3.4.0 * @see StatementUtil#applyTransactionTimeout(Statement, Integer, Integer) */ protected void applyTransactionTimeout(Statement statement) throws SQLException { StatementUtil.applyTransactionTimeout(statement, statement.getQueryTimeout(), transaction.getTimeout()); } private void handleLocallyCachedOutputParameters(MappedStatement ms, CacheKey key, Object parameter, BoundSql boundSql) { if (ms.getStatementType() == StatementType.CALLABLE) { final Object cachedParameter = localOutputParameterCache.getObject(key); if (cachedParameter != null && parameter != null) { final MetaObject metaCachedParameter = configuration.newMetaObject(cachedParameter); final MetaObject metaParameter = configuration.newMetaObject(parameter); for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) { if (parameterMapping.getMode() != ParameterMode.IN) { final String parameterName = parameterMapping.getProperty(); final Object cachedValue = metaCachedParameter.getValue(parameterName); metaParameter.setValue(parameterName, cachedValue); } } } } } private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { List<E> list; localCache.putObject(key, EXECUTION_PLACEHOLDER); try { list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql); } finally { localCache.removeObject(key); } localCache.putObject(key, list); if (ms.getStatementType() == StatementType.CALLABLE) { localOutputParameterCache.putObject(key, parameter); } return list; } protected Connection getConnection(Log statementLog) throws SQLException { Connection connection = transaction.getConnection(); if (statementLog.isDebugEnabled()) { return ConnectionLogger.newInstance(connection, statementLog, queryStack); } else { return connection; } } @Override public void setExecutorWrapper(Executor wrapper) { this.wrapper = wrapper; } private static class DeferredLoad { private final MetaObject resultObject; private final String property; private final Class<?> targetType; private final CacheKey key; private final PerpetualCache localCache; private final ObjectFactory objectFactory; private final ResultExtractor resultExtractor; // issue #781 public DeferredLoad(MetaObject resultObject, String property, CacheKey key, PerpetualCache localCache, Configuration configuration, Class<?> targetType) { this.resultObject = resultObject; this.property = property; this.key = key; this.localCache = localCache; this.objectFactory = configuration.getObjectFactory(); this.resultExtractor = new ResultExtractor(configuration, objectFactory); this.targetType = targetType; } public boolean canLoad() { return localCache.getObject(key) != null && localCache.getObject(key) != EXECUTION_PLACEHOLDER; } public void load() { @SuppressWarnings("unchecked") // we suppose we get back a List List<Object> list = (List<Object>) localCache.getObject(key); Object value = resultExtractor.extractObjectFromList(list, targetType); resultObject.setValue(property, value); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.discovery; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.errorprone.annotations.concurrent.GuardedBy; import org.apache.druid.java.util.common.logger.Logger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** * Common code used by various implementations of DruidNodeDiscovery. * * User code is supposed to arrange for following methods to be called, * {@link #childAdded(DiscoveryDruidNode)} * {@link #childRemoved(DiscoveryDruidNode)} * {@link #cacheInitialized()} * {@link #resetNodes(Map)} * * Then {@link #registerListener(DruidNodeDiscovery.Listener)} and {@link #getAllNodes()} can be delegated to the * implementation here. */ public class BaseNodeRoleWatcher { private static final Logger LOGGER = new Logger(BaseNodeRoleWatcher.class); private final NodeRole nodeRole; /** * hostAndPort -> DiscoveryDruidNode */ private final ConcurrentMap<String, DiscoveryDruidNode> nodes = new ConcurrentHashMap<>(); private final Collection<DiscoveryDruidNode> unmodifiableNodes = Collections.unmodifiableCollection(nodes.values()); private final ExecutorService listenerExecutor; private final List<DruidNodeDiscovery.Listener> nodeListeners = new ArrayList<>(); private final Object lock = new Object(); private final CountDownLatch cacheInitialized = new CountDownLatch(1); public BaseNodeRoleWatcher( ExecutorService listenerExecutor, NodeRole nodeRole ) { this.listenerExecutor = listenerExecutor; this.nodeRole = nodeRole; } public Collection<DiscoveryDruidNode> getAllNodes() { boolean nodeViewInitialized; try { nodeViewInitialized = cacheInitialized.await((long) 30, TimeUnit.SECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); nodeViewInitialized = false; } if (!nodeViewInitialized) { LOGGER.info( "Cache for node role [%s] not initialized yet; getAllNodes() might not return full information.", nodeRole.getJsonName() ); } return unmodifiableNodes; } public void registerListener(DruidNodeDiscovery.Listener listener) { synchronized (lock) { // No need to wait on CountDownLatch, because we are holding the lock under which it could only be counted down. if (cacheInitialized.getCount() == 0) { // It is important to take a snapshot here as list of nodes might change by the time listeners process // the changes. List<DiscoveryDruidNode> currNodes = Lists.newArrayList(nodes.values()); safeSchedule( () -> { listener.nodesAdded(currNodes); listener.nodeViewInitialized(); }, "Exception occured in nodesAdded([%s]) in listener [%s].", currNodes, listener ); } nodeListeners.add(listener); } } public void childAdded(DiscoveryDruidNode druidNode) { synchronized (lock) { if (!nodeRole.equals(druidNode.getNodeRole())) { LOGGER.error( "Node[%s] of role[%s] addition ignored due to mismatched role (expected role[%s]).", druidNode.getDruidNode().getUriToUse(), druidNode.getNodeRole().getJsonName(), nodeRole.getJsonName() ); return; } LOGGER.info("Node[%s] of role[%s] detected.", druidNode.getDruidNode().getUriToUse(), nodeRole.getJsonName()); addNode(druidNode); } } @GuardedBy("lock") private void addNode(DiscoveryDruidNode druidNode) { DiscoveryDruidNode prev = nodes.putIfAbsent(druidNode.getDruidNode().getHostAndPortToUse(), druidNode); if (prev == null) { // No need to wait on CountDownLatch, because we are holding the lock under which it could only be counted down. if (cacheInitialized.getCount() == 0) { List<DiscoveryDruidNode> newNode = ImmutableList.of(druidNode); for (DruidNodeDiscovery.Listener listener : nodeListeners) { safeSchedule( () -> listener.nodesAdded(newNode), "Exception occured in nodeAdded(node=[%s]) in listener [%s].", druidNode.getDruidNode().getHostAndPortToUse(), listener ); } } } else { LOGGER.error( "Node[%s] of role[%s] discovered but existed already [%s].", druidNode.getDruidNode().getUriToUse(), nodeRole.getJsonName(), prev ); } } public void childRemoved(DiscoveryDruidNode druidNode) { synchronized (lock) { if (!nodeRole.equals(druidNode.getNodeRole())) { LOGGER.error( "Node[%s] of role[%s] removal ignored due to mismatched role (expected role[%s]).", druidNode.getDruidNode().getUriToUse(), druidNode.getNodeRole().getJsonName(), nodeRole.getJsonName() ); return; } LOGGER.info("Node[%s] of role[%s] went offline.", druidNode.getDruidNode().getUriToUse(), nodeRole.getJsonName()); removeNode(druidNode); } } @GuardedBy("lock") private void removeNode(DiscoveryDruidNode druidNode) { DiscoveryDruidNode prev = nodes.remove(druidNode.getDruidNode().getHostAndPortToUse()); if (prev == null) { LOGGER.error( "Noticed disappearance of unknown druid node [%s] of role[%s].", druidNode.getDruidNode().getUriToUse(), druidNode.getNodeRole().getJsonName() ); return; } // No need to wait on CountDownLatch, because we are holding the lock under which it could only be counted down. if (cacheInitialized.getCount() == 0) { List<DiscoveryDruidNode> nodeRemoved = ImmutableList.of(druidNode); for (DruidNodeDiscovery.Listener listener : nodeListeners) { safeSchedule( () -> listener.nodesRemoved(nodeRemoved), "Exception occured in nodeRemoved(node[%s] of role[%s]) in listener [%s].", druidNode.getDruidNode().getUriToUse(), druidNode.getNodeRole().getJsonName(), listener ); } } } public void cacheInitialized() { synchronized (lock) { // No need to wait on CountDownLatch, because we are holding the lock under which it could only be // counted down. if (cacheInitialized.getCount() == 0) { LOGGER.error("cache is already initialized. ignoring cache initialization event."); return; } LOGGER.info("Node watcher of role[%s] is now initialized.", nodeRole.getJsonName()); for (DruidNodeDiscovery.Listener listener : nodeListeners) { // It is important to take a snapshot here as list of nodes might change by the time listeners process // the changes. List<DiscoveryDruidNode> currNodes = Lists.newArrayList(nodes.values()); safeSchedule( () -> { listener.nodesAdded(currNodes); listener.nodeViewInitialized(); }, "Exception occured in nodesAdded([%s]) in listener [%s].", currNodes, listener ); } cacheInitialized.countDown(); } } public void resetNodes(Map<String, DiscoveryDruidNode> fullNodes) { synchronized (lock) { List<DiscoveryDruidNode> nodesAdded = new ArrayList<>(); List<DiscoveryDruidNode> nodesDeleted = new ArrayList<>(); for (Map.Entry<String, DiscoveryDruidNode> e : fullNodes.entrySet()) { if (!nodes.containsKey(e.getKey())) { nodesAdded.add(e.getValue()); } } for (Map.Entry<String, DiscoveryDruidNode> e : nodes.entrySet()) { if (!fullNodes.containsKey(e.getKey())) { nodesDeleted.add(e.getValue()); } } for (DiscoveryDruidNode node : nodesDeleted) { nodes.remove(node.getDruidNode().getHostAndPortToUse()); } for (DiscoveryDruidNode node : nodesAdded) { nodes.put(node.getDruidNode().getHostAndPortToUse(), node); } // No need to wait on CountDownLatch, because we are holding the lock under which it could only be counted down. if (cacheInitialized.getCount() == 0) { for (DruidNodeDiscovery.Listener listener : nodeListeners) { safeSchedule( () -> { if (!nodesAdded.isEmpty()) { listener.nodesAdded(nodesAdded); } if (!nodesDeleted.isEmpty()) { listener.nodesRemoved(nodesDeleted); } }, "Exception occured in resetNodes in listener [%s].", listener ); } } } } private void safeSchedule(Runnable runnable, String errMsgFormat, Object... args) { listenerExecutor.submit(() -> { try { runnable.run(); } catch (Exception ex) { LOGGER.error(errMsgFormat, args); } }); } }
package arsenic.support.lottie.model.animatable; import arsenic.support.lottie.value.Keyframe; import arsenic.support.lottie.animation.keyframe.BaseKeyframeAnimation; import arsenic.support.lottie.animation.keyframe.ColorKeyframeAnimation; import java.util.List; public class AnimatableColorValue extends BaseAnimatableValue<Integer, Integer> { public AnimatableColorValue(List<Keyframe<Integer>> keyframes) { super(keyframes); } @Override public BaseKeyframeAnimation<Integer, Integer> createAnimation() { return new ColorKeyframeAnimation(keyframes); } }
package de.busse_apps.hmintpmd.widget; /* * Copyright 2015 Bernd Busse * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context; import android.content.res.TypedArray; import android.graphics.PixelFormat; import android.graphics.Rect; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.lang.ref.WeakReference; import de.busse_apps.hmintpmd.R; public class CircleMeterView extends SurfaceView implements SurfaceHolder.Callback { public static final int MAX_DEGREE = 360; private SurfaceHolder mHolder; private CircleMeterData mData; private CircleMeterDrawingThread mThread; private Rect mDrawingRect = new Rect(); private CircleMeterHandler mCircleMeterHandler; private CircleMeterCallback mCallback; private Bundle mThreadState; private boolean isSurfaceCreated; public CircleMeterView(Context context, AttributeSet attrs) { super(context, attrs); if (!isInEditMode()) { setZOrderOnTop(true); } mData = new CircleMeterData(); TypedArray styled = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CircleMeterView, 0, 0); try { mData.degreePerSecond = styled.getInteger( R.styleable.CircleMeterView_degree_per_second, 90); mData.arcWidth = styled .getDimensionPixelSize(R.styleable.CircleMeterView_arc_width, 10); mData.borderWidth = styled.getDimensionPixelSize( R.styleable.CircleMeterView_border_width, 2); mData.colorLow = styled.getColor(R.styleable.CircleMeterView_color_low, getResources() .getColor(R.color.circle_meter_green)); mData.colorMid = styled.getColor(R.styleable.CircleMeterView_color_mid, getResources() .getColor(R.color.circle_meter_orange)); mData.colorHi = styled.getColor(R.styleable.CircleMeterView_color_hi, getResources() .getColor(R.color.circle_meter_red)); } finally { styled.recycle(); } mData.maxValue = 0; mData.maxDegree = 0; mHolder = getHolder(); mHolder.addCallback(this); mHolder.setFormat(PixelFormat.TRANSPARENT); mCircleMeterHandler = new CircleMeterHandler(this); mThread = new CircleMeterDrawingThread(mHolder, mCircleMeterHandler, mData); isSurfaceCreated = false; } public CircleMeterDrawingThread getThread() { return mThread; } public void setCallback(Object callback) { try { mCallback = (CircleMeterCallback) callback; } catch (ClassCastException e) { throw new ClassCastException(callback.toString() + " must implement CircleMeterCallback!"); } } public int getDegreePerSecond() { return mData.degreePerSecond; } public void setDegreePerSecond(int speed) { mData.degreePerSecond = speed; restartThread(); } public int getArcWidth() { return mData.arcWidth; } public void setArcWidth(int width) { mData.arcWidth = width; restartThread(); } public int getBorderWidth() { return mData.borderWidth; } public void setBorderWidth(int width) { mData.borderWidth = width; restartThread(); } public double getMaxValue() { return mData.maxValue; } public void setMaxValue(double value) { mData.maxValue = value; restartThread(); } public double getMaxDegree() { return mData.maxDegree; } public void setMaxDegree(double degree) { mData.maxDegree = degree; restartThread(); } public int getColorLow() { return mData.colorLow; } public void setColorLow(int color) { mData.colorLow = color; } public int getColorMid() { return mData.colorMid; } public void setColorMid(int color) { mData.colorMid = color; } public int getColorHi() { return mData.colorHi; } public void setColorHi(int color) { mData.colorHi = color; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = Integer.MAX_VALUE; int height = Integer.MAX_VALUE; int widthSize; int heightSize; final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY; boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY; if (resizeWidth || resizeHeight) { // We may change at least one Dimension // Get the max possible width/height given our constraints widthSize = resolveSize(Integer.MAX_VALUE, widthMeasureSpec); heightSize = resolveSize(Integer.MAX_VALUE, heightMeasureSpec); // See what our actual aspect ratio is float actualAspect = (float) (widthSize - getPaddingLeft() - getPaddingRight()) / (heightSize - getPaddingTop() - getPaddingBottom()); if (Math.abs(actualAspect - 1.0f) > 0.0000001) { boolean done = false; // Try adjusting width to be proportional to height if (resizeWidth) { int newWidth = heightSize - getPaddingTop() - getPaddingBottom() + getPaddingLeft() + getPaddingRight(); // Allow the width to outgrow its original estimate if // height is fixed. if (!resizeHeight) { widthSize = resolveAdjustedSize(newWidth, Integer.MAX_VALUE, widthMeasureSpec); } if (newWidth <= widthSize) { widthSize = newWidth; done = true; } } // Try adjusting height to be proportional to width if (!done && resizeHeight) { int newHeight = widthSize - getPaddingLeft() - getPaddingRight() + getPaddingTop() + getPaddingBottom(); // Allow the height to outgrow its original estimate if // width is fixed. if (!resizeWidth) { heightSize = resolveAdjustedSize(newHeight, Integer.MAX_VALUE, heightMeasureSpec); } if (newHeight <= heightSize) { heightSize = newHeight; } } } } else { // We are not allowed to change dimensions widthSize = resolveSize(width, widthMeasureSpec); heightSize = resolveSize(height, heightMeasureSpec); } setMeasuredDimension(widthSize, heightSize); } private void configureBounds() { int padding = mData.borderWidth + mData.arcWidth / 2; int left = getPaddingLeft() + padding; int top = getPaddingTop() + padding; int right = getPaddingRight() + padding; int bottom = getPaddingBottom() + padding; int width = getWidth() - left - right; int height = getHeight() - top - bottom; if (width >= height) { int diff = (width - height) / 2; bottom = height + top; right = width + left - diff; left = left + diff; } else { int diff = (height - width) / 2; right = width + left; bottom = height + top - diff; top = top + diff; } mDrawingRect.set(left, top, right, bottom); } private int resolveAdjustedSize(int desiredSize, int maxSize, int measureSpec) { int result = desiredSize; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.UNSPECIFIED: // Parent says we can be as big as we want. Just don't be larger // than max size imposed on ourselves. result = Math.min(desiredSize, maxSize); break; case MeasureSpec.AT_MOST: // Parent says we can be as big as we want, up to specSize. // Don't be larger than specSize, and don't be larger than // the max size imposed on ourselves. result = Math.min(Math.min(desiredSize, specSize), maxSize); break; case MeasureSpec.EXACTLY: // No choice. Do what we are told. result = specSize; break; } return result; } private void doDrawingFinished() { if (mCallback != null) { mCallback.onDrawingFinished(); } } private void doProgressUpdate(double value, double degree) { if (mCallback != null) { mCallback.onProgressUpdate(value, degree); } } private void restartThread() { if (mThread.isRunning()) { mThread.pause(); mThreadState = mThread.saveState(new Bundle()); } mThread = new CircleMeterDrawingThread(mHolder, mCircleMeterHandler, mData); if (mThreadState != null) { mThread.restoreState(mThreadState); } if (isSurfaceCreated) { mThread.setRunning(true); mThread.start(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { configureBounds(); mThread.setDrawingBounds(mDrawingRect); mThread.redraw(); } @Override public void surfaceCreated(SurfaceHolder holder) { isSurfaceCreated = true; if (mThread.getState() == Thread.State.TERMINATED) { mThread = new CircleMeterDrawingThread(mHolder, mCircleMeterHandler, mData); } if (mThreadState != null) { mThread.restoreState(mThreadState); } mThread.setRunning(true); mThread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { isSurfaceCreated = false; boolean retry = true; mThread.setRunning(false); mThreadState = mThread.saveState(new Bundle()); while (retry) { try { mThread.join(); retry = false; } catch (InterruptedException ignored) { } } } /** * public Interface for callback actions */ public interface CircleMeterCallback { public void onDrawingFinished(); public void onProgressUpdate(double value, double degree); } /** * public static Handler for callback actions */ public static class CircleMeterHandler extends Handler { public static final String KEY_EVENT = "de.busse_apps.hmintpmd.common.CircleMeterView.CircleMeterHandler.eventType"; public static final String KEY_VALUE = "de.busse_apps.hmintpmd.common.CircleMeterView.CircleMeterHandler.value"; public static final String KEY_DEGREE = "de.busse_apps.hmintpmd.common.CircleMeterView.CircleMeterHandler.degree"; public static final int EVENT_FINISHED = 1; public static final int EVENT_UPDATE = 2; private final WeakReference<CircleMeterView> mCircleMeterView; public CircleMeterHandler(CircleMeterView view) { mCircleMeterView = new WeakReference<>(view); } @Override public void handleMessage(Message m) { CircleMeterView view = mCircleMeterView.get(); if (view != null) { switch (m.getData().getInt(KEY_EVENT)) { case EVENT_FINISHED: view.doDrawingFinished(); break; case EVENT_UPDATE: double value = m.getData().getDouble(KEY_VALUE); double degree = m.getData().getDouble(KEY_DEGREE); view.doProgressUpdate(value, degree); break; default: break; } } } } /** * public DataHolder for easy use of SavedInstanceState Bundle */ public class CircleMeterData { public double maxValue; public double maxDegree; public int degreePerSecond; public int arcWidth; public int borderWidth; public int colorLow; public int colorMid; public int colorHi; } }
package net.stegantsov.torrent.client; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.TextPage; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HTMLParserListener; import com.gargoylesoftware.htmlunit.html.HtmlPage; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.log4j.Logger; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * User: stegan * Date: 20.10.13 * Time: 0:42 */ public final class UTorrentClient implements Client { private static final Logger LOG = Logger.getLogger(UTorrentClient.class); private static final int TIMEOUT = 30000; private static final boolean USE_INSECURE_SSL = true; private static final BrowserVersion BROWSER_VERSION = BrowserVersion.CHROME; private WebClient webClient; private String token; private final String login; private final String password; private final String url; public UTorrentClient(final String login, final String password, final String url) { this.login = login; this.password = password; this.url = url; } @SuppressWarnings("unchecked") @Override public synchronized List<TorrentData> getTorrents() throws IOException { //todo check alive status if (webClient == null) { connect(); } TextPage tp = webClient.getPage(url + "/?list=1&token=" + token); List<List> tc = JSONArray.toList(JSONObject.fromObject(tp.getContent()).getJSONArray("torrents")); List<TorrentData> result = new ArrayList<>(); for (List ti : tc) { if (ti.size() >= 8) { TorrentData torrentData = new TorrentData(); torrentData.setHash(String.valueOf(ti.get(0))); try { torrentData.setRatio(Double.parseDouble(String.valueOf(ti.get(7))) / 1000); torrentData.setStatus(Integer.parseInt(String.valueOf(ti.get(1)))); torrentData.setUploadSpeed(Integer.parseInt(String.valueOf(ti.get(8)))); torrentData.setPercentProgress(Integer.parseInt(String.valueOf(ti.get(4)))); } catch (NumberFormatException nfe) { throw new IOException("Unable to parse data"); } result.add(torrentData); } else { throw new IOException("Received unknown structure of torrent's list"); } } LOG.debug(Thread.currentThread() + ":" + super.toString() + " Torrents retrieved: " + result); return result; } @Override public synchronized void delete(String hash) throws IOException { if (webClient == null) { connect(); } LOG.debug(Thread.currentThread() + ":" + super.toString() + " Delete torrent by hash: " + hash); //todo possible to check deletion status!? TextPage tp = webClient.getPage(url + "/?action=remove&hash=" + hash + "&token=" + token); LOG.debug("Content: " + tp.getContent()); } @Override public void close() throws IOException { if (webClient != null) { webClient.closeAllWindows(); } } private void connect() throws IOException { if (login == null || password == null || url == null) { throw new IllegalStateException("login password url are missed"); } LOG.debug(Thread.currentThread() + ":" + super.toString() + " Connecting to: " + url); webClient = new WebClient(BROWSER_VERSION); webClient.getOptions().setUseInsecureSSL(USE_INSECURE_SSL); webClient.getOptions().setTimeout(TIMEOUT); webClient.getOptions().setCssEnabled(false); webClient.setHTMLParserListener(HTMLParserListener.LOG_REPORTER); webClient.getCookieManager().setCookiesEnabled(true); webClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(login, password)); HtmlPage p = webClient.getPage(url + "/token.html"); token = p.getElementById("token").asText(); if (token == null || token.isEmpty()) { throw new IOException("Unable to retrieve token"); } LOG.debug(Thread.currentThread() + ":" + super.toString() + " Connection success. Token: " + token); } @Override public String toString() { return "UTorrentClient{" + "login='" + login + '\'' + ", url='" + url + '\'' + '}'; } }
/** * FRC Team 3555 */ package org.aluminati3555.mp.file.reader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; /** * This class reads an encoded motion profile from the filesystem * * @author Caleb Heydon */ public class MPReader { // Name of the file private String file; // Was there an error loading the file? private boolean error; // The motion profile private double[][] profile; /** * Returns the path of the file * * @return */ public String getFile() { return file; } /** * Returns true if an error was encountered * * @return */ public boolean getError() { return error; } /** * Returns the motion profile * * @return */ public double[][] getProfile() { return profile; } /** * Loads the motion profile from the disk */ private boolean loadMP() { boolean error = false; try { DataInputStream input = new DataInputStream(new GZIPInputStream(new FileInputStream(new File(file)))); // Read length int length = input.readInt(); profile = new double[length][3]; for (int i = 0; i < length; i++) { profile[i][0] = input.readDouble(); profile[i][1] = input.readDouble(); profile[i][2] = input.readDouble(); } input.close(); } catch (IOException e) { error = true; } return error; } public MPReader(String file) { this.file = file; this.error = loadMP(); } }
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2014 AS3Boyan * Copyright 2014-2014 Elias Ku * * 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.plugins.haxe.compilation; import com.intellij.compiler.options.CompileStepBeforeRun; import com.intellij.execution.ExecutorRegistry; import com.intellij.execution.configurations.ModuleBasedConfiguration; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.configurations.RunConfigurationModule; import com.intellij.execution.executors.DefaultDebugExecutor; import com.intellij.openapi.compiler.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.SdkAdditionalData; import com.intellij.openapi.roots.CompilerModuleExtension; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderEnumerator; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.plugins.haxe.HaxeBundle; import com.intellij.plugins.haxe.config.HaxeTarget; import com.intellij.plugins.haxe.config.sdk.HaxeSdkAdditionalDataBase; import com.intellij.plugins.haxe.ide.module.HaxeModuleSettings; import com.intellij.plugins.haxe.ide.module.HaxeModuleType; import com.intellij.plugins.haxe.module.HaxeModuleSettingsBase; import com.intellij.plugins.haxe.runner.debugger.HaxeDebugRunner; import com.intellij.plugins.haxe.tests.runner.HaxeTestsConfiguration; import com.intellij.plugins.haxe.util.HaxeCommonCompilerUtil; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import java.io.DataInput; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class HaxeCompiler implements SourceProcessingCompiler { private static final Logger LOG = Logger.getInstance("#com.intellij.plugins.haxe.compilation.HaxeCompiler"); /* // flag to indicate whether a module needs to be built private static HashMap<Module, Boolean> skipBuildMap = new HashMap<Module, Boolean>(); // holds the change set for each module to track whether anything changed since last build private static HashMap<Module, Set<String>> changeSetMap = new HashMap<Module, Set<String>>(); */ @NotNull public String getDescription() { return HaxeBundle.message("haxe.compiler.description"); } @Override public boolean validateConfiguration(CompileScope scope) { return true; } @NotNull @Override public ProcessingItem[] getProcessingItems(CompileContext context) { final List<ProcessingItem> itemList = new ArrayList<ProcessingItem>(); for (final Module module : getModulesToCompile(context.getCompileScope() /*, context.getProject() */)) { itemList.add(new MyProcessingItem(module)); } return itemList.toArray(new ProcessingItem[itemList.size()]); } private static List<Module> getModulesToCompile(final CompileScope scope /*, final Project project */) { final List<Module> result = new ArrayList<Module>(); for (final Module module : scope.getAffectedModules()) { if (ModuleType.get(module) != HaxeModuleType.getInstance()) continue; result.add(module); /* boolean skipBuilding = false; // default: always build //-- are any changes since last build if (changeSetMap.get(module) != null) { // was built at least once, in past ... final Set<String> latestChangeSet = new HashSet<String>(); Collection<VirtualFile> vFileCollection = FileTypeIndex .getFiles(HaxeFileType.HAXE_FILE_TYPE, module.getModuleWithDependenciesScope()); final VirtualFile[] virtualFiles = vFileCollection.toArray(new VirtualFile[0]); for (VirtualFile file : virtualFiles) { final FileStatus fileStatus = FileStatusManager.getInstance(project).getStatus(file); if (fileStatus.equals(FileStatus.NOT_CHANGED) || fileStatus.equals(FileStatus.UNKNOWN)) continue; latestChangeSet.add(file.getPath()); } skipBuilding = latestChangeSet.equals(changeSetMap.get(module)); changeSetMap.put(module, latestChangeSet); } else { changeSetMap.put(module, new HashSet<String>()); } skipBuildMap.put(module, new Boolean(skipBuilding)); if (! skipBuilding) { result.add(module); } */ } return result; } @Override public ProcessingItem[] process(CompileContext context, ProcessingItem[] items) { final RunConfiguration runConfiguration = CompileStepBeforeRun.getRunConfiguration(context.getCompileScope()); if (runConfiguration instanceof ModuleBasedConfiguration) { return run(context, items, (ModuleBasedConfiguration)runConfiguration); } return make(context, items); } private static ProcessingItem[] run(CompileContext context, ProcessingItem[] items, ModuleBasedConfiguration configuration) { final Module module = configuration.getConfigurationModule().getModule(); if (module == null) { context.addMessage(CompilerMessageCategory.ERROR, HaxeBundle.message("no.module.for.run.configuration", configuration.getName()), null, -1, -1); return ProcessingItem.EMPTY_ARRAY; } HaxeCommonCompilerUtil.CompilationContext compilationContext = createCompilationContext(context, module, configuration); if (compileModule(context, module, compilationContext)) { final int index = findProcessingItemIndexByModule(items, configuration.getConfigurationModule()); if (index != -1) { return new ProcessingItem[]{items[index]}; } } return ProcessingItem.EMPTY_ARRAY; } private static ProcessingItem[] make(CompileContext context, ProcessingItem[] items) { final List<ProcessingItem> result = new ArrayList<ProcessingItem>(); for (ProcessingItem processingItem : items) { if (!(processingItem instanceof MyProcessingItem)) { continue; } final MyProcessingItem myProcessingItem = (MyProcessingItem)processingItem; if (compileModule(context, myProcessingItem.myModule, createCompilationContext(context, myProcessingItem.myModule, null))) { result.add(processingItem); } } return result.toArray(new ProcessingItem[result.size()]); } private static boolean compileModule(final CompileContext context, Module module, @NotNull final HaxeCommonCompilerUtil.CompilationContext compilationContext) { /* if ((skipBuildMap.get(module) != null) && (skipBuildMap.get(module).booleanValue())) { return false; } */ if (!ModuleUtil.getModuleType(module).equals(HaxeModuleType.getInstance())) { return true; } boolean compiled = HaxeCommonCompilerUtil.compile(compilationContext); if (!compiled) { context.addMessage(CompilerMessageCategory.ERROR, "Compilation failed", null, 0, 0); } return compiled; } private static HaxeCommonCompilerUtil.CompilationContext createCompilationContext(final CompileContext context, final Module module, ModuleBasedConfiguration configuration) { final HaxeModuleSettings settings = HaxeModuleSettings.getInstance(module); final boolean isDebug = ExecutorRegistry.getInstance() .isStarting(context.getProject(), DefaultDebugExecutor.EXECUTOR_ID, HaxeDebugRunner.HAXE_DEBUG_RUNNER_ID); final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); final Sdk sdk = moduleRootManager.getSdk(); if (sdk == null) { context.addMessage(CompilerMessageCategory.ERROR, HaxeBundle.message("no.sdk.for.module", module.getName()), null, -1, -1); return null; } HaxeTestsConfiguration haxeTestsConfiguration = null; if(configuration != null && configuration instanceof HaxeTestsConfiguration) { haxeTestsConfiguration = (HaxeTestsConfiguration)configuration; } final HaxeTestsConfiguration finalHaxeTestsConfiguration = haxeTestsConfiguration; return new HaxeCommonCompilerUtil.CompilationContext() { private String myErrorRoot; @NotNull @Override public HaxeModuleSettingsBase getModuleSettings() { return settings; } @Override public String getModuleName() { return module.getName(); } @Override public String getCompilationClass() { return getIsTestBuild() ? finalHaxeTestsConfiguration.getRunnerClass() : getModuleSettings().getMainClass(); } @Override public String getOutputFileName() { return getFileNameWithCurrentExtension(getModuleSettings().getOutputFileName()); } @Override public Boolean getIsTestBuild() { return finalHaxeTestsConfiguration != null; } @Override public void errorHandler(String message) { context.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1); } @Override public void warningHandler(String message) { context.addMessage(CompilerMessageCategory.WARNING, message, null, -1, -1); } @Override public void infoHandler(String message) { context.addMessage(CompilerMessageCategory.INFORMATION, message, null, -1, -1); } public void statisticsHandler(String message) { context.addMessage(CompilerMessageCategory.INFORMATION, message, null, -1, -1); } @Override public void log(String message) { LOG.debug(message); } @Override public String getSdkName() { return sdk.getName(); } @Override public String getSdkHomePath() { return sdk.getHomePath(); } @Override public String getHaxelibPath() { SdkAdditionalData data = sdk.getSdkAdditionalData(); return data instanceof HaxeSdkAdditionalDataBase ? ((HaxeSdkAdditionalDataBase)data).getHaxelibPath() : null; } @Override public boolean isDebug() { return isDebug; } @Override public List<String> getSourceRoots() { final List<String> result = new ArrayList<String>(); for (VirtualFile sourceRoot : OrderEnumerator.orderEntries(module).recursively().withoutSdk().exportedOnly().sources().getRoots()) { result.add(sourceRoot.getPath()); } for (VirtualFile sourceRoot : OrderEnumerator.orderEntries(module).librariesOnly().getSourceRoots()) { result.add(sourceRoot.getPath()); } return result; } @Override public String getCompileOutputPath() { final CompilerModuleExtension moduleExtension = CompilerModuleExtension.getInstance(module); final String outputUrl = moduleExtension != null ? moduleExtension.getCompilerOutputUrl() : null; return VfsUtilCore.urlToPath(outputUrl); } @Override public void setErrorRoot(String root) { myErrorRoot = root; } @Override public String getErrorRoot() { return (myErrorRoot != null) ? myErrorRoot : PathUtil.getParentPath(module.getModuleFilePath()); } @Override public void handleOutput(String[] lines) { HaxeCompilerUtil.fillContext(context, getErrorRoot(), lines); } @Override public HaxeTarget getHaxeTarget() { //actually only neko target is supported for tests return getIsTestBuild() ? HaxeTarget.NEKO : getModuleSettings().getHaxeTarget(); } private String getFileNameWithCurrentExtension(String fileName) { if (getHaxeTarget() != null) { return getHaxeTarget().getTargetFileNameWithExtension(FileUtil.getNameWithoutExtension(fileName)); } return fileName; } @Override public String getModuleDirPath() { return PathUtil.getParentPath(module.getModuleFilePath()); } }; } private static int findProcessingItemIndexByModule(ProcessingItem[] items, RunConfigurationModule moduleConfiguration) { final Module module = moduleConfiguration.getModule(); if (module == null || module.getModuleFile() == null) { return -1; } for (int i = 0; i < items.length; ++i) { if (module.getModuleFile().equals(items[i].getFile())) { return i; } } return -1; } @Override public ValidityState createValidityState(DataInput in) throws IOException { return new EmptyValidityState(); } private static class MyProcessingItem implements ProcessingItem { private final Module myModule; private MyProcessingItem(Module module) { myModule = module; } @NotNull public VirtualFile getFile() { return myModule.getModuleFile(); } public ValidityState getValidityState() { return new EmptyValidityState(); } } }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.gaap.v20180529.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ModifySecurityRuleRequest extends AbstractModel{ /** * Rule ID */ @SerializedName("RuleId") @Expose private String RuleId; /** * Rule name: up to 30 characters. The extra characters will be truncated. */ @SerializedName("AliasName") @Expose private String AliasName; /** * Security policy ID */ @SerializedName("PolicyId") @Expose private String PolicyId; /** * Get Rule ID * @return RuleId Rule ID */ public String getRuleId() { return this.RuleId; } /** * Set Rule ID * @param RuleId Rule ID */ public void setRuleId(String RuleId) { this.RuleId = RuleId; } /** * Get Rule name: up to 30 characters. The extra characters will be truncated. * @return AliasName Rule name: up to 30 characters. The extra characters will be truncated. */ public String getAliasName() { return this.AliasName; } /** * Set Rule name: up to 30 characters. The extra characters will be truncated. * @param AliasName Rule name: up to 30 characters. The extra characters will be truncated. */ public void setAliasName(String AliasName) { this.AliasName = AliasName; } /** * Get Security policy ID * @return PolicyId Security policy ID */ public String getPolicyId() { return this.PolicyId; } /** * Set Security policy ID * @param PolicyId Security policy ID */ public void setPolicyId(String PolicyId) { this.PolicyId = PolicyId; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "RuleId", this.RuleId); this.setParamSimple(map, prefix + "AliasName", this.AliasName); this.setParamSimple(map, prefix + "PolicyId", this.PolicyId); } }
/* Copyright (C) 2018 Chris Deter 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 de.mach.tools.neodesigner.core; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import de.mach.tools.neodesigner.core.category.CategoryTranslator; import de.mach.tools.neodesigner.core.datamodel.Domain.DomainId; import de.mach.tools.neodesigner.core.datamodel.Field; import de.mach.tools.neodesigner.core.datamodel.ForeignKey; import de.mach.tools.neodesigner.core.datamodel.Index; import de.mach.tools.neodesigner.core.datamodel.Table; import de.mach.tools.neodesigner.core.datamodel.impl.FieldImpl; import de.mach.tools.neodesigner.core.datamodel.impl.ForeignKeyImpl; import de.mach.tools.neodesigner.core.datamodel.impl.IndexImpl; import de.mach.tools.neodesigner.core.datamodel.impl.TableImpl; import de.mach.tools.neodesigner.inex.ImportTask; import de.mach.tools.neodesigner.inex.nimport.ImportJsonTask; public class TestUtil { static Map<String, String> getCatList() { final Map<String, String> categoryToName = new HashMap<>(); categoryToName.put("0,0", "Cat0"); categoryToName.put("1", "Cat1"); categoryToName.put("1,1", "Cat1a"); categoryToName.put("1,2", "Cat1b"); categoryToName.put("1,3", "Cat1c"); categoryToName.put("1,4", "Cat1d"); categoryToName.put("1,5", "Cate"); return categoryToName; } static Table getExampleTable() { final Table t = new TableImpl("ExampleTable"); final Table reft = new TableImpl("ExampleRefTable"); t.setCategory("1,1"); final Field f = new FieldImpl("Feld", DomainId.STRING, 10, true, "", t); final Field f2 = new FieldImpl("FeldZwei", DomainId.AMOUNT, 0, true, "", t); final Field f3 = new FieldImpl("FeldDrei", DomainId.DATE, 0, false, "", t); final Index i = new IndexImpl("XIF10" + "BlaBlub", t); final Index i2 = new IndexImpl("XIE10" + "TestIndex", t); final Index xpk = new IndexImpl("XPKTable", t); xpk.addField(f2); final ForeignKey fk = new ForeignKeyImpl("R_10", t); t.addField(f); t.addField(f2); t.addField(f3); i.addField(f); i.addField(f2); i2.addField(f2); i2.addField(f3); fk.setIndex(i); fk.setRefTable(reft); reft.addField(new FieldImpl("FeldZwei", DomainId.AMOUNT, 0, true, "", t)); reft.getRefForeignKeys().add(fk); // fk.getIndex().setAltName("Feld", "FeldZwei"); t.getIndizies().add(i2); t.getIndizies().add(i); t.getForeignKeys().add(fk); t.setXpk(xpk); return t; } public static List<Table> getTableList() { final List<Table> lt = new ArrayList<>(); for (int j = 0; j < 5; j++) { final Table t = new TableImpl("Table" + j); t.setCategory("1," + j); final Field f = new FieldImpl("Feld" + j, DomainId.STRING, 10, true, "", t); final Field f2 = new FieldImpl("FeldZwei" + j, DomainId.AMOUNT, 0, true, "", t); final Field f3 = new FieldImpl("FeldDrei" + j, DomainId.DATE, 0, false, "", t); final Index i = new IndexImpl("XIF10" + j + "BlaBlub", t); final Index i2 = new IndexImpl("XIE10" + j + "TestIndex", t); final Index xpk = new IndexImpl("XPKTable" + j, t); xpk.addField(f2); final ForeignKey fk = new ForeignKeyImpl("R_10" + j, t); t.addField(f); // Feld 3 ist vor Feld 2 t.addField(f3); t.addField(f2); i.addField(f); i2.addField(f); fk.setIndex(i); fk.setRefTable(t); fk.setFkOrder(f, 1); // fk.getIndex().setAltName("Feld" + j, "FeldZwei" + j); t.getIndizies().add(i2); t.getIndizies().add(i); t.getForeignKeys().add(fk); t.setXpk(xpk); lt.add(t); } return lt; } public static Model getDatamodel() { ConfigSaver catConfig = new MockConfigSaver(); String jsonCsv = "{\"tables\":[{\"n\":\"TABLE0\",\"cat\":\"0,0\",\"fl\":[{\"n\":\"FELD0\",\"dom\":\"String\",\"l\":50,\"isnull\":false},{\"n\":\"FELDZWEI0\",\"dom\":\"Counter\",\"isnull\":false},{\"n\":\"FELDDREI0\",\"dom\":\"Date\",\"isnull\":true}],\"xpk\":{\"n\":\"XPKTABLE0\",\"unique\":true,\"fl\":[\"FELDZWEI0\"]},\"il\":[{\"n\":\"XIE100TESTINDEX\",\"unique\":false,\"fl\":[\"FELD0\"]},{\"n\":\"XIF100BLABLUB\",\"unique\":false,\"fl\":[\"FELD0\"]}],\"fkl\":[{\"n\":\"R_100\",\"rt\":\"TABLE0\",\"fl\":[\"FELD0\"]}]},{\"n\":\"TABLE1\",\"cat\":\"0,0\",\"fl\":[{\"n\":\"FELD1\",\"dom\":\"String\",\"l\":50,\"isnull\":false},{\"n\":\"FELDZWEI1\",\"dom\":\"Counter\",\"isnull\":false},{\"n\":\"FELDDREI1\",\"dom\":\"Date\",\"isnull\":true}],\"xpk\":{\"n\":\"XPKTABLE1\",\"unique\":true,\"fl\":[\"FELDZWEI1\"]},\"il\":[{\"n\":\"XIE101TESTINDEX\",\"unique\":false,\"fl\":[\"FELD1\"]},{\"n\":\"XIF101BLABLUB\",\"unique\":false,\"fl\":[\"FELD1\"]}],\"fkl\":[{\"n\":\"R_101\",\"rt\":\"TABLE1\",\"fl\":[\"FELD1\"]}]},{\"n\":\"TABLE2\",\"cat\":\"10,1\",\"fl\":[{\"n\":\"FELD2\",\"dom\":\"String\",\"l\":50,\"isnull\":false},{\"n\":\"FELDZWEI2\",\"dom\":\"Counter\",\"isnull\":false},{\"n\":\"FELDDREI2\",\"dom\":\"Date\",\"isnull\":true}],\"xpk\":{\"n\":\"XPKTABLE2\",\"unique\":true,\"fl\":[\"FELDZWEI2\"]},\"il\":[{\"n\":\"XIE102TESTINDEX\",\"unique\":false,\"fl\":[\"FELD2\"]},{\"n\":\"XIF102BLABLUB\",\"unique\":false,\"fl\":[\"FELD2\"]}],\"fkl\":[{\"n\":\"R_102\",\"rt\":\"TABLE2\",\"fl\":[\"FELD2\"]}]},{\"n\":\"TABLE3\",\"cat\":\"0,0\",\"fl\":[{\"n\":\"FELD3\",\"dom\":\"String\",\"l\":50,\"isnull\":false},{\"n\":\"FELDZWEI3\",\"dom\":\"Counter\",\"isnull\":false},{\"n\":\"FELDDREI3\",\"dom\":\"Date\",\"isnull\":true}],\"xpk\":{\"n\":\"XPKTABLE3\",\"unique\":true,\"fl\":[\"FELDZWEI3\"]},\"il\":[{\"n\":\"XIE103TESTINDEX\",\"unique\":false,\"fl\":[\"FELD3\"]},{\"n\":\"XIF103BLABLUB\",\"unique\":false,\"fl\":[\"FELD3\"]}],\"fkl\":[{\"n\":\"R_103\",\"rt\":\"TABLE3\",\"fl\":[\"FELD3\"]}]},{\"n\":\"TABLE4\",\"cat\":\"0,0\",\"fl\":[{\"n\":\"FELD4\",\"dom\":\"String\",\"l\":50,\"isnull\":false},{\"n\":\"FELDZWEI4\",\"dom\":\"Counter\",\"isnull\":false},{\"n\":\"FELDDREI4\",\"dom\":\"Date\",\"isnull\":true}],\"xpk\":{\"n\":\"XPKTABLE4\",\"unique\":true,\"fl\":[\"FELDZWEI4\"]},\"il\":[{\"n\":\"XIE104TESTINDEX\",\"unique\":false,\"fl\":[\"FELD4\"]},{\"n\":\"XIF104BLABLUB\",\"unique\":false,\"fl\":[\"FELD4\"]}],\"fkl\":[{\"n\":\"R_104\",\"rt\":\"TABLE4\",\"fl\":[\"FELD4\"]}]}],\"categories\":[{\"id\":\"0\",\"n\":\"BeispielUeberschrift\"},{\"id\":\"0,0\",\"n\":\"BeispielKategorie\"},{\"id\":\"10\",\"n\":\"BeispielUeberschrift2\"},{\"id\":\"10,1\",\"n\":\"BeispielKategorie2\"}]}"; ImportTask it = new ImportJsonTask(new CategoryTranslator(catConfig), jsonCsv); it.startImport(); final Model model = new ModelImpl(new MockConfigSaver(), catConfig); model.importTables(it.getList()); return model; } }
package org.shapleyvalue.application.impl.fraud; import static org.junit.Assert.*; import java.util.Map; import org.junit.Test; import org.shapleyvalue.application.facade.CoalitionStrategy; import org.shapleyvalue.application.facade.ShapleyApplicationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FraudRuleApplicationTest { private final Logger logger = LoggerFactory.getLogger(FraudRuleApplicationTest.class); @Test public void testEvaluationOneRule() { FraudRuleApplication evaluation = new FraudRuleApplication.FraudRuleApplicationBuilder() .addRule("Rule1", 1) .build(); Map<String,Double> output = evaluation.calculate(); double phiRule1 = output.get("Rule1"); assertEquals(phiRule1, 1.0, 0.01); } @Test public void testEvaluationTwoRules() { FraudRuleApplication evaluation = new FraudRuleApplication.FraudRuleApplicationBuilder() .addRule("Rule1", 1) .addRule("Rule2", 1) .build(); Map<String,Double> output = evaluation.calculate(); double phiRule1 = output.get("Rule1"); double phiRule2 = output.get("Rule2"); assertEquals(phiRule1, 0.5, 0.01); assertEquals(phiRule2, 0.5, 0.01); } @Test public void testEvaluationFourRules() { FraudRuleApplication evaluation = new FraudRuleApplication.FraudRuleApplicationBuilder() .addRule("Rule1", 1,2,3) .addRule("Rule2", 1,2,3) .addRule("Rule3", 1,2,3) .addRule("Rule4", 4) .build(); Map<String,Double> output = evaluation.calculate(); double phiRule1 = output.get("Rule1"); double phiRule2 = output.get("Rule2"); double phiRule3 = output.get("Rule3"); double phiRule4 = output.get("Rule4"); assertEquals(phiRule1, 0.25, 0.01); assertEquals(phiRule2, 0.25, 0.01); assertEquals(phiRule3, 0.25, 0.01); assertEquals(phiRule4, 0.25, 0.01); } @Test public void testEvaluationFourRulesPerStep() throws ShapleyApplicationException { FraudRuleApplication evaluation = new FraudRuleApplication.FraudRuleApplicationBuilder() .addRule("Rule1", 1,2,3) .addRule("Rule2", 1,2,3) .addRule("Rule3", 1,2,3) .addRule("Rule4", 4) .build(); Map<String,Double> output =null; while(!evaluation.isLastCoalitionReached()) { output = evaluation.calculate(1); } double phiRule1 = output.get("Rule1"); double phiRule2 = output.get("Rule2"); double phiRule3 = output.get("Rule3"); double phiRule4 = output.get("Rule4"); assertEquals(phiRule1, 0.25, 0.01); assertEquals(phiRule2, 0.25, 0.01); assertEquals(phiRule3, 0.25, 0.01); assertEquals(phiRule4, 0.25, 0.01); } @Test public void testEvaluationXXXRules() throws ShapleyApplicationException { FraudRuleApplication evaluation = new FraudRuleApplication.FraudRuleApplicationBuilder() .addRule("Rule1", 1,2,3,4,5,7,9) .addRule("Rule2", 1,3,6,8) .addRule("Rule3", 1,2,7) .addRule("Rule4", 1,9) .addRule("Rule5", 2) .addRule("Rule6", 1,2) .addRule("Rule7", 3) .addRule("Rule8", 9) .addRule("Rule9", 1,8) .build(); for(int i=1; i<10;i++) { Map<String,Double> output = evaluation.calculate(10_000,CoalitionStrategy.RANDOM); logger.info("OUTPUT {}",output); double phiRule1 = output.get("Rule1"); double phiRule2 = output.get("Rule2"); logger.info("loop {}",i); logger.info("phiRule1={}",String.format("%.3f", phiRule1)); logger.info("phiRule2={}",String.format("%.3f", phiRule2)); } } @Test public void testIsLastCoalitionReachedFalse() throws ShapleyApplicationException { FraudRuleApplication evaluation = new FraudRuleApplication.FraudRuleApplicationBuilder() .addRule("Rule1", 1,2,3) .addRule("Rule2", 1,2,3) .build(); assertFalse(evaluation.isLastCoalitionReached()); } @Test public void testIsLastCoalitionReachedTrue() throws ShapleyApplicationException { FraudRuleApplication evaluation = new FraudRuleApplication.FraudRuleApplicationBuilder() .addRule("Rule1", 1,2,3) .addRule("Rule2", 1,2,3) .build(); assertFalse(evaluation.isLastCoalitionReached()); evaluation.calculate(1); assertFalse(evaluation.isLastCoalitionReached()); evaluation.calculate(1); assertTrue(evaluation.isLastCoalitionReached()); } }
/** * This software is released as part of the Pumpernickel project. * All com.pump resources in the Pumpernickel project are distributed under the * MIT License: * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt * More information about the Pumpernickel project is available here: * https://mickleness.github.io/pumpernickel/ */ package com.pump.io; import com.pump.data.AbstractAttributeDataImpl; import com.pump.data.Key; import com.pump.swing.Cancellable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.util.*; import java.util.Map.Entry; public class DirectoryCopyTask extends AbstractAttributeDataImpl implements Cancellable { static final Key<File> KEY_SOURCE_DIRECTORY = new Key<>(File.class, "srcDir"); static final Key<File> KEY_DEST_DIRECTORY = new Key<>(File.class, "destDir"); static final Key<Boolean> KEY_DELETE_EXTRA_DEST_FILES = new Key<>( Boolean.class, "deleteExtraDestFiles"); static final Key<Boolean> KEY_CANCELLED = new Key<>(Boolean.class, "cancelled"); static final Key<Boolean> KEY_FINISHED = new Key<>(Boolean.class, "finished"); static final Key<Integer> KEY_TOTAL_FILES_TO_COPY = new Key<>(Integer.class, "totalFileCount"); static final Key<Integer> KEY_CURRENT_FILES_COPIED = new Key<>( Integer.class, "currentFileCount"); static final Key<Long> KEY_CURRENT_BYTES_COPIED = new Key<>(Long.class, "currentBytesCopied"); static final Key<File> KEY_CURRENT_FILE = new Key<>(File.class, "currentFile"); static final Key<Long> KEY_TOTAL_BYTES_TO_COPY = new Key<>(Long.class, "totalBytesCopied"); static final Key<Throwable> KEY_THROWABLE = new Key<>(Throwable.class, "throwable"); private static final long serialVersionUID = 1L; final transient List<ActionListener> cancelListeners = new LinkedList<>(); final transient List<ActionListener> finishListeners = new LinkedList<>(); transient Thread workerThread; public DirectoryCopyTask(File srcDir, File dstDir, boolean deleteExtraDestFiles) { if (!srcDir.isDirectory()) { throw new IllegalArgumentException("srcDir must be a directory (" + srcDir.getAbsolutePath() + ")"); } if (dstDir.exists() && !dstDir.isDirectory()) { throw new IllegalArgumentException("dstDir must be a directory (" + dstDir.getAbsolutePath() + ")"); } setAttribute(KEY_CURRENT_FILES_COPIED, 0); setAttribute(KEY_TOTAL_FILES_TO_COPY, 0); setAttribute(KEY_CURRENT_BYTES_COPIED, 0L); setAttribute(KEY_TOTAL_BYTES_TO_COPY, 0L); setAttribute(KEY_FINISHED, Boolean.FALSE); setAttribute(KEY_CANCELLED, Boolean.FALSE); setAttribute(KEY_SOURCE_DIRECTORY, srcDir); setAttribute(KEY_DEST_DIRECTORY, dstDir); setAttribute(KEY_DELETE_EXTRA_DEST_FILES, deleteExtraDestFiles); workerThread = new Thread(new WorkerRunnable(this)); workerThread.start(); addPropertyChangeListener(KEY_CANCELLED.getName(), evt -> { for (ActionListener l : cancelListeners .toArray(new ActionListener[0])) { try { l.actionPerformed( new ActionEvent(DirectoryCopyTask.this, 0, "cancelled")); } catch (Exception e) { Thread.currentThread() .getUncaughtExceptionHandler() .uncaughtException( Thread.currentThread(), e); } } }); addPropertyChangeListener(KEY_FINISHED.getName(), evt -> { for (ActionListener l : finishListeners .toArray(new ActionListener[0])) { try { l.actionPerformed(new ActionEvent( DirectoryCopyTask.this, 0, "finished")); } catch (Exception e) { Thread.currentThread() .getUncaughtExceptionHandler() .uncaughtException( Thread.currentThread(), e); } } }); } @Override public void cancel() { setAttribute(KEY_CANCELLED, true); } @Override public boolean isCancelled() { return Boolean.TRUE.equals(getAttribute(KEY_CANCELLED)); } @Override public boolean isFinished() { return Boolean.TRUE.equals(getAttribute(KEY_FINISHED)); } @Override public void addCancelListener(ActionListener l) { cancelListeners.add(l); } @Override public void addFinishListener(ActionListener l) { finishListeners.add(l); } @Override public void removeCancelListener(ActionListener l) { cancelListeners.remove(l); } @Override public void removeFinishListener(ActionListener l) { finishListeners.remove(l); } void incrementProgress(long fileSize, File copiedFile) { getAttributeLock().writeLock().lock(); try { int fileCount = getAttribute(KEY_CURRENT_FILES_COPIED); long byteCount = getAttribute(KEY_CURRENT_BYTES_COPIED); setAttribute(KEY_CURRENT_FILE, copiedFile); setAttribute(KEY_CURRENT_FILES_COPIED, fileCount + 1); setAttribute(KEY_CURRENT_BYTES_COPIED, byteCount + fileSize); } finally { getAttributeLock().writeLock().unlock(); } } void incrementWorkload(long fileSize) { getAttributeLock().writeLock().lock(); try { int fileCount = getAttribute(KEY_TOTAL_FILES_TO_COPY); long byteCount = getAttribute(KEY_TOTAL_BYTES_TO_COPY); setAttribute(KEY_TOTAL_FILES_TO_COPY, fileCount + 1); setAttribute(KEY_TOTAL_BYTES_TO_COPY, byteCount + fileSize); } finally { getAttributeLock().writeLock().unlock(); } } /** * Block until this task is complete. */ public void join() throws Exception { workerThread.join(); Throwable t = getThrowable(); if (t instanceof Exception) {throw (Exception) t;} if (t instanceof Error) {throw (Error) t;} } public Throwable getThrowable() { return getAttribute(KEY_THROWABLE); } void setThrowable(Throwable t) { setAttribute(KEY_THROWABLE, t); } static class WorkerRunnable implements Runnable { final DirectoryCopyTask task; final File src; final File dst; final Map<File, Long> filesToCopy = new HashMap<>(); public WorkerRunnable(DirectoryCopyTask task) { this.task = task; src = task.getAttribute(KEY_SOURCE_DIRECTORY); dst = task.getAttribute(KEY_DEST_DIRECTORY); } @Override public void run() { try { index(); copyFiles(); } catch (IOException e) { task.setThrowable(e); task.cancel(); } } private void copyFiles() throws IOException { String srcPath = src.getAbsolutePath(); String dstPath = dst.getAbsolutePath(); for (Entry<File, Long> entry : filesToCopy.entrySet()) { File srcFile = entry.getKey(); String filePath = srcFile.getAbsolutePath(); if (filePath.startsWith(srcPath)) { String relPath = filePath.substring(srcPath.length()); String destFilePath = dstPath + relPath; File destFile = new File(destFilePath); IOUtils.copy(srcFile, destFile); task.incrementProgress(entry.getValue(), entry.getKey()); } } } /** * Prepares this job. Populate filesToCopy and update the # of files and * bytes to copy. */ private void index() throws IOException { if (task.getAttribute(KEY_DELETE_EXTRA_DEST_FILES)) { indexAndDelete(src, dst); } else { index(src, dst); } } private void index(File src, File dst) throws IOException { for (File child : src.listFiles()) { File dstChild = new File(dst, child.getName()); if (child.isDirectory()) { if (dstChild.exists()) { if (!dstChild.isDirectory()) { throw new IOException("the file " + dstChild.getAbsolutePath() + " exists as a file, but this operation expects a directory"); } } else { FileUtils.mkdir(dstChild); } index(child, dstChild); } else { if (dstChild.getName().equals(".DS_Store")) {continue;} Collection<String> terms = Arrays.asList( "BufferedAnimationPanel.java", "edit2_control_zoom_normal.png", "edit2_control_zoom_normal@2x.png", "tooltip_back_bottom.png", "tooltip_back_bottom@2x.png", "tooltip_back_bottom_arrow.png", "tooltip_back_bottom_arrow@2x.png", "tooltip_back_bottom_left.png", "tooltip_back_bottom_left@2x.png", "tooltip_back_bottom_right.png", "tooltip_back_bottom_right@2x.png", "tooltip_back_left.png", "tooltip_back_left@2x.png", "tooltip_back_left_arrow.png", "tooltip_back_left_arrow@2x.png", "tooltip_back_middle.png", "tooltip_back_middle@2x.png", "tooltip_back_right.png", "tooltip_back_right@2x.png", "tooltip_back_right_arrow.png", "tooltip_back_right_arrow@2x.png", "tooltip_back_top_arrow.png", "tooltip_back_top_arrow@2x.png", "trayIcon.png", "frame_icon.png", "Equations.java"); if (terms.contains(dstChild.getName())) {continue;} if (dstChild.exists()) { if (IOUtils.equals(child, dstChild)) { continue; } // if we use indexAndDelete we can delete/overwrite dst // files, but this operation never deletes data // If we ever add a way to prompt the user with q's, // this is a good candidate throw new IOException("a file named " + child.getName() + " already exists at " + dst.getAbsolutePath()); } enqueue(child); } } } private Map<String, File> getFiles(File dir) { Map<String, File> returnValue = new HashMap<>(); for (File child : dir.listFiles()) { returnValue.put(child.getName(), child); } return returnValue; } private void enqueue(File srcFile) { long size = srcFile.length(); task.incrementWorkload(size); filesToCopy.put(srcFile, size); } private void indexAndDelete(File src, File dst) throws IOException { Map<String, File> srcFiles = getFiles(src); Map<String, File> dstFiles = getFiles(dst); for (Entry<String, File> srcEntry : srcFiles.entrySet()) { File dstFile = dstFiles.remove(srcEntry.getKey()); if (dstFile == null) { enqueue(srcEntry.getValue()); } else if (dstFile.isDirectory()) { // if we reach this point: maybe we should add a way to // prompt the user for feedback? this could be very harmful. throw new IOException("will not delete directory " + dstFile.getAbsolutePath() + " to copy file " + srcEntry.getValue().getName()); } else if (IOUtils.equals(srcEntry.getValue(), dstFile)) { // continue; } else { // the files are different if (!dstFile.delete()) { throw new IOException("File.delete() failed for " + dstFile.getAbsolutePath()); } enqueue(srcEntry.getValue()); } } for (File dstFile : dstFiles.values()) { if (!dstFile.delete()) { throw new IOException("File.delete() failed for " + dstFile.getAbsolutePath()); } } } } }