code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package me.vilsol.nmswrapper.wraps.unparsed; import me.vilsol.nmswrapper.NMSWrapper; import me.vilsol.nmswrapper.reflections.ReflectiveClass; import me.vilsol.nmswrapper.reflections.ReflectiveMethod; import me.vilsol.nmswrapper.wraps.NMSItemStack; import me.vilsol.nmswrapper.wraps.NMSWorld; import java.util.Random; @ReflectiveClass(name = "BlockCommand") public class NMSBlockCommand extends NMSBlockContainer { public NMSBlockCommand(Object nmsObject){ super(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.BlockCommand#a(java.util.Random) */ @ReflectiveMethod(name = "a", types = {Random.class}) public int a(Random random){ return (int) NMSWrapper.getInstance().exec(nmsObject, random); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.BlockCommand#b() */ @ReflectiveMethod(name = "b", types = {}) public int b(){ return (int) NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.BlockCommand#doPhysics(net.minecraft.server.v1_9_R1.World, net.minecraft.server.v1_9_R1.BlockPosition, net.minecraft.server.v1_9_R1.IBlockData, net.minecraft.server.v1_9_R1.Block) */ @ReflectiveMethod(name = "doPhysics", types = {NMSWorld.class, NMSBlockPosition.class, NMSIBlockData.class, NMSBlock.class}) public void doPhysics(NMSWorld world, NMSBlockPosition blockPosition, NMSIBlockData iBlockData, NMSBlock block){ NMSWrapper.getInstance().exec(nmsObject, world, blockPosition, iBlockData, block); } /** * @see net.minecraft.server.v1_9_R1.BlockCommand#fromLegacyData(int) */ @ReflectiveMethod(name = "fromLegacyData", types = {int.class}) public NMSIBlockData fromLegacyData(int i){ return (NMSIBlockData) NMSWrapper.getInstance().createApplicableObject(NMSWrapper.getInstance().exec(nmsObject, i)); } /** * @see net.minecraft.server.v1_9_R1.BlockCommand#getPlacedState(net.minecraft.server.v1_9_R1.World, net.minecraft.server.v1_9_R1.BlockPosition, net.minecraft.server.v1_9_R1.EnumDirection, float, float, float, int, net.minecraft.server.v1_9_R1.EntityLiving) */ @ReflectiveMethod(name = "getPlacedState", types = {NMSWorld.class, NMSBlockPosition.class, NMSEnumDirection.class, float.class, float.class, float.class, int.class, NMSEntityLiving.class}) public NMSIBlockData getPlacedState(NMSWorld world, NMSBlockPosition blockPosition, NMSEnumDirection enumDirection, float f, float f1, float f2, int i, NMSEntityLiving entityLiving){ return (NMSIBlockData) NMSWrapper.getInstance().createApplicableObject(NMSWrapper.getInstance().exec(nmsObject, world, blockPosition, enumDirection, f, f1, f2, i, entityLiving)); } /** * @see net.minecraft.server.v1_9_R1.BlockCommand#getStateList() */ @ReflectiveMethod(name = "getStateList", types = {}) public NMSBlockStateList getStateList(){ return new NMSBlockStateList(NMSWrapper.getInstance().exec(nmsObject)); } /** * @see net.minecraft.server.v1_9_R1.BlockCommand#interact(net.minecraft.server.v1_9_R1.World, net.minecraft.server.v1_9_R1.BlockPosition, net.minecraft.server.v1_9_R1.IBlockData, net.minecraft.server.v1_9_R1.EntityHuman, net.minecraft.server.v1_9_R1.EnumDirection, float, float, float) */ @ReflectiveMethod(name = "interact", types = {NMSWorld.class, NMSBlockPosition.class, NMSIBlockData.class, NMSEntityHuman.class, NMSEnumDirection.class, float.class, float.class, float.class}) public boolean interact(NMSWorld world, NMSBlockPosition blockPosition, NMSIBlockData iBlockData, NMSEntityHuman entityHuman, NMSEnumDirection enumDirection, float f, float f1, float f2){ return (boolean) NMSWrapper.getInstance().exec(nmsObject, world, blockPosition, iBlockData, entityHuman, enumDirection, f, f1, f2); } /** * @see net.minecraft.server.v1_9_R1.BlockCommand#isComplexRedstone() */ @ReflectiveMethod(name = "isComplexRedstone", types = {}) public boolean isComplexRedstone(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.BlockCommand#l(net.minecraft.server.v1_9_R1.World, net.minecraft.server.v1_9_R1.BlockPosition) */ @ReflectiveMethod(name = "l", types = {NMSWorld.class, NMSBlockPosition.class}) public int l(NMSWorld world, NMSBlockPosition blockPosition){ return (int) NMSWrapper.getInstance().exec(nmsObject, world, blockPosition); } /** * @see net.minecraft.server.v1_9_R1.BlockCommand#postPlace(net.minecraft.server.v1_9_R1.World, net.minecraft.server.v1_9_R1.BlockPosition, net.minecraft.server.v1_9_R1.IBlockData, net.minecraft.server.v1_9_R1.EntityLiving, net.minecraft.server.v1_9_R1.ItemStack) */ @ReflectiveMethod(name = "postPlace", types = {NMSWorld.class, NMSBlockPosition.class, NMSIBlockData.class, NMSEntityLiving.class, NMSItemStack.class}) public void postPlace(NMSWorld world, NMSBlockPosition blockPosition, NMSIBlockData iBlockData, NMSEntityLiving entityLiving, NMSItemStack itemStack){ NMSWrapper.getInstance().exec(nmsObject, world, blockPosition, iBlockData, entityLiving, itemStack); } /** * @see net.minecraft.server.v1_9_R1.BlockCommand#toLegacyData(net.minecraft.server.v1_9_R1.IBlockData) */ @ReflectiveMethod(name = "toLegacyData", types = {NMSIBlockData.class}) public int toLegacyData(NMSIBlockData iBlockData){ return (int) NMSWrapper.getInstance().exec(nmsObject, iBlockData); } }
Vilsol/NMSWrapper
src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSBlockCommand.java
Java
apache-2.0
5,654
/* * 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.ads.googleads.v10.services; import com.google.ads.googleads.v10.services.stub.CustomInterestServiceStubSettings; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.ClientSettings; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import java.io.IOException; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link CustomInterestServiceClient}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li> The default service address (googleads.googleapis.com) and default port (443) are used. * <li> Credentials are acquired automatically through Application Default Credentials. * <li> Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the total timeout of mutateCustomInterests to 30 seconds: * * <pre>{@code * CustomInterestServiceSettings.Builder customInterestServiceSettingsBuilder = * CustomInterestServiceSettings.newBuilder(); * customInterestServiceSettingsBuilder * .mutateCustomInterestsSettings() * .setRetrySettings( * customInterestServiceSettingsBuilder * .mutateCustomInterestsSettings() * .getRetrySettings() * .toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)) * .build()); * CustomInterestServiceSettings customInterestServiceSettings = * customInterestServiceSettingsBuilder.build(); * }</pre> */ @Generated("by gapic-generator-java") public class CustomInterestServiceSettings extends ClientSettings<CustomInterestServiceSettings> { /** Returns the object with the settings used for calls to mutateCustomInterests. */ public UnaryCallSettings<MutateCustomInterestsRequest, MutateCustomInterestsResponse> mutateCustomInterestsSettings() { return ((CustomInterestServiceStubSettings) getStubSettings()).mutateCustomInterestsSettings(); } public static final CustomInterestServiceSettings create(CustomInterestServiceStubSettings stub) throws IOException { return new CustomInterestServiceSettings.Builder(stub.toBuilder()).build(); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return CustomInterestServiceStubSettings.defaultExecutorProviderBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return CustomInterestServiceStubSettings.getDefaultEndpoint(); } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return CustomInterestServiceStubSettings.getDefaultServiceScopes(); } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return CustomInterestServiceStubSettings.defaultCredentialsProviderBuilder(); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return CustomInterestServiceStubSettings.defaultGrpcTransportProviderBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return CustomInterestServiceStubSettings.defaultTransportChannelProvider(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return CustomInterestServiceStubSettings.defaultApiClientHeaderProviderBuilder(); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected CustomInterestServiceSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); } /** Builder for CustomInterestServiceSettings. */ public static class Builder extends ClientSettings.Builder<CustomInterestServiceSettings, Builder> { protected Builder() throws IOException { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(CustomInterestServiceStubSettings.newBuilder(clientContext)); } protected Builder(CustomInterestServiceSettings settings) { super(settings.getStubSettings().toBuilder()); } protected Builder(CustomInterestServiceStubSettings.Builder stubSettings) { super(stubSettings); } private static Builder createDefault() { return new Builder(CustomInterestServiceStubSettings.newBuilder()); } public CustomInterestServiceStubSettings.Builder getStubSettingsBuilder() { return ((CustomInterestServiceStubSettings.Builder) getStubSettings()); } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods( getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); return this; } /** Returns the builder for the settings used for calls to mutateCustomInterests. */ public UnaryCallSettings.Builder<MutateCustomInterestsRequest, MutateCustomInterestsResponse> mutateCustomInterestsSettings() { return getStubSettingsBuilder().mutateCustomInterestsSettings(); } @Override public CustomInterestServiceSettings build() throws IOException { return new CustomInterestServiceSettings(this); } } }
googleads/google-ads-java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/CustomInterestServiceSettings.java
Java
apache-2.0
7,392
package com.oneone.uuu.coolweather; import android.app.Fragment; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.oneone.uuu.coolweather.db.City; import com.oneone.uuu.coolweather.db.County; import com.oneone.uuu.coolweather.db.Province; import com.oneone.uuu.coolweather.util.HttpUtil; import com.oneone.uuu.coolweather.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by uuu on 17-8-15. */ public class ChooseAreaFragment extends Fragment { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private Button backButton; private ListView listView; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); private List<Province> provinceList; private List<City> cityList; private List<County> countyList; private Province selectedProvince; private City selectedCity; private int currentLevel; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View view = inflater.inflate(R.layout.choose_area,container,false); titleText = (TextView) view.findViewById(R.id.title_text); backButton = (Button) view.findViewById(R.id.back_button); listView = (ListView) view.findViewById(R.id.list_view); adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1,dataList); listView.setAdapter(adapter); return view; } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent,View view,int position,long id){ if(currentLevel == LEVEL_PROVINCE){ selectedProvince = provinceList.get(position); queryCities(); }else if(currentLevel == LEVEL_CITY){ selectedCity = cityList.get(position); queryCounties(); }else if(currentLevel == LEVEL_COUNTY){ String weatherId = countyList.get(position).getWeatherId(); if(getActivity() instanceof MainActivity){ Intent intent = new Intent(getActivity(),WeatherActivity.class); intent.putExtra("weather_id",weatherId); startActivity(intent); getActivity().finish(); }else if(getActivity() instanceof WeatherActivity){ WeatherActivity activity = (WeatherActivity)getActivity(); activity.drawerLayout.closeDrawers(); activity.swipeRefresh.setRefreshing(true); activity.requestWeather(weatherId); } } } }); backButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ if(currentLevel == LEVEL_COUNTY){ queryCities(); }else if(currentLevel == LEVEL_CITY){ queryProvinces(); } } }); queryProvinces(); } private void queryProvinces(){ titleText.setText("中国"); backButton.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); if(provinceList.size()>0){ dataList.clear(); for(Province province : provinceList){ dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; }else { String adress = "http://guolin.tech/api/china"; queryFromServer(adress,"province"); } } private void queryCities(){ titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); cityList = DataSupport.where("provinceid = ?",String.valueOf(selectedProvince.getId())).find(City.class); if(cityList.size()>0){ dataList.clear(); for(City city: cityList){ dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_CITY; }else { int provinceCode = selectedProvince.getProvinceCode(); String address = "http://guolin.tech/api/china/"+provinceCode; queryFromServer(address,"city"); } } private void queryCounties(){ titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); countyList = DataSupport.where("cityid = ?",String.valueOf(selectedCity.getId())).find(County.class); if(countyList.size()>0){ dataList.clear(); for(County county :countyList){ dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_COUNTY; }else { int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); String address = "http://guolin.tech/api/china/"+provinceCode +"/"+cityCode; queryFromServer(address,"county"); } } private void queryFromServer(String address, final String type){ showProgressDialog(); HttpUtil.sendOkHttpRequest(address, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException{ String responseText = response.body().string(); boolean result = false; if("province".equals(type)){ result = Utility.handleProvinceResponse(responseText); }else if("city".equals(type)){ result = Utility.handleCityResponse(responseText,selectedProvince.getId()); }else if("county".equals(type)){ result = Utility.handleCountyResponse(responseText,selectedCity.getId()); } if(result){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if("province".equals(type)){ queryProvinces(); }else if("city".equals(type)){ queryCities(); }else if("county".equals(type)){ queryCounties(); } } }); } } @Override public void onFailure(Call call, IOException e){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show(); } }); } }); } private void showProgressDialog(){ if(progressDialog == null){ progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } private void closeProgressDialog(){ if(progressDialog!=null){ progressDialog.dismiss(); } } }
hehai2017/coolweather
app/src/main/java/com/oneone/uuu/coolweather/ChooseAreaFragment.java
Java
apache-2.0
8,548
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.eks.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.eks.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DescribeIdentityProviderConfigResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeIdentityProviderConfigResultJsonUnmarshaller implements Unmarshaller<DescribeIdentityProviderConfigResult, JsonUnmarshallerContext> { public DescribeIdentityProviderConfigResult unmarshall(JsonUnmarshallerContext context) throws Exception { DescribeIdentityProviderConfigResult describeIdentityProviderConfigResult = new DescribeIdentityProviderConfigResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return describeIdentityProviderConfigResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("identityProviderConfig", targetDepth)) { context.nextToken(); describeIdentityProviderConfigResult.setIdentityProviderConfig(IdentityProviderConfigResponseJsonUnmarshaller.getInstance().unmarshall( context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return describeIdentityProviderConfigResult; } private static DescribeIdentityProviderConfigResultJsonUnmarshaller instance; public static DescribeIdentityProviderConfigResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DescribeIdentityProviderConfigResultJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-eks/src/main/java/com/amazonaws/services/eks/model/transform/DescribeIdentityProviderConfigResultJsonUnmarshaller.java
Java
apache-2.0
3,092
package cn.elvea.platform.core.socket.interceptor; import lombok.extern.slf4j.Slf4j; import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.stereotype.Component; /** * WebSocketChannelInterceptor * * @author elvea * @since 0.0.1 */ @Slf4j @Component public class WebSocketChannelInterceptor implements ChannelInterceptor { }
elveahuang/platform
platform-modules/platform-core-biz/src/main/java/cn/elvea/platform/core/socket/interceptor/WebSocketChannelInterceptor.java
Java
apache-2.0
369
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.core.server.cluster.ha; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl; import org.apache.activemq.artemis.core.server.impl.ColocatedActivation; import org.apache.activemq.artemis.core.server.impl.LiveActivation; public class ColocatedPolicy implements HAPolicy<LiveActivation> { /*live stuff*/ private boolean requestBackup = ActiveMQDefaultConfiguration.isDefaultHapolicyRequestBackup(); private int backupRequestRetries = ActiveMQDefaultConfiguration.getDefaultHapolicyBackupRequestRetries(); private long backupRequestRetryInterval = ActiveMQDefaultConfiguration.getDefaultHapolicyBackupRequestRetryInterval(); private int maxBackups = ActiveMQDefaultConfiguration.getDefaultHapolicyMaxBackups(); private int backupPortOffset = ActiveMQDefaultConfiguration.getDefaultHapolicyBackupPortOffset(); /*backup stuff*/ private List<String> excludedConnectors = new ArrayList<>(); private BackupPolicy backupPolicy; private HAPolicy<LiveActivation> livePolicy; public ColocatedPolicy(boolean requestBackup, int backupRequestRetries, long backupRequestRetryInterval, int maxBackups, int backupPortOffset, List<String> excludedConnectors, HAPolicy livePolicy, BackupPolicy backupPolicy) { this.requestBackup = requestBackup; this.backupRequestRetries = backupRequestRetries; this.backupRequestRetryInterval = backupRequestRetryInterval; this.maxBackups = maxBackups; this.backupPortOffset = backupPortOffset; this.excludedConnectors = excludedConnectors; this.livePolicy = livePolicy; this.backupPolicy = backupPolicy; } @Override public String getBackupGroupName() { final HAPolicy<LiveActivation> livePolicy = this.livePolicy; if (livePolicy == null) { return null; } return livePolicy.getBackupGroupName(); } @Override public String getScaleDownGroupName() { return null; } @Override public boolean isSharedStore() { return backupPolicy.isSharedStore(); } @Override public boolean isBackup() { return false; } @Override public LiveActivation createActivation(ActiveMQServerImpl server, boolean wasLive, Map<String, Object> activationParams, ActiveMQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception { return new ColocatedActivation(server, this, livePolicy.createActivation(server, wasLive, activationParams, shutdownOnCriticalIO)); } @Override public boolean canScaleDown() { return false; } @Override public String getScaleDownClustername() { return null; } public boolean isRequestBackup() { return requestBackup; } public void setRequestBackup(boolean requestBackup) { this.requestBackup = requestBackup; } public int getBackupRequestRetries() { return backupRequestRetries; } public void setBackupRequestRetries(int backupRequestRetries) { this.backupRequestRetries = backupRequestRetries; } public long getBackupRequestRetryInterval() { return backupRequestRetryInterval; } public void setBackupRequestRetryInterval(long backupRequestRetryInterval) { this.backupRequestRetryInterval = backupRequestRetryInterval; } public int getMaxBackups() { return maxBackups; } public void setMaxBackups(int maxBackups) { this.maxBackups = maxBackups; } public int getBackupPortOffset() { return backupPortOffset; } public void setBackupPortOffset(int backupPortOffset) { this.backupPortOffset = backupPortOffset; } public List<String> getExcludedConnectors() { return excludedConnectors; } public void setExcludedConnectors(List<String> excludedConnectors) { this.excludedConnectors = excludedConnectors; } public HAPolicy<LiveActivation> getLivePolicy() { return livePolicy; } public void setLivePolicy(HAPolicy<LiveActivation> livePolicy) { this.livePolicy = livePolicy; } public BackupPolicy getBackupPolicy() { return backupPolicy; } public void setBackupPolicy(BackupPolicy backupPolicy) { this.backupPolicy = backupPolicy; } }
andytaylor/activemq-artemis
artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ha/ColocatedPolicy.java
Java
apache-2.0
5,516
package com.github.czyzby.reinvent.websocket.sample.client; import com.github.czyzby.reinvent.shared.networking.Packet; import com.github.czyzby.reinvent.websocket.client.WebSocketClient; import com.github.czyzby.reinvent.websocket.client.util.WebSockets; import com.github.czyzby.reinvent.websocket.sample.shared.CallbackPacket; import com.github.czyzby.reinvent.websocket.sample.shared.MessagePacket; /** Main entry point of example client application. * * @author MJ */ public class SimpleWebSocketClient { private final WebSocketClient<Packet<?>> client; public SimpleWebSocketClient() { client = new MyWebSocketClient(); client.setListener(new MyWebSocketListener(client)); client.initiate(); } public void connect() { client.connect(WebSockets.toWebSocketUrl("localhost", 8880)); System.out.println("We've connected to: " + client.getUrl()); } public void sayHelloToTheServer() { client.sendKeepAlivePacket(); System.out.println("Sending message..."); client.send(new MessagePacket("Hello from client!")); System.out.println("Asking for response..."); client.send(new CallbackPacket()); } public void disconnect() { client.close(); client.destroy(); } public static void main(final String... args) throws Exception { final SimpleWebSocketClient client = new SimpleWebSocketClient(); client.connect(); client.sayHelloToTheServer(); Thread.sleep(1000); System.out.println("OK, we're done."); client.disconnect(); System.exit(0); } }
czyzby/reinvent
tests/src/com/github/czyzby/reinvent/websocket/sample/client/SimpleWebSocketClient.java
Java
apache-2.0
1,642
package br.com.caelum.leilao.dominio; import java.util.Calendar; public class Pagamento { private double valor; private Calendar data; public Pagamento(double valor, Calendar data) { this.valor = valor; this.data = data; } public double getValor() { return valor; } public Calendar getData() { return data; } }
wesleyegberto/courses-projects
java/java-tests/mock-java/src/main/java/br/com/caelum/leilao/dominio/Pagamento.java
Java
apache-2.0
330
// // Copyright 2016 Cityzen Data // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.warp10.script.fwt.wavelets; import io.warp10.script.fwt.Wavelet; public class Wavelet_db11 extends Wavelet { private static final int transformWavelength = 2; private static final double[] scalingDeComposition = new double[] { 4.494274277236352e-06, -3.463498418698379e-05, 5.443907469936638e-05, 0.00024915252355281426, -0.0008930232506662366, -0.00030859285881515924, 0.004928417656058778, -0.0033408588730145018, -0.015364820906201324, 0.02084090436018004, 0.03133509021904531, -0.06643878569502022, -0.04647995511667613, 0.14981201246638268, 0.06604358819669089, -0.27423084681792875, -0.16227524502747828, 0.41196436894789695, 0.6856867749161785, 0.44989976435603013, 0.1440670211506196, 0.01869429776147044, }; private static final double[] waveletDeComposition = new double[] { -0.01869429776147044, 0.1440670211506196, -0.44989976435603013, 0.6856867749161785, -0.41196436894789695, -0.16227524502747828, 0.27423084681792875, 0.06604358819669089, -0.14981201246638268, -0.04647995511667613, 0.06643878569502022, 0.03133509021904531, -0.02084090436018004, -0.015364820906201324, 0.0033408588730145018, 0.004928417656058778, 0.00030859285881515924, -0.0008930232506662366, -0.00024915252355281426, 5.443907469936638e-05, 3.463498418698379e-05, 4.494274277236352e-06, }; private static final double[] scalingReConstruction = new double[] { 0.01869429776147044, 0.1440670211506196, 0.44989976435603013, 0.6856867749161785, 0.41196436894789695, -0.16227524502747828, -0.27423084681792875, 0.06604358819669089, 0.14981201246638268, -0.04647995511667613, -0.06643878569502022, 0.03133509021904531, 0.02084090436018004, -0.015364820906201324, -0.0033408588730145018, 0.004928417656058778, -0.00030859285881515924, -0.0008930232506662366, 0.00024915252355281426, 5.443907469936638e-05, -3.463498418698379e-05, 4.494274277236352e-06, }; private static final double[] waveletReConstruction = new double[] { 4.494274277236352e-06, 3.463498418698379e-05, 5.443907469936638e-05, -0.00024915252355281426, -0.0008930232506662366, 0.00030859285881515924, 0.004928417656058778, 0.0033408588730145018, -0.015364820906201324, -0.02084090436018004, 0.03133509021904531, 0.06643878569502022, -0.04647995511667613, -0.14981201246638268, 0.06604358819669089, 0.27423084681792875, -0.16227524502747828, -0.41196436894789695, 0.6856867749161785, -0.44989976435603013, 0.1440670211506196, -0.01869429776147044, }; static { // // Reverse the arrays as we do convolutions // reverse(scalingDeComposition); reverse(waveletDeComposition); } private static final void reverse(double[] array) { int i = 0; int j = array.length - 1; while (i < j) { double tmp = array[i]; array[i] = array[j]; array[j] = tmp; i++; j--; } } public int getTransformWavelength() { return transformWavelength; } public int getMotherWavelength() { return waveletReConstruction.length; } public double[] getScalingDeComposition() { return scalingDeComposition; } public double[] getWaveletDeComposition() { return waveletDeComposition; } public double[] getScalingReConstruction() { return scalingReConstruction; } public double[] getWaveletReConstruction() { return waveletReConstruction; } }
StevenLeRoux/warp10-platform
warp10/src/main/java/io/warp10/script/fwt/wavelets/Wavelet_db11.java
Java
apache-2.0
3,926
package edu.washington.nsre.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; public class StringUtil { public static String string2stringkey(String str) { str = Stemmer.stem(str); return str.trim().replaceAll("\\s", "_").toLowerCase(); } public static String string2stringkeystrict(String str) { return str.trim().replaceAll("\\s", "_").toLowerCase(); } public static String removeParentheses(String a) { char[] ach = a.toCharArray(); StringBuilder sb = new StringBuilder(); int stackdepth = 0; for (int i = 0; i < ach.length; i++) { if (ach[i] == '(') { stackdepth++; } else if (ach[i] == ')' && stackdepth > 0) { stackdepth--; } else if (stackdepth == 0) { sb.append(ach[i]); } } return sb.toString(); } public static String removeNonAscii(String raw, String torep) { return raw.replaceAll("[^\\x00-\\x7F]", ""); } public static String removeBlanket(String a, char blanket1, char blanket2) { char[] ach = a.toCharArray(); StringBuilder sb = new StringBuilder(); int stackdepth = 0; for (int i = 0; i < ach.length; i++) { if (ach[i] == blanket1) { stackdepth++; } else if (ach[i] == blanket2 && stackdepth > 0) { stackdepth--; if (stackdepth == 0) { sb.append(" "); } } else if (stackdepth == 0) { if (ach[i] == ' ') { sb.append("_"); } else { sb.append(ach[i]); } } } return sb.toString(); } public static List<String> sortAndRemoveDuplicate(List<String> list) { HashSet<String> temp = new HashSet<String>(); for (String a : list) { temp.add(a.toLowerCase()); } ArrayList<String> result = new ArrayList<String>(); result.addAll(temp); Collections.sort(result); // String previous = ""; // Iterator<String> it = list.iterator(); // while(it.hasNext()){ // String cur = it.next(); // if(cur.equals(previous)){ // it.remove(); // }else{ // previous = cur; // } // } return result; } public static List<String> tokenize(String str, char[] stopChar) { List<String> result = new ArrayList<String>(); HashSet<Character> stopCharSet = new HashSet<Character>(); for (char a : stopChar) stopCharSet.add(a); char[] cs = str.toCharArray(); int bufferStart = 0; for (int i = 0; i < cs.length; i++) { if (stopCharSet.contains(cs[i])) { addWord(result, bufferStart, i, str); bufferStart = i + 1;// give up this char because it is stop char } else if (Character.isUpperCase(cs[i])) { if (i > 0 && Character.isLowerCase(cs[i - 1])) { addWord(result, bufferStart, i, str); bufferStart = i; } } else if (Character.isLowerCase(cs[i])) { // if two previous characters are both Upper case, then shoot // the word if (i > 1 && Character.isUpperCase(cs[i - 1]) && Character.isUpperCase(cs[i - 2])) { addWord(result, bufferStart, i, str); bufferStart = i; } } else { // joke haha } } addWord(result, bufferStart, cs.length, str); return result; } public static List<String> tokenize(String str) { return tokenize(str, new char[] { ' ', '\t' }); } private static void addWord(List<String> list, int start, int end, String str) { if (end > start) list.add(str.substring(start, end)); } public static int numOfShareWords(List<String> sortedList1, List<String> sortedList2) { int i = 0, j = 0, num = 0; while (i < sortedList1.size() && j < sortedList2.size()) { String a = sortedList1.get(i); String b = sortedList2.get(j); int c = a.compareTo(b); if (c == 0) { num++; i++; j++; } else if (c < 0) { i++; } else { j++; } } return num; } /** * Config: 0: toLowerCase; 1: removeStop; 2: stem * */ public static int numOfShareWords(String str1, String str2, boolean[] config) { List<String> l1 = tokenize(str1, new char[] { ' ', '_' }); List<String> l2 = tokenize(str2, new char[] { ' ', '_' }); return numOfShareWords(l1, l2, config); } public static List<String> getSharedWords(String str1, String str2, boolean[] config) { List<String> l1 = tokenize(str1, new char[] { ' ', '_' }); List<String> l2 = tokenize(str2, new char[] { ' ', '_' }); List<String> temp1 = new ArrayList<String>(); List<String> temp2 = new ArrayList<String>(); listconvert(l1, temp1, config); listconvert(l2, temp2, config); List<String> shared = new ArrayList<String>(); int i = 0, j = 0, num = 0; while (i < temp1.size() && j < temp2.size()) { String a = temp1.get(i); String b = temp2.get(j); /** 0: to lower case */ if (config[0]) { a = a.toLowerCase(); b = b.toLowerCase(); } int c = a.compareTo(b); if (c == 0) { num++; i++; j++; shared.add(a); } else if (c < 0) { i++; } else { j++; } } return shared; } /** * Config: 0: toLowerCase; 1: removeStop; 2: stem * */ public static int numOfShareWords(List<String> wordlist1, List<String> wordlist2, boolean[] config) { List<String> temp1 = new ArrayList<String>(); List<String> temp2 = new ArrayList<String>(); listconvert(wordlist1, temp1, config); listconvert(wordlist2, temp2, config); // Collections.sort(temp1); // Collections.sort(temp2); int i = 0, j = 0, num = 0; while (i < temp1.size() && j < temp2.size()) { String a = temp1.get(i); String b = temp2.get(j); /** 0: to lower case */ if (config[0]) { a = a.toLowerCase(); b = b.toLowerCase(); } int c = a.compareTo(b); if (c == 0) { num++; i++; j++; } else if (c < 0) { i++; } else { j++; } } return num; } private static void listconvert(List<String> original, List<String> converted, boolean[] config) { HashSet<String> temp = new HashSet(); for (String w : original) { // remove stop words if (config[1]) { if (RemoveStopwords.isStop(w)) { continue; } } // convert to lower case if (config[0]) { w = w.toLowerCase(); } // stem if (config[2]) { w = Stemmer.stem(w); } temp.add(w); } converted.addAll(temp); Collections.sort(converted); } public static int numOfShareWords(String str1, String str2, int[] par_return) { str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); List<String> l1 = tokenize(str1, new char[] { ' ', '_' }); List<String> l2 = tokenize(str2, new char[] { ' ', '_' }); List<String> sorted_l1 = new ArrayList<String>(); List<String> sorted_l2 = new ArrayList<String>(); for (String a : l1) sorted_l1.add(a.toLowerCase()); for (String a : l2) sorted_l2.add(a.toLowerCase()); Collections.sort(sorted_l1); Collections.sort(sorted_l2); par_return[0] = l1.size(); par_return[1] = l2.size(); return numOfShareWords(sorted_l1, sorted_l2); } public static int numOfShareWords(String str1, String str2) { List<String> l1 = tokenize(str1, new char[] { ' ', '_' }); List<String> l2 = tokenize(str2, new char[] { ' ', '_' }); l1 = sortUniq(l1); l2 = sortUniq(l2); return numOfShareWords(l1, l2); } public static int numOfShareWords(String str1, String str2, char[] split) { List<String> l1 = tokenize(str1, split); List<String> l2 = tokenize(str2, split); l1 = sortUniq(l1); l2 = sortUniq(l2); return numOfShareWords(l1, l2); } public static double cosineSimilarity(String[] tkn0, String[] tkn1) { HashMap<String, int[]> map = new HashMap<String, int[]>(); for (int i = 0; i < tkn0.length; i++) { String t = tkn0[i].toLowerCase(); if (!map.containsKey(t)) { map.put(t, new int[2]); } map.get(t)[0]++; // if (!RemoveStopwords.isStop(t)) { // // } } for (int i = 0; i < tkn1.length; i++) { String t = tkn1[i].toLowerCase(); if (!map.containsKey(t)) { map.put(t, new int[2]); } map.get(t)[1]++; // if (!RemoveStopwords.isStop(t)) { // // } } double dot = 0; double norma = 0; double normb = 0; for (Entry<String, int[]> e : map.entrySet()) { int[] v = e.getValue(); dot += v[0] * v[1]; norma += v[0] * v[0]; normb += v[1] * v[1]; } norma = Math.sqrt(norma); normb = Math.sqrt(normb); if (dot == 0) { return 0; } else { return dot / (norma * normb); } } public static List<String> sortUniq(List<String> list) { HashSet<String> tmp = new HashSet<String>(); for (String a : list) { tmp.add(a); } List<String> result = new ArrayList<String>(); result.addAll(tmp); Collections.sort(result); return result; } public static int numOfShareInteger(List<Integer> sortedList1, List<Integer> sortedList2) { int i = 0, j = 0, num = 0; while (i < sortedList1.size() && j < sortedList2.size()) { int a = sortedList1.get(i); int b = sortedList2.get(j); int c = a - b; if (c == 0) { num++; i++; j++; } else if (c < 0) { i++; } else { j++; } } return num; } /** The string contains none English letters */ public static boolean doesContainLetter(String a) { char[] c = a.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] >= 'a' && c[i] <= 'z' || c[i] >= 'A' && c[i] <= 'Z') { return true; } } return false; } public static boolean isPunct(String a) { String b = a.replaceAll("\\p{Punct}", ""); if (b.length() == 0 && a.length() > 0) { return true; } else { return false; } } /** The string contains none English letters */ public static boolean containOnlyLetter(String a) { char[] c = a.toCharArray(); int letternumber = 0; for (int i = 0; i < c.length; i++) { if (c[i] >= 'a' && c[i] <= 'z' || c[i] >= 'A' && c[i] <= 'Z' || c[i] == ' ') { letternumber++; } } if (letternumber == c.length) { return true; } else { return false; } } /** The string contains none English letters */ public static String replaceNonLetter(String a, char replaceChar) { char[] c = a.toCharArray(); int letternumber = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < c.length; i++) { if (c[i] >= 'a' && c[i] <= 'z' || c[i] >= 'A' && c[i] <= 'Z' || c[i] == ' ') { sb.append(c[i]); } else { sb.append(replaceChar); } } return sb.toString(); } public static List<Integer> locateArgInTokens(String[] tokens, String[] argsplit) { List<Integer> position = new ArrayList<Integer>(); // List<String> argsplit = StringUtil.tokenize(arg); for (int i = 0; i < tokens.length; i++) { boolean isStart = true; for (int j = 0; j < argsplit.length; j++) { if (i + j >= tokens.length || !tokens[i + j].equals(argsplit[j])) { isStart = false; break; } } if (isStart) { position.add(i); } } return position; } public static String join(String[] tokens, String delimiter) { if (tokens == null) { return "null"; } if (tokens.length == 0) { return ""; } StringBuilder sb = new StringBuilder(); sb.append(tokens[0]); for (int i = 1; i < tokens.length; i++) sb.append(delimiter).append(tokens[i]); return sb.toString(); } public static String join(String[] tokens, String delimiter, int start, int end) { if (tokens == null) { return "null"; } if (tokens.length == 0) { return ""; } StringBuilder sb = new StringBuilder(); sb.append(tokens[start]); for (int i = start + 1; i < end; i++) sb.append(delimiter).append(tokens[i]); return sb.toString(); } public static String join(String delimiter, Object... tkns) { StringBuilder sb = new StringBuilder(); for (Object t : tkns) { sb.append(t.toString()).append(delimiter); } return sb.toString(); } public static String join(String[] tokens, String delimiter, int[] position) { if (tokens == null) { return "null"; } if (tokens.length == 0) { return ""; } StringBuilder sb = new StringBuilder(); sb.append(tokens[0]); position[0] = 0; for (int i = 1; i < tokens.length; i++) { position[i] = sb.length() + delimiter.length(); sb.append(delimiter).append(tokens[i]); } return sb.toString(); } public static String join(List<String> tokens, String delimiter) { if (tokens == null) { return "null"; } if (tokens.size() == 0) { return ""; } StringBuilder sb = new StringBuilder(); sb.append(tokens.get(0)); for (int i = 1; i < tokens.size(); i++) sb.append(delimiter).append(tokens.get(i)); return sb.toString(); } public static List<String> concat(String[]... arrays) { List<String> result = new ArrayList<String>(); for (String[] p : arrays) { for (String x : p) { result.add(x); } } return result; } public static String uppercaseFirstLetter(String token) { char[] chs = token.toCharArray(); chs[0] = Character.toUpperCase(chs[0]); String s = new String(chs); return s; } public static boolean isCapStartString(String a) { if (a.length() > 0) { char a0 = a.charAt(0); if (a0 <= 'Z' && a0 >= 'A') { return true; } } return false; } public static int compareStrings(String[] a, String[] b, int[] columns) { for (int i = 0; i < columns.length; i++) { int k = columns[i]; int r = a[k].compareTo(b[k]); if (r != 0) { return r; } } return 0; } public static int compareStrings(String[] a, String[] b, int[] columns, boolean[] isNumber) { for (int i = 0; i < columns.length; i++) { int k = columns[i]; int r = a[k].compareTo(b[k]); if (isNumber[i]) { r = Double.compare(Double.parseDouble(b[k]), Double.parseDouble(a[k])); } if (r != 0) { return r; } } return 0; } public static void main(String[] args) { D.p(cosineSimilarity(new String[] { "I", "am" }, new String[] { "I", "am" })); } }
zhangcongle/NewsSpikeRe
nsre2/src/main/java/edu/washington/nsre/util/StringUtil.java
Java
apache-2.0
13,780
/** * $Id: SubscriptionData.java 1835 2013-05-16 02:00:50Z shijia.wxr $ */ package com.alibaba.rocketmq.common.protocol.heartbeat; import java.util.HashSet; import java.util.Set; import com.alibaba.fastjson.annotation.JSONField; /** * 订阅 * * @author shijia.wxr<vintage.wang@gmail.com> */ public class SubscriptionData implements Comparable<SubscriptionData> { public final static String SUB_ALL = "*"; private boolean classFilterMode = false; // 主题 private String topic; // 过滤tag表达式 private String subString; private Set<String> tagsSet = new HashSet<String>(); private Set<Integer> codeSet = new HashSet<Integer>(); // 版本 private long subVersion = System.currentTimeMillis(); /** * Java过滤类,通过专有的上传接口上传到Filter Server */ @JSONField(serialize = false) private String filterClassSource; public String getFilterClassSource() { return filterClassSource; } public void setFilterClassSource(String filterClassSource) { this.filterClassSource = filterClassSource; } public SubscriptionData() { } public SubscriptionData(String topic, String subString) { super(); this.topic = topic; this.subString = subString; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getSubString() { return subString; } public void setSubString(String subString) { this.subString = subString; } public Set<String> getTagsSet() { return tagsSet; } public void setTagsSet(Set<String> tagsSet) { this.tagsSet = tagsSet; } public long getSubVersion() { return subVersion; } public void setSubVersion(long subVersion) { this.subVersion = subVersion; } public Set<Integer> getCodeSet() { return codeSet; } public void setCodeSet(Set<Integer> codeSet) { this.codeSet = codeSet; } public boolean isClassFilterMode() { return classFilterMode; } public void setClassFilterMode(boolean classFilterMode) { this.classFilterMode = classFilterMode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (classFilterMode ? 1231 : 1237); result = prime * result + ((codeSet == null) ? 0 : codeSet.hashCode()); result = prime * result + ((subString == null) ? 0 : subString.hashCode()); result = prime * result + ((tagsSet == null) ? 0 : tagsSet.hashCode()); result = prime * result + ((topic == null) ? 0 : topic.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SubscriptionData other = (SubscriptionData) obj; if (classFilterMode != other.classFilterMode) return false; if (codeSet == null) { if (other.codeSet != null) return false; } else if (!codeSet.equals(other.codeSet)) return false; if (subString == null) { if (other.subString != null) return false; } else if (!subString.equals(other.subString)) return false; if (subVersion != other.subVersion) return false; if (tagsSet == null) { if (other.tagsSet != null) return false; } else if (!tagsSet.equals(other.tagsSet)) return false; if (topic == null) { if (other.topic != null) return false; } else if (!topic.equals(other.topic)) return false; return true; } @Override public String toString() { return "SubscriptionData [classFilterMode=" + classFilterMode + ", topic=" + topic + ", subString=" + subString + ", tagsSet=" + tagsSet + ", codeSet=" + codeSet + ", subVersion=" + subVersion + "]"; } @Override public int compareTo(SubscriptionData other) { String thisValue = this.topic + "@" + this.subString; String otherValue = other.topic + "@" + other.subString; return thisValue.compareTo(otherValue); } }
liujia128/RocketMQ-Master-analyze
rocketmq-common/src/main/java/com/alibaba/rocketmq/common/protocol/heartbeat/SubscriptionData.java
Java
apache-2.0
4,555
/* * Copyright 2016 West Coast Informatics, LLC */ package com.wci.umls.server.jpa.test.content; import static org.junit.Assert.assertTrue; import org.apache.log4j.Logger; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.wci.umls.server.helpers.CopyConstructorTester; import com.wci.umls.server.helpers.EqualsHashcodeTester; import com.wci.umls.server.helpers.GetterSetterTester; import com.wci.umls.server.helpers.XmlSerializationTester; import com.wci.umls.server.jpa.ModelUnitSupport; import com.wci.umls.server.jpa.content.SemanticTypeComponentJpa; import com.wci.umls.server.jpa.helpers.IndexedFieldTester; import com.wci.umls.server.jpa.helpers.NullableFieldTester; import com.wci.umls.server.model.content.SemanticTypeComponent; /** * Unit testing for {@link SemanticTypeComponentJpa}. */ public class SemanticTypeComponentJpaUnitTest extends ModelUnitSupport { /** The model object to test. */ private SemanticTypeComponentJpa object; /** * Setup class. */ @BeforeClass public static void setupClass() { // do nothing } /** * Setup. */ @Before public void setup() { object = new SemanticTypeComponentJpa(); } /** * Test getter and setter methods of model object. * * @throws Exception the exception */ @Test public void testModelGetSet() throws Exception { Logger.getLogger(getClass()).debug("TEST testModelGetSet"); GetterSetterTester tester = new GetterSetterTester(object); tester.exclude("type"); tester.exclude("name"); tester.test(); } /** * Test equals and hascode methods. * * @throws Exception the exception */ @Test public void testModelEqualsHashcode() throws Exception { Logger.getLogger(getClass()).debug("TEST testModelEqualsHashcode"); EqualsHashcodeTester tester = new EqualsHashcodeTester(object); tester.include("suppressible"); tester.include("obsolete"); tester.include("branch"); tester.include("terminology"); tester.include("terminologyId"); tester.include("semanticType"); assertTrue(tester.testIdentityFieldEquals()); assertTrue(tester.testNonIdentityFieldEquals()); assertTrue(tester.testIdentityFieldNotEquals()); assertTrue(tester.testIdentityFieldHashcode()); assertTrue(tester.testNonIdentityFieldHashcode()); assertTrue(tester.testIdentityFieldDifferentHashcode()); } /** * Test copy constructor. * * @throws Exception the exception */ @Test public void testModelCopy() throws Exception { Logger.getLogger(getClass()).debug("TEST testModelCopy"); CopyConstructorTester tester = new CopyConstructorTester(object); assertTrue(tester.testCopyConstructor(SemanticTypeComponent.class)); } /** * Test XML serialization. * * @throws Exception the exception */ @Test public void testModelXmlSerialization() throws Exception { Logger.getLogger(getClass()).debug("TEST testModelXmlSerialization"); XmlSerializationTester tester = new XmlSerializationTester(object); assertTrue(tester.testXmlSerialization()); } /** * Test not null fields. * * @throws Exception the exception */ @Test public void testModelNotNullField() throws Exception { NullableFieldTester tester = new NullableFieldTester(object); tester.include("timestamp"); tester.include("lastModified"); tester.include("lastModifiedBy"); tester.include("suppressible"); tester.include("obsolete"); tester.include("published"); tester.include("publishable"); tester.include("terminology"); tester.include("terminologyId"); tester.include("version"); tester.include("semanticType"); tester.include("workflowStatus"); assertTrue(tester.testNotNullFields()); } /** * Test field indexing. * * @throws Exception the exception */ @Test public void testModelIndexedFields() throws Exception { Logger.getLogger(getClass()).debug("TEST testModelIndexedFields"); // Test analyzed fields // n/a // Test non analyzed fields IndexedFieldTester tester = new IndexedFieldTester(object); tester = new IndexedFieldTester(object); tester.include("id"); tester.include("lastModified"); tester.include("lastModifiedBy"); tester.include("suppressible"); tester.include("obsolete"); tester.include("published"); tester.include("publishable"); tester.include("terminologyId"); tester.include("terminology"); tester.include("version"); tester.include("semanticType"); tester.include("branch"); tester.include("workflowStatus"); assertTrue(tester.testNotAnalyzedIndexedFields()); } /** * Teardown. */ @After public void teardown() { // do nothing } /** * Teardown class. */ @AfterClass public static void teardownClass() { // do nothing } }
WestCoastInformatics/UMLS-Terminology-Server
jpa-model/src/test/java/com/wci/umls/server/jpa/test/content/SemanticTypeComponentJpaUnitTest.java
Java
apache-2.0
4,953
/** * @author Daniel Domínguez Restoy * @version 1.0 */ package uma.finalproject.support; public class Users_list_item { private String username; private String picture; private String bbdd_ID; private String group_ID; private String account; private boolean useCert; private String certificate; public Users_list_item(String name, String pic, String id, String guid, String mail, boolean cert, String certificate){ username = name; picture = pic; bbdd_ID = id; account = mail; useCert = cert; group_ID = guid; this.certificate = certificate; } public String getName(){ return username; } public String getImage(){ return picture; } public String getID(){ return bbdd_ID; } public String getAccount(){ return account; } public String getGUID(){ return group_ID; } public boolean hasCertificate(){ return useCert; } public String getCertificate(){ return certificate; } }
Drestoy/Safepoll
App files/src/uma/finalproject/support/Users_list_item.java
Java
apache-2.0
942
package com.captstudios.games.tafl.core.es.components.render; import com.artemis.Component; public class AiProcessingComponent implements Component { public float timeElapsed; public int index; @Override public void reset() { timeElapsed = 0; index = 0; } }
apotapov/tafl
core/src/com/captstudios/games/tafl/core/es/components/render/AiProcessingComponent.java
Java
apache-2.0
298
/* * 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.google.android.exoplayer2.source.dash; import android.net.Uri; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.drm.DrmInitData; import com.google.android.exoplayer2.extractor.ChunkIndex; import com.google.android.exoplayer2.extractor.Extractor; import com.google.android.exoplayer2.extractor.mkv.MatroskaExtractor; import com.google.android.exoplayer2.extractor.mp4.FragmentedMp4Extractor; import com.google.android.exoplayer2.source.chunk.ChunkExtractorWrapper; import com.google.android.exoplayer2.source.chunk.InitializationChunk; import com.google.android.exoplayer2.source.dash.manifest.DashManifest; import com.google.android.exoplayer2.source.dash.manifest.DashManifestParser; import com.google.android.exoplayer2.source.dash.manifest.Period; import com.google.android.exoplayer2.source.dash.manifest.RangedUri; import com.google.android.exoplayer2.source.dash.manifest.Representation; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DataSpec; import com.google.android.exoplayer2.upstream.HttpDataSource; import com.google.android.exoplayer2.upstream.ParsingLoadable; import com.google.android.exoplayer2.util.MimeTypes; import java.io.IOException; import java.util.List; /** * Utility methods for DASH streams. */ public final class DashUtil { /** * Loads a DASH manifest. * * @param dataSource The {@link HttpDataSource} from which the manifest should be read. * @param uri The {@link Uri} of the manifest to be read. * @return An instance of {@link DashManifest}. * @throws IOException Thrown when there is an error while loading. */ public static DashManifest loadManifest(DataSource dataSource, Uri uri) throws IOException { DataSpec dataSpec = new DataSpec(uri, DataSpec.FLAG_ALLOW_CACHING_UNKNOWN_LENGTH | DataSpec.FLAG_ALLOW_GZIP); ParsingLoadable<DashManifest> loadable = new ParsingLoadable<>(dataSource, dataSpec, C.DATA_TYPE_MANIFEST, new DashManifestParser()); loadable.load(); return loadable.getResult(); } /** * Loads {@link DrmInitData} for a given period in a DASH manifest. * * @param dataSource The {@link HttpDataSource} from which data should be loaded. * @param period The {@link Period}. * @return The loaded {@link DrmInitData}, or null if none is defined. * @throws IOException Thrown when there is an error while loading. * @throws InterruptedException Thrown if the thread was interrupted. */ public static DrmInitData loadDrmInitData(DataSource dataSource, Period period) throws IOException, InterruptedException { int primaryTrackType = C.TRACK_TYPE_VIDEO; Representation representation = getFirstRepresentation(period, primaryTrackType); if (representation == null) { primaryTrackType = C.TRACK_TYPE_AUDIO; representation = getFirstRepresentation(period, primaryTrackType); if (representation == null) { return null; } } Format manifestFormat = representation.format; Format sampleFormat = DashUtil.loadSampleFormat(dataSource, primaryTrackType, representation); return sampleFormat == null ? manifestFormat.drmInitData : sampleFormat.copyWithManifestFormatInfo(manifestFormat).drmInitData; } /** * Loads initialization data for the {@code representation} and returns the sample {@link Format}. * * @param dataSource The source from which the data should be loaded. * @param trackType The type of the representation. Typically one of the * {@link com.google.android.exoplayer2.C} {@code TRACK_TYPE_*} constants. * @param representation The representation which initialization chunk belongs to. * @return the sample {@link Format} of the given representation. * @throws IOException Thrown when there is an error while loading. * @throws InterruptedException Thrown if the thread was interrupted. */ public static Format loadSampleFormat(DataSource dataSource, int trackType, Representation representation) throws IOException, InterruptedException { ChunkExtractorWrapper extractorWrapper = loadInitializationData(dataSource, trackType, representation, false); return extractorWrapper == null ? null : extractorWrapper.getSampleFormats()[0]; } /** * Loads initialization and index data for the {@code representation} and returns the {@link * ChunkIndex}. * * @param dataSource The source from which the data should be loaded. * @param trackType The type of the representation. Typically one of the * {@link com.google.android.exoplayer2.C} {@code TRACK_TYPE_*} constants. * @param representation The representation which initialization chunk belongs to. * @return The {@link ChunkIndex} of the given representation, or null if no initialization or * index data exists. * @throws IOException Thrown when there is an error while loading. * @throws InterruptedException Thrown if the thread was interrupted. */ public static ChunkIndex loadChunkIndex(DataSource dataSource, int trackType, Representation representation) throws IOException, InterruptedException { ChunkExtractorWrapper extractorWrapper = loadInitializationData(dataSource, trackType, representation, true); return extractorWrapper == null ? null : (ChunkIndex) extractorWrapper.getSeekMap(); } /** * Loads initialization data for the {@code representation} and optionally index data then * returns a {@link ChunkExtractorWrapper} which contains the output. * * @param dataSource The source from which the data should be loaded. * @param trackType The type of the representation. Typically one of the * {@link com.google.android.exoplayer2.C} {@code TRACK_TYPE_*} constants. * @param representation The representation which initialization chunk belongs to. * @param loadIndex Whether to load index data too. * @return A {@link ChunkExtractorWrapper} for the {@code representation}, or null if no * initialization or (if requested) index data exists. * @throws IOException Thrown when there is an error while loading. * @throws InterruptedException Thrown if the thread was interrupted. */ private static ChunkExtractorWrapper loadInitializationData(DataSource dataSource, int trackType, Representation representation, boolean loadIndex) throws IOException, InterruptedException { RangedUri initializationUri = representation.getInitializationUri(); if (initializationUri == null) { return null; } ChunkExtractorWrapper extractorWrapper = newWrappedExtractor(trackType, representation.format); RangedUri requestUri; if (loadIndex) { RangedUri indexUri = representation.getIndexUri(); if (indexUri == null) { return null; } // It's common for initialization and index data to be stored adjacently. Attempt to merge // the two requests together to request both at once. requestUri = initializationUri.attemptMerge(indexUri, representation.baseUrl); if (requestUri == null) { loadInitializationData(dataSource, representation, extractorWrapper, initializationUri); requestUri = indexUri; } } else { requestUri = initializationUri; } loadInitializationData(dataSource, representation, extractorWrapper, requestUri); return extractorWrapper; } private static void loadInitializationData(DataSource dataSource, Representation representation, ChunkExtractorWrapper extractorWrapper, RangedUri requestUri) throws IOException, InterruptedException { DataSpec dataSpec = new DataSpec(requestUri.resolveUri(representation.baseUrl), requestUri.start, requestUri.length, representation.getCacheKey()); InitializationChunk initializationChunk = new InitializationChunk(dataSource, dataSpec, representation.format, C.SELECTION_REASON_UNKNOWN, null /* trackSelectionData */, extractorWrapper); initializationChunk.load(); } private static ChunkExtractorWrapper newWrappedExtractor(int trackType, Format format) { String mimeType = format.containerMimeType; boolean isWebm = mimeType.startsWith(MimeTypes.VIDEO_WEBM) || mimeType.startsWith(MimeTypes.AUDIO_WEBM); Extractor extractor = isWebm ? new MatroskaExtractor() : new FragmentedMp4Extractor(); return new ChunkExtractorWrapper(extractor, trackType, format); } private static Representation getFirstRepresentation(Period period, int type) { int index = period.getAdaptationSetIndex(type); if (index == C.INDEX_UNSET) { return null; } List<Representation> representations = period.adaptationSets.get(index).representations; return representations.isEmpty() ? null : representations.get(0); } private DashUtil() {} }
KiminRyu/ExoPlayer
library/dash/src/main/java/com/google/android/exoplayer2/source/dash/DashUtil.java
Java
apache-2.0
9,533
/** * Copyright 2014 Fernando Rincon Martin <frm.rincon@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.abstractform.core; import java.util.Iterator; import java.util.ServiceLoader; import javax.management.ServiceNotFoundException; /** * Utility class to get FormToolkit from Service Loader * * @author Fernando Rincon Martin <frm.rincon@gmail.com> * */ @SuppressWarnings("rawtypes") public class FormService { private static FormService instance; private ServiceLoader<FormToolkit> loader; private FormService() { loader = ServiceLoader.load(FormToolkit.class); } /** * Return a singleton instance * * @return The singleton instance */ public static synchronized FormService getInstance() { if (instance == null) { instance = new FormService(); } return instance; } /** * Find in the Service Loader a {@link FormToolkit} that returns the required form instance type of rendered forms * * @param implementationClass * The specific implementation class that the form toolkit must return * @return The FormToolkit that build form instances of that its specific implementation returns the given class * @throws ServiceNotFoundException * When a FormToolkit is not found */ @SuppressWarnings("unchecked") public <S> FormToolkit<S> getFormToolkit(Class<S> implementationClass) throws ServiceNotFoundException { Iterator<FormToolkit> it = loader.iterator(); FormToolkit toolkit = null; while (toolkit == null && it.hasNext()) { FormToolkit tl = it.next(); if (implementationClass.isAssignableFrom(tl.getImplementationClass())) { toolkit = tl; } } if (toolkit == null) { throw new ServiceNotFoundException(); } else { return toolkit; } } }
frincon/abstractform
org.abstractform.core/src/main/java/org/abstractform/core/FormService.java
Java
apache-2.0
2,291
package org.jetbrains.jsonProtocol; import org.jetbrains.annotations.NotNull; import org.jetbrains.io.JsonReaderEx; import java.util.Map; final class MapFactory<T> extends ObjectFactory<Map<String, T>> { private final ObjectFactory<T> valueFactory; MapFactory(@NotNull ObjectFactory<T> valueFactory) { this.valueFactory = valueFactory; } @Override public Map<String, T> read(JsonReaderEx reader) { return JsonReaders.readMap(reader, valueFactory); } }
goodwinnk/intellij-community
platform/script-debugger/protocol/protocol-reader-runtime/src/org/jetbrains/jsonProtocol/MapFactory.java
Java
apache-2.0
477
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.connectcontactlens; import javax.annotation.Generated; import com.amazonaws.ClientConfigurationFactory; import com.amazonaws.annotation.NotThreadSafe; import com.amazonaws.client.builder.AwsAsyncClientBuilder; import com.amazonaws.client.AwsAsyncClientParams; /** * Fluent builder for {@link com.amazonaws.services.connectcontactlens.AmazonConnectContactLensAsync}. Use of the * builder is preferred over using constructors of the client class. **/ @NotThreadSafe @Generated("com.amazonaws:aws-java-sdk-code-generator") public final class AmazonConnectContactLensAsyncClientBuilder extends AwsAsyncClientBuilder<AmazonConnectContactLensAsyncClientBuilder, AmazonConnectContactLensAsync> { private static final ClientConfigurationFactory CLIENT_CONFIG_FACTORY = new ClientConfigurationFactory();; /** * @return Create new instance of builder with all defaults set. */ public static AmazonConnectContactLensAsyncClientBuilder standard() { return new AmazonConnectContactLensAsyncClientBuilder(); } /** * @return Default async client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} and * {@link com.amazonaws.regions.DefaultAwsRegionProviderChain} chain */ public static AmazonConnectContactLensAsync defaultClient() { return standard().build(); } private AmazonConnectContactLensAsyncClientBuilder() { super(CLIENT_CONFIG_FACTORY); } /** * Construct an asynchronous implementation of AmazonConnectContactLensAsync using the current builder * configuration. * * @param params * Current builder configuration represented as a parameter object. * @return Fully configured implementation of AmazonConnectContactLensAsync. */ @Override protected AmazonConnectContactLensAsync build(AwsAsyncClientParams params) { return new AmazonConnectContactLensAsyncClient(params); } }
aws/aws-sdk-java
aws-java-sdk-connectcontactlens/src/main/java/com/amazonaws/services/connectcontactlens/AmazonConnectContactLensAsyncClientBuilder.java
Java
apache-2.0
2,581
/** * 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.ws.security.validate; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import org.apache.ws.security.NamePasswordCallbackHandler; import org.apache.ws.security.WSConstants; import org.apache.ws.security.WSSecurityException; import org.apache.ws.security.handler.RequestData; import org.apache.ws.security.message.token.UsernameToken; /** * This class validates a processed UsernameToken, extracted from the Credential passed to * the validate method. * Username/password validation is delegated to JAAS LoginContext. */ public class JAASUsernameTokenValidator implements Validator { private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(JAASUsernameTokenValidator.class); private String contextName = null; public void setContextName(String name) { contextName = name; } public String getContextName() { return contextName; } /** * Validate the credential argument. It must contain a non-null UsernameToken. A * CallbackHandler implementation is also required to be set. * Validator * If the password type is either digest or plaintext, it extracts a password from the * CallbackHandler and then compares the passwords appropriately. * * If the password is null it queries a hook to allow the user to validate UsernameTokens * of this type. * * @param credential the Credential to be validated * @param data the RequestData associated with the request * @throws WSSecurityException on a failed validation */ public Credential validate(Credential credential, RequestData data) throws WSSecurityException { if (credential == null || credential.getUsernametoken() == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noCredential"); } String user = null; String password = null; UsernameToken usernameToken = credential.getUsernametoken(); user = usernameToken.getName(); String pwType = usernameToken.getPasswordType(); if (log.isDebugEnabled()) { log.debug("UsernameToken user " + usernameToken.getName()); log.debug("UsernameToken password type " + pwType); } if (usernameToken.isHashed()) { log.warn("Authentication failed as hashed username token not supported"); throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION); } password = usernameToken.getPassword(); if (!WSConstants.PASSWORD_TEXT.equals(pwType)) { log.warn("Password type " + pwType + " not supported"); throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION); } if (!(user != null && user.length() > 0 && password != null && password.length() > 0)) { log.warn("User or password empty"); throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION); } try { CallbackHandler handler = getCallbackHandler(user, password); LoginContext ctx = new LoginContext(getContextName(), handler); ctx.login(); Subject subject = ctx.getSubject(); credential.setSubject(subject); } catch (LoginException ex) { log.info("Authentication failed", ex); throw new WSSecurityException( WSSecurityException.FAILED_AUTHENTICATION, null, null, ex ); } return credential; } protected CallbackHandler getCallbackHandler(String name, String password) { return new NamePasswordCallbackHandler(name, password); } }
fatfredyy/wss4j-ecc
src/main/java/org/apache/ws/security/validate/JAASUsernameTokenValidator.java
Java
apache-2.0
4,787
package de.rheinfabrik.heimdalldroid.actvities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; import de.rheinfabrik.heimdalldroid.R; import de.rheinfabrik.heimdalldroid.adapter.TraktTvListsRecyclerViewAdapter; import de.rheinfabrik.heimdalldroid.network.TraktTvApiFactory; import de.rheinfabrik.heimdalldroid.network.models.TraktTvList; import de.rheinfabrik.heimdalldroid.network.oauth2.TraktTvOauth2AccessTokenManager; import de.rheinfabrik.heimdalldroid.utils.AlertDialogFactory; import de.rheinfabrik.heimdalldroid.utils.IntentFactory; import de.rheinfabrik.heimdalldroid.utils.rx.RxAppCompatActivity; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import static rx.android.lifecycle.LifecycleObservable.bindActivityLifecycle; /** * Activity showing either the list of the user's repositories or the login screen. * You may want to move most of this code to your presenter class or view model. * For the sake of simplicity the code is inside the activity. */ public class MainActivity extends RxAppCompatActivity { // Constants private static final int AUTHORIZATION_REQUEST_CODE = 1; // Members @InjectView(R.id.recyclerView) protected RecyclerView mRecyclerView; @InjectView(R.id.toolbar) protected Toolbar mToolbar; @InjectView(R.id.swipeRefreshLayout) protected SwipeRefreshLayout mSwipeRefreshLayout; private TraktTvOauth2AccessTokenManager mTokenManager; // Activity lifecycle @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set content view setContentView(R.layout.activity_main); // Inject views ButterKnife.inject(this); // Setup toolbar setSupportActionBar(mToolbar); // Setup swipe refresh layout mSwipeRefreshLayout.setOnRefreshListener(MainActivity.this::refresh); // Setup recycler view LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(layoutManager); // Grab a new manager mTokenManager = TraktTvOauth2AccessTokenManager.from(this); // Check if we are logged in refresh(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Check if the request code is correct if (requestCode == AUTHORIZATION_REQUEST_CODE) { // Check if login was successful if (resultCode == Activity.RESULT_OK) { loadLists(); } } } // Private Api private void loadLists() { // Load the lists Observable<List<TraktTvList>> listsObservable = mTokenManager /* Grab a valid access token (automatically refreshes the token if it is expired) */ .getValidAccessToken() /* Load lists */ .concatMap(authorizationHeader -> TraktTvApiFactory.newApiService().getLists(authorizationHeader)); // Bind to lifecycle bindActivityLifecycle(lifecycle(), listsObservable) .observeOn(AndroidSchedulers.mainThread()) .subscribe(lists -> { if (lists == null || lists.isEmpty()) { handleEmptyList(); } else { handleSuccess(lists); } }, x -> handleError()); } // Start the LoginActivity. private void showLogin() { mSwipeRefreshLayout.setRefreshing(false); Intent loginIntent = IntentFactory.loginIntent(this); startActivityForResult(loginIntent, AUTHORIZATION_REQUEST_CODE); } // Shows a dialog saying that there were no lists. private void handleEmptyList() { mSwipeRefreshLayout.setRefreshing(false); AlertDialogFactory.noListsFoundDialog(this).show(); } // Show an error dialog private void handleError() { mSwipeRefreshLayout.setRefreshing(false); AlertDialogFactory.errorAlertDialog(this).show(); } // Update our recycler view private void handleSuccess(List<TraktTvList> traktTvLists) { mSwipeRefreshLayout.setRefreshing(false); mRecyclerView.setAdapter(new TraktTvListsRecyclerViewAdapter(traktTvLists)); } // Check if logged in and show either login or load lists private void refresh() { mSwipeRefreshLayout.setRefreshing(true); mTokenManager.getStorage().hasAccessToken() .observeOn(AndroidSchedulers.mainThread()) .subscribe(loggedIn -> { if (loggedIn) { loadLists(); } else { showLogin(); } }); } }
leasual/Heimdall.droid
sample/src/main/java/de/rheinfabrik/heimdalldroid/actvities/MainActivity.java
Java
apache-2.0
5,285
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2010 Oracle. All rights reserved. * * $Id: DatabaseComparatorsTest.java,v 1.18 2010/01/04 15:50:58 cwl Exp $ */ package com.sleepycat.je; import java.io.File; import java.util.Comparator; import com.sleepycat.bind.tuple.IntegerBinding; import com.sleepycat.bind.tuple.TupleBase; import com.sleepycat.bind.tuple.TupleInput; import com.sleepycat.bind.tuple.TupleOutput; import com.sleepycat.je.config.EnvironmentParams; import com.sleepycat.je.util.DualTestCase; import com.sleepycat.je.util.TestUtils; public class DatabaseComparatorsTest extends DualTestCase { private File envHome; private Environment env; private boolean DEBUG = false; public DatabaseComparatorsTest() { envHome = new File(System.getProperty(TestUtils.DEST_DIR)); } @Override public void setUp() throws Exception { super.setUp(); TestUtils.removeLogFiles("Setup", envHome, false); } @Override public void tearDown() throws Exception { super.tearDown(); } private void openEnv() throws DatabaseException { openEnv(false); } private void openEnv(boolean transactional) throws DatabaseException { EnvironmentConfig envConfig = TestUtils.initEnvConfig(); envConfig.setAllowCreate(true); envConfig.setTransactional(transactional); envConfig.setConfigParam(EnvironmentParams.ENV_CHECK_LEAKS.getName(), "true"); /* Prevent compression. */ envConfig.setConfigParam("je.env.runINCompressor", "false"); envConfig.setConfigParam("je.env.runCheckpointer", "false"); envConfig.setConfigParam("je.env.runEvictor", "false"); envConfig.setConfigParam("je.env.runCleaner", "false"); env = create(envHome, envConfig); } private Database openDb (boolean transactional, boolean dups, Class<? extends Comparator<byte[]>> btreeComparator, Class<? extends Comparator<byte[]>> dupComparator) throws DatabaseException { DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setAllowCreate(true); dbConfig.setSortedDuplicates(dups); dbConfig.setTransactional(transactional); if (btreeComparator != null) { dbConfig.setBtreeComparator(btreeComparator); } if (dupComparator != null) { dbConfig.setDuplicateComparator(dupComparator); } return env.openDatabase(null, "testDB", dbConfig); } public void testSR12517() throws Exception { openEnv(); Database db = openDb(false /*transactional*/, false /*dups*/, ReverseComparator.class, ReverseComparator.class); DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); /* Insert 5 items. */ for (int i = 0; i < 5; i++) { IntegerBinding.intToEntry(i, key); IntegerBinding.intToEntry(i, data); assertEquals(OperationStatus.SUCCESS, db.put(null, key, data)); /* Add a dup. */ IntegerBinding.intToEntry(i * 2, data); assertEquals(OperationStatus.SUCCESS, db.put(null, key, data)); } read(db); db.close(); close(env); openEnv(); db = openDb(false /*transactional*/, false /*dups*/, ReverseComparator.class, ReverseComparator.class); read(db); db.close(); close(env); env = null; } public void testDatabaseCompareKeysArgs() throws Exception { openEnv(); Database db = openDb(false /*transactional*/, false /*dups*/, null, null); DatabaseEntry entry1 = new DatabaseEntry(); DatabaseEntry entry2 = new DatabaseEntry(); try { db.compareKeys(null, entry2); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } try { db.compareKeys(entry1, null); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } try { db.compareDuplicates(null, entry2); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } try { db.compareDuplicates(entry1, null); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } IntegerBinding.intToEntry(1, entry1); try { db.compareKeys(entry1, entry2); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } try { db.compareKeys(entry2, entry1); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } try { db.compareDuplicates(entry1, entry2); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } try { db.compareDuplicates(entry2, entry1); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } entry1.setPartial(true); IntegerBinding.intToEntry(1, entry2); try { db.compareKeys(entry1, entry2); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } try { db.compareKeys(entry2, entry1); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } try { db.compareDuplicates(entry1, entry2); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } try { db.compareDuplicates(entry2, entry1); fail("should have thrown IAE"); } catch (IllegalArgumentException IAE) { } } public void testSR16816DefaultComparator() throws Exception { doTestSR16816(null, null, 1); } public void testSR16816ReverseComparator() throws Exception { doTestSR16816(ReverseComparator.class, ReverseComparator.class, -1); } private void doTestSR16816(Class btreeComparator, Class dupComparator, int expectedSign) throws Exception { openEnv(); Database db = openDb(false /*transactional*/, false /*dups*/, btreeComparator, dupComparator); DatabaseEntry entry1 = new DatabaseEntry(); DatabaseEntry entry2 = new DatabaseEntry(); IntegerBinding.intToEntry(1, entry1); IntegerBinding.intToEntry(2, entry2); assertEquals(expectedSign * -1, db.compareKeys(entry1, entry2)); assertEquals(0, db.compareKeys(entry1, entry1)); assertEquals(0, db.compareKeys(entry2, entry2)); assertEquals(expectedSign * 1, db.compareKeys(entry2, entry1)); assertEquals(expectedSign * -1, db.compareDuplicates(entry1, entry2)); assertEquals(0, db.compareDuplicates(entry1, entry1)); assertEquals(0, db.compareDuplicates(entry2, entry2)); assertEquals(expectedSign * 1, db.compareDuplicates(entry2, entry1)); db.close(); close(env); env = null; } private void read(Database db) throws DatabaseException { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); /* Iterate */ Cursor c = db.openCursor(null, null); int expected = 4; while (c.getNext(key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS) { assertEquals(expected, IntegerBinding.entryToInt(key)); expected--; if (DEBUG) { System.out.println("cursor: k=" + IntegerBinding.entryToInt(key) + " d=" + IntegerBinding.entryToInt(data)); } } assertEquals(expected, -1); c.close(); /* Retrieve 5 items */ for (int i = 0; i < 5; i++) { IntegerBinding.intToEntry(i, key); assertEquals(OperationStatus.SUCCESS, db.get(null, key, data, LockMode.DEFAULT)); assertEquals(i, IntegerBinding.entryToInt(key)); assertEquals(i * 2, IntegerBinding.entryToInt(data)); if (DEBUG) { System.out.println("k=" + IntegerBinding.entryToInt(key) + " d=" + IntegerBinding.entryToInt(data)); } } } public static class ReverseComparator implements Comparator<byte[]> { public ReverseComparator() { } public int compare(byte[] o1, byte[] o2) { DatabaseEntry arg1 = new DatabaseEntry(o1); DatabaseEntry arg2 = new DatabaseEntry(o2); int val1 = IntegerBinding.entryToInt(arg1); int val2 = IntegerBinding.entryToInt(arg2); if (val1 < val2) { return 1; } else if (val1 > val2) { return -1; } else { return 0; } } } /** * Checks that when reusing a slot and then aborting the transaction, the * original data is restored, when using a btree comparator. [#15704] * * When using partial keys to reuse a slot with a different--but equal * according to a custom comparator--key, a bug caused corruption of an * existing record after an abort. The sequence for a non-duplicate * database and a btree comparator that compares only the first integer in * a two integer key is: * * 100 Insert LN key={0,0} txn 1 * 110 Commit txn 1 * 120 Delete LN key={0,0} txn 2 * 130 Insert LN key={0,1} txn 2 * 140 Abort txn 2 * * When key {0,1} is inserted at LSN 130, it reuses the slot for {0,0} * because these two keys are considered equal by the comparator. When txn * 2 is aborted, it restores LSN 100 in the slot, but the key in the BIN * stays {0,1}. Fetching the record after the abort gives key {0,1}. */ public void testReuseSlotAbortPartialKey() throws DatabaseException { doTestReuseSlotPartialKey(false /*runRecovery*/); } /** * Same as testReuseSlotAbortPartialKey but runs recovery after the abort. */ public void testReuseSlotRecoverPartialKey() throws DatabaseException { doTestReuseSlotPartialKey(true /*runRecovery*/); } private void doTestReuseSlotPartialKey(boolean runRecovery) throws DatabaseException { openEnv(true /*transactional*/); Database db = openDb (true /*transactional*/, false /*dups*/, Partial2PartComparator.class /*btreeComparator*/, null /*dupComparator*/); DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); OperationStatus status; /* Insert key={0,0}/data={0} using auto-commit. */ status = db.put(null, entry(0, 0), entry(0)); assertSame(OperationStatus.SUCCESS, status); key = entry(0, 1); data = entry(0); status = db.getSearchBoth(null, key, data, null); assertSame(OperationStatus.SUCCESS, status); check(key, 0, 0); check(data, 0); /* Delete, insert key={0,1}/data={1}, abort. */ Transaction txn = env.beginTransaction(null, null); status = db.delete(txn, entry(0, 1)); assertSame(OperationStatus.SUCCESS, status); status = db.get(txn, entry(0, 0), data, null); assertSame(OperationStatus.NOTFOUND, status); status = db.put(txn, entry(0, 1), entry(1)); assertSame(OperationStatus.SUCCESS, status); key = entry(0, 0); data = entry(1); status = db.getSearchBoth(txn, key, data, null); assertSame(OperationStatus.SUCCESS, status); check(key, 0, 1); check(data, 1); txn.abort(); if (runRecovery) { db.close(); close(env); env = null; openEnv(true /*transactional*/); db = openDb (true /*transactional*/, false /*dups*/, Partial2PartComparator.class /*btreeComparator*/, null /*dupComparator*/); } /* Check that we rolled back to key={0,0}/data={0}. */ key = entry(0, 1); data = entry(0); status = db.getSearchBoth(null, key, data, null); assertSame(OperationStatus.SUCCESS, status); check(key, 0, 0); check(data, 0); db.close(); close(env); env = null; } /** * Same as testReuseSlotAbortPartialKey but for reuse of duplicate data * slots. [#15704] * * The sequence for a duplicate database and a duplicate comparator that * compares only the first integer in a two integer data value is: * * 100 Insert LN key={0}/data={0,0} txn 1 * 110 Insert LN key={0}/data={1,1} txn 1 * 120 Commit txn 1 * 130 Delete LN key={0}/data={0,0} txn 2 * 140 Insert LN key={0}/data={0,1} txn 2 * 150 Abort txn 2 * * When data {0,1} is inserted at LSN 140, it reuses the slot for {0,0} * because these two data values are considered equal by the comparator. * When txn 2 is aborted, it restores LSN 100 in the slot, but the data in * the DBIN stays {0,1}. Fetching the record after the abort gives data * {0,1}. */ public void testReuseSlotAbortPartialDup() throws DatabaseException { doTestReuseSlotPartialDup(false /*runRecovery*/); } /** * Same as testReuseSlotAbortPartialDup but runs recovery after the abort. */ public void testReuseSlotRecoverPartialDup() throws DatabaseException { doTestReuseSlotPartialDup(true /*runRecovery*/); } private void doTestReuseSlotPartialDup(boolean runRecovery) throws DatabaseException { openEnv(true /*transactional*/); Database db = openDb (true /*transactional*/, true /*dups*/, null /*btreeComparator*/, Partial2PartComparator.class /*dupComparator*/); DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); OperationStatus status; /* Insert key={0}/data={0,0} using auto-commit. */ Transaction txn = env.beginTransaction(null, null); status = db.put(txn, entry(0), entry(0, 0)); assertSame(OperationStatus.SUCCESS, status); status = db.put(txn, entry(0), entry(1, 1)); assertSame(OperationStatus.SUCCESS, status); txn.commit(); key = entry(0); data = entry(0, 1); status = db.getSearchBoth(null, key, data, null); assertSame(OperationStatus.SUCCESS, status); check(key, 0); check(data, 0, 0); /* Delete, insert key={0}/data={0,1}, abort. */ txn = env.beginTransaction(null, null); Cursor cursor = db.openCursor(txn, null); key = entry(0); data = entry(0, 1); status = cursor.getSearchBoth(key, data, null); assertSame(OperationStatus.SUCCESS, status); check(key, 0); check(data, 0, 0); status = cursor.delete(); assertSame(OperationStatus.SUCCESS, status); status = cursor.put(entry(0), entry(0, 1)); assertSame(OperationStatus.SUCCESS, status); key = entry(0); data = entry(0, 1); status = cursor.getSearchBoth(key, data, null); assertSame(OperationStatus.SUCCESS, status); check(key, 0); check(data, 0, 1); cursor.close(); txn.abort(); if (runRecovery) { db.close(); close(env); env = null; openEnv(true /*transactional*/); db = openDb (true /*transactional*/, true /*dups*/, null /*btreeComparator*/, Partial2PartComparator.class /*dupComparator*/); } /* Check that we rolled back to key={0,0}/data={0}. */ key = entry(0); data = entry(0, 1); status = db.getSearchBoth(null, key, data, null); assertSame(OperationStatus.SUCCESS, status); check(key, 0); check(data, 0, 0); db.close(); close(env); env = null; } /** * Check that we prohibit the case where dups are configured and the btree * comparator does not compare all bytes of the key. To support this would * require maintaining the BIN slot and DIN/DBIN.dupKey fields to be * transactionally correct. This is impractical since INs by design are * non-transctional. [#15704] */ public void testDupsWithPartialComparatorNotAllowed() throws DatabaseException { openEnv(false /*transactional*/); Database db = openDb (false /*transactional*/, true /*dups*/, Partial2PartComparator.class /*btreeComparator*/, null /*dupComparator*/); OperationStatus status; /* Insert key={0,0}/data={0} and data={1}. */ status = db.put(null, entry(0, 0), entry(0)); assertSame(OperationStatus.SUCCESS, status); try { status = db.put(null, entry(0, 1), entry(1)); fail(status.toString()); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().indexOf ("Custom Btree comparator matches two non-identical keys " + "in a Database with duplicates configured") >= 0); } db.close(); close(env); env = null; } private void check(DatabaseEntry entry, int p1) { assertEquals(4, entry.getSize()); TupleInput input = TupleBase.entryToInput(entry); assertEquals(p1, input.readInt()); } private void check(DatabaseEntry entry, int p1, int p2) { assertEquals(8, entry.getSize()); TupleInput input = TupleBase.entryToInput(entry); assertEquals(p1, input.readInt()); assertEquals(p2, input.readInt()); } /* private void dump(Database db, Transaction txn) throws DatabaseException { System.out.println("-- dump --"); DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); OperationStatus status; Cursor c = db.openCursor(txn, null); while (c.getNext(key, data, null) == OperationStatus.SUCCESS) { TupleInput keyInput = TupleBase.entryToInput(key); int keyP1 = keyInput.readInt(); int keyP2 = keyInput.readInt(); int dataVal = IntegerBinding.entryToInt(data); System.out.println("keyP1=" + keyP1 + " keyP2=" + keyP2 + " dataVal=" + dataVal); } c.close(); } */ private DatabaseEntry entry(int p1) { DatabaseEntry entry = new DatabaseEntry(); TupleOutput output = new TupleOutput(); output.writeInt(p1); TupleBase.outputToEntry(output, entry); return entry; } private DatabaseEntry entry(int p1, int p2) { DatabaseEntry entry = new DatabaseEntry(); TupleOutput output = new TupleOutput(); output.writeInt(p1); output.writeInt(p2); TupleBase.outputToEntry(output, entry); return entry; } /** * Writes two integers to the byte array. */ private void make2PartEntry(int p1, int p2, DatabaseEntry entry) { TupleOutput output = new TupleOutput(); output.writeInt(p1); output.writeInt(p2); TupleBase.outputToEntry(output, entry); } /** * Compares only the first integer in the byte arrays. */ public static class Partial2PartComparator implements Comparator<byte[]> { public int compare(byte[] o1, byte[] o2) { int val1 = new TupleInput(o1).readInt(); int val2 = new TupleInput(o2).readInt(); return val1 - val2; } } }
bjorndm/prebake
code/third_party/bdb/test/com/sleepycat/je/DatabaseComparatorsTest.java
Java
apache-2.0
20,595
/* * Copyright 2014~2015 Dan Haywood * * 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.incode.module.commchannel.fixture.scripts.scenarios; import org.apache.isis.applib.fixturescripts.DiscoverableFixtureScript; import org.apache.isis.applib.services.clock.ClockService; import org.incode.module.commchannel.dom.impl.emailaddress.T_addEmailAddress; import org.incode.module.commchannel.dom.impl.phoneorfax.T_addPhoneOrFaxNumber; import org.incode.module.commchannel.dom.impl.postaladdress.T_addPostalAddress; import org.incode.module.commchannel.dom.impl.type.CommunicationChannelType; import org.incode.module.commchannel.fixture.dom.CommChannelDemoObject; import org.incode.module.commchannel.fixture.dom.CommChannelDemoObjectMenu; import org.incode.module.commchannel.fixture.dom.CommunicationChannelOwnerLinkForDemoObject; import org.incode.module.commchannel.fixture.scripts.teardown.CommChannelDemoObjectsTearDownFixture; public class CommChannelDemoObjectsFixture extends DiscoverableFixtureScript { public CommChannelDemoObjectsFixture() { withDiscoverability(Discoverability.DISCOVERABLE); } @Override protected void execute(final ExecutionContext executionContext) { // prereqs executionContext.executeChild(this, new CommChannelDemoObjectsTearDownFixture()); final CommChannelDemoObject demoOwner = create("Foo", executionContext); wrap(addEmailAddress(demoOwner)).$$("foo@example.com", "Other Email", null); wrap(addPhoneOrFaxNumber(demoOwner)).$$(CommunicationChannelType.PHONE_NUMBER, "555 1234", "Home Number", null); wrap(addPhoneOrFaxNumber(demoOwner)).$$(CommunicationChannelType.FAX_NUMBER, "555 4321", "Work Fax", null); final CommChannelDemoObject bar = create("Bar", executionContext); wrap(addPostalAddress(demoOwner)).$$( "45", "High Street", "Oxford", null, null, "UK", "Shipping Address", null, false); final CommChannelDemoObject baz = create("Baz", executionContext); } T_addEmailAddress addEmailAddress(final CommChannelDemoObject demoOwner) { return mixin(CommunicationChannelOwnerLinkForDemoObject._addEmailAddress.class, demoOwner); } T_addPhoneOrFaxNumber addPhoneOrFaxNumber(final CommChannelDemoObject demoOwner) { return mixin(CommunicationChannelOwnerLinkForDemoObject._addPhoneOrFaxNumber.class, demoOwner); } T_addPostalAddress addPostalAddress(final CommChannelDemoObject demoOwner) { return mixin(CommunicationChannelOwnerLinkForDemoObject._addPostalAddress.class, demoOwner); } // ////////////////////////////////////// private CommChannelDemoObject create( final String name, final ExecutionContext executionContext) { return executionContext.addResult(this, wrap(commChannelDemoObjectMenu).create(name)); } // ////////////////////////////////////// @javax.inject.Inject CommChannelDemoObjectMenu commChannelDemoObjectMenu; @javax.inject.Inject ClockService clockService; }
incodehq/incode-module-commchannel
fixture/src/main/java/org/incode/module/commchannel/fixture/scripts/scenarios/CommChannelDemoObjectsFixture.java
Java
apache-2.0
3,596
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.javascript.rhino.Node; import java.util.List; import java.util.Map; import java.util.Set; /** * Tests for {@link PeepholeFoldConstants} in isolation. Tests for * the interaction of multiple peephole passes are in * {@link PeepholeIntegrationTest}. */ public final class PeepholeFoldConstantsTest extends CompilerTestCase { private boolean late; private boolean useTypes = true; @Override public void setUp() throws Exception { super.setUp(); late = false; useTypes = true; } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeFoldConstants(late, useTypes)); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 1 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } public void testUndefinedComparison1() { fold("undefined == undefined", "true"); fold("undefined == null", "true"); fold("undefined == void 0", "true"); fold("undefined == 0", "false"); fold("undefined == 1", "false"); fold("undefined == 'hi'", "false"); fold("undefined == true", "false"); fold("undefined == false", "false"); fold("undefined === undefined", "true"); fold("undefined === null", "false"); fold("undefined === void 0", "true"); foldSame("undefined == this"); foldSame("undefined == x"); fold("undefined != undefined", "false"); fold("undefined != null", "false"); fold("undefined != void 0", "false"); fold("undefined != 0", "true"); fold("undefined != 1", "true"); fold("undefined != 'hi'", "true"); fold("undefined != true", "true"); fold("undefined != false", "true"); fold("undefined !== undefined", "false"); fold("undefined !== void 0", "false"); fold("undefined !== null", "true"); foldSame("undefined != this"); foldSame("undefined != x"); fold("undefined < undefined", "false"); fold("undefined > undefined", "false"); fold("undefined >= undefined", "false"); fold("undefined <= undefined", "false"); fold("0 < undefined", "false"); fold("true > undefined", "false"); fold("'hi' >= undefined", "false"); fold("null <= undefined", "false"); fold("undefined < 0", "false"); fold("undefined > true", "false"); fold("undefined >= 'hi'", "false"); fold("undefined <= null", "false"); fold("null == undefined", "true"); fold("0 == undefined", "false"); fold("1 == undefined", "false"); fold("'hi' == undefined", "false"); fold("true == undefined", "false"); fold("false == undefined", "false"); fold("null === undefined", "false"); fold("void 0 === undefined", "true"); fold("undefined == NaN", "false"); fold("NaN == undefined", "false"); fold("undefined == Infinity", "false"); fold("Infinity == undefined", "false"); fold("undefined == -Infinity", "false"); fold("-Infinity == undefined", "false"); fold("({}) == undefined", "false"); fold("undefined == ({})", "false"); fold("([]) == undefined", "false"); fold("undefined == ([])", "false"); fold("(/a/g) == undefined", "false"); fold("undefined == (/a/g)", "false"); fold("(function(){}) == undefined", "false"); fold("undefined == (function(){})", "false"); fold("undefined != NaN", "true"); fold("NaN != undefined", "true"); fold("undefined != Infinity", "true"); fold("Infinity != undefined", "true"); fold("undefined != -Infinity", "true"); fold("-Infinity != undefined", "true"); fold("({}) != undefined", "true"); fold("undefined != ({})", "true"); fold("([]) != undefined", "true"); fold("undefined != ([])", "true"); fold("(/a/g) != undefined", "true"); fold("undefined != (/a/g)", "true"); fold("(function(){}) != undefined", "true"); fold("undefined != (function(){})", "true"); foldSame("this == undefined"); foldSame("x == undefined"); } public void testUndefinedComparison2() { fold("\"123\" !== void 0", "true"); fold("\"123\" === void 0", "false"); fold("void 0 !== \"123\"", "true"); fold("void 0 === \"123\"", "false"); } public void testUndefinedComparison3() { fold("\"123\" !== undefined", "true"); fold("\"123\" === undefined", "false"); fold("undefined !== \"123\"", "true"); fold("undefined === \"123\"", "false"); } public void testUndefinedComparison4() { fold("1 !== void 0", "true"); fold("1 === void 0", "false"); fold("null !== void 0", "true"); fold("null === void 0", "false"); fold("undefined !== void 0", "false"); fold("undefined === void 0", "true"); } public void testNullComparison1() { fold("null == undefined", "true"); fold("null == null", "true"); fold("null == void 0", "true"); fold("null == 0", "false"); fold("null == 1", "false"); fold("null == 'hi'", "false"); fold("null == true", "false"); fold("null == false", "false"); fold("null === undefined", "false"); fold("null === null", "true"); fold("null === void 0", "false"); foldSame("null === x"); foldSame("null == this"); foldSame("null == x"); fold("null != undefined", "false"); fold("null != null", "false"); fold("null != void 0", "false"); fold("null != 0", "true"); fold("null != 1", "true"); fold("null != 'hi'", "true"); fold("null != true", "true"); fold("null != false", "true"); fold("null !== undefined", "true"); fold("null !== void 0", "true"); fold("null !== null", "false"); foldSame("null != this"); foldSame("null != x"); fold("null < null", "false"); fold("null > null", "false"); fold("null >= null", "true"); fold("null <= null", "true"); fold("0 < null", "false"); fold("0 > null", "false"); fold("0 >= null", "true"); fold("true > null", "true"); fold("'hi' < null", "false"); fold("'hi' >= null", "false"); fold("null <= null", "true"); fold("null < 0", "false"); fold("null > true", "false"); fold("null < 'hi'", "false"); fold("null >= 'hi'", "false"); fold("null <= null", "true"); fold("null == null", "true"); fold("0 == null", "false"); fold("1 == null", "false"); fold("'hi' == null", "false"); fold("true == null", "false"); fold("false == null", "false"); fold("null === null", "true"); fold("void 0 === null", "false"); fold("null == NaN", "false"); fold("NaN == null", "false"); fold("null == Infinity", "false"); fold("Infinity == null", "false"); fold("null == -Infinity", "false"); fold("-Infinity == null", "false"); fold("({}) == null", "false"); fold("null == ({})", "false"); fold("([]) == null", "false"); fold("null == ([])", "false"); fold("(/a/g) == null", "false"); fold("null == (/a/g)", "false"); fold("(function(){}) == null", "false"); fold("null == (function(){})", "false"); fold("null != NaN", "true"); fold("NaN != null", "true"); fold("null != Infinity", "true"); fold("Infinity != null", "true"); fold("null != -Infinity", "true"); fold("-Infinity != null", "true"); fold("({}) != null", "true"); fold("null != ({})", "true"); fold("([]) != null", "true"); fold("null != ([])", "true"); fold("(/a/g) != null", "true"); fold("null != (/a/g)", "true"); fold("(function(){}) != null", "true"); fold("null != (function(){})", "true"); foldSame("({a:f()}) == null"); foldSame("null == ({a:f()})"); foldSame("([f()]) == null"); foldSame("null == ([f()])"); foldSame("this == null"); foldSame("x == null"); } public void testBooleanBooleanComparison() { foldSame("!x == !y"); foldSame("!x < !y"); foldSame("!x !== !y"); foldSame("!x == !x"); // foldable foldSame("!x < !x"); // foldable foldSame("!x !== !x"); // foldable } public void testBooleanNumberComparison() { foldSame("!x == +y"); foldSame("!x <= +y"); fold("!x !== +y", "true"); } public void testNumberBooleanComparison() { foldSame("+x == !y"); foldSame("+x <= !y"); fold("+x === !y", "false"); } public void testBooleanStringComparison() { foldSame("!x == '' + y"); foldSame("!x <= '' + y"); fold("!x !== '' + y", "true"); } public void testStringBooleanComparison() { foldSame("'' + x == !y"); foldSame("'' + x <= !y"); fold("'' + x === !y", "false"); } public void testNumberNumberComparison() { fold("1 > 1", "false"); fold("2 == 3", "false"); fold("3.6 === 3.6", "true"); foldSame("+x > +y"); foldSame("+x == +y"); foldSame("+x === +y"); foldSame("+x == +x"); foldSame("+x === +x"); foldSame("+x > +x"); // foldable } public void testStringStringComparison() { fold("'a' < 'b'", "true"); fold("'a' <= 'b'", "true"); fold("'a' > 'b'", "false"); fold("'a' >= 'b'", "false"); fold("+'a' < +'b'", "false"); foldSame("typeof a < 'a'"); foldSame("'a' >= typeof a"); fold("typeof a < typeof a", "false"); fold("typeof a >= typeof a", "true"); fold("typeof 3 > typeof 4", "false"); fold("typeof function() {} < typeof function() {}", "false"); fold("'a' == 'a'", "true"); fold("'b' != 'a'", "true"); foldSame("'undefined' == typeof a"); foldSame("typeof a != 'number'"); foldSame("'undefined' == typeof a"); foldSame("'undefined' == typeof a"); fold("typeof a == typeof a", "true"); fold("'a' === 'a'", "true"); fold("'b' !== 'a'", "true"); fold("typeof a === typeof a", "true"); fold("typeof a !== typeof a", "false"); foldSame("'' + x <= '' + y"); foldSame("'' + x != '' + y"); foldSame("'' + x === '' + y"); foldSame("'' + x <= '' + x"); // potentially foldable foldSame("'' + x != '' + x"); // potentially foldable foldSame("'' + x === '' + x"); // potentially foldable } public void testNumberStringComparison() { fold("1 < '2'", "true"); fold("2 > '1'", "true"); fold("123 > '34'", "true"); fold("NaN >= 'NaN'", "false"); fold("1 == '2'", "false"); fold("1 != '1'", "false"); fold("NaN == 'NaN'", "false"); fold("1 === '1'", "false"); fold("1 !== '1'", "true"); foldSame("+x > '' + y"); foldSame("+x == '' + y"); fold("+x !== '' + y", "true"); } public void testStringNumberComparison() { fold("'1' < 2", "true"); fold("'2' > 1", "true"); fold("'123' > 34", "true"); fold("'NaN' < NaN", "false"); fold("'1' == 2", "false"); fold("'1' != 1", "false"); fold("'NaN' == NaN", "false"); fold("'1' === 1", "false"); fold("'1' !== 1", "true"); foldSame("'' + x < +y"); foldSame("'' + x == +y"); fold("'' + x === +y", "false"); } public void testNaNComparison() { fold("NaN < NaN", "false"); fold("NaN >= NaN", "false"); fold("NaN == NaN", "false"); fold("NaN === NaN", "false"); fold("NaN < null", "false"); fold("null >= NaN", "false"); fold("NaN == null", "false"); fold("null != NaN", "true"); fold("null === NaN", "false"); fold("NaN < undefined", "false"); fold("undefined >= NaN", "false"); fold("NaN == undefined", "false"); fold("undefined != NaN", "true"); fold("undefined === NaN", "false"); foldSame("NaN < x"); foldSame("x >= NaN"); foldSame("NaN == x"); foldSame("x != NaN"); fold("NaN === x", "false"); fold("x !== NaN", "true"); foldSame("NaN == foo()"); } public void testObjectComparison1() { fold("!new Date()", "false"); fold("!!new Date()", "true"); fold("new Date() == null", "false"); fold("new Date() == undefined", "false"); fold("new Date() != null", "true"); fold("new Date() != undefined", "true"); fold("null == new Date()", "false"); fold("undefined == new Date()", "false"); fold("null != new Date()", "true"); fold("undefined != new Date()", "true"); } public void testUnaryOps() { // These cases are handled by PeepholeRemoveDeadCode. foldSame("!foo()"); foldSame("~foo()"); foldSame("-foo()"); // These cases are handled here. fold("a=!true", "a=false"); fold("a=!10", "a=false"); fold("a=!false", "a=true"); foldSame("a=!foo()"); fold("a=-0", "a=-0.0"); fold("a=-(0)", "a=-0.0"); foldSame("a=-Infinity"); fold("a=-NaN", "a=NaN"); foldSame("a=-foo()"); fold("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=+true", "a=1"); fold("a=+10", "a=10"); fold("a=+false", "a=0"); foldSame("a=+foo()"); foldSame("a=+f"); fold("a=+(f?true:false)", "a=+(f?1:0)"); // TODO(johnlenz): foldable fold("a=+0", "a=0"); fold("a=+Infinity", "a=Infinity"); fold("a=+NaN", "a=NaN"); fold("a=+-7", "a=-7"); fold("a=+.5", "a=.5"); fold("a=~0xffffffff", "a=0"); fold("a=~~0xffffffff", "a=-1"); testSame("a=~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testUnaryOpsStringCompare() { foldSame("a = -1"); fold("a = ~0", "a = -1"); fold("a = ~1", "a = -2"); fold("a = ~101", "a = -102"); } public void testFoldLogicalOp() { fold("x = true && x", "x = x"); fold("x = [foo()] && x", "x = ([foo()],x)"); fold("x = false && x", "x = false"); fold("x = true || x", "x = true"); fold("x = false || x", "x = x"); fold("x = 0 && x", "x = 0"); fold("x = 3 || x", "x = 3"); fold("x = false || 0", "x = 0"); // unfoldable, because the right-side may be the result fold("a = x && true", "a=x&&true"); fold("a = x && false", "a=x&&false"); fold("a = x || 3", "a=x||3"); fold("a = x || false", "a=x||false"); fold("a = b ? c : x || false", "a=b?c:x||false"); fold("a = b ? x || false : c", "a=b?x||false:c"); fold("a = b ? c : x && true", "a=b?c:x&&true"); fold("a = b ? x && true : c", "a=b?x&&true:c"); // folded, but not here. foldSame("a = x || false ? b : c"); foldSame("a = x && true ? b : c"); fold("x = foo() || true || bar()", "x = foo()||true"); fold("x = foo() || true && bar()", "x = foo()||bar()"); fold("x = foo() || false && bar()", "x = foo()||false"); fold("x = foo() && false && bar()", "x = foo()&&false"); fold("x = foo() && false || bar()", "x = (foo()&&false,bar())"); // TODO(tbreisacher): Fix and re-enable. //fold("x = foo() || false || bar()", "x = foo()||bar()"); //fold("x = foo() && true && bar()", "x = foo()&&bar()"); fold("1 && b()", "b()"); fold("a() && (1 && b())", "a() && b()"); // TODO(johnlenz): Consider folding the following to: // "(a(),1) && b(); foldSame("(a() && 1) && b()"); // Really not foldable, because it would change the type of the // expression if foo() returns something equivalent, but not // identical, to true. Cf. FoldConstants.tryFoldAndOr(). foldSame("x = foo() && true || bar()"); foldSame("foo() && true || bar()"); } public void testFoldBitwiseOp() { fold("x = 1 & 1", "x = 1"); fold("x = 1 & 2", "x = 0"); fold("x = 3 & 1", "x = 1"); fold("x = 3 & 3", "x = 3"); fold("x = 1 | 1", "x = 1"); fold("x = 1 | 2", "x = 3"); fold("x = 3 | 1", "x = 3"); fold("x = 3 | 3", "x = 3"); fold("x = 1 ^ 1", "x = 0"); fold("x = 1 ^ 2", "x = 3"); fold("x = 3 ^ 1", "x = 2"); fold("x = 3 ^ 3", "x = 0"); fold("x = -1 & 0", "x = 0"); fold("x = 0 & -1", "x = 0"); fold("x = 1 & 4", "x = 0"); fold("x = 2 & 3", "x = 2"); // make sure we fold only when we are supposed to -- not when doing so would // lose information or when it is performed on nonsensical arguments. fold("x = 1 & 1.1", "x = 1"); fold("x = 1.1 & 1", "x = 1"); fold("x = 1 & 3000000000", "x = 0"); fold("x = 3000000000 & 1", "x = 0"); // Try some cases with | as well fold("x = 1 | 4", "x = 5"); fold("x = 1 | 3", "x = 3"); fold("x = 1 | 1.1", "x = 1"); foldSame("x = 1 | 3E9"); fold("x = 1 | 3000000001", "x = -1294967295"); fold("x = 4294967295 | 0", "x = -1"); } public void testFoldBitwiseOp2() { fold("x = y & 1 & 1", "x = y & 1"); fold("x = y & 1 & 2", "x = y & 0"); fold("x = y & 3 & 1", "x = y & 1"); fold("x = 3 & y & 1", "x = y & 1"); fold("x = y & 3 & 3", "x = y & 3"); fold("x = 3 & y & 3", "x = y & 3"); fold("x = y | 1 | 1", "x = y | 1"); fold("x = y | 1 | 2", "x = y | 3"); fold("x = y | 3 | 1", "x = y | 3"); fold("x = 3 | y | 1", "x = y | 3"); fold("x = y | 3 | 3", "x = y | 3"); fold("x = 3 | y | 3", "x = y | 3"); fold("x = y ^ 1 ^ 1", "x = y ^ 0"); fold("x = y ^ 1 ^ 2", "x = y ^ 3"); fold("x = y ^ 3 ^ 1", "x = y ^ 2"); fold("x = 3 ^ y ^ 1", "x = y ^ 2"); fold("x = y ^ 3 ^ 3", "x = y ^ 0"); fold("x = 3 ^ y ^ 3", "x = y ^ 0"); fold("x = Infinity | NaN", "x=0"); fold("x = 12 | NaN", "x=12"); } public void testFoldingMixTypesLate() { late = true; fold("x = x + '2'", "x+='2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x-=2"); fold("x = x ^ '2'", "x^=2"); fold("x = '2' ^ x", "x^=2"); fold("x = '2' & x", "x&=2"); fold("x = '2' | x", "x|=2"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingMixTypesEarly() { late = false; foldSame("x = x + '2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x = x - 2"); fold("x = x ^ '2'", "x = x ^ 2"); fold("x = '2' ^ x", "x = 2 ^ x"); fold("x = '2' & x", "x = 2 & x"); fold("x = '2' | x", "x = 2 | x"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingAdd1() { fold("x = null + true", "x=1"); foldSame("x = a + true"); fold("x = '' + {}", "x = '[object Object]'"); fold("x = [] + {}", "x = '[object Object]'"); fold("x = {} + []", "x = '[object Object]'"); fold("x = {} + ''", "x = '[object Object]'"); } public void testFoldingAdd2() { fold("x = false + []", "x='false'"); fold("x = [] + true", "x='true'"); fold("NaN + []", "'NaN'"); } public void testFoldBitwiseOpStringCompare() { fold("x = -1 | 0", "x = -1"); } public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("x = 0x90000000 >>> 28", "x = 9"); fold("x = 0xffffffff << 0", "x = -1"); fold("x = 0xffffffff << 4", "x = -16"); testSame("1 << 32"); testSame("1 << -1"); testSame("1 >> 32"); testSame("1.5 << 0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); testSame("1 << .5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); testSame("1.5 >>> 0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); testSame("1 >>> .5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); testSame("1.5 >> 0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); testSame("1 >> .5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testFoldBitShiftsStringCompare() { fold("x = -1 << 1", "x = -2"); fold("x = -1 << 8", "x = -256"); fold("x = -1 >> 1", "x = -1"); fold("x = -2 >> 1", "x = -1"); fold("x = -1 >> 0", "x = -1"); } public void testStringAdd() { fold("x = 'a' + \"bc\"", "x = \"abc\""); fold("x = 'a' + 5", "x = \"a5\""); fold("x = 5 + 'a'", "x = \"5a\""); fold("x = 'a' + ''", "x = \"a\""); fold("x = \"a\" + foo()", "x = \"a\"+foo()"); fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\""); fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it! fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()"); fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold! fold("x = foo() + 'a' + 2", "x = foo()+\"a2\""); fold("x = '' + null", "x = \"null\""); fold("x = true + '' + false", "x = \"truefalse\""); fold("x = '' + []", "x = ''"); // cannot fold (but nice if we can) } public void testIssue821() { foldSame("var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4;"); foldSame("var a = ((Math.random() ? 0 : 1) ||" + "(Math.random()>0.5? '1' : 2 )) + 3 + 4;"); } public void testFoldConstructor() { fold("x = this[new String('a')]", "x = this['a']"); fold("x = ob[new String(12)]", "x = ob['12']"); fold("x = ob[new String(false)]", "x = ob['false']"); fold("x = ob[new String(null)]", "x = ob['null']"); fold("x = 'a' + new String('b')", "x = 'ab'"); fold("x = 'a' + new String(23)", "x = 'a23'"); fold("x = 2 + new String(1)", "x = '21'"); foldSame("x = ob[new String(a)]"); foldSame("x = new String('a')"); foldSame("x = (new String('a'))[3]"); } public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); foldSame("z = x * y"); foldSame("x = y * 5"); foldSame("x = 1 / 0"); fold("x = 3 % 2", "x = 1"); fold("x = 3 % -2", "x = 1"); fold("x = -1 % 3", "x = -1"); foldSame("x = 1 % 0"); } public void testFoldArithmetic2() { foldSame("x = y + 10 + 20"); foldSame("x = y / 2 / 4"); fold("x = y * 2.25 * 3", "x = y * 6.75"); foldSame("z = x * y"); foldSame("x = y * 5"); fold("x = y + (z * 24 * 60 * 60 * 1000)", "x = y + z * 864E5"); } public void testFoldArithmetic3() { fold("x = null * undefined", "x = NaN"); fold("x = null * 1", "x = 0"); fold("x = (null - 1) * 2", "x = -2"); fold("x = (null + 1) * 2", "x = 2"); } public void testFoldArithmeticInfinity() { fold("x=-Infinity-2", "x=-Infinity"); fold("x=Infinity-2", "x=Infinity"); fold("x=Infinity*5", "x=Infinity"); } public void testFoldArithmeticStringComp() { fold("x = 10 - 20", "x = -10"); } public void testFoldComparison() { fold("x = 0 == 0", "x = true"); fold("x = 1 == 2", "x = false"); fold("x = 'abc' == 'def'", "x = false"); fold("x = 'abc' == 'abc'", "x = true"); fold("x = \"\" == ''", "x = true"); fold("x = foo() == bar()", "x = foo()==bar()"); fold("x = 1 != 0", "x = true"); fold("x = 'abc' != 'def'", "x = true"); fold("x = 'a' != 'a'", "x = false"); fold("x = 1 < 20", "x = true"); fold("x = 3 < 3", "x = false"); fold("x = 10 > 1.0", "x = true"); fold("x = 10 > 10.25", "x = false"); fold("x = y == y", "x = y==y"); // Maybe foldable given type information fold("x = y < y", "x = false"); fold("x = y > y", "x = false"); fold("x = 1 <= 1", "x = true"); fold("x = 1 <= 0", "x = false"); fold("x = 0 >= 0", "x = true"); fold("x = -1 >= 9", "x = false"); fold("x = true == true", "x = true"); fold("x = false == false", "x = true"); fold("x = false == null", "x = false"); fold("x = false == true", "x = false"); fold("x = true == null", "x = false"); fold("0 == 0", "true"); fold("1 == 2", "false"); fold("'abc' == 'def'", "false"); fold("'abc' == 'abc'", "true"); fold("\"\" == ''", "true"); foldSame("foo() == bar()"); fold("1 != 0", "true"); fold("'abc' != 'def'", "true"); fold("'a' != 'a'", "false"); fold("1 < 20", "true"); fold("3 < 3", "false"); fold("10 > 1.0", "true"); fold("10 > 10.25", "false"); foldSame("x == x"); fold("x < x", "false"); fold("x > x", "false"); fold("1 <= 1", "true"); fold("1 <= 0", "false"); fold("0 >= 0", "true"); fold("-1 >= 9", "false"); fold("true == true", "true"); fold("false == null", "false"); fold("false == true", "false"); fold("true == null", "false"); } // ===, !== comparison tests public void testFoldComparison2() { fold("x = 0 === 0", "x = true"); fold("x = 1 === 2", "x = false"); fold("x = 'abc' === 'def'", "x = false"); fold("x = 'abc' === 'abc'", "x = true"); fold("x = \"\" === ''", "x = true"); fold("x = foo() === bar()", "x = foo()===bar()"); fold("x = 1 !== 0", "x = true"); fold("x = 'abc' !== 'def'", "x = true"); fold("x = 'a' !== 'a'", "x = false"); fold("x = y === y", "x = y===y"); fold("x = true === true", "x = true"); fold("x = false === false", "x = true"); fold("x = false === null", "x = false"); fold("x = false === true", "x = false"); fold("x = true === null", "x = false"); fold("0 === 0", "true"); fold("1 === 2", "false"); fold("'abc' === 'def'", "false"); fold("'abc' === 'abc'", "true"); fold("\"\" === ''", "true"); foldSame("foo() === bar()"); fold("1 === '1'", "false"); fold("1 === true", "false"); fold("1 !== '1'", "true"); fold("1 !== true", "true"); fold("1 !== 0", "true"); fold("'abc' !== 'def'", "true"); fold("'a' !== 'a'", "false"); foldSame("x === x"); fold("true === true", "true"); fold("false === null", "false"); fold("false === true", "false"); fold("true === null", "false"); } public void testFoldComparison3() { fold("x = !1 == !0", "x = false"); fold("x = !0 == !0", "x = true"); fold("x = !1 == !1", "x = true"); fold("x = !1 == null", "x = false"); fold("x = !1 == !0", "x = false"); fold("x = !0 == null", "x = false"); fold("!0 == !0", "true"); fold("!1 == null", "false"); fold("!1 == !0", "false"); fold("!0 == null", "false"); fold("x = !0 === !0", "x = true"); fold("x = !1 === !1", "x = true"); fold("x = !1 === null", "x = false"); fold("x = !1 === !0", "x = false"); fold("x = !0 === null", "x = false"); fold("!0 === !0", "true"); fold("!1 === null", "false"); fold("!1 === !0", "false"); fold("!0 === null", "false"); } public void testFoldComparison4() { foldSame("[] == false"); // true foldSame("[] == true"); // false foldSame("[0] == false"); // true foldSame("[0] == true"); // false foldSame("[1] == false"); // false foldSame("[1] == true"); // true foldSame("({}) == false"); // false foldSame("({}) == true"); // true } public void testFoldGetElem1() { fold("x = [,10][0]", "x = void 0"); fold("x = [10, 20][0]", "x = 10"); fold("x = [10, 20][1]", "x = 20"); testSame("x = [10, 20][0.5]", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); testSame("x = [10, 20][-1]", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); testSame("x = [10, 20][2]", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); foldSame("x = [foo(), 0][1]"); fold("x = [0, foo()][1]", "x = foo()"); foldSame("x = [0, foo()][0]"); foldSame("for([1][0] in {});"); } public void testFoldGetElem2() { fold("x = 'string'[5]", "x = 'g'"); fold("x = 'string'[0]", "x = 's'"); fold("x = 's'[0]", "x = 's'"); foldSame("x = '\uD83D\uDCA9'[0]"); testSame("x = 'string'[0.5]", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); testSame("x = 'string'[-1]", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); testSame("x = 'string'[6]", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); } public void testFoldComplex() { fold("x = (3 / 1.0) + (1 * 2)", "x = 5"); fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true"); fold("x = 'abc' + 5 + 10", "x = \"abc510\""); } public void testFoldLeft() { foldSame("(+x - 1) + 2"); // not yet fold("(+x + 1) + 2", "+x + 3"); } public void testFoldArrayLength() { // Can fold fold("x = [].length", "x = 0"); fold("x = [1,2,3].length", "x = 3"); fold("x = [a,b].length", "x = 2"); // Not handled yet fold("x = [,,1].length", "x = 3"); // Cannot fold fold("x = [foo(), 0].length", "x = [foo(),0].length"); foldSame("x = y.length"); } public void testFoldStringLength() { // Can fold basic strings. fold("x = ''.length", "x = 0"); fold("x = '123'.length", "x = 3"); // Test Unicode escapes are accounted for. fold("x = '123\u01dc'.length", "x = 4"); } public void testFoldTypeof() { fold("x = typeof 1", "x = \"number\""); fold("x = typeof 'foo'", "x = \"string\""); fold("x = typeof true", "x = \"boolean\""); fold("x = typeof false", "x = \"boolean\""); fold("x = typeof null", "x = \"object\""); fold("x = typeof undefined", "x = \"undefined\""); fold("x = typeof void 0", "x = \"undefined\""); fold("x = typeof []", "x = \"object\""); fold("x = typeof [1]", "x = \"object\""); fold("x = typeof [1,[]]", "x = \"object\""); fold("x = typeof {}", "x = \"object\""); fold("x = typeof function() {}", "x = 'function'"); foldSame("x = typeof[1,[foo()]]"); foldSame("x = typeof{bathwater:baby()}"); } public void testFoldInstanceOf() { // Non object types are never instances of anything. fold("64 instanceof Object", "false"); fold("64 instanceof Number", "false"); fold("'' instanceof Object", "false"); fold("'' instanceof String", "false"); fold("true instanceof Object", "false"); fold("true instanceof Boolean", "false"); fold("!0 instanceof Object", "false"); fold("!0 instanceof Boolean", "false"); fold("false instanceof Object", "false"); fold("null instanceof Object", "false"); fold("undefined instanceof Object", "false"); fold("NaN instanceof Object", "false"); fold("Infinity instanceof Object", "false"); // Array and object literals are known to be objects. fold("[] instanceof Object", "true"); fold("({}) instanceof Object", "true"); // These cases is foldable, but no handled currently. foldSame("new Foo() instanceof Object"); // These would require type information to fold. foldSame("[] instanceof Foo"); foldSame("({}) instanceof Foo"); fold("(function() {}) instanceof Object", "true"); // An unknown value should never be folded. foldSame("x instanceof Foo"); } public void testDivision() { // Make sure the 1/3 does not expand to 0.333333 foldSame("print(1/3)"); // Decimal form is preferable to fraction form when strings are the // same length. fold("print(1/2)", "print(0.5)"); } public void testAssignOpsLate() { late = true; fold("x=x+y", "x+=y"); foldSame("x=y+x"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); fold("x=x-y", "x-=y"); foldSame("x=y-x"); fold("x=x|y", "x|=y"); fold("x=y|x", "x|=y"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); // This is OK, really. fold("({a:1}).a = ({a:1}).a + 1", "({a:1}).a = 2"); } public void testAssignOpsEarly() { late = false; foldSame("x=x+y"); foldSame("x=y+x"); foldSame("x=x*y"); foldSame("x=y*x"); foldSame("x.y=x.y+z"); foldSame("next().x = next().x + 1"); foldSame("x=x-y"); foldSame("x=y-x"); foldSame("x=x|y"); foldSame("x=y|x"); foldSame("x=x*y"); foldSame("x=y*x"); foldSame("x.y=x.y+z"); foldSame("next().x = next().x + 1"); // This is OK, really. fold("({a:1}).a = ({a:1}).a + 1", "({a:1}).a = 2"); } public void testFoldAdd1() { fold("x=false+1", "x=1"); fold("x=true+1", "x=2"); fold("x=1+false", "x=1"); fold("x=1+true", "x=2"); } public void testFoldLiteralNames() { fold("NaN == NaN", "false"); fold("Infinity == Infinity", "true"); fold("Infinity == NaN", "false"); fold("undefined == NaN", "false"); fold("undefined == Infinity", "false"); fold("Infinity >= Infinity", "true"); fold("NaN >= NaN", "false"); } public void testFoldLiteralsTypeMismatches() { fold("true == true", "true"); fold("true == false", "false"); fold("true == null", "false"); fold("false == null", "false"); // relational operators convert its operands fold("null <= null", "true"); // 0 = 0 fold("null >= null", "true"); fold("null > null", "false"); fold("null < null", "false"); fold("false >= null", "true"); // 0 = 0 fold("false <= null", "true"); fold("false > null", "false"); fold("false < null", "false"); fold("true >= null", "true"); // 1 > 0 fold("true <= null", "false"); fold("true > null", "true"); fold("true < null", "false"); fold("true >= false", "true"); // 1 > 0 fold("true <= false", "false"); fold("true > false", "true"); fold("true < false", "false"); } public void testFoldLeftChildConcat() { foldSame("x +5 + \"1\""); fold("x+\"5\" + \"1\"", "x + \"51\""); // fold("\"a\"+(c+\"b\")", "\"a\"+c+\"b\""); fold("\"a\"+(\"b\"+c)", "\"ab\"+c"); } public void testFoldLeftChildOp() { fold("x * Infinity * 2", "x * Infinity"); foldSame("x - Infinity - 2"); // want "x-Infinity" foldSame("x - 1 + Infinity"); foldSame("x - 2 + 1"); foldSame("x - 2 + 3"); foldSame("1 + x - 2 + 1"); foldSame("1 + x - 2 + 3"); foldSame("1 + x - 2 + 3 - 1"); foldSame("f(x)-0"); foldSame("x-0-0"); foldSame("x+2-2+2"); foldSame("x+2-2+2-2"); foldSame("x-2+2"); foldSame("x-2+2-2"); foldSame("x-2+2-2+2"); foldSame("1+x-0-NaN"); foldSame("1+f(x)-0-NaN"); foldSame("1+x-0+NaN"); foldSame("1+f(x)-0+NaN"); foldSame("1+x+NaN"); // unfoldable foldSame("x+2-2"); // unfoldable foldSame("x+2"); // nothing to do foldSame("x-2"); // nothing to do } public void testFoldSimpleArithmeticOp() { foldSame("x*NaN"); foldSame("NaN/y"); foldSame("f(x)-0"); foldSame("f(x)*1"); foldSame("1*f(x)"); foldSame("0+a+b"); foldSame("0-a-b"); foldSame("a+b-0"); foldSame("(1+x)*NaN"); foldSame("(1+f(x))*NaN"); // don't fold side-effects } public void testFoldLiteralsAsNumbers() { fold("x/'12'", "x/12"); fold("x/('12'+'6')", "x/126"); fold("true*x", "1*x"); fold("x/false", "x/0"); // should we add an error check? :) } public void testNotFoldBackToTrueFalse() { late = false; fold("!0", "true"); fold("!1", "false"); fold("!3", "false"); late = true; foldSame("!0"); foldSame("!1"); fold("!3", "false"); foldSame("false"); foldSame("true"); } public void testFoldBangConstants() { fold("1 + !0", "2"); fold("1 + !1", "1"); fold("'a ' + !1", "'a false'"); fold("'a ' + !0", "'a true'"); } public void testFoldMixed() { fold("''+[1]", "'1'"); fold("false+[]", "\"false\""); } public void testFoldVoid() { foldSame("void 0"); fold("void 1", "void 0"); fold("void x", "void 0"); foldSame("void x()"); } public void testObjectLiteral() { test("(!{})", "false"); test("(!{a:1})", "false"); testSame("(!{a:foo()})"); testSame("(!{'a':foo()})"); } public void testArrayLiteral() { test("(![])", "false"); test("(![1])", "false"); test("(![a])", "false"); testSame("(![foo()])"); } public void testIssue601() { testSame("'\\v' == 'v'"); testSame("'v' == '\\v'"); testSame("'\\u000B' == '\\v'"); } public void testFoldObjectLiteralRef1() { // Leave extra side-effects in place testSame("var x = ({a:foo(),b:bar()}).a"); testSame("var x = ({a:1,b:bar()}).a"); testSame("function f() { return {b:foo(), a:2}.a; }"); // on the LHS the object act as a temporary leave it in place. testSame("({a:x}).a = 1"); test("({a:x}).a += 1", "({a:x}).a = x + 1"); testSame("({a:x}).a ++"); testSame("({a:x}).a --"); // functions can't reference the object through 'this'. testSame("({a:function(){return this}}).a"); testSame("({get a() {return this}}).a"); testSame("({set a(b) {return this}}).a"); // Leave unknown props alone, the might be on the prototype testSame("({}).a"); // setters by themselves don't provide a definition testSame("({}).a"); testSame("({set a(b) {}}).a"); // sets don't hide other definitions. test("({a:1,set a(b) {}}).a", "1"); // get is transformed to a call (gets don't have self referential names) test("({get a() {}}).a", "(function (){})()"); // sets don't hide other definitions. test("({get a() {},set a(b) {}}).a", "(function (){})()"); // a function remains a function not a call. test("var x = ({a:function(){return 1}}).a", "var x = function(){return 1}"); test("var x = ({a:1}).a", "var x = 1"); test("var x = ({a:1, a:2}).a", "var x = 2"); test("var x = ({a:1, a:foo()}).a", "var x = foo()"); test("var x = ({a:foo()}).a", "var x = foo()"); test("function f() { return {a:1, b:2}.a; }", "function f() { return 1; }"); // GETELEM is handled the same way. test("var x = ({'a':1})['a']", "var x = 1"); } public void testFoldObjectLiteralRef2() { late = false; test("({a:x}).a += 1", "({a:x}).a = x + 1"); late = true; testSame("({a:x}).a += 1"); } public void testIEString() { testSame("!+'\\v1'"); } public void testIssue522() { testSame("[][1] = 1;"); } public void testTypeBasedFoldConstant() { enableTypeCheck(); test("var /** number */ x; x + 1 + 1 + x", "var /** number */ x; x + 2 + x"); test("var /** boolean */ x; x + 1 + 1 + x", "var /** boolean */ x; x + 2 + x"); test("var /** null */ x; x + 1 + 1 + x", "var /** null */ x; 2"); test("var /** undefined */ x; x + 1 + 1 + x", "var /** undefined */ x; NaN"); test("var /** null */ x; var y = true > x;", "var /** null */ x; var y = true;"); test("var /** null */ x; var y = null > x;", "var /** null */ x; var y = false;"); testSame("var /** string */ x; x + 1 + 1 + x"); useTypes = false; testSame("var /** number */ x; x + 1 + 1 + x"); disableTypeCheck(); } public void foldDefineProperties1() { test("Object.defineProperties({}, {})", "{}"); test("Object.defineProperties(a, {})", "a"); testSame("Object.defineProperties(a, {anything:1})"); } private static final ImmutableList<String> LITERAL_OPERANDS = ImmutableList.of( "null", "undefined", "void 0", "true", "false", "!0", "!1", "0", "1", "''", "'123'", "'abc'", "'def'", "NaN", "Infinity", // TODO(nicksantos): Add more literals "-Infinity" //"({})", // "[]" //"[0]", //"Object", //"(function() {})" ); public void testInvertibleOperators() { Map<String, String> inverses = ImmutableMap.<String, String>builder() .put("==", "!=") .put("===", "!==") .put("<=", ">") .put("<", ">=") .put(">=", "<") .put(">", "<=") .put("!=", "==") .put("!==", "===") .build(); Set<String> comparators = ImmutableSet.of("<=", "<", ">=", ">"); Set<String> equalitors = ImmutableSet.of("==", "==="); Set<String> uncomparables = ImmutableSet.of("undefined", "void 0"); List<String> operators = ImmutableList.copyOf(inverses.values()); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = 0; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); String inverse = inverses.get(op); // Test invertability. if (comparators.contains(op)) { if (uncomparables.contains(a) || uncomparables.contains(b) || (a.equals("null") && NodeUtil.getStringNumberValue(b) == null)) { assertSameResults(join(a, op, b), "false"); assertSameResults(join(a, inverse, b), "false"); } } else if (a.equals(b) && equalitors.contains(op)) { if (a.equals("NaN") || a.equals("Infinity") || a.equals("-Infinity")) { fold(join(a, op, b), a.equals("NaN") ? "false" : "true"); } else { assertSameResults(join(a, op, b), "true"); assertSameResults(join(a, inverse, b), "false"); } } else { assertNotSameResults(join(a, op, b), join(a, inverse, b)); } } } } } public void testCommutativeOperators() { late = true; List<String> operators = ImmutableList.of( "==", "!=", "===", "!==", "*", "|", "&", "^"); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = iOperandA; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); // Test commutativity. assertSameResults(join(a, op, b), join(b, op, a)); } } } } public void testConvertToNumberNegativeInf() { foldSame("var x = 3 * (r ? Infinity : -Infinity);"); } private static String join(String operandA, String op, String operandB) { return operandA + " " + op + " " + operandB; } private void assertSameResults(String exprA, String exprB) { assertEquals( "Expressions did not fold the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA), process(exprB)); } private void assertNotSameResults(String exprA, String exprB) { assertFalse( "Expressions folded the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA).equals(process(exprB))); } private String process(String js) { return printHelper(js, true); } private String printHelper(String js, boolean runProcessor) { Compiler compiler = createCompiler(); CompilerOptions options = getOptions(); compiler.init( ImmutableList.<SourceFile>of(), ImmutableList.of(SourceFile.fromCode("testcode", js)), options); Node root = compiler.parseInputs(); assertNotNull("Unexpected parse error(s): " + Joiner.on("\n").join(compiler.getErrors()) + "\nEXPR: " + js, root); Node externsRoot = root.getFirstChild(); Node mainRoot = externsRoot.getNext(); if (runProcessor) { getProcessor(compiler).process(externsRoot, mainRoot); } return compiler.toSource(mainRoot); } }
brad4d/closure-compiler
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
Java
apache-2.0
45,231
package com.kyleduo.rabbits; /** * 保存是否跳转成功,以及过程信息:拦截信息、参数、目标等 * <p> * Created by kyle on 19/12/2017. */ public class RabbitResult { public static final int STATUS_ERROR = 0; public static final int STATUS_SUCCESS = 1; public static final int STATUS_NOT_FOUND = 2; public static final int STATUS_NOT_FINISH = 3; private int code; private String reason; private Object target; public RabbitResult(int code, String reason, Object target) { this.code = code; this.reason = reason; this.target = target; } public static RabbitResult error(String reason) { return new RabbitResult(STATUS_ERROR, reason, null); } public static RabbitResult notFound(String url) { return new RabbitResult(STATUS_NOT_FOUND, "Page not found: " + url, null); } public static RabbitResult success(Object target) { return new RabbitResult(STATUS_SUCCESS, "success", target); } public static RabbitResult success() { return success(null); } public static RabbitResult notFinished() { return new RabbitResult(STATUS_NOT_FINISH, "", null); } public int getCode() { return code; } public String getReason() { return reason; } public Object getTarget() { return target; } public boolean isSuccess() { return getCode() == STATUS_SUCCESS; } public boolean isFinished() { return getCode() != STATUS_NOT_FINISH; } @Override public boolean equals(Object obj) { if (obj instanceof RabbitResult) { return this.code == ((RabbitResult) obj).code && this.target == ((RabbitResult) obj).target; } return false; } @Override public String toString() { switch (code) { case STATUS_ERROR: return "Result: ERROR, " + reason; case STATUS_SUCCESS: if (target == null) { return "Result: SUCCESS"; } else { return "Result: SUCCESS, " + target; } case STATUS_NOT_FOUND: return "Result: NOT_FOUND, " + reason; case STATUS_NOT_FINISH: return "Result: NOT_FINISH"; } return "Result: UNKNOWN"; } }
kyleduo/Rabbits
Rabbits/rabbits/src/main/java/com/kyleduo/rabbits/RabbitResult.java
Java
apache-2.0
2,401
package com.jfixby.r3.fokker.unit.text; import com.jfixby.r3.api.ui.unit.ComponentsFactory; import com.jfixby.r3.api.ui.unit.LayerBasedComponent; import com.jfixby.r3.api.ui.unit.geometry.RectangleComponent; import com.jfixby.r3.api.ui.unit.layer.Layer; import com.jfixby.r3.api.ui.unit.raster.CanvasComponent; import com.jfixby.r3.api.ui.unit.raster.Raster; import com.jfixby.r3.api.ui.unit.txt.TextBar; import com.jfixby.r3.api.ui.unit.txt.TextBarSpecs; import com.jfixby.r3.fokker.unit.RedComponentsFactory; import com.jfixby.scarabei.api.assets.ID; import com.jfixby.scarabei.api.color.Color; import com.jfixby.scarabei.api.color.Colors; import com.jfixby.scarabei.api.debug.Debug; import com.jfixby.scarabei.api.err.Err; import com.jfixby.scarabei.api.floatn.ReadOnlyFloat2; import com.jfixby.scarabei.api.geometry.CanvasPosition; import com.jfixby.scarabei.api.geometry.Geometry; import com.jfixby.scarabei.api.math.Angle; import com.jfixby.strings.api.Text; import com.jfixby.strings.api.TextTranslation; public class RedTextBar implements TextBar, LayerBasedComponent { final ComponentsFactory componentsFactory; private final Layer root; ID font_id; private final CanvasPosition position = Geometry.newCanvasPosition(); // private Raster bg_raster; private final float padding; private String locale_name; private final Text text; private final float font_scale; private final float font_size; private CanvasComponent background; // private final AssetID id; private RedTextBarText current_text; private Color font_color; private final RectangleComponent rectangle; private final String rawText; @Override public String toString () { // return "TextBar[text=" + this.text + ", font_id=" + this.font_id + ", position=" + this.position + ", padding=" // + this.padding + ", locale_name=" + this.locale_name + ", font_scale=" + this.font_scale + ", font_size=" // + this.font_size + ", background=" + this.background + ", font_color=" + this.font_color + "]"; // return "TextBar[" + this.getName() + "]"; } public RedTextBar (final TextBarSpecs text_specs, final RedComponentsFactory componentsFactory) { this.componentsFactory = componentsFactory; this.root = componentsFactory.newLayer(); this.font_id = text_specs.getFont(); this.padding = text_specs.getPadding(); final Raster bg_raster = text_specs.getBackgroundRaster(); this.font_scale = text_specs.getFontScale(); this.font_size = text_specs.getFontSize(); this.text = text_specs.getText(); this.rawText = text_specs.getRawText(); this.locale_name = text_specs.getLocaleName(); this.font_color = text_specs.getFontColor(); if (this.font_color == null) { this.font_color = Colors.BLACK(); } // root.attachComponent(bg_raster); this.rectangle = componentsFactory.getGeometryDepartment().newRectangle(); this.rectangle.setFillColor(Colors.WHITE().customize().setAlpha(0.5f)); this.background = this.rectangle; this.background = bg_raster; if (this.background != null) { this.root.attachComponent(this.background); this.rectangle.setSize(bg_raster.getWidth(), bg_raster.getHeight()); } // Debug.checkNull("getText()", text); this.createText(); if (this.background != null) { this.background.setPosition(0, 0); } } @Override public void setRawText (final String text_string) { Debug.checkNull("text_string", text_string); if (text_string.equals(this.rawText)) { return; } if (this.current_text != null) { this.disposeText(); } // Debug.checkTrue("no children", this.root.listChildren().size() == 0); this.current_text = new RedTextBarText(this, text_string, this.font_size, this.padding, this.font_scale, this.font_color, this.font_id); this.current_text.attach(this.root); this.updateTextPosition(); } @Override public String getRawText () { return this.current_text.getRawText(); } private void createText () { String text_string = null; if (this.text != null) { final TextTranslation translation = this.text.listTranslations().getByLocalization(this.locale_name); if (translation == null) { this.text.listTranslations().print(); Err.reportError("Localization not found: " + this.locale_name); } text_string = translation.getString().getChars(); } else { text_string = ""; if (this.rawText != null) { text_string = this.rawText; } } Debug.checkNull("text_string", text_string); if (this.current_text != null) { this.disposeText(); } // if (this.root.listChildren().size() != 0) { // this.root.print(); // } // Debug.checkTrue("no children", this.root.listChildren().size() == 0); this.current_text = new RedTextBarText(this, text_string, this.font_size, this.padding, this.font_scale, this.font_color, this.font_id); this.current_text.attach(this.root); this.updateTextPosition(); } private void updateText () { this.disposeText(); this.createText(); } private void disposeText () { this.current_text.dispose(); this.current_text = null; } @Override public void setPosition (final double canvas_x, final double canvas_y) { this.position.setXY(canvas_x, canvas_y); this.updateTextPosition(); } private void updateTextPosition () { this.current_text.updatePosition(this.position); if (this.background != null) { this.background.setPosition(this.position); } this.current_text.updatePosition(this.position); } @Override public void setRotation (final Angle rotation) { this.position.setRotation(rotation); this.updateTextPosition(); } @Override public void setRotation (final double rotation) { this.position.setRotation(rotation); this.updateTextPosition(); } @Override public void hide () { this.root.hide(); } @Override public void show () { this.root.show(); } @Override public boolean isVisible () { return this.root.isVisible(); } @Override public void setName (final String name) { this.root.setName(name); } @Override public String getName () { return this.root.getName(); } @Override public void setVisible (final boolean b) { this.root.setVisible(b); } @Override public Layer getRoot () { return this.root; } @Override public double getPositionX () { return this.position.getX(); } @Override public double getPositionY () { return this.position.getY(); } @Override public Angle getRotation () { return this.position.getRotation(); } @Override public void setLocaleName (final String locale_name) { final String old_locale = this.locale_name; this.locale_name = Debug.checkNull("locale_name", locale_name); Debug.checkEmpty("locale_name", locale_name); if (!old_locale.equals(locale_name)) { } this.updateText(); } @Override public String getLocaleName () { return this.locale_name; } @Override public void setPosition (final CanvasPosition position) { this.position.setPosition(position); this.updateTextPosition(); } @Override public void setPosition (final ReadOnlyFloat2 position) { this.position.setPosition(position); this.updateTextPosition(); } @Override public void offset (final double x, final double y) { this.position.add(x, y); this.updateTextPosition(); } @Override public void setPositionX (final double x) { this.position.setX(x); this.updateTextPosition(); } @Override public void setPositionY (final double y) { this.position.setY(y); this.updateTextPosition(); } // final Rectangle shape = Geometry.newRectangle(); // // @Override // public Rectangle shape () { // this.shape.setPosition(this.position); // this.shape.setSize(this.rectangle.shape()); // return this.shape; // } }
JFixby/RedTriplane
fokker-core/src/com/jfixby/r3/fokker/unit/text/RedTextBar.java
Java
apache-2.0
7,647
/* * Copyright 2012-2017 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.config.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * The output for the <a>DescribeConfigurationRecorders</a> action. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConfigurationRecorders" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeConfigurationRecordersResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * A list that contains the descriptions of the specified configuration recorders. * </p> */ private com.amazonaws.internal.SdkInternalList<ConfigurationRecorder> configurationRecorders; /** * <p> * A list that contains the descriptions of the specified configuration recorders. * </p> * * @return A list that contains the descriptions of the specified configuration recorders. */ public java.util.List<ConfigurationRecorder> getConfigurationRecorders() { if (configurationRecorders == null) { configurationRecorders = new com.amazonaws.internal.SdkInternalList<ConfigurationRecorder>(); } return configurationRecorders; } /** * <p> * A list that contains the descriptions of the specified configuration recorders. * </p> * * @param configurationRecorders * A list that contains the descriptions of the specified configuration recorders. */ public void setConfigurationRecorders(java.util.Collection<ConfigurationRecorder> configurationRecorders) { if (configurationRecorders == null) { this.configurationRecorders = null; return; } this.configurationRecorders = new com.amazonaws.internal.SdkInternalList<ConfigurationRecorder>(configurationRecorders); } /** * <p> * A list that contains the descriptions of the specified configuration recorders. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setConfigurationRecorders(java.util.Collection)} or * {@link #withConfigurationRecorders(java.util.Collection)} if you want to override the existing values. * </p> * * @param configurationRecorders * A list that contains the descriptions of the specified configuration recorders. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeConfigurationRecordersResult withConfigurationRecorders(ConfigurationRecorder... configurationRecorders) { if (this.configurationRecorders == null) { setConfigurationRecorders(new com.amazonaws.internal.SdkInternalList<ConfigurationRecorder>(configurationRecorders.length)); } for (ConfigurationRecorder ele : configurationRecorders) { this.configurationRecorders.add(ele); } return this; } /** * <p> * A list that contains the descriptions of the specified configuration recorders. * </p> * * @param configurationRecorders * A list that contains the descriptions of the specified configuration recorders. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeConfigurationRecordersResult withConfigurationRecorders(java.util.Collection<ConfigurationRecorder> configurationRecorders) { setConfigurationRecorders(configurationRecorders); 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 (getConfigurationRecorders() != null) sb.append("ConfigurationRecorders: ").append(getConfigurationRecorders()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeConfigurationRecordersResult == false) return false; DescribeConfigurationRecordersResult other = (DescribeConfigurationRecordersResult) obj; if (other.getConfigurationRecorders() == null ^ this.getConfigurationRecorders() == null) return false; if (other.getConfigurationRecorders() != null && other.getConfigurationRecorders().equals(this.getConfigurationRecorders()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getConfigurationRecorders() == null) ? 0 : getConfigurationRecorders().hashCode()); return hashCode; } @Override public DescribeConfigurationRecordersResult clone() { try { return (DescribeConfigurationRecordersResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
dagnir/aws-sdk-java
aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/DescribeConfigurationRecordersResult.java
Java
apache-2.0
6,093
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * 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,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <hr> * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * This file has been modified by the OpenOLAT community. Changes are licensed * under the Apache 2.0 license as the original file. */ package org.olat.modules.fo.archiver.formatters; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringEscapeUtils; import org.olat.core.commons.modules.bc.vfs.OlatRootFolderImpl; import org.olat.core.id.Identity; import org.olat.core.id.UserConstants; import org.olat.core.logging.AssertException; import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; import org.olat.core.util.WebappHelper; import org.olat.core.util.ZipUtil; import org.olat.core.util.filter.FilterFactory; import org.olat.core.util.nodes.INode; import org.olat.core.util.vfs.VFSItem; import org.olat.modules.fo.ForumManager; import org.olat.modules.fo.MessageNode; /** * Initial Date: Dec 19, 2013 <br> * * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com * @author Patrick Brunner, Alexander Schneider */ public class ForumStreamedRTFFormatter extends ForumFormatter { private static final OLog log = Tracing.createLoggerFor(ForumStreamedRTFFormatter.class); private ZipOutputStream exportStream; private ForumManager fm = ForumManager.getInstance(); final Pattern PATTERN_HTML_BOLD = Pattern.compile("<strong>(.*?)</strong>", Pattern.CASE_INSENSITIVE); final Pattern PATTERN_HTML_ITALIC = Pattern.compile("<em>(.*?)</em>", Pattern.CASE_INSENSITIVE); final Pattern PATTERN_HTML_BREAK = Pattern.compile("<br />", Pattern.CASE_INSENSITIVE); final Pattern PATTERN_HTML_PARAGRAPH = Pattern.compile("<p>(.*?)</p>", Pattern.CASE_INSENSITIVE); final Pattern PATTERN_HTML_AHREF = Pattern.compile("<a href=\"([^\"]+)\"[^>]*>(.*?)</a>", Pattern.CASE_INSENSITIVE); final Pattern PATTERN_HTML_LIST = Pattern.compile("<li>(.*?)</li>", Pattern.CASE_INSENSITIVE); final Pattern HTML_SPACE_PATTERN = Pattern.compile("&nbsp;"); final Pattern PATTERN_CSS_O_FOQUOTE = Pattern.compile("<div class=\"b_quote_wrapper\">\\s*<div class=\"b_quote_author mceNonEditable\">(.*?)</div>\\s*<blockquote class=\"b_quote\">\\s*(.*?)\\s*</blockquote>\\s*</div>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); final Pattern PATTERN_THREEPOINTS = Pattern.compile("&#8230;", Pattern.CASE_INSENSITIVE); final String THREEPOINTS = "..."; //TODO: (LD) translate this! private String HIDDEN_STR = "VERBORGEN"; private final String path; /** * * @param container * @param filePerThread */ public ForumStreamedRTFFormatter(ZipOutputStream exportStream, String path, boolean filePerThread) { // init String Buffer in ForumFormatter super(); // where to write this.exportStream = exportStream; this.filePerThread = filePerThread; this.path = path; addStandardImages(); } private String fileName; /** * @see org.olat.core.util.tree.Visitor#visit(org.olat.core.util.nodes.INode) */ public void visit(INode node) { MessageNode mn = (MessageNode)node; if (isTopThread) { //important! fileName = "Thread_" + mn.getKey().toString() + ".rtf"; isTopThread = false; } // Message Title sb.append("{\\pard \\brdrb\\brdrs\\brdrw10 \\f1\\fs30\\b "); sb.append(getImageRTF(mn)); sb.append(getTitlePrefix(mn)); sb.append(mn.getTitle()); sb.append("\\par}"); // Message Body sb.append("{\\pard \\f0"); sb.append(convertHTMLMarkupToRTF(mn.getBody())); sb.append("\\par}"); // Message key sb.append("{\\pard \\f0\\fs15 Message key: "); sb.append(mn.getKey()); sb.append("} \\line "); sb.append("{\\pard \\f0\\fs15 created: "); // Creator and creation date sb.append(mn.getCreator().getUser().getProperty(UserConstants.FIRSTNAME, null)); sb.append(", "); sb.append(mn.getCreator().getUser().getProperty(UserConstants.LASTNAME, null)); sb.append(" "); sb.append(mn.getCreationDate().toString()); // Modifier and modified date Identity modifier = mn.getModifier(); if (modifier != null) { sb.append(" \\line modified: "); sb.append(modifier.getUser().getProperty(UserConstants.FIRSTNAME, null)); sb.append(", "); sb.append(modifier.getUser().getProperty(UserConstants.LASTNAME, null)); sb.append(" "); sb.append(mn.getModifiedDate().toString()); } sb.append(" \\par}"); // attachment(s) OlatRootFolderImpl msgContainer = fm.getMessageContainer(getForumKey(), mn.getKey()); List<VFSItem> attachments = msgContainer.getItems(); if (attachments != null && attachments.size() > 0){ sb.append("{\\pard \\f0\\fs15 Attachment(s): "); boolean commaFlag = false; for (VFSItem attachment: attachments) { if (commaFlag) sb.append(", "); sb.append(attachment.getName()); commaFlag = true; ZipUtil.addToZip(attachment, path + "/attachments", exportStream); } sb.append("} \\line"); } sb.append("{\\pard \\brdrb\\brdrs\\brdrw10 \\par}"); } private void addStandardImages() { String[] images = new String[]{ "fo_sticky_closed", "fo_closed", "fo_sticky"}; try { for(String image:images) { String iconPath = getImagePath(image); if (iconPath != null) { File file = new File(iconPath); if (file.exists()) { exportStream.putNextEntry(new ZipEntry(path + "/" + file.getName())); FileUtils.copyFile(file, exportStream); exportStream.closeEntry(); } } } } catch (IOException e) { e.printStackTrace(); } } /** * * @see org.olat.modules.fo.archiver.formatters.ForumFormatter#openThread() */ public void openThread() { super.openThread(); if(filePerThread){ sb.append("{\\rtf1\\ansi\\deff0"); sb.append("{\\fonttbl {\\f0\\fswiss Arial;}} "); sb.append("\\deflang1033\\plain"); } sb.append("{\\pard \\brdrb \\brdrs \\brdrdb \\brsp20 \\par}{\\pard\\par}"); } /** * * @see org.olat.modules.fo.archiver.formatters.ForumFormatter#getThreadResult() */ public StringBuilder closeThread() { String footerThread = "{\\pard \\brdrb \\brdrs \\brdrw20 \\brsp20 \\par}{\\pard\\par}"; sb.append(footerThread); if(filePerThread){ sb.append("}"); writeToFile(sb); sb = new StringBuilder(); } return sb; } /** * * @see org.olat.modules.fo.archiver.formatters.ForumFormatter#openForum() */ public void openForum(){ if(!filePerThread){ //make one ForumFile Long forumKey = getForumKey(); fileName = "Threads_" + forumKey.toString() + ".rtf"; sb.append("{\\rtf1\\ansi\\deff0"); sb.append("{\\fonttbl {\\f0\\fswiss Arial;}} "); sb.append("\\deflang1033\\plain"); } } /** * * @see org.olat.modules.fo.archiver.formatters.ForumFormatter#closeForum() */ public StringBuilder closeForum(){ if(!filePerThread){ String footerForum = "}"; sb.append(footerForum); writeToFile(sb); } return sb; } /** * * @param append * @param buff */ private void writeToFile(StringBuilder buff){ try { StringBuilder out = new StringBuilder(); int len = buff.length(); for (int i = 0; i < len; i++) { char c = buff.charAt(i); int val = c; if (val > 127) { out.append("\\u").append(String.valueOf(val)).append("?"); } else { out.append(c); } } String encoded = out.toString(); exportStream.putNextEntry(new ZipEntry(path + "/" + fileName)); IOUtils.write(encoded, exportStream); exportStream.closeEntry(); } catch (UnsupportedEncodingException ueEx) { throw new AssertException("could not encode stream from forum export file: " + ueEx); } catch (IOException e) { throw new AssertException("could not write to forum export file: " + e); } } /** * * @param originalText * @return */ private String convertHTMLMarkupToRTF(String originalText){ String htmlText = originalText; Matcher mb = PATTERN_HTML_BOLD.matcher(htmlText); StringBuffer bolds = new StringBuffer(); while (mb.find()) { mb.appendReplacement(bolds, "{\\\\b $1} "); } mb.appendTail(bolds); htmlText = bolds.toString(); Matcher mi = PATTERN_HTML_ITALIC.matcher(htmlText); StringBuffer italics = new StringBuffer(); while (mi.find()) { mi.appendReplacement(italics, "{\\\\i $1} "); } mi.appendTail(italics); htmlText = italics.toString(); Matcher mbr = PATTERN_HTML_BREAK.matcher(htmlText); StringBuffer breaks = new StringBuffer(); while(mbr.find()){ mbr.appendReplacement(breaks, "\\\\line "); } mbr.appendTail(breaks); htmlText = breaks.toString(); Matcher mofo = PATTERN_CSS_O_FOQUOTE.matcher(htmlText); StringBuffer foquotes = new StringBuffer(); while(mofo.find()){ mofo.appendReplacement(foquotes, "\\\\line {\\\\i $1} {\\\\pard $2\\\\par}"); } mofo.appendTail(foquotes); htmlText = foquotes.toString(); Matcher mp = PATTERN_HTML_PARAGRAPH.matcher(htmlText); StringBuffer paragraphs = new StringBuffer(); while(mp.find()){ mp.appendReplacement(paragraphs, "\\\\line $1 \\\\line"); } mp.appendTail(paragraphs); htmlText = paragraphs.toString(); Matcher mahref = PATTERN_HTML_AHREF.matcher(htmlText); StringBuffer ahrefs = new StringBuffer(); while(mahref.find()){ mahref.appendReplacement(ahrefs, "{\\\\field{\\\\*\\\\fldinst{HYPERLINK\"$1\"}}{\\\\fldrslt{\\\\ul $2}}}"); } mahref.appendTail(ahrefs); htmlText = ahrefs.toString(); Matcher mli = PATTERN_HTML_LIST.matcher(htmlText); StringBuffer lists = new StringBuffer(); while(mli.find()){ mli.appendReplacement(lists, "$1\\\\line "); } mli.appendTail(lists); htmlText = lists.toString(); Matcher mtp = PATTERN_THREEPOINTS.matcher(htmlText); StringBuffer tps = new StringBuffer(); while (mtp.find()) { mtp.appendReplacement(tps, THREEPOINTS); } mtp.appendTail(tps); htmlText = tps.toString(); // strip all other html-fragments, because not convertable that easy htmlText = FilterFactory.getHtmlTagsFilter().filter(htmlText); // Remove all &nbsp; Matcher tmp = HTML_SPACE_PATTERN.matcher(htmlText); htmlText = tmp.replaceAll(" "); htmlText = StringEscapeUtils.unescapeHtml(htmlText); return htmlText; } /** * * @param messageNode * @return title prefix for hidden forum threads. */ private String getTitlePrefix(MessageNode messageNode) { StringBuilder sb = new StringBuilder(); if(messageNode.isHidden()) { sb.append(HIDDEN_STR); } if(sb.length()>1) { sb.append(": "); } return sb.toString(); } /** * Gets the RTF image section for the input messageNode. * @param messageNode * @return the RTF image section for the input messageNode. */ private String getImageRTF(MessageNode messageNode) { StringBuilder sb = new StringBuilder(); for(String fileName : addImagesToVFSContainer(messageNode)) { sb.append("{\\field\\fldedit{\\*\\fldinst { INCLUDEPICTURE ") .append("\"").append(fileName).append("\"") .append(" \\\\d }}{\\fldrslt {}}}"); } return sb.toString(); } /** * Retrieves the appropriate images for the input messageNode, if any, * and adds it to the input container. * * @param messageNode * @param container * @return */ private List<String> addImagesToVFSContainer(MessageNode messageNode) { List<String> fileNameList = new ArrayList<String>(); String iconPath = null; if(messageNode.isClosed() && messageNode.isSticky()) { iconPath = getImagePath("fo_sticky_closed"); } else if(messageNode.isClosed()) { iconPath = getImagePath("fo_closed"); } else if(messageNode.isSticky()) { iconPath = getImagePath("fo_sticky"); } if (iconPath != null) { File file = new File(iconPath); if (file.exists()) { fileNameList.add(file.getName()); } else { log.error("Could not find image for forum RTF formatter::" + iconPath); } } return fileNameList; } /** * TODO: LD: to clarify whether there it a better way to get the image path? * Gets the image path. * @param val * @return the path of the static icon image. */ private String getImagePath(Object val) { return WebappHelper.getContextRealPath("/static/images/forum/" + val.toString() + ".png"); } }
stevenhva/InfoLearn_OpenOLAT
src/main/java/org/olat/modules/fo/archiver/formatters/ForumStreamedRTFFormatter.java
Java
apache-2.0
13,207
/* * Copyright 2015 Gerald Muecke, gerald.muecke@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.inkstand.deployment.resteasy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collection; import io.inkstand.Management; import io.inkstand.cdi.ResourcesAndProviders; import io.inkstand.scribble.Scribble; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class DynamicResteasyConfigurationTest { @Mock private ResourcesAndProviders scanner; @InjectMocks private DynamicResteasyConfiguration subject; @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testGetProviderClasses() throws Exception { //prepare when(scanner.getProviderClasses()).thenReturn(Arrays.<Class>asList(Resource.class, ManagementResource.class)); when(scanner.getProviderClasses(Management.class)).thenReturn(Arrays.<Class>asList(ManagementResource.class)); //act Collection<Class> providers = subject.getProviderClasses(); //assert assertNotNull(providers); assertEquals(1, providers.size()); assertTrue(providers.contains(Resource.class)); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testGetResourceClasses() throws Exception { //prepare when(scanner.getResourceClasses()).thenReturn(Arrays.<Class>asList(Resource.class, ManagementResource.class)); when(scanner.getResourceClasses(Management.class)).thenReturn(Arrays.<Class>asList(ManagementResource.class)); //act Collection<Class> resource = subject.getResourceClasses(); //assert assertNotNull(resource); assertEquals(1, resource.size()); assertTrue(resource.contains(Resource.class)); } @Test public void testGetContextRoot_configured() throws Exception { Scribble.inject("root").asConfigProperty("inkstand.rest.contextRoot").into(subject); assertEquals("root", subject.getContextRoot()); } @Test public void testGetContextRoot_unconfigured() throws Exception { assertEquals("", subject.getContextRoot()); } static class Resource {} @Management static class ManagementResource{ } }
inkstand-io/inkstand
inkstand-undertow/inkstand-undertow-resteasy/src/test/java/io/inkstand/deployment/resteasy/DynamicResteasyConfigurationTest.java
Java
apache-2.0
3,091
/******************************************************************************* * Copyright 2016 Intuit * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.intuit.wasabi.experimentobjects; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; /** * This tests the functionality of the {@link ExperimentList} */ public class ExperimentListTest { private ExperimentList expList = new ExperimentList(42); private ExperimentList expList2 = new ExperimentList(7); @Test public void testBuilder() { //equals of the lists is dependend on the elements inside the list assertEquals(expList.hashCode(), expList2.hashCode()); expList2.addExperiment(new Experiment()); assertNotEquals(expList.hashCode(), expList2.hashCode()); } @Test public void testEquals() { assertTrue(expList.equals(expList2)); } @Test public void testContents() { ExperimentList el = new ExperimentList(3); Experiment exp1 = new Experiment(); Experiment exp2 = new Experiment(); el.addExperiment(exp1); el.addExperiment(exp2); assertTrue("Experiments are not in the list.", el.getExperiments().contains(exp1) && el.getExperiments().contains(exp2)); } }
intuit/wasabi
modules/experiment-objects/src/test/java/com/intuit/wasabi/experimentobjects/ExperimentListTest.java
Java
apache-2.0
1,974
package ru.dionisius; /** * Created by Dionisius on 18.01.2017. */ public interface Template { String generate(String template, Object[] data); }
dionisius1976/java-a-to-z
chapter_004/5_DIP/src/test/java/ru/dionisius/Template.java
Java
apache-2.0
153
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.directconnect.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.directconnect.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * CreatePrivateVirtualInterfaceRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CreatePrivateVirtualInterfaceRequestProtocolMarshaller implements Marshaller<Request<CreatePrivateVirtualInterfaceRequest>, CreatePrivateVirtualInterfaceRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("OvertureService.CreatePrivateVirtualInterface").serviceName("AmazonDirectConnect").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public CreatePrivateVirtualInterfaceRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<CreatePrivateVirtualInterfaceRequest> marshall(CreatePrivateVirtualInterfaceRequest createPrivateVirtualInterfaceRequest) { if (createPrivateVirtualInterfaceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<CreatePrivateVirtualInterfaceRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, createPrivateVirtualInterfaceRequest); protocolMarshaller.startMarshalling(); CreatePrivateVirtualInterfaceRequestMarshaller.getInstance().marshall(createPrivateVirtualInterfaceRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-directconnect/src/main/java/com/amazonaws/services/directconnect/model/transform/CreatePrivateVirtualInterfaceRequestProtocolMarshaller.java
Java
apache-2.0
2,918
/* * 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.eagle.common.config; public final class EagleConfigConstants { public final static String SERVICE_ENV = "eagle.service.env"; public final static String SERVICE_HOST = "eagle.service.host"; public final static String SERVICE_PORT = "eagle.service.port"; public final static String SERVICE_HBASE_ZOOKEEPER_QUORUM = "eagle.service.hbase-zookeeper-quorum"; public final static String SERVICE_HBASE_ZOOKEEPER_PROPERTY_CLIENTPORT = "eagle.service.hbase-zookeeper-property-clientPort"; public final static String SERVICE_ZOOKEEPER_ZNODE_PARENT = "eagle.service.zookeeper-znode-parent"; public final static String SERVICE_HBASE_CLIENT_IPC_POOL_SIZE = "eagle.service.hbase-client-ipc-pool-size"; public final static String SERVICE_STORAGE_TYPE = "eagle.service.storage-type"; public final static String SERVICE_COPROCESSOR_ENABLED = "eagle.service.coprocessor-enabled"; public final static String SERVICE_TABLE_NAME_PREFIXED_WITH_ENVIRONMENT = "eagle.service.table-name-prefixed-with-environment"; public final static String SERVICE_HBASE_CLIENT_SCAN_CACHE_SIZE = "eagle.service.hbase-client-scan-cache-size"; public final static String SERVICE_THREADPOOL_CORE_SIZE = "eagle.service.threadpool-core-size"; public final static String SERVICE_THREADPOOL_MAX_SIZE = "eagle.service.threadpool-max-size"; public final static String SERVICE_THREADPOOL_SHRINK_SIZE = "eagle.service.threadpool-shrink-size"; public final static String SERVICE_AUDITING_ENABLED = "eagle.service.audit-enabled"; public final static String EAGLE_TIME_ZONE = "eagle.timezone"; public final static String DEFAULT_EAGLE_TIME_ZONE = "UTC"; public final static int DEFAULT_THREAD_POOL_CORE_SIZE = 10; public final static int DEFAULT_THREAD_POOL_MAX_SIZE = 20; public final static long DEFAULT_THREAD_POOL_SHRINK_TIME = 60000L; public final static String DEFAULT_SERVICE_HOST = "localhost"; public final static String DEFAULT_STORAGE_TYPE = "hbase"; public final static int DEFAULT_SERVICE_PORT = 8080; public final static String DEFAULT_ZOOKEEPER_ZNODE_PARENT = "/hbase-unsecure"; public final static String EAGLE_PROPS="eagleProps"; public final static String EAGLE_SERVICE = "eagleService"; public final static String HOST = "host"; public final static String PORT = "port"; public final static String USERNAME = "username"; public final static String PASSWORD = "password"; public final static String SITE = "site"; @Deprecated public final static String DATA_SOURCE = "dataSource"; public final static String APPLICATION = "application"; public final static String WEB_CONFIG = "web"; public final static String APP_CONFIG = "app"; public final static String CLASSIFICATION_CONFIG = "classification"; public final static String LOCAL_MODE = "local"; public final static String CLUSTER_MODE = "cluster"; }
rlugojr/incubator-eagle
eagle-core/eagle-query/eagle-common/src/main/java/org/apache/eagle/common/config/EagleConfigConstants.java
Java
apache-2.0
3,749
/* * Copyright (C) 2017 Julien Viet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.vertx.mysqlclient.impl.codec; import io.netty.buffer.ByteBuf; import io.vertx.core.Future; import io.vertx.mysqlclient.impl.datatype.DataFormat; import io.vertx.mysqlclient.impl.protocol.CommandType; import io.vertx.sqlclient.impl.command.SimpleQueryCommand; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import static io.vertx.mysqlclient.impl.protocol.Packets.*; class SimpleQueryCommandCodec<T> extends QueryCommandBaseCodec<T, SimpleQueryCommand<T>> { SimpleQueryCommandCodec(SimpleQueryCommand<T> cmd) { super(cmd, DataFormat.TEXT); } @Override void encode(MySQLEncoder encoder) { super.encode(encoder); sendQueryCommand(); } @Override protected void handleInitPacket(ByteBuf payload) { // may receive ERR_Packet, OK_Packet, LOCAL INFILE Request, Text Resultset int firstByte = payload.getUnsignedByte(payload.readerIndex()); if (firstByte == OK_PACKET_HEADER) { OkPacket okPacket = decodeOkPacketPayload(payload); handleSingleResultsetDecodingCompleted(okPacket.serverStatusFlags(), okPacket.affectedRows(), okPacket.lastInsertId()); } else if (firstByte == ERROR_PACKET_HEADER) { handleErrorPacketPayload(payload); } else if (firstByte == 0xFB) { handleLocalInfile(payload); } else { handleResultsetColumnCountPacketBody(payload); } } private void sendQueryCommand() { ByteBuf packet = allocateBuffer(); // encode packet header int packetStartIdx = packet.writerIndex(); packet.writeMediumLE(0); // will set payload length later by calculation packet.writeByte(sequenceId); // encode packet payload packet.writeByte(CommandType.COM_QUERY); packet.writeCharSequence(cmd.sql(), encoder.encodingCharset); // set payload length int payloadLength = packet.writerIndex() - packetStartIdx - 4; packet.setMediumLE(packetStartIdx, payloadLength); sendPacket(packet, payloadLength); } private void handleLocalInfile(ByteBuf payload) { payload.skipBytes(1); String filename = readRestOfPacketString(payload, StandardCharsets.UTF_8); /* We will try to use zero-copy file transfer in order to gain better performance. File content needs to be wrapped in MySQL packets so we calculate the length of the file and then send a pre-calculated packet header with the content. */ File file = new File(filename); long fileLength = file.length(); List<Supplier<Future<Void>>> sendingFileInPacketContList = new ArrayList<>(); int offset = 0; int length = (int) fileLength; while (length > PACKET_PAYLOAD_LENGTH_LIMIT) { final int currentOffset = offset; sendingFileInPacketContList.add(() -> sendFileInPacket(filename, currentOffset, 0xFFFFFF)); length -= PACKET_PAYLOAD_LENGTH_LIMIT; offset += PACKET_PAYLOAD_LENGTH_LIMIT; } final int tailLength = length; final int tailOffset = offset; sendingFileInPacketContList.add(() -> sendFileInPacket(filename, tailOffset, tailLength)); // this can not be null Future<Void> cont = sendingFileInPacketContList.get(0).get(); for (int i = 1; i < sendingFileInPacketContList.size(); i++) { Supplier<Future<Void>> futureSupplier = sendingFileInPacketContList.get(i); cont = cont.flatMap(v -> futureSupplier.get()); } // an empty packet needs to be sent after the file is sent in MySQL packets cont.onComplete(v -> sendEmptyPacket()); } private Future<Void> sendFileInPacket(String filename, int offset, int length) { ByteBuf packetHeader = allocateBuffer(4); packetHeader.writeMediumLE(length); packetHeader.writeByte(sequenceId++); encoder.chctx.write(packetHeader); return encoder.socketConnection.socket().sendFile(filename, offset, length); } private void sendEmptyPacket() { ByteBuf packet = allocateBuffer(4); // encode packet header packet.writeMediumLE(0); packet.writeByte(sequenceId); sendNonSplitPacket(packet); } }
vietj/vertx-pg-client
vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/SimpleQueryCommandCodec.java
Java
apache-2.0
4,702
/********************************************************************** Copyright (c) 2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********************************************************************/ package com.google.appengine.datanucleus; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.datanucleus.mapping.DatastoreTable; import com.google.appengine.datanucleus.mapping.DependentDeleteRequest; import com.google.appengine.datanucleus.mapping.FetchMappingConsumer; import org.datanucleus.ClassLoaderResolver; import org.datanucleus.PropertyNames; import org.datanucleus.exceptions.NucleusObjectNotFoundException; import org.datanucleus.exceptions.NucleusOptimisticException; import org.datanucleus.metadata.AbstractClassMetaData; import org.datanucleus.metadata.AbstractMemberMetaData; import org.datanucleus.metadata.ColumnMetaData; import org.datanucleus.metadata.DiscriminatorMetaData; import org.datanucleus.metadata.IdentityType; import org.datanucleus.metadata.VersionMetaData; import org.datanucleus.metadata.VersionStrategy; import org.datanucleus.store.AbstractPersistenceHandler; import org.datanucleus.ExecutionContext; import org.datanucleus.state.ObjectProvider; import org.datanucleus.store.PersistenceBatchType; import org.datanucleus.store.StoreManager; import org.datanucleus.store.VersionHelper; import org.datanucleus.store.mapped.DatastoreClass; import org.datanucleus.store.mapped.DatastoreField; import org.datanucleus.store.mapped.mapping.ArrayMapping; import org.datanucleus.store.mapped.mapping.CollectionMapping; import org.datanucleus.store.mapped.mapping.IndexMapping; import org.datanucleus.store.mapped.mapping.JavaTypeMapping; import org.datanucleus.store.mapped.mapping.MapMapping; import org.datanucleus.store.mapped.mapping.MappingCallbacks; import org.datanucleus.store.schema.naming.ColumnType; import org.datanucleus.store.types.SCO; import org.datanucleus.util.Localiser; import org.datanucleus.util.NucleusLogger; import org.datanucleus.util.StringUtils; import java.sql.Timestamp; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Handler for persistence requests for GAE/J datastore. Lifecycle management processes persists, updates, deletes * and field access and hands them off here to interface with the datastore. * No method in here should be called from anywhere other than DataNucleus core. * <h3>Persistence Process</h3> * Receive calls to the following from DataNucleus core for persistence events. All persistence events arrive in * the store plugin in the order they are performed by the user. Optimistic operations are queued until flush(). * <p> * <b>PersistenceHandler.insertObject</b><br/> * <ol> * <li>CREATE Entity belonging to the appropriate entity group to represent the object.</li> * * <li>If the entity is “owned” the entity group must be established before the Entity is initially put(), * there is no way to adjust it after. So when persisting an Entity that is a child of some other Entity, you need to * figure out who its parent is before you can do this first put. * <ol> * <li>Key 'id' can be assigned by datastore (long, Long)</li> * <li>Key 'name' can be assigned by the application (or value-generator) (String)</li> * </ol></li> * * <li>Create StoreFieldManager, and set properties in Entity for all fields which have values ready. * <ol> * <li>If “identity” not set on this related object, make note of and skip relation fields.</li> * <li>If related object is detached, note its field number</li> * <li>If “identity” set on this related object, and related object not persistent, flush the related object(s) to * get their Key(s).</li> * </ol></li> * * <li>PUT the Entity in datastore</li> * <li>Set any generated id back on the Entity</li> * <li>If fields noted in step 3.1 * <ol> * <li>Reuse StoreFieldManager from above, and process fields noted earlier. * <ol> * <li>Attach any detached related objects</li> * <li>Persist and flush new related object(s), and add property(s) for relation fields to the Entity</li> * </ol></li> * <li>PUT the updated Entity in datastore</li> * </ol></li> * * </ol> * </p> * * <p> * <b>PersistenceHandler.updateObject</b><br/> * <ol> * <li>GET Entity that represents the object</li> * <li>Populate all updated fields that have values ready, forcing the flush of any relation fields that don't have * their id present, and attach any detached related objects</li> * <li>PUT the updated Entity in datastore</li> * </ol> * </p> * <p> * <b>PersistenceHandler.deleteObject</b><br/> * <ol> * <li>GET Entity that represents the object</li> * <li>Handle any cascade deletion</li> * <li>DELETE the Entity from datastore</li> * </ol> * </p> * * @author Max Ross <maxr@google.com> * @author Andy Jefferson */ public class DatastorePersistenceHandler extends AbstractPersistenceHandler { protected static final Localiser GAE_LOCALISER = Localiser.getInstance( "com.google.appengine.datanucleus.Localisation", DatastoreManager.class.getClassLoader()); private final Map<ExecutionContext, BatchPutManager> batchPutManagerByExecutionContext = new ConcurrentHashMap(); private final Map<ExecutionContext, BatchDeleteManager> batchDeleteManagerByExecutionContext = new ConcurrentHashMap(); private final DatastoreManager datastoreMgr; /** * Constructor. * @param storeMgr The StoreManager to use. */ public DatastorePersistenceHandler(StoreManager storeMgr) { super(storeMgr); this.datastoreMgr = (DatastoreManager) storeMgr; } public void close() {} protected BatchPutManager getBatchPutManager(ExecutionContext ec) { BatchPutManager putMgr = batchPutManagerByExecutionContext.get(ec); if (putMgr == null) { putMgr = new BatchPutManager(); batchPutManagerByExecutionContext.put(ec, putMgr); } return putMgr; } protected BatchDeleteManager getBatchDeleteManager(ExecutionContext ec) { BatchDeleteManager deleteMgr = batchDeleteManagerByExecutionContext.get(ec); if (deleteMgr == null) { deleteMgr = new BatchDeleteManager(ec); batchDeleteManagerByExecutionContext.put(ec, deleteMgr); } return deleteMgr; } /* (non-Javadoc) * @see org.datanucleus.store.AbstractPersistenceHandler#batchStart(org.datanucleus.store.ExecutionContext, org.datanucleus.store.PersistenceBatchType) */ @Override public void batchStart(ExecutionContext ec, PersistenceBatchType batchType) { if (batchType == PersistenceBatchType.PERSIST) { getBatchPutManager(ec).start(); } else if (batchType == PersistenceBatchType.DELETE) { getBatchDeleteManager(ec).start(); } } /* (non-Javadoc) * @see org.datanucleus.store.AbstractPersistenceHandler#batchEnd(org.datanucleus.store.ExecutionContext, org.datanucleus.store.PersistenceBatchType) */ @Override public void batchEnd(ExecutionContext ec, PersistenceBatchType batchType) { if (batchType == PersistenceBatchType.PERSIST) { getBatchPutManager(ec).finish(this); batchPutManagerByExecutionContext.remove(ec); } else if (batchType == PersistenceBatchType.DELETE) { getBatchDeleteManager(ec).finish(this); batchDeleteManagerByExecutionContext.remove(ec); } } /** * Method to insert the specified managed object into the datastore. * @param op ObjectProvider for the managed object */ public void insertObject(ObjectProvider op) { // Make sure writes are permitted assertReadOnlyForUpdateOfObject(op); datastoreMgr.validateMetaDataForClass(op.getClassMetaData()); // If we're in the middle of a batch operation just register the ObjectProvider that needs the insertion BatchPutManager batchPutMgr = getBatchPutManager(op.getExecutionContext()); if (batchPutMgr.batchOperationInProgress()) { batchPutMgr.add(op); return; } insertObjectsInternal(Collections.singletonList(op)); } /** * Method to perform the work of inserting the specified objects. If multiple are to be inserted then * performs it initially as a batch PUT. If some of these need subsequent work (e.g forcing the persist of * children followed by a repersist to link to the children) then this is done one-by-one. */ void insertObjectsInternal(List<ObjectProvider> opsToInsert) { if (opsToInsert == null || opsToInsert.isEmpty()) { return; } // All must be in same ExecutionContext ExecutionContext ec = opsToInsert.get(0).getExecutionContext(); List<PutState> putStateList = Utils.newArrayList(); for (ObjectProvider op : opsToInsert) { AbstractClassMetaData cmd = op.getClassMetaData(); // Create the Entity, and populate all fields that can be populated (this will omit any owned child objects // if we don't have the key of this object yet). StoreFieldManager fieldMgr = new StoreFieldManager(op, EntityUtils.determineKind(cmd, ec)); op.provideFields(op.getClassMetaData().getAllMemberPositions(), fieldMgr); // Make sure the Entity parent is set (if any) Object assignedParentPk = fieldMgr.establishEntityGroup(); Entity entity = fieldMgr.getEntity(); if (!datastoreMgr.storageVersionAtLeast(StorageVersion.READ_OWNED_CHILD_KEYS_FROM_PARENTS)) { // Older storage versions : store list positions in the element DatastoreTable table = datastoreMgr.getDatastoreClass(op.getClassMetaData().getFullClassName(), ec.getClassLoaderResolver()); Collection<JavaTypeMapping> orderMappings = table.getExternalOrderMappings().values(); for (JavaTypeMapping orderMapping : orderMappings) { if (orderMapping instanceof IndexMapping) { Object orderValue = op.getAssociatedValue(orderMapping); if (orderValue != null) { // Set order index on the entity DatastoreField indexProp = orderMapping.getDatastoreMapping(0).getDatastoreField(); entity.setProperty(indexProp.getIdentifier().toString(), orderValue); // Is this indexed in the datastore? } else { // Element has been persisted and has the owner set, but not positioned, so leave til user does it } } } } // Set version handleVersioningBeforeWrite(op, entity, true, "inserting"); // Set discriminator if (op.getClassMetaData().hasDiscriminatorStrategy()) { DiscriminatorMetaData dismd = op.getClassMetaData().getDiscriminatorMetaDataRoot(); EntityUtils.setEntityProperty(entity, dismd, EntityUtils.getDiscriminatorPropertyName(datastoreMgr.getIdentifierFactory(), dismd), op.getClassMetaData().getDiscriminatorValue()); } // Add Multi-tenancy discriminator if applicable if (storeMgr.getStringProperty(PropertyNames.PROPERTY_TENANT_ID) != null) { if ("true".equalsIgnoreCase(cmd.getValueForExtension("multitenancy-disable"))) { // Don't bother with multitenancy for this class } else { String name = storeMgr.getNamingFactory().getColumnName(cmd, ColumnType.MULTITENANCY_COLUMN); EntityUtils.setEntityProperty(entity, cmd, name, storeMgr.getStringProperty(PropertyNames.PROPERTY_TENANT_ID)); } } // Update parent PK field on pojo AbstractMemberMetaData parentPkMmd = datastoreMgr.getMetaDataForParentPK(cmd); if (assignedParentPk != null) { // we automatically assigned a parent to the entity so make sure that makes it back on to the pojo op.replaceField(parentPkMmd.getAbsoluteFieldNumber(), assignedParentPk); } // Add the "state" for this put to the list. putStateList.add(new PutState(op, fieldMgr, entity)); } // PUT all entities in single call if (!putStateList.isEmpty()) { DatastoreTransaction txn = null; AbstractClassMetaData acmd = null; List<Entity> entityList = Utils.newArrayList(); for (PutState putState : putStateList) { if (txn == null) { txn = datastoreMgr.getDatastoreTransaction(ec); } if (acmd == null) { acmd = putState.op.getClassMetaData(); } entityList.add(putState.entity); } EntityUtils.putEntitiesIntoDatastore(ec, entityList); for (PutState putState : putStateList) { putState.op.setAssociatedValue(txn, putState.entity); } } // Post-processing for all puts for (PutState putState : putStateList) { AbstractClassMetaData cmd = putState.op.getClassMetaData(); // Set the generated key back on the pojo. If the pk field is a Key just set it on the field directly. // If the pk field is a String, convert the Key to a String, similarly for long. // Assumes we only have a single pk member position Object newId = null; Class pkType = null; boolean identityStrategyUsed = false; if (cmd.pkIsDatastoreAttributed(storeMgr)) { if (cmd.getIdentityType() == IdentityType.APPLICATION) { // Assume only 1 PK field identityStrategyUsed = true; pkType = cmd.getMetaDataForManagedMemberAtAbsolutePosition(cmd.getPKMemberPositions()[0]).getType(); } else if (cmd.getIdentityType() == IdentityType.DATASTORE) { identityStrategyUsed = true; pkType = Key.class; ColumnMetaData colmd = cmd.getIdentityMetaData().getColumnMetaData(); if (colmd != null) { if ("varchar".equalsIgnoreCase(colmd.getJdbcType()) || "char".equalsIgnoreCase(colmd.getJdbcType())) { pkType = String.class; } else if ("integer".equalsIgnoreCase(colmd.getJdbcType()) || "numeric".equalsIgnoreCase(colmd.getJdbcType())) { pkType = Long.class; } } } } if (identityStrategyUsed) { // Update the identity of the object with the datastore-assigned id if (pkType.equals(Key.class)) { newId = putState.entity.getKey(); } else if (pkType.equals(String.class)) { if (MetaDataUtils.hasEncodedPKField(cmd)) { newId = KeyFactory.keyToString(putState.entity.getKey()); } else { newId = putState.entity.getKey().getName(); } } else if (pkType.equals(Long.class) || pkType.equals(long.class)) { newId = putState.entity.getKey().getId(); } putState.op.setPostStoreNewObjectId(newId); } // Update relation fields (including cascade-persist etc) if (putState.fieldMgr.storeRelations(KeyRegistry.getKeyRegistry(ec))) { // PUT Entity into datastore with these changes EntityUtils.putEntityIntoDatastore(ec, putState.entity); } putState.op.replaceAllLoadedSCOFieldsWithWrappers(); if (ec.getStatistics() != null) { ec.getStatistics().incrementInsertCount(); } } } /** * Method to update the specified fields of the managed object in the datastore. * @param op ObjectProvider of the managed object * @param fieldNumbers Fields to be updated in the datastore */ public void updateObject(ObjectProvider op, int fieldNumbers[]) { if (op.getLifecycleState().isDeleted()) { // don't perform updates on objects that are already deleted - this will cause them to be recreated // This happens with JPAOneToOneTest/JDOOneToOneTest when deleting, called from DependentDeleteRequest return; } // Make sure writes are permitted assertReadOnlyForUpdateOfObject(op); datastoreMgr.validateMetaDataForClass(op.getClassMetaData()); AbstractClassMetaData cmd = op.getClassMetaData(); long startTime = System.currentTimeMillis(); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { StringBuffer fieldStr = new StringBuffer(); for (int i=0;i<fieldNumbers.length;i++) { if (i > 0) { fieldStr.append(","); } fieldStr.append(cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]).getName()); } NucleusLogger.DATASTORE_PERSIST.debug(GAE_LOCALISER.msg("AppEngine.Update.Start", StringUtils.toJVMIDString(op.getObject()), op.getInternalObjectId(), fieldStr.toString())); } ExecutionContext ec = op.getExecutionContext(); Entity entity = (Entity) op.getAssociatedValue(datastoreMgr.getDatastoreTransaction(ec)); if (entity == null) { // Corresponding entity hasn't been fetched yet, so get it. Key key = EntityUtils.getPkAsKey(op); entity = EntityUtils.getEntityFromDatastore(datastoreMgr.getDatastoreServiceForReads(ec), op, key); } // Update the Entity with the specified fields StoreFieldManager fieldMgr = new StoreFieldManager(op, entity, fieldNumbers); op.provideFields(fieldNumbers, fieldMgr); // Check and update the version handleVersioningBeforeWrite(op, entity, true, "updating"); // Update relation fields (including cascade-persist etc) fieldMgr.storeRelations(KeyRegistry.getKeyRegistry(op.getExecutionContext())); // PUT Entity into datastore DatastoreTransaction txn = EntityUtils.putEntityIntoDatastore(ec, entity); op.setAssociatedValue(txn, entity); op.replaceAllLoadedSCOFieldsWithWrappers(); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug(GAE_LOCALISER.msg("AppEngine.ExecutionTime", (System.currentTimeMillis() - startTime))); } if (ec.getStatistics() != null) { ec.getStatistics().incrementUpdateCount(); } } /** * Method to delete the specified managed object from the datastore. * @param op ObjectProvider of the managed object */ public void deleteObject(ObjectProvider op) { // Make sure writes are permitted assertReadOnlyForUpdateOfObject(op); datastoreMgr.validateMetaDataForClass(op.getClassMetaData()); long startTime = System.currentTimeMillis(); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug(GAE_LOCALISER.msg("AppEngine.Delete.Start", StringUtils.toJVMIDString(op.getObject()), op.getInternalObjectId())); } ExecutionContext ec = op.getExecutionContext(); Entity entity = (Entity) op.getAssociatedValue(datastoreMgr.getDatastoreTransaction(ec)); if (entity == null) { // Corresponding entity hasn't been fetched yet, so get it. Key key = EntityUtils.getPkAsKey(op); entity = EntityUtils.getEntityFromDatastore(datastoreMgr.getDatastoreServiceForReads(ec), op, key); } DatastoreTransaction txn = datastoreMgr.getDatastoreTransaction(ec); if (txn != null) { txn.addDeletedKey(entity.getKey()); } // Check the version is valid to delete; any updates since read? handleVersioningBeforeWrite(op, entity, false, "deleting"); // first handle any dependent deletes that need deleting before we delete this object ClassLoaderResolver clr = ec.getClassLoaderResolver(); DatastoreClass dc = datastoreMgr.getDatastoreClass(op.getObject().getClass().getName(), clr); DependentDeleteRequest req = new DependentDeleteRequest(dc, op.getClassMetaData(), clr); Set relatedObjectsToDelete = req.execute(op, entity); Key keyToDelete = EntityUtils.getPkAsKey(op); // If we're in the middle of a batch operation just register the key that needs the delete BatchDeleteManager bdm = getBatchDeleteManager(ec); if (bdm.batchOperationInProgress()) { bdm.add(new BatchDeleteManager.BatchDeleteState(txn, keyToDelete)); if (relatedObjectsToDelete != null && !relatedObjectsToDelete.isEmpty()) { // Delete any related objects that need deleting after the delete of this object Iterator iter = relatedObjectsToDelete.iterator(); while (iter.hasNext()) { Object relatedObject = iter.next(); ec.deleteObjectInternal(relatedObject); } } if (ec.getStatistics() != null) { ec.getStatistics().incrementDeleteCount(); } return; } // Delete this object EntityUtils.deleteEntitiesFromDatastore(ec, Collections.singletonList(keyToDelete)); if (relatedObjectsToDelete != null && !relatedObjectsToDelete.isEmpty()) { // Delete any related objects that need deleting after the delete of this object Iterator iter = relatedObjectsToDelete.iterator(); while (iter.hasNext()) { Object relatedObject = iter.next(); ec.deleteObjectInternal(relatedObject); } } if (ec.getStatistics() != null) { ec.getStatistics().incrementDeleteCount(); } if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug(GAE_LOCALISER.msg("AppEngine.ExecutionTime", (System.currentTimeMillis() - startTime))); } } /** * Method to fetch the specified fields of the managed object from the datastore. * @param op ObjectProvider of the object whose fields need fetching * @param fieldNumbers Fields to fetch */ public void fetchObject(ObjectProvider op, int fieldNumbers[]) { if (fieldNumbers == null || fieldNumbers.length == 0) { return; } AbstractClassMetaData cmd = op.getClassMetaData(); datastoreMgr.validateMetaDataForClass(cmd); // We always fetch the entire object, so if the state manager // already has an associated Entity we know that associated // Entity has all the fields. ExecutionContext ec = op.getExecutionContext(); Entity entity = (Entity) op.getAssociatedValue(datastoreMgr.getDatastoreTransaction(ec)); if (entity == null) { Key pk = EntityUtils.getPkAsKey(op); entity = EntityUtils.getEntityFromDatastore(datastoreMgr.getDatastoreServiceForReads(ec), op, pk); // Throws NucleusObjectNotFoundException if necessary } if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled()) { // Debug information about what we are retrieving StringBuffer str = new StringBuffer("Fetching object \""); str.append(StringUtils.toJVMIDString(op.getObject())).append("\" (id="); str.append(op.getInternalObjectId()).append(")").append(" fields ["); for (int i=0;i<fieldNumbers.length;i++) { if (i > 0) { str.append(","); } str.append(cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]).getName()); } str.append("]"); NucleusLogger.DATASTORE_RETRIEVE.debug(str); } long startTime = System.currentTimeMillis(); if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled()) { NucleusLogger.DATASTORE_RETRIEVE.debug(GAE_LOCALISER.msg("AppEngine.Fetch.Start", StringUtils.toJVMIDString(op.getObject()), op.getInternalObjectId())); } op.replaceFields(fieldNumbers, new FetchFieldManager(op, entity, fieldNumbers)); // Refresh version in case not yet set (e.g created HOLLOW object, and this is first fetch) VersionMetaData vmd = cmd.getVersionMetaDataForClass(); if (cmd.isVersioned()) { Object versionValue = entity.getProperty(EntityUtils.getVersionPropertyName(datastoreMgr.getIdentifierFactory(), vmd)); if (vmd.getVersionStrategy() == VersionStrategy.DATE_TIME) { versionValue = new Timestamp((Long)versionValue); } op.setVersion(versionValue); } // Run post-fetch mapping callbacks. What is this actually achieving? AbstractMemberMetaData[] fmds = new AbstractMemberMetaData[fieldNumbers.length]; for (int i = 0; i < fmds.length; i++) { fmds[i] = op.getClassMetaData().getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]); } ClassLoaderResolver clr = ec.getClassLoaderResolver(); DatastoreClass dc = datastoreMgr.getDatastoreClass(op.getObject().getClass().getName(), clr); FetchMappingConsumer consumer = new FetchMappingConsumer(op.getClassMetaData()); dc.provideMappingsForMembers(consumer, fmds, true); dc.provideDatastoreIdMappings(consumer); dc.providePrimaryKeyMappings(consumer); for (MappingCallbacks callback : consumer.getMappingCallbacks()) { // Arrays and Maps don't use backing stores if (callback instanceof ArrayMapping || callback instanceof MapMapping) { // Do nothing since arrays and maps are stored in the parent property and loaded above using FetchFieldManager } else if (callback instanceof CollectionMapping) { CollectionMapping m = (CollectionMapping)callback; Object val = op.provideField(m.getMemberMetaData().getAbsoluteFieldNumber()); if (val == null || !(val instanceof SCO)) { // Not yet wrapped, so make sure we wrap it callback.postFetch(op); } } else { callback.postFetch(op); } } if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled()) { NucleusLogger.DATASTORE_RETRIEVE.debug(GAE_LOCALISER.msg("AppEngine.ExecutionTime", (System.currentTimeMillis() - startTime))); } if (ec.getStatistics() != null) { ec.getStatistics().incrementFetchCount(); } } /** * Method to locate the specified managed objects in the datastore. * @param ops ObjectProviders for the managed objects * @throws NucleusObjectNotFoundException if any of the objects aren't found in the datastore */ public void locateObjects(ObjectProvider[] ops) { if (ops == null) { return; } List<Key> keysToLocate = Utils.newArrayList(); for (int i=0;i<ops.length;i++) { Key key = EntityUtils.getPkAsKey(ops[i]); keysToLocate.add(key); } EntityUtils.getEntitiesFromDatastore(datastoreMgr.getDatastoreServiceForReads(ops[0].getExecutionContext()), keysToLocate, ops[0].getExecutionContext()); } /** * Method to locate the specified managed object in the datastore. * @param op ObjectProvider for the managed object * @throws NucleusObjectNotFoundException if the object isn't found in the datastore */ public void locateObject(ObjectProvider op) { datastoreMgr.validateMetaDataForClass(op.getClassMetaData()); EntityUtils.getEntityFromDatastore(datastoreMgr.getDatastoreServiceForReads(op.getExecutionContext()), op, EntityUtils.getPkAsKey(op)); } /** * Implementation of this operation is optional and is intended for * datastores that instantiate the model objects themselves (as opposed * to letting datanucleus do it). The App Engine datastore lets * datanucleus instantiate the model objects so we just return null. */ public Object findObject(ExecutionContext ec, Object id) { return null; } /** * Method to check optimistic versioning, and to set the version on the entity when required. * @param op ObjectProvider for the object * @param entity The entity being updated * @param versionBehavior Behaviour required for versioning here * @param operation Convenience string for messages */ private void handleVersioningBeforeWrite(ObjectProvider op, Entity entity, boolean increment, String operation) { AbstractClassMetaData cmd = op.getClassMetaData(); VersionMetaData vmd = cmd.getVersionMetaDataForClass(); if (cmd.isVersioned()) { ExecutionContext ec = op.getExecutionContext(); String versionPropertyName = EntityUtils.getVersionPropertyName(datastoreMgr.getIdentifierFactory(), vmd); Object curVersion = op.getVersion(); if (curVersion != null) { // Fetch the latest and greatest version of the entity from the datastore // to see if anyone has made a change underneath us. We need to execute // the fetch outside a txn to guarantee that we see the latest version. if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) { NucleusLogger.DATASTORE_NATIVE.debug("Getting entity with key " + entity.getKey()); } Entity refreshedEntity; try { if (ec.getStatistics() != null) { ec.getStatistics().incrementNumReads(); } refreshedEntity = datastoreMgr.getDatastoreServiceForReads(op.getExecutionContext()).get(entity.getKey()); } catch (EntityNotFoundException e) { // someone deleted out from under us throw new NucleusOptimisticException(GAE_LOCALISER.msg("AppEngine.OptimisticError.EntityHasBeenDeleted", operation, cmd.getFullClassName(), entity.getKey())); } Object datastoreVersion = refreshedEntity.getProperty(versionPropertyName); if (vmd.getVersionStrategy() == VersionStrategy.DATE_TIME) { datastoreVersion = new Timestamp((Long) datastoreVersion); } if (!datastoreVersion.equals(curVersion)) { throw new NucleusOptimisticException(GAE_LOCALISER.msg("AppEngine.OptimisticError.EntityHasBeenUpdated", operation, cmd.getFullClassName(), entity.getKey())); } } Object nextVersion = VersionHelper.getNextVersion(vmd.getVersionStrategy(), curVersion); op.setTransactionalVersion(nextVersion); if (vmd.getVersionStrategy() == VersionStrategy.DATE_TIME) { EntityUtils.setEntityProperty(entity, vmd, versionPropertyName, ((Timestamp)nextVersion).getTime()); } else { EntityUtils.setEntityProperty(entity, vmd, versionPropertyName, nextVersion); } // Version field - update the version on the object if (increment && vmd.getFieldName() != null) { AbstractMemberMetaData verfmd = ((AbstractClassMetaData)vmd.getParent()).getMetaDataForMember(vmd.getFieldName()); if (nextVersion instanceof Number) { // Version can be long, Long, int, Integer, short, Short (or Timestamp). Number nextNumber = (Number) nextVersion; if (verfmd.getType().equals(Long.class) || verfmd.getType().equals(Long.TYPE)) { nextVersion = nextNumber.longValue(); } else if (verfmd.getType().equals(Integer.class) || verfmd.getType().equals(Integer.TYPE)) { nextVersion = nextNumber.intValue(); } else if (verfmd.getType().equals(Short.class) || verfmd.getType().equals(Short.TYPE)) { nextVersion = nextNumber.shortValue(); } } op.replaceField(verfmd.getAbsoluteFieldNumber(), nextVersion); } } } /** * All the information needed to perform a put on an Entity. */ private static final class PutState { private final ObjectProvider op; private final StoreFieldManager fieldMgr; private final Entity entity; private PutState(ObjectProvider op, StoreFieldManager fieldMgr, Entity entity) { this.op = op; this.fieldMgr = fieldMgr; this.entity = entity; } } }
GoogleCloudPlatform/datanucleus-appengine
src/com/google/appengine/datanucleus/DatastorePersistenceHandler.java
Java
apache-2.0
31,678
/* * Copyright 2020 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/billing/v1/cloud_billing.proto package com.google.cloud.billing.v1; public interface ListBillingAccountsResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.billing.v1.ListBillingAccountsResponse) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * A list of billing accounts. * </pre> * * <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code> */ java.util.List<com.google.cloud.billing.v1.BillingAccount> getBillingAccountsList(); /** * * * <pre> * A list of billing accounts. * </pre> * * <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code> */ com.google.cloud.billing.v1.BillingAccount getBillingAccounts(int index); /** * * * <pre> * A list of billing accounts. * </pre> * * <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code> */ int getBillingAccountsCount(); /** * * * <pre> * A list of billing accounts. * </pre> * * <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code> */ java.util.List<? extends com.google.cloud.billing.v1.BillingAccountOrBuilder> getBillingAccountsOrBuilderList(); /** * * * <pre> * A list of billing accounts. * </pre> * * <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code> */ com.google.cloud.billing.v1.BillingAccountOrBuilder getBillingAccountsOrBuilder(int index); /** * * * <pre> * A token to retrieve the next page of results. To retrieve the next page, * call `ListBillingAccounts` again with the `page_token` field set to this * value. This field is empty if there are no more results to retrieve. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ java.lang.String getNextPageToken(); /** * * * <pre> * A token to retrieve the next page of results. To retrieve the next page, * call `ListBillingAccounts` again with the `page_token` field set to this * value. This field is empty if there are no more results to retrieve. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ com.google.protobuf.ByteString getNextPageTokenBytes(); }
googleapis/java-billing
proto-google-cloud-billing-v1/src/main/java/com/google/cloud/billing/v1/ListBillingAccountsResponseOrBuilder.java
Java
apache-2.0
3,069
/* ### * IP: Apache License 2.0 with LLVM Exceptions */ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.1 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package SWIG; public final class SymbolType { public final static SymbolType eSymbolTypeAny = new SymbolType("eSymbolTypeAny", lldbJNI.eSymbolTypeAny_get()); public final static SymbolType eSymbolTypeInvalid = new SymbolType("eSymbolTypeInvalid", lldbJNI.eSymbolTypeInvalid_get()); public final static SymbolType eSymbolTypeAbsolute = new SymbolType("eSymbolTypeAbsolute"); public final static SymbolType eSymbolTypeCode = new SymbolType("eSymbolTypeCode"); public final static SymbolType eSymbolTypeResolver = new SymbolType("eSymbolTypeResolver"); public final static SymbolType eSymbolTypeData = new SymbolType("eSymbolTypeData"); public final static SymbolType eSymbolTypeTrampoline = new SymbolType("eSymbolTypeTrampoline"); public final static SymbolType eSymbolTypeRuntime = new SymbolType("eSymbolTypeRuntime"); public final static SymbolType eSymbolTypeException = new SymbolType("eSymbolTypeException"); public final static SymbolType eSymbolTypeSourceFile = new SymbolType("eSymbolTypeSourceFile"); public final static SymbolType eSymbolTypeHeaderFile = new SymbolType("eSymbolTypeHeaderFile"); public final static SymbolType eSymbolTypeObjectFile = new SymbolType("eSymbolTypeObjectFile"); public final static SymbolType eSymbolTypeCommonBlock = new SymbolType("eSymbolTypeCommonBlock"); public final static SymbolType eSymbolTypeBlock = new SymbolType("eSymbolTypeBlock"); public final static SymbolType eSymbolTypeLocal = new SymbolType("eSymbolTypeLocal"); public final static SymbolType eSymbolTypeParam = new SymbolType("eSymbolTypeParam"); public final static SymbolType eSymbolTypeVariable = new SymbolType("eSymbolTypeVariable"); public final static SymbolType eSymbolTypeVariableType = new SymbolType("eSymbolTypeVariableType"); public final static SymbolType eSymbolTypeLineEntry = new SymbolType("eSymbolTypeLineEntry"); public final static SymbolType eSymbolTypeLineHeader = new SymbolType("eSymbolTypeLineHeader"); public final static SymbolType eSymbolTypeScopeBegin = new SymbolType("eSymbolTypeScopeBegin"); public final static SymbolType eSymbolTypeScopeEnd = new SymbolType("eSymbolTypeScopeEnd"); public final static SymbolType eSymbolTypeAdditional = new SymbolType("eSymbolTypeAdditional"); public final static SymbolType eSymbolTypeCompiler = new SymbolType("eSymbolTypeCompiler"); public final static SymbolType eSymbolTypeInstrumentation = new SymbolType("eSymbolTypeInstrumentation"); public final static SymbolType eSymbolTypeUndefined = new SymbolType("eSymbolTypeUndefined"); public final static SymbolType eSymbolTypeObjCClass = new SymbolType("eSymbolTypeObjCClass"); public final static SymbolType eSymbolTypeObjCMetaClass = new SymbolType("eSymbolTypeObjCMetaClass"); public final static SymbolType eSymbolTypeObjCIVar = new SymbolType("eSymbolTypeObjCIVar"); public final static SymbolType eSymbolTypeReExported = new SymbolType("eSymbolTypeReExported"); public final int swigValue() { return swigValue; } public String toString() { return swigName; } public static SymbolType swigToEnum(int swigValue) { if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) return swigValues[swigValue]; for (int i = 0; i < swigValues.length; i++) if (swigValues[i].swigValue == swigValue) return swigValues[i]; throw new IllegalArgumentException("No enum " + SymbolType.class + " with value " + swigValue); } private SymbolType(String swigName) { this.swigName = swigName; this.swigValue = swigNext++; } private SymbolType(String swigName, int swigValue) { this.swigName = swigName; this.swigValue = swigValue; swigNext = swigValue+1; } private SymbolType(String swigName, SymbolType swigEnum) { this.swigName = swigName; this.swigValue = swigEnum.swigValue; swigNext = this.swigValue+1; } private static SymbolType[] swigValues = { eSymbolTypeAny, eSymbolTypeInvalid, eSymbolTypeAbsolute, eSymbolTypeCode, eSymbolTypeResolver, eSymbolTypeData, eSymbolTypeTrampoline, eSymbolTypeRuntime, eSymbolTypeException, eSymbolTypeSourceFile, eSymbolTypeHeaderFile, eSymbolTypeObjectFile, eSymbolTypeCommonBlock, eSymbolTypeBlock, eSymbolTypeLocal, eSymbolTypeParam, eSymbolTypeVariable, eSymbolTypeVariableType, eSymbolTypeLineEntry, eSymbolTypeLineHeader, eSymbolTypeScopeBegin, eSymbolTypeScopeEnd, eSymbolTypeAdditional, eSymbolTypeCompiler, eSymbolTypeInstrumentation, eSymbolTypeUndefined, eSymbolTypeObjCClass, eSymbolTypeObjCMetaClass, eSymbolTypeObjCIVar, eSymbolTypeReExported }; private static int swigNext = 0; private final int swigValue; private final String swigName; }
NationalSecurityAgency/ghidra
Ghidra/Debug/Debugger-swig-lldb/src/main/java/SWIG/SymbolType.java
Java
apache-2.0
5,156
/* ### * IP: GHIDRA * * 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 docking.widgets.table.constrainteditor; import java.math.BigInteger; import docking.widgets.table.constraint.ColumnConstraint; import docking.widgets.table.constraint.ColumnData; import docking.widgets.table.constraint.provider.EditorProvider; /** * Provides an editor for editing constraints for unsigned 64 bit values. */ public class UnsignedLongConstraintEditorProvider implements EditorProvider<BigInteger> { @Override public ColumnConstraintEditor<BigInteger> getEditor( ColumnConstraint<BigInteger> columnConstraint, ColumnData<BigInteger> columnDataSource) { return new UnsignedLongConstraintEditor(columnConstraint); } @Override public BigInteger parseValue(String value, Object dataSource) { return new BigInteger(value, 16); } @Override public String toString(BigInteger value) { return value.toString(16); } }
NationalSecurityAgency/ghidra
Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constrainteditor/UnsignedLongConstraintEditorProvider.java
Java
apache-2.0
1,446
package org.sagebionetworks.repo.model.dbo.schema; import java.util.List; import org.sagebionetworks.repo.model.schema.BoundObjectType; import org.sagebionetworks.repo.model.schema.JsonSchema; import org.sagebionetworks.repo.model.schema.JsonSchemaInfo; import org.sagebionetworks.repo.model.schema.JsonSchemaObjectBinding; import org.sagebionetworks.repo.model.schema.JsonSchemaVersionInfo; public interface JsonSchemaDao { /** * Get the version information for the given version ID * * @param versionId * @return */ JsonSchemaVersionInfo getVersionInfo(String versionId); /** * Get the versionId for a specific schema version. * * @param organizationName * @param schemaName * @param semanticVersion * @return */ String getVersionId(String organizationName, String schemaName, String semanticVersion); /** * Get the JsonSchemaVersionInfo for a specific version. * * @param organizationName * @param schemaName * @param semanticVersion * @return */ JsonSchemaVersionInfo getVersionInfo(String organizationName, String schemaName, String semanticVersion); /** * Get the versionId of the latest version for a schema. * * @param organizationName * @param schemaName * @return */ String getLatestVersionId(String organizationName, String schemaName); /** * Get the latest versionId for a schemaId. * @param schemaId * @return */ String getLatestVersionId(String schemaId); /** * Get the latest JsonSchemaVersionInfo for a schema. * * @param organizationName * @param schemaNames * @return */ JsonSchemaVersionInfo getVersionLatestInfo(String organizationName, String schemaName); /** * Get the schema ID for the given organization and name. * @param organizationName * @param schemaName * @return */ String getSchemaId(String organizationName, String schemaName); /** * Truncate all data. */ void truncateAll(); /** * Get the schema for the given version ID. * * @param organizationName * @param schemaName * @return */ JsonSchema getSchema(String versionId); /** * Attempt to delete the given schema. * * @param schemaId */ int deleteSchema(String schemaId); /** * Delete a specific version of a schema. * */ void deleteSchemaVersion(String versionId); /** * Create a new schema version for the given request. * * @param request * @return */ JsonSchemaVersionInfo createNewSchemaVersion(NewSchemaVersionRequest request); /** * List the schemas for the given organization. * @param organizationName * @param limit * @param offset * @return */ List<JsonSchemaInfo> listSchemas(String organizationName, long limit, long offset); /** * List the versions for the given organization and schema names. * @param organizationName * @param schemaName * @param limitForQuery * @param offset * @return */ List<JsonSchemaVersionInfo> listSchemaVersions(String organizationName, String schemaName, long limit, long offset); /** * Bind a JsonSchema to the provided objectId-objectType pair. * @param request */ JsonSchemaObjectBinding bindSchemaToObject(BindSchemaRequest request); /** * Get the JSON schema bound to the given objectId and type. * @param objectId * @param objectType * @return */ JsonSchemaObjectBinding getSchemaBindingForObject(Long objectId, BoundObjectType objectType); /** * Clear the bound schema from an Object. * @param objectId * @param objectType */ void clearBoundSchema(Long objectId, BoundObjectType objectType); }
xschildw/Synapse-Repository-Services
lib/jdomodels/src/main/java/org/sagebionetworks/repo/model/dbo/schema/JsonSchemaDao.java
Java
apache-2.0
3,569
package org.goldenroute.cq.model; import android.media.Image; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class Question implements Serializable { private final String index; private final String description; private final Map<String, Image> images; private final Map<String, String> choices; private final String correctAnswer; private String currentAnswer; private int weight; public Question(String index, String description, Map<String, String> choices, Map<String, Image> images, String correctAnswer) { this.index = index; this.description = description; this.choices = new HashMap<>(); this.images = new HashMap<>(); this.choices.putAll(choices); if (images != null) { this.images.putAll(images); } this.correctAnswer = correctAnswer; this.currentAnswer = null; this.weight = 0; } public String getIndex() { return this.index; } public String getDescription() { return this.description; } public Map<String, String> getChoices() { return Collections.unmodifiableMap(this.choices); } public Map<String, Image> getImage() { return Collections.unmodifiableMap(this.images); } public String getCorrectAnswer() { return this.correctAnswer; } public String getCurrentAnswer() { return this.currentAnswer; } public void setCurrentAnswer(String value) { this.currentAnswer = value; } public int getWeight() { return this.weight; } public void setWeight(int value) { if (value >= 0) { this.weight = value; } } }
edwardluzi/cq-android
app/src/main/java/org/goldenroute/cq/model/Question.java
Java
apache-2.0
1,787
package in.rahul.Client; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; public class ClientSocketMain extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private JLabel lblServerIP; private JTextField txtServerIP; private JLabel lblPort; private JTextField txtPort; private JButton btnConnect; private JTextArea txtMsgList; private JTextField txtMsg; private JButton btnSend; public ClientSocketMain() { WindowAdapter wa = new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { dispose(); } }; this.addWindowListener(wa); this.setLayout(null); this.setSize(525, 720); this.setTitle("Client Chat Window"); this.setVisible(true); lblServerIP = new JLabel("Server IP"); lblServerIP.setBounds(40, 40, 60, 25); lblServerIP.setFocusable(true); this.add(lblServerIP); txtServerIP = new JTextField(); txtServerIP.setBounds(110, 40, 100, 25); this.add(txtServerIP); lblPort = new JLabel("Port"); lblPort.setBounds(240, 40, 30, 25); this.add(lblPort); txtPort = new JTextField(); txtPort.setBounds(280, 40, 70, 25); this.add(txtPort); btnConnect = new JButton("Connect"); btnConnect.setBounds(370, 40, 100, 25); btnConnect.addActionListener(this); this.add(btnConnect); txtMsgList = new JTextArea(); txtMsgList.setBounds(40, 80, 430, 500); txtMsgList.setEditable(false); this.add(txtMsgList); txtMsg = new JTextField(); txtMsg.setBounds(40, 600, 350, 25); this.add(txtMsg); btnSend = new JButton("Send"); btnSend.setBounds(390, 600, 80, 25); btnSend.addActionListener(this); this.add(btnSend); repaint(); } @Override public void actionPerformed(ActionEvent ae) { Object src = ae.getSource(); if (src == btnConnect) { onConnect(); } else if (src == btnSend) { onSend(); } } private void onConnect() { } private void onSend() { } @Override public void paint(Graphics g) { // TODO Auto-generated method stub super.paint(g); repaint(); } public static void main(String[] args) { ClientSocketMain serverSocketMain = new ClientSocketMain(); } }
RGU5Android/JavaDemoCDAC
19.04.GUIForChatting/src/in/rahul/Client/ClientSocketMain.java
Java
apache-2.0
2,523
package ecologylab.bigsemantics.generated.library.creativeWork.scholarlyArticle; /** * Automatically generated by MetaMetadataJavaTranslator * * DO NOT modify this code manually: All your changes may get lost! * * Copyright (2017) Interface Ecology Lab. */ import ecologylab.bigsemantics.metadata.Metadata; import ecologylab.bigsemantics.metadata.builtins.MetadataBuiltinsTypesScope; import ecologylab.bigsemantics.metadata.scalar.MetadataInteger; import ecologylab.bigsemantics.metametadata.MetaMetadataCompositeField; import ecologylab.bigsemantics.namesandnums.SemanticsNames; import ecologylab.serialization.annotations.simpl_inherit; import ecologylab.serialization.annotations.simpl_scalar; import java.lang.Integer; import java.util.List; import java.util.Map; /** *Citation numbers. */ @simpl_inherit public class CitationInfo extends Metadata { @simpl_scalar private MetadataInteger totalCitation; @simpl_scalar private MetadataInteger selfCitation; public CitationInfo() { super(); } public CitationInfo(MetaMetadataCompositeField mmd) { super(mmd); } public MetadataInteger totalCitation() { MetadataInteger result = this.totalCitation; if (result == null) { result = new MetadataInteger(); this.totalCitation = result; } return result; } public Integer getTotalCitation() { return this.totalCitation == null ? 0 : totalCitation().getValue(); } public MetadataInteger getTotalCitationMetadata() { return totalCitation; } public void setTotalCitation(Integer totalCitation) { if (totalCitation != 0) this.totalCitation().setValue(totalCitation); } public void setTotalCitationMetadata(MetadataInteger totalCitation) { this.totalCitation = totalCitation; } public MetadataInteger selfCitation() { MetadataInteger result = this.selfCitation; if (result == null) { result = new MetadataInteger(); this.selfCitation = result; } return result; } public Integer getSelfCitation() { return this.selfCitation == null ? 0 : selfCitation().getValue(); } public MetadataInteger getSelfCitationMetadata() { return selfCitation; } public void setSelfCitation(Integer selfCitation) { if (selfCitation != 0) this.selfCitation().setValue(selfCitation); } public void setSelfCitationMetadata(MetadataInteger selfCitation) { this.selfCitation = selfCitation; } }
ecologylab/BigSemanticsWrapperRepository
BigSemanticsGeneratedClassesJava/src/ecologylab/bigsemantics/generated/library/creativeWork/scholarlyArticle/CitationInfo.java
Java
apache-2.0
2,376
package mblog.core.data; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * @author Beldon */ public class CardTransactionRecord implements Serializable { private static final long serialVersionUID = 8090260110013930023L; private long id; private String customerName;//客户姓名 private BigDecimal feeAmt;//手续费金额 private String agencyName;//所属代理机构名称 private BigDecimal transacount;//交易金额 private String terminalId;//终端编号 private String deal_data;//交易日期 private String deal_time;//交易时间 private String dealTypeName;//交易类型 private String bankcardNumber;//银行卡号 private String idcard;//身份证 private String moblieNoV;//手机号码 private String serialNumber;//交易流水号 private String onlyCode;//交易流水号 private String sysSource;//刷卡平台 private Date dealTime;// private Long point;//返现 private Long point1;//个人返现 private Long point2;//全体返现 private Long userId;// private String realterminalId; private Date createTime;// @Override public String toString() { return "serialNumber:"+serialNumber+",transacount:"+transacount+",moblieNoV:"+moblieNoV+",terminalId:"+terminalId; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public BigDecimal getFeeAmt() { return feeAmt; } public void setFeeAmt(BigDecimal feeAmt) { this.feeAmt = feeAmt; } public String getAgencyName() { return agencyName; } public void setAgencyName(String agencyName) { this.agencyName = agencyName; } public BigDecimal getTransacount() { return transacount; } public void setTransacount(BigDecimal transacount) { this.transacount = transacount; } public String getTerminalId() { return terminalId; } public void setTerminalId(String terminalId) { this.terminalId = terminalId; } public String getDeal_data() { return deal_data; } public void setDeal_data(String deal_data) { this.deal_data = deal_data; } public String getDeal_time() { return deal_time; } public void setDeal_time(String deal_time) { this.deal_time = deal_time; } public String getDealTypeName() { return dealTypeName; } public void setDealTypeName(String dealTypeName) { this.dealTypeName = dealTypeName; } public String getBankcardNumber() { return bankcardNumber; } public void setBankcardNumber(String bankcardNumber) { this.bankcardNumber = bankcardNumber; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } public String getMoblieNoV() { return moblieNoV; } public void setMoblieNoV(String moblieNoV) { this.moblieNoV = moblieNoV; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getOnlyCode() { return onlyCode; } public void setOnlyCode(String onlyCode) { this.onlyCode = onlyCode; } public String getSysSource() { return sysSource; } public void setSysSource(String sysSource) { this.sysSource = sysSource; } public Date getDealTime() { return dealTime; } public void setDealTime(Date dealTime) { this.dealTime = dealTime; } public Long getPoint() { return point; } public void setPoint(Long point) { this.point = point; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getRealterminalId() { return realterminalId; } public void setRealterminalId(String realterminalId) { this.realterminalId = realterminalId; } public Long getPoint1() { return point1; } public void setPoint1(Long point1) { this.point1 = point1; } public Long getPoint2() { return point2; } public void setPoint2(Long point2) { this.point2 = point2; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
tang2988/mblog4tys
mblog-core/src/main/java/mblog/core/data/CardTransactionRecord.java
Java
apache-2.0
4,478
package com.topie.group.persistence.domain; // Generated by Hibernate Tools import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * GroupType . * * @author Lingo */ @Entity @Table(name = "GROUP_TYPE") public class GroupType implements java.io.Serializable { private static final long serialVersionUID = 0L; /** null. */ private Long id; /** null. */ private String name; /** null. */ private String tenantId; /** . */ private Set<GroupInfo> groupInfos = new HashSet<GroupInfo>(0); public GroupType() { } public GroupType(Long id) { this.id = id; } public GroupType(Long id, String name, String tenantId, Set<GroupInfo> groupInfos) { this.id = id; this.name = name; this.tenantId = tenantId; this.groupInfos = groupInfos; } /** @return null. */ @Id @Column(name = "ID", unique = true, nullable = false) public Long getId() { return this.id; } /** * @param id * null. */ public void setId(Long id) { this.id = id; } /** @return null. */ @Column(name = "NAME", length = 50) public String getName() { return this.name; } /** * @param name * null. */ public void setName(String name) { this.name = name; } /** @return null. */ @Column(name = "TENANT_ID", length = 64) public String getTenantId() { return this.tenantId; } /** * @param tenantId * null. */ public void setTenantId(String tenantId) { this.tenantId = tenantId; } /** @return . */ @OneToMany(fetch = FetchType.LAZY, mappedBy = "groupType") public Set<GroupInfo> getGroupInfos() { return this.groupInfos; } /** * @param groupInfos * . */ public void setGroupInfos(Set<GroupInfo> groupInfos) { this.groupInfos = groupInfos; } }
topie/topie-oa
src/main/java/com/topie/group/persistence/domain/GroupType.java
Java
apache-2.0
2,199
package org.pac4j.core.config; import org.pac4j.core.exception.TechnicalException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * To build a configuration from a factory. * * @author Jerome Leleu * @since 1.8.0 */ public final class ConfigBuilder { private final static Logger logger = LoggerFactory.getLogger(ConfigBuilder.class); @SuppressWarnings("unchecked") public synchronized static Config build(final String factoryName, final Object... parameters) { try { logger.info("Build the configuration from factory: {}", factoryName); var tccl = Thread.currentThread().getContextClassLoader(); final Class<ConfigFactory> clazz; if (tccl == null) { clazz = (Class<ConfigFactory>) Class.forName(factoryName); } else { clazz = (Class<ConfigFactory>) Class.forName(factoryName, true, tccl); } final var factory = clazz.getDeclaredConstructor().newInstance(); return factory.build(parameters); } catch (final Exception e) { throw new TechnicalException("Cannot build configuration", e); } } }
pac4j/pac4j
pac4j-core/src/main/java/org/pac4j/core/config/ConfigBuilder.java
Java
apache-2.0
1,194
/* * 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.sis.internal.metadata.sql; import java.sql.SQLException; import java.sql.SQLDataException; import java.sql.DatabaseMetaData; import org.apache.sis.util.Static; import org.apache.sis.util.Characters; import org.apache.sis.util.CharSequences; import org.apache.sis.util.Workaround; import org.apache.sis.util.resources.Errors; /** * Utilities relative to the SQL language. * * <strong>DO NOT USE</strong> * * This class is for Apache SIS internal usage and may change in any future version. * * @author Martin Desruisseaux (Geomatys) * @version 0.8 * @since 0.7 * @module */ public final class SQLUtilities extends Static { /** * Do not allow instantiation of this class. */ private SQLUtilities() { } /** * Returns a simplified form of the URL (truncated before the first {@code ?} or {@code ;} character), * for logging or informative purpose only. * * @param metadata the metadata of the database. * @return a simplified version of database URL. * @throws SQLException if an error occurred while fetching the URL. */ public static String getSimplifiedURL(final DatabaseMetaData metadata) throws SQLException { String url = metadata.getURL(); int s1 = url.indexOf('?'); if (s1 < 0) s1 = url.length(); int s2 = url.indexOf(';'); if (s2 < 0) s2 = url.length(); return url.substring(0, Math.min(s1, s2)); } /** * Converts the given string to a boolean value, or returns {@code null} if the value is unrecognized. * This method recognizes "true", "false", "yes", "no", "t", "f", 0 and 1 (case insensitive). * * @param text the characters to convert to a boolean value, or {@code null}. * @return the given characters as a boolean value, or {@code null} if the given text was null or empty. * @throws SQLDataException if the given text is non-null and non-empty but not recognized. * * @since 0.8 */ public static Boolean toBoolean(final String text) throws SQLException { if (text == null) { return null; } switch (text.length()) { case 0: return null; case 1: { switch (text.charAt(0)) { case '0': case 'n': case 'N': case 'f': case 'F': return Boolean.FALSE; case '1': case 'y': case 'Y': case 't': case 'T': return Boolean.TRUE; } break; } default: { if (text.equalsIgnoreCase("true") || text.equalsIgnoreCase("yes")) return Boolean.TRUE; if (text.equalsIgnoreCase("false") || text.equalsIgnoreCase("no")) return Boolean.FALSE; break; } } throw new SQLDataException(Errors.format(Errors.Keys.CanNotConvertValue_2, text, Boolean.class)); } /** * Returns a string like the given string but with all characters that are not letter or digit * replaced by the wildcard % character. * * <p>This method avoid to put a % symbol as the first character, since it prevent some databases * to use their index.</p> * * @param identifier the identifier to get as a SQL LIKE pattern. * @return the given identifier as a SQL LIKE pattern. */ public static String toLikePattern(final String identifier) { boolean isLetterOrDigit = false; final StringBuilder buffer = new StringBuilder(identifier.length()); for (int c, i = 0; i < identifier.length(); i += Character.charCount(c)) { c = identifier.codePointAt(i); if (Character.isLetterOrDigit(c)) { buffer.appendCodePoint(c); isLetterOrDigit = true; } else if (isLetterOrDigit) { isLetterOrDigit = false; buffer.append('%'); } else { final int p = buffer.length(); if (p == 0 || buffer.charAt(p-1) != '%') { buffer.appendCodePoint(c != '%' ? c : '_'); } } } return buffer.toString(); } /** * Workaround for what seems to be a Derby 10.11 bug, which seems to behave as if the LIKE pattern * had a trailing % wildcard. This can be verified with the following query on the EPSG database: * * {@preformat sql * SELECT COORD_REF_SYS_CODE, COORD_REF_SYS_NAME FROM EPSG."Coordinate Reference System" * WHERE COORD_REF_SYS_NAME LIKE 'NTF%Paris%Lambert%zone%I' * } * * which returns "NTF (Paris) / Lambert zone I" as expected but also zones II and III. * * @param expected the string to search. * @param actual the string found in the database. * @return {@code true} if the given string can be accepted. */ @Workaround(library = "Derby", version = "10.11") public static boolean filterFalsePositive(final String expected, final String actual) { return CharSequences.equalsFiltered(expected, actual, Characters.Filter.LETTERS_AND_DIGITS, false); } }
Geomatys/sis
core/sis-metadata/src/main/java/org/apache/sis/internal/metadata/sql/SQLUtilities.java
Java
apache-2.0
5,926
/* * Copyright (C) 2016 Jorge Ruesga * * 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.ruesga.rview.gerrit.model; import com.google.gson.annotations.SerializedName; import java.util.Map; /** * @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#cherry-pick-change-info" */ public class CherryPickChangeInfo extends ChangeInfo { @SerializedName("contains_git_conflicts") public boolean containsGitConflicts; }
jruesga/rview
gerrit/src/main/java/com/ruesga/rview/gerrit/model/CherryPickChangeInfo.java
Java
apache-2.0
975
/* * Copyright (C) 2013 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.builder.testing; import com.android.annotations.NonNull; import com.android.builder.testing.api.DeviceConnector; import com.android.builder.testing.api.TestException; import com.android.utils.ILogger; import com.google.common.annotations.Beta; import java.io.File; import java.util.Collection; import java.util.List; /** * A test runner able to run tests on a list of {@link DeviceConnector} */ @Beta public interface TestRunner { /** * Returns true if the tests succeeded. * * @param projectName * @param variantName * @param testApk * @param testData * @param deviceList * @param maxThreads the max number of threads to run in parallel. 0 means unlimited. * @param timeoutInMs time out in milliseconds * @param installOptions parameters passed to the pm install command. * @param resultsDir * @param coverageDir * @param logger * @return true if the test succeed * * @throws TestException * @throws InterruptedException */ boolean runTests( @NonNull String projectName, @NonNull String variantName, @NonNull File testApk, @NonNull TestData testData, @NonNull List<? extends DeviceConnector> deviceList, int maxThreads, int timeoutInMs, @NonNull Collection<String> installOptions, @NonNull File resultsDir, @NonNull File coverageDir, @NonNull ILogger logger) throws TestException, NoAuthorizedDeviceFoundException, InterruptedException; class NoAuthorizedDeviceFoundException extends Exception { public NoAuthorizedDeviceFoundException() { super("No suitable device connected"); } } }
consulo/consulo-android
tools-base/build-system/builder/src/main/java/com/android/builder/testing/TestRunner.java
Java
apache-2.0
2,446
/* * @(#)MmeEquivalentPlmn.java 1.0 09/12/14 * * This file has been auto-generated by JNC, the * Java output format plug-in of pyang. * Origin: module "hcta-epc", revision: "2014-09-18". */ package hctaEpc.mmeSgsn.subscriber; import Element; import Epc; import JNCException; import Leaf; import YangString; import com.tailf.jnc.YangElement; /** * This class represents an element from * the namespace http://hitachi-cta.com/ns/epc * generated to "src/hctaEpc/mmeSgsn/subscriber/mme-equivalent-plmn" * <p> * See line 610 in * scConfig.yang * * @version 1.0 2014-12-09 * @author Auto Generated */ public class MmeEquivalentPlmn extends YangElement { private static final long serialVersionUID = 1L; /** * Constructor for an empty MmeEquivalentPlmn object. */ public MmeEquivalentPlmn() { super(Epc.NAMESPACE, "mme-equivalent-plmn"); } /** * Constructor for an initialized MmeEquivalentPlmn object, * * @param nameValue Key argument of child. */ public MmeEquivalentPlmn(YangString nameValue) throws JNCException { super(Epc.NAMESPACE, "mme-equivalent-plmn"); Leaf name = new Leaf(Epc.NAMESPACE, "name"); name.setValue(nameValue); insertChild(name, childrenNames()); } /** * Constructor for an initialized MmeEquivalentPlmn object, * with String keys. * @param nameValue Key argument of child. */ public MmeEquivalentPlmn(String nameValue) throws JNCException { super(Epc.NAMESPACE, "mme-equivalent-plmn"); Leaf name = new Leaf(Epc.NAMESPACE, "name"); name.setValue(new YangString(nameValue)); insertChild(name, childrenNames()); } /** * Clones this object, returning an exact copy. * @return A clone of the object. */ public MmeEquivalentPlmn clone() { MmeEquivalentPlmn copy; try { copy = new MmeEquivalentPlmn(getNameValue().toString()); } catch (JNCException e) { copy = null; } return (MmeEquivalentPlmn)cloneContent(copy); } /** * Clones this object, returning a shallow copy. * @return A clone of the object. Children are not included. */ public MmeEquivalentPlmn cloneShallow() { MmeEquivalentPlmn copy; try { copy = new MmeEquivalentPlmn(getNameValue().toString()); } catch (JNCException e) { copy = null; } return (MmeEquivalentPlmn)cloneShallowContent(copy); } /** * @return An array with the identifiers of any key children */ public String[] keyNames() { return new String[] { "name", }; } /** * @return An array with the identifiers of any children, in order. */ public String[] childrenNames() { return new String[] { "name", "plmn-list", }; } /* Access methods for leaf child: "name". */ /** * Gets the value for child leaf "name". * @return The value of the leaf. */ public YangString getNameValue() throws JNCException { return (YangString)getValue("name"); } /** * Sets the value for child leaf "name", * using instance of generated typedef class. * @param nameValue The value to set. * @param nameValue used during instantiation. */ public void setNameValue(YangString nameValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "name", nameValue, childrenNames()); } /** * Sets the value for child leaf "name", * using a String value. * @param nameValue used during instantiation. */ public void setNameValue(String nameValue) throws JNCException { setNameValue(new YangString(nameValue)); } /** * This method is used for creating a subtree filter. * The added "name" leaf will not have a value. */ public void addName() throws JNCException { setLeafValue(Epc.NAMESPACE, "name", null, childrenNames()); } /* Access methods for optional leaf child: "plmn-list". */ /** * Gets the value for child leaf "plmn-list". * @return The value of the leaf. */ public YangString getPlmnListValue() throws JNCException { return (YangString)getValue("plmn-list"); } /** * Sets the value for child leaf "plmn-list", * using instance of generated typedef class. * @param plmnListValue The value to set. * @param plmnListValue used during instantiation. */ public void setPlmnListValue(YangString plmnListValue) throws JNCException { setLeafValue(Epc.NAMESPACE, "plmn-list", plmnListValue, childrenNames()); } /** * Sets the value for child leaf "plmn-list", * using a String value. * @param plmnListValue used during instantiation. */ public void setPlmnListValue(String plmnListValue) throws JNCException { setPlmnListValue(new YangString(plmnListValue)); } /** * Unsets the value for child leaf "plmn-list". */ public void unsetPlmnListValue() throws JNCException { delete("plmn-list"); } /** * This method is used for creating a subtree filter. * The added "plmn-list" leaf will not have a value. */ public void addPlmnList() throws JNCException { setLeafValue(Epc.NAMESPACE, "plmn-list", null, childrenNames()); } /** * Marks the leaf "plmn-list" with operation "replace". */ public void markPlmnListReplace() throws JNCException { markLeafReplace("plmnList"); } /** * Marks the leaf "plmn-list" with operation "merge". */ public void markPlmnListMerge() throws JNCException { markLeafMerge("plmnList"); } /** * Marks the leaf "plmn-list" with operation "create". */ public void markPlmnListCreate() throws JNCException { markLeafCreate("plmnList"); } /** * Marks the leaf "plmn-list" with operation "delete". */ public void markPlmnListDelete() throws JNCException { markLeafDelete("plmnList"); } /** * Support method for addChild. * Adds a child to this object. * * @param child The child to add */ public void addChild(Element child) { super.addChild(child); } }
jnpr-shinma/yangfile
hitel/src/hctaEpc/mmeSgsn/subscriber/MmeEquivalentPlmn.java
Java
apache-2.0
6,546
/* * 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.catalina.servlets; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import javax.servlet.http.HttpServletResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Assert; import org.junit.Test; import static org.apache.catalina.startup.SimpleHttpClient.CRLF; import org.apache.catalina.Context; import org.apache.catalina.Wrapper; import org.apache.catalina.startup.SimpleHttpClient; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.websocket.server.WsContextListener; public class TestDefaultServlet extends TomcatBaseTest { /* * Test attempting to access special paths (WEB-INF/META-INF) using * DefaultServlet. */ @Test public void testGetSpecials() throws Exception { Tomcat tomcat = getTomcatInstance(); String contextPath = "/examples"; File appDir = new File(getBuildDirectory(), "webapps" + contextPath); // app dir is relative to server home tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); tomcat.start(); final ByteChunk res = new ByteChunk(); int rc =getUrl("http://localhost:" + getPort() + contextPath + "/WEB-INF/web.xml", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/WEB-INF/doesntexistanywhere", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/WEB-INF/", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/META-INF/MANIFEST.MF", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/META-INF/doesntexistanywhere", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); } /* * Verify serving of gzipped resources from context root. */ @Test public void testGzippedFile() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); File gzipIndex = new File(appDir, "index.html.gz"); long gzipSize = gzipIndex.length(); File index = new File(appDir, "index.html"); long indexSize = index.length(); // app dir is relative to server home Context ctxt = tomcat.addContext("", appDir.getAbsolutePath()); Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default", "org.apache.catalina.servlets.DefaultServlet"); defaultServlet.addInitParameter("gzip", "true"); ctxt.addServletMappingDecoded("/", "default"); ctxt.addMimeMapping("html", "text/html"); tomcat.start(); TestCompressedClient gzipClient = new TestCompressedClient(getPort()); gzipClient.reset(); gzipClient.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: gzip, br" + CRLF + CRLF }); gzipClient.connect(); gzipClient.processRequest(); assertTrue(gzipClient.isResponse200()); List<String> responseHeaders = gzipClient.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Encoding: gzip")); assertTrue(responseHeaders.contains("Content-Length: " + gzipSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); gzipClient.reset(); gzipClient.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF+ CRLF }); gzipClient.connect(); gzipClient.processRequest(); assertTrue(gzipClient.isResponse200()); responseHeaders = gzipClient.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Type: text/html")); assertFalse(responseHeaders.contains("Content-Encoding: gzip")); assertTrue(responseHeaders.contains("Content-Length: " + indexSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); } /* * Verify serving of brotli compressed resources from context root. */ @Test public void testBrotliCompressedFile() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); long brSize = new File(appDir, "index.html.br").length(); long indexSize = new File(appDir, "index.html").length(); // app dir is relative to server home Context ctxt = tomcat.addContext("", appDir.getAbsolutePath()); Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default", "org.apache.catalina.servlets.DefaultServlet"); defaultServlet.addInitParameter("precompressed", "true"); ctxt.addServletMappingDecoded("/", "default"); ctxt.addMimeMapping("html", "text/html"); tomcat.start(); TestCompressedClient client = new TestCompressedClient(getPort()); client.reset(); client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: br, gzip" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); List<String> responseHeaders = client.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Encoding: br")); assertTrue(responseHeaders.contains("Content-Length: " + brSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); client.reset(); client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF+ CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); responseHeaders = client.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Type: text/html")); assertFalse(responseHeaders.contains("Content-Encoding")); assertTrue(responseHeaders.contains("Content-Length: " + indexSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); } /* * Verify serving of custom compressed resources from context root. */ @Test public void testCustomCompressedFile() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); long brSize = new File(appDir, "index.html.br").length(); long gzSize = new File(appDir, "index.html.gz").length(); // app dir is relative to server home Context ctxt = tomcat.addContext("", appDir.getAbsolutePath()); Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default", DefaultServlet.class.getName()); defaultServlet.addInitParameter("precompressed", "gzip=.gz,custom=.br"); ctxt.addServletMappingDecoded("/", "default"); ctxt.addMimeMapping("html", "text/html"); tomcat.start(); TestCompressedClient client = new TestCompressedClient(getPort()); client.reset(); client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: br, gzip ; q = 0.5 , custom" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); List<String> responseHeaders = client.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Encoding: custom")); assertTrue(responseHeaders.contains("Content-Length: " + brSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); client.reset(); client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: br;q=1,gzip,custom" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); responseHeaders = client.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Encoding: gzip")); assertTrue(responseHeaders.contains("Content-Length: " + gzSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); } /* * Verify that "*" and "identity" values are handled correctly in accept-encoding header. */ @Test public void testIdentityAndStarAcceptEncodings() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); long brSize = new File(appDir, "index.html.br").length(); long indexSize = new File(appDir, "index.html").length(); // app dir is relative to server home Context ctxt = tomcat.addContext("", appDir.getAbsolutePath()); Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default", DefaultServlet.class.getName()); defaultServlet.addInitParameter("precompressed", "br=.br,gzip=.gz"); ctxt.addServletMappingDecoded("/", "default"); ctxt.addMimeMapping("html", "text/html"); tomcat.start(); TestCompressedClient client = new TestCompressedClient(getPort()); client.reset(); client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: gzip;q=0.9,*" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); List<String> responseHeaders = client.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Encoding: br")); assertTrue(responseHeaders.contains("Content-Length: " + brSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); client.reset(); client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: gzip;q=0.9,br;q=0,identity," + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); responseHeaders = client.getResponseHeaders(); assertFalse(responseHeaders.contains("Content-Encoding")); assertTrue(responseHeaders.contains("Content-Length: " + indexSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); } /* * Verify preferring of brotli in default configuration for actual Firefox and Chrome requests. */ @Test public void testBrotliPreference() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); long brSize = new File(appDir, "index.html.br").length(); // app dir is relative to server home Context ctxt = tomcat.addContext("", appDir.getAbsolutePath()); Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default", DefaultServlet.class.getName()); defaultServlet.addInitParameter("precompressed", "true"); ctxt.addServletMappingDecoded("/", "default"); ctxt.addMimeMapping("html", "text/html"); tomcat.start(); TestCompressedClient client = new TestCompressedClient(getPort()); // Firefox 45 Accept-Encoding client.reset(); client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: gzip, deflate, br" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); List<String> responseHeaders = client.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Encoding: br")); assertTrue(responseHeaders.contains("Content-Length: " + brSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); // Chrome 50 Accept-Encoding client.reset(); client.setRequest(new String[] { "GET /index.html HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: Close" + CRLF + "Accept-Encoding: gzip, deflate, sdch, br" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); responseHeaders = client.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Encoding: br")); assertTrue(responseHeaders.contains("Content-Length: " + brSize)); assertTrue(responseHeaders.contains("Vary: accept-encoding")); } /* * Test https://bz.apache.org/bugzilla/show_bug.cgi?id=50026 * Verify serving of resources from context root with subpath mapping. */ @Test public void testGetWithSubpathmount() throws Exception { Tomcat tomcat = getTomcatInstance(); String contextPath = "/examples"; File appDir = new File(getBuildDirectory(), "webapps" + contextPath); // app dir is relative to server home org.apache.catalina.Context ctx = tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); ctx.addApplicationListener(WsContextListener.class.getName()); // Override the default servlet with our own mappings Tomcat.addServlet(ctx, "default2", new DefaultServlet()); ctx.addServletMappingDecoded("/", "default2"); ctx.addServletMappingDecoded("/servlets/*", "default2"); ctx.addServletMappingDecoded("/static/*", "default2"); tomcat.start(); final ByteChunk res = new ByteChunk(); // Make sure DefaultServlet isn't exposing special directories // by remounting the webapp under a sub-path int rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/WEB-INF/web.xml", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/WEB-INF/doesntexistanywhere", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/WEB-INF/", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/META-INF/MANIFEST.MF", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/META-INF/doesntexistanywhere", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); // Make sure DefaultServlet is serving resources relative to the // context root regardless of where the it is mapped final ByteChunk rootResource = new ByteChunk(); rc =getUrl("http://localhost:" + getPort() + contextPath + "/index.html", rootResource, null); assertEquals(HttpServletResponse.SC_OK, rc); final ByteChunk subpathResource = new ByteChunk(); rc =getUrl("http://localhost:" + getPort() + contextPath + "/servlets/index.html", subpathResource, null); assertEquals(HttpServletResponse.SC_OK, rc); assertFalse(rootResource.toString().equals(subpathResource.toString())); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/index.html", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); } /* * Test https://bz.apache.org/bugzilla/show_bug.cgi?id=50413 Serving a * custom error page */ @Test public void testCustomErrorPage() throws Exception { File appDir = new File(getTemporaryDirectory(), "MyApp"); File webInf = new File(appDir, "WEB-INF"); addDeleteOnTearDown(appDir); if (!webInf.mkdirs() && !webInf.isDirectory()) { fail("Unable to create directory [" + webInf + "]"); } File webxml = new File(appDir, "WEB-INF/web.xml"); try (FileOutputStream fos = new FileOutputStream(webxml); Writer w = new OutputStreamWriter(fos, "UTF-8");) { w.write("<?xml version='1.0' encoding='UTF-8'?>\n" + "<web-app xmlns='http://java.sun.com/xml/ns/j2ee' " + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + " xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee " + " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd'" + " version='2.4'>\n" + "<error-page>\n<error-code>404</error-code>\n" + "<location>/404.html</location>\n</error-page>\n" + "</web-app>\n"); } File error404 = new File(appDir, "404.html"); try (FileOutputStream fos = new FileOutputStream(error404); Writer w = new OutputStreamWriter(fos, "ISO-8859-1")) { w.write("It is 404.html"); } Tomcat tomcat = getTomcatInstance(); String contextPath = "/MyApp"; tomcat.addWebapp(null, contextPath, appDir.getAbsolutePath()); tomcat.start(); TestCustomErrorClient client = new TestCustomErrorClient(tomcat.getConnector().getLocalPort()); client.reset(); client.setRequest(new String[] { "GET /MyApp/missing HTTP/1.0" +CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse404()); assertEquals("It is 404.html", client.getResponseBody()); SimpleDateFormat format = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); String tomorrow = format.format(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)); // https://bz.apache.org/bugzilla/show_bug.cgi?id=50413 // client.reset(); client.setRequest(new String[] { "GET /MyApp/missing HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: close" + CRLF + "If-Modified-Since: " + tomorrow + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse404()); assertEquals("It is 404.html", client.getResponseBody()); // https://bz.apache.org/bugzilla/show_bug.cgi?id=50413#c6 // client.reset(); client.setRequest(new String[] { "GET /MyApp/missing HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: close" + CRLF + "Range: bytes=0-100" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse404()); assertEquals("It is 404.html", client.getResponseBody()); } /* * Test what happens if a custom 404 page is configured, * but its file is actually missing. */ @Test public void testCustomErrorPageMissing() throws Exception { File appDir = new File(getTemporaryDirectory(), "MyApp"); File webInf = new File(appDir, "WEB-INF"); addDeleteOnTearDown(appDir); if (!webInf.mkdirs() && !webInf.isDirectory()) { fail("Unable to create directory [" + webInf + "]"); } File webxml = new File(appDir, "WEB-INF/web.xml"); try (FileOutputStream fos = new FileOutputStream(webxml); Writer w = new OutputStreamWriter(fos, "UTF-8");) { w.write("<?xml version='1.0' encoding='UTF-8'?>\n" + "<web-app xmlns='http://java.sun.com/xml/ns/j2ee' " + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + " xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee " + " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd'" + " version='2.4'>\n" + "<error-page>\n<error-code>404</error-code>\n" + "<location>/404-absent.html</location>\n</error-page>\n" + "</web-app>\n"); } Tomcat tomcat = getTomcatInstance(); String contextPath = "/MyApp"; tomcat.addWebapp(null, contextPath, appDir.getAbsolutePath()); tomcat.start(); TestCustomErrorClient client = new TestCustomErrorClient(tomcat.getConnector().getLocalPort()); client.reset(); client.setRequest(new String[] { "GET /MyApp/missing HTTP/1.0" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse404()); } /* * Verifies that the same Content-Length is returned for both GET and HEAD * operations when a static resource served by the DefaultServlet is * included. */ @Test public void testBug57601() throws Exception { Tomcat tomcat = getTomcatInstanceTestWebapp(false, true); Map<String,List<String>> resHeaders= new HashMap<>(); String path = "http://localhost:" + getPort() + "/test/bug5nnnn/bug57601.jsp"; ByteChunk out = new ByteChunk(); int rc = getUrl(path, out, resHeaders); Assert.assertEquals(HttpServletResponse.SC_OK, rc); String length = resHeaders.get("Content-Length").get(0); Assert.assertEquals(Long.parseLong(length), out.getLength()); out.recycle(); rc = headUrl(path, out, resHeaders); Assert.assertEquals(HttpServletResponse.SC_OK, rc); Assert.assertEquals(0, out.getLength()); Assert.assertEquals(length, resHeaders.get("Content-Length").get(0)); tomcat.stop(); } public static int getUrl(String path, ByteChunk out, Map<String, List<String>> resHead) throws IOException { out.recycle(); return TomcatBaseTest.getUrl(path, out, resHead); } private static class TestCustomErrorClient extends SimpleHttpClient { public TestCustomErrorClient(int port) { setPort(port); } @Override public boolean isResponseBodyOK() { return true; } } private static class TestCompressedClient extends SimpleHttpClient { public TestCompressedClient(int port) { setPort(port); } @Override public boolean isResponseBodyOK() { return true; } } }
Nickname0806/Test_Q4
test/org/apache/catalina/servlets/TestDefaultServlet.java
Java
apache-2.0
24,892
package ru.job4j.h4isp; import ru.job4j.utils.Utils; import java.util.ArrayList; import java.util.List; /** * @author Vitaly Vasilyev, date: 05.06.2019, e-mail: rav.energ@rambler.ru * @version 1.0 */ public class MenuItem { /** * Имя пункта меню. */ private static final String NAME = "Задача "; /** * Список дочерних элементов пункта меню. */ private final List<MenuItem> children = new ArrayList<>(); /** * Номер пункта меню. */ private final String number; /** * @param number номер для присвоения. */ public MenuItem(final String number) { this.number = number; } /** * @return список дочерних элементов. * У каждого элемента список дочерних элементов сортируется прежде, чем вернуть из метода. */ public List<MenuItem> getChildren() { children.sort(Utils.compareMenuItems()); return this.children; } /** * @return номер пункта меню. */ public String getNumber() { return this.number; } /** * @param child дочерний элемент для добавления в список. */ public void addChild(final MenuItem child) { this.children.add(child); } /** * @return количество знаков "-" в соответствии с номером пункта меню. */ private String countPoints() { final StringBuilder sb = new StringBuilder(""); for (char c : this.number.toCharArray()) { if (c == '.') { sb.append("-"); } } return sb.toString(); } /** * @return строк.представление. */ @Override public String toString() { return String.format("%s%s%s", countPoints(), NAME, this.number); } }
Ravmouse/vvasilyev
chapter_010/src/main/java/ru/job4j/h4isp/MenuItem.java
Java
apache-2.0
2,054
package de.wathoserver.fb_bike_adjuster.cli; import java.util.logging.Logger; import org.springframework.boot.SpringApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.shell.support.logging.HandlerUtils; /** * spring shell application * * @author linux_china * @see https://github.com/linux-china/spring-boot-starter-shell */ public class SpringShellApplication { public static void run(Object source, String... args) { run(new Object[] {source}, args); } public static void run(Object[] sources, String[] args) { ConfigurableApplicationContext ctx = new SpringApplication(sources).run(args); try { new BootShim(args, ctx).run(); } finally { HandlerUtils.flushAllHandlers(Logger.getLogger("")); } } }
watho/FitB_Adjuster
src/main/java/de/wathoserver/fb_bike_adjuster/cli/SpringShellApplication.java
Java
apache-2.0
807
package de.wellnerbou.chronic.logparser; import com.google.gson.stream.JsonReader; import de.wellnerbou.chronic.replay.LogLineData; import org.assertj.core.api.Assertions; import org.junit.Test; import java.io.InputStream; import java.io.InputStreamReader; /** * @author Paul Wellner Bou <paul@wellnerbou.de> */ public class ElasticSearchJsonLogLineParserTest { final ElasticSearchJsonLogLineParser elasticSearchJsonLogLineParser = new ElasticSearchJsonLogLineParser(); @Test public void parseLine() { final String resourceUrlStr = "/elasticsearch-example.json"; final InputStream is = this.getClass().getResourceAsStream(resourceUrlStr); final JsonReader jsonReader = new JsonReader(new InputStreamReader(is)); final LogLineData lineData = elasticSearchJsonLogLineParser.parseLine(jsonReader); final LogLineData expected = new LogLineData(); expected.setTime(1460429014000L); expected.setDuration(141546L); expected.setStatusCode("200"); expected.setRequestMethod("GET"); expected.setRequest("/one"); expected.setHost("example.com"); expected.setReferrer("http://referrer.example.com/1"); expected.setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"); Assertions.assertThat(lineData).isEqualToComparingFieldByField(expected); } @Test public void parseLine2() { final String resourceUrlStr = "/simplified.json"; final InputStream is = this.getClass().getResourceAsStream(resourceUrlStr); final JsonReader jsonReader = new JsonReader(new InputStreamReader(is)); final LogLineData lineData = elasticSearchJsonLogLineParser.parseLine(jsonReader); final LogLineData expected = new LogLineData(); expected.setTime(1460350800000L); expected.setDuration(0); expected.setStatusCode("304"); expected.setRequestMethod("GET"); expected.setRequest("/one"); expected.setReferrer("-"); expected.setHost("host1.example.com"); expected.setUserAgent("Mozilla/4.0 (compatible;)"); Assertions.assertThat(lineData).isEqualToComparingFieldByField(expected); } }
paulwellnerbou/chronicreplay
src/test/java/de/wellnerbou/chronic/logparser/ElasticSearchJsonLogLineParserTest.java
Java
apache-2.0
2,100
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.server.browserlaunchers; import com.google.common.base.Charsets; import com.google.common.collect.Maps; import com.google.common.io.ByteStreams; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.thoughtworks.selenium.CommandProcessor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import java.util.UUID; import java.util.logging.Logger; public class ServerHttpChannel implements Runnable { private final static Logger log = Logger.getLogger(ServerHttpChannel.class.getName()); private final String serverUrl; private final String sessionId; private final CommandProcessor processor; private final ProcessorCommands commands = new ProcessorCommands(); private int sequenceNumber; private HttpURLConnection connection; private volatile boolean carryOn = true; public ServerHttpChannel(String sessionId, int serverPort, CommandProcessor processor) { this.sessionId = sessionId; this.processor = processor; serverUrl = String.format( "http://localhost:%d/selenium-server/driver/?localFrameAddress=top&seleniumWindowName=&uniqueId=%s", serverPort, UUID.randomUUID()); } public void run() { try { send("OK," + sessionId, null); while (carryOn) { String raw = read(); log.fine("read complete: " + raw); if (carryOn) { carryOn = execute(processor, raw); } } send("OK", null); } catch (ConnectException e) { log.warning("Unable to connect to server. Assuming shutdown."); // And fall out the bottom of the run method. Don't clean up, just in // case. } catch (IOException e) { throw new RuntimeException(e); } } private boolean execute(CommandProcessor processor, String raw) throws IOException { Map<String, String> command = parse(raw); if (command == null) { return false; } String[] args; if (command.containsKey("value")) { args = new String[2]; args[0] = command.get("target"); args[1] = command.get("value"); } else { args = new String[1]; args[1] = command.get("target"); } String commandName = command.get("command"); if ("retryLast".equals(commandName)) { send("RETRY", "retry=true"); return true; } StringBuilder value = new StringBuilder(); try { String result = commands.execute(processor, commandName, args); value.append("OK"); if (result != null) { value.append(",").append(result); } } catch (Throwable e) { value.append("ERROR,").append(e.getMessage()); } send(value.toString(), null); return true; } private Map<String, String> parse(String raw) { if (!raw.startsWith("json=")) { return null; } JsonObject converted = new JsonParser().parse(raw.substring("json=".length())).getAsJsonObject(); Map<String, String> toReturn = Maps.newHashMap(); for (Map.Entry<String, JsonElement> entry : converted.entrySet()) { toReturn.put(entry.getKey(), entry.getValue().getAsString()); } return toReturn; } public void kill() { carryOn = false; } public void send(String postedData, String urlParams) throws IOException { log.fine("Sending a response: " + postedData); StringBuilder builder = new StringBuilder(serverUrl).append("&sessionId=").append(sessionId); if (sequenceNumber == 0) { builder.append("&seleniumStart=true"); } builder.append("&sequenceNumber=").append(sequenceNumber++); if (urlParams != null) { builder.append("&").append(urlParams); } StringBuilder response = new StringBuilder("postedData="); response.append(URLEncoder.encode(postedData, Charsets.UTF_8.name())); byte[] toSend = response.toString().getBytes(Charsets.UTF_8); connection = (HttpURLConnection) new URL(builder.toString()).openConnection(); connection.setUseCaches(false); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF8"); connection.setRequestProperty("Content-Length", String.valueOf(toSend.length)); OutputStream out = connection.getOutputStream(); try { out.write(toSend); out.flush(); } finally { out.close(); } } public String read() throws IOException { InputStream input = connection.getInputStream(); byte[] bytes = null; try { bytes = ByteStreams.toByteArray(input); } finally { input.close(); } connection.disconnect(); connection = null; return new String(bytes, Charsets.UTF_8); } }
joshuaduffy/selenium
java/server/src/org/openqa/selenium/server/browserlaunchers/ServerHttpChannel.java
Java
apache-2.0
5,742
package com.cloudata.structured.web; import java.io.IOException; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.cloudata.structured.sql.SqlEngine; import com.cloudata.structured.sql.SqlEngineFactory; import com.cloudata.structured.sql.SqlSession; import com.cloudata.structured.sql.SqlStatement; @Path("/{storeId}/sql") public class SqlEndpoint { @Inject SqlEngineFactory sqlEngineFactory; @PathParam("storeId") long storeId; @GET @Produces(MediaType.APPLICATION_JSON) public Response queryJson(@QueryParam("sql") String sql) throws IOException { SqlEngine sqlEngine = sqlEngineFactory.get(storeId); SqlSession session = sqlEngine.createSession(); SqlStatement statement = sqlEngine.parse(session, sql); if (!statement.isSimple()) { throw new UnsupportedOperationException(); } return Response.ok(statement).build(); } }
justinsb/cloudata
cloudata-structured/src/main/java/com/cloudata/structured/web/SqlEndpoint.java
Java
apache-2.0
1,124
/* * Copyright (c) 2017. California Community Colleges Technology Center * * 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.pesc.sdk.message.functionalacknowledgement.v1_2; import com.google.common.collect.Lists; import org.apache.commons.lang3.builder.ToStringBuilder; import org.pesc.sdk.core.coremain.v1_14.SeverityCodeType; import java.util.List; /** * Created with IntelliJ IDEA. * User: sallen * Date: 6/2/2014 * Time: 3:28 PM * To change this template use File | Settings | File Templates. */ public class ValidationResponse { private SeverityCodeType severity = null; List<SyntaxErrorType> errors = Lists.newArrayList(); public SeverityCodeType getSeverity() { return severity; } public void setSeverity(SeverityCodeType severity) { this.severity = severity; } /** * Add passed in error to <CODE>ValidationResponse.errors</CODE> and sets <CODE>ValidationResponse.severity</CODE> based on error severity. * @param error */ public void addError(SyntaxErrorType error){ addError(error, false); } /** * Add passed in error to top of <CODE>ValidationResponse.errors</CODE> list and sets <CODE>ValidationResponse.severity</CODE> based on error severity. * @param error */ public void addErrorToTop(SyntaxErrorType error){ addError(error, true); } private void addError(SyntaxErrorType error, boolean addToTop){ SeverityCodeType severityCode = error.getSeverityCode(); if(severityCode!=null && severityCode!=this.severity){ if(this.severity ==null || severityCode==SeverityCodeType.FATAL_ERROR){ this.severity = severityCode; }else if(this.severity ==SeverityCodeType.WARNING && severityCode==SeverityCodeType.ERROR){ this.severity = severityCode; } } if(addToTop){ this.getErrors().add(0, error); }else { this.getErrors().add(error); } } public List<SyntaxErrorType> getErrors() { return errors; } @Override public String toString() { return new ToStringBuilder(this) .append("severity", severity) .append("errors", errorToString()) .toString(); } private List<String> errorToString(){ List<String> errorStrings = Lists.newArrayList(); for(SyntaxErrorType error: this.errors){ errorStrings.add(new ToStringBuilder(error) .append("severityCode", error.getSeverityCode()) .append("errorMessage", error.getErrorMessage()) .toString()); } return errorStrings; } }
jhwhetstone/cdsWebserver
pesc-sdk/src/main/java/org/pesc/sdk/message/functionalacknowledgement/v1_2/ValidationResponse.java
Java
apache-2.0
3,258
/* * Copyright 2014-2019 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.comprehend.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.comprehend.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DocumentClassifierProperties JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DocumentClassifierPropertiesJsonUnmarshaller implements Unmarshaller<DocumentClassifierProperties, JsonUnmarshallerContext> { public DocumentClassifierProperties unmarshall(JsonUnmarshallerContext context) throws Exception { DocumentClassifierProperties documentClassifierProperties = new DocumentClassifierProperties(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("DocumentClassifierArn", targetDepth)) { context.nextToken(); documentClassifierProperties.setDocumentClassifierArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("LanguageCode", targetDepth)) { context.nextToken(); documentClassifierProperties.setLanguageCode(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Status", targetDepth)) { context.nextToken(); documentClassifierProperties.setStatus(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Message", targetDepth)) { context.nextToken(); documentClassifierProperties.setMessage(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("SubmitTime", targetDepth)) { context.nextToken(); documentClassifierProperties.setSubmitTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("EndTime", targetDepth)) { context.nextToken(); documentClassifierProperties.setEndTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("TrainingStartTime", targetDepth)) { context.nextToken(); documentClassifierProperties.setTrainingStartTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("TrainingEndTime", targetDepth)) { context.nextToken(); documentClassifierProperties.setTrainingEndTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("InputDataConfig", targetDepth)) { context.nextToken(); documentClassifierProperties.setInputDataConfig(DocumentClassifierInputDataConfigJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("OutputDataConfig", targetDepth)) { context.nextToken(); documentClassifierProperties.setOutputDataConfig(DocumentClassifierOutputDataConfigJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("ClassifierMetadata", targetDepth)) { context.nextToken(); documentClassifierProperties.setClassifierMetadata(ClassifierMetadataJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("DataAccessRoleArn", targetDepth)) { context.nextToken(); documentClassifierProperties.setDataAccessRoleArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("VolumeKmsKeyId", targetDepth)) { context.nextToken(); documentClassifierProperties.setVolumeKmsKeyId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("VpcConfig", targetDepth)) { context.nextToken(); documentClassifierProperties.setVpcConfig(VpcConfigJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return documentClassifierProperties; } private static DocumentClassifierPropertiesJsonUnmarshaller instance; public static DocumentClassifierPropertiesJsonUnmarshaller getInstance() { if (instance == null) instance = new DocumentClassifierPropertiesJsonUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-comprehend/src/main/java/com/amazonaws/services/comprehend/model/transform/DocumentClassifierPropertiesJsonUnmarshaller.java
Java
apache-2.0
6,447
/* * Copyright (c) 2017, Inversoft 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 org.example.action.nested.treeCollisions; import org.primeframework.mvc.action.annotation.Action; /** * @author Brian Pontarelli */ @Action(prefixParameters = "{pre3}") public class SecondAction { public String param; public String param2; public String pre3; public String post() { return "success"; } }
prime-framework/prime-mvc
src/test/java/org/example/action/nested/treeCollisions/SecondAction.java
Java
apache-2.0
956
package org.wikipedia.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import org.wikipedia.WikipediaApp; import org.wikipedia.editing.summaries.EditSummary; import org.wikipedia.history.HistoryEntry; import org.wikipedia.pageimages.PageImage; import org.wikipedia.readinglist.database.ReadingListRow; import org.wikipedia.readinglist.page.ReadingListPageRow; import org.wikipedia.savedpages.SavedPage; import org.wikipedia.search.RecentSearch; import org.wikipedia.useroption.database.UserOptionRow; import org.wikipedia.util.log.L; public class Database extends SQLiteOpenHelper { private static final String DATABASE_NAME = "wikipedia.db"; private static final int DATABASE_VERSION = 13; private final DatabaseTable<?>[] databaseTables = { HistoryEntry.DATABASE_TABLE, PageImage.DATABASE_TABLE, RecentSearch.DATABASE_TABLE, SavedPage.DATABASE_TABLE, EditSummary.DATABASE_TABLE, // Order matters. UserOptionDatabaseTable has a dependency on // UserOptionHttpDatabaseTable table when upgrading so this table must appear before it. UserOptionRow.HTTP_DATABASE_TABLE, UserOptionRow.DATABASE_TABLE, ReadingListPageRow.DISK_DATABASE_TABLE, ReadingListPageRow.HTTP_DATABASE_TABLE, ReadingListPageRow.DATABASE_TABLE, ReadingListRow.DATABASE_TABLE }; public Database(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { for (DatabaseTable<?> table : databaseTables) { table.upgradeSchema(sqLiteDatabase, 0, DATABASE_VERSION); } } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int from, int to) { L.i("Upgrading from=" + from + " to=" + to); WikipediaApp.getInstance().putCrashReportProperty("fromDatabaseVersion", String.valueOf(from)); for (DatabaseTable<?> table : databaseTables) { table.upgradeSchema(sqLiteDatabase, from, to); } } }
carloshwa/apps-android-wikipedia
app/src/main/java/org/wikipedia/database/Database.java
Java
apache-2.0
2,219
// Copyright 2004, 2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry.services; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tapestry.IRequestCycle; import org.apache.tapestry.web.WebRequest; import org.apache.tapestry.web.WebResponse; /** * Access point for thread-local information about the current request. * * @author Howard Lewis Ship * @since 4.0 */ public interface RequestGlobals { void store(HttpServletRequest request, HttpServletResponse response); void store(WebRequest request, WebResponse response); void store(IRequestCycle cycle); HttpServletRequest getRequest(); WebRequest getWebRequest(); HttpServletResponse getResponse(); WebResponse getWebResponse(); IRequestCycle getRequestCycle(); }
apache/tapestry4
framework/src/java/org/apache/tapestry/services/RequestGlobals.java
Java
apache-2.0
1,394
/** * 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.tez.dag.app.dag.impl; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.util.StringInterner; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.state.InvalidStateTransitonException; import org.apache.hadoop.yarn.state.MultipleArcTransition; import org.apache.hadoop.yarn.state.SingleArcTransition; import org.apache.hadoop.yarn.state.StateMachine; import org.apache.hadoop.yarn.state.StateMachineFactory; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.RackResolver; import org.apache.hadoop.yarn.util.Records; import org.apache.tez.common.counters.DAGCounter; import org.apache.tez.common.counters.TezCounters; import org.apache.tez.dag.api.TezConfiguration; import org.apache.tez.dag.api.TezUncheckedException; import org.apache.tez.dag.api.TaskLocationHint; import org.apache.tez.dag.api.oldrecords.TaskAttemptReport; import org.apache.tez.dag.api.oldrecords.TaskAttemptState; import org.apache.tez.dag.app.AppContext; import org.apache.tez.dag.app.ContainerContext; import org.apache.tez.dag.app.TaskAttemptListener; import org.apache.tez.dag.app.TaskHeartbeatHandler; import org.apache.tez.dag.app.dag.Task; import org.apache.tez.dag.app.dag.TaskAttempt; import org.apache.tez.dag.app.dag.TaskAttemptStateInternal; import org.apache.tez.dag.app.dag.Vertex; import org.apache.tez.dag.app.dag.event.DAGEvent; import org.apache.tez.dag.app.dag.event.DAGEventCounterUpdate; import org.apache.tez.dag.app.dag.event.DAGEventDiagnosticsUpdate; import org.apache.tez.dag.app.dag.event.DAGEventType; import org.apache.tez.dag.app.dag.event.DiagnosableEvent; import org.apache.tez.dag.app.dag.event.TaskAttemptEvent; import org.apache.tez.dag.app.dag.event.TaskAttemptEventAttemptFailed; import org.apache.tez.dag.app.dag.event.TaskAttemptEventContainerTerminated; import org.apache.tez.dag.app.dag.event.TaskAttemptEventTerminationCauseEvent; import org.apache.tez.dag.app.dag.event.TaskAttemptEventOutputFailed; import org.apache.tez.dag.app.dag.event.TaskAttemptEventSchedule; import org.apache.tez.dag.app.dag.event.TaskAttemptEventStartedRemotely; import org.apache.tez.dag.app.dag.event.TaskAttemptEventStatusUpdate; import org.apache.tez.dag.app.dag.event.TaskAttemptEventType; import org.apache.tez.dag.app.dag.event.TaskEventTAUpdate; import org.apache.tez.dag.app.dag.event.TaskEventType; import org.apache.tez.dag.app.dag.event.VertexEventRouteEvent; import org.apache.tez.dag.app.dag.event.SpeculatorEventTaskAttemptStatusUpdate; import org.apache.tez.dag.app.rm.AMSchedulerEventTAEnded; import org.apache.tez.dag.app.rm.AMSchedulerEventTALaunchRequest; import org.apache.tez.dag.history.DAGHistoryEvent; import org.apache.tez.dag.history.HistoryEvent; import org.apache.tez.dag.history.events.TaskAttemptFinishedEvent; import org.apache.tez.dag.history.events.TaskAttemptStartedEvent; import org.apache.tez.dag.records.TaskAttemptTerminationCause; import org.apache.tez.dag.records.TezDAGID; import org.apache.tez.dag.records.TezTaskAttemptID; import org.apache.tez.dag.records.TezTaskID; import org.apache.tez.dag.records.TezVertexID; import org.apache.tez.dag.utils.TezBuilderUtils; import org.apache.tez.runtime.api.events.InputFailedEvent; import org.apache.tez.runtime.api.events.InputReadErrorEvent; import org.apache.tez.runtime.api.events.TaskStatusUpdateEvent; import org.apache.tez.runtime.api.impl.EventMetaData; import org.apache.tez.runtime.api.impl.TaskSpec; import org.apache.tez.runtime.api.impl.TaskStatistics; import org.apache.tez.runtime.api.impl.TezEvent; import org.apache.tez.runtime.api.impl.EventMetaData.EventProducerConsumerType; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; public class TaskAttemptImpl implements TaskAttempt, EventHandler<TaskAttemptEvent> { // TODO Ensure MAPREDUCE-4457 is factored in. Also MAPREDUCE-4068. // TODO Consider TAL registration in the TaskAttempt instead of the container. private static final Logger LOG = LoggerFactory.getLogger(TaskAttemptImpl.class); private static final String LINE_SEPARATOR = System .getProperty("line.separator"); static final TezCounters EMPTY_COUNTERS = new TezCounters(); protected final Configuration conf; @SuppressWarnings("rawtypes") protected EventHandler eventHandler; private final TezTaskAttemptID attemptId; private final Clock clock; private TaskAttemptTerminationCause terminationCause = TaskAttemptTerminationCause.UNKNOWN_ERROR; private final List<String> diagnostics = new ArrayList<String>(); private final Lock readLock; private final Lock writeLock; protected final AppContext appContext; private final TaskHeartbeatHandler taskHeartbeatHandler; private long launchTime = 0; private long finishTime = 0; private String trackerName; private int httpPort; // TODO Can these be replaced by the container object TEZ-1037 private Container container; private ContainerId containerId; private NodeId containerNodeId; private String nodeHttpAddress; private String nodeRackName; private final Task task; private final Vertex vertex; @VisibleForTesting TaskAttemptStatus reportedStatus; private DAGCounter localityCounter; org.apache.tez.runtime.api.impl.TaskStatistics statistics; // Used to store locality information when Set<String> taskHosts = new HashSet<String>(); Set<String> taskRacks = new HashSet<String>(); private Set<TezTaskAttemptID> uniquefailedOutputReports = new HashSet<TezTaskAttemptID>(); private static double MAX_ALLOWED_OUTPUT_FAILURES_FRACTION; private static int MAX_ALLOWED_OUTPUT_FAILURES; protected final boolean isRescheduled; private final Resource taskResource; private final ContainerContext containerContext; private final boolean leafVertex; protected static final FailedTransitionHelper FAILED_HELPER = new FailedTransitionHelper(); protected static final KilledTransitionHelper KILLED_HELPER = new KilledTransitionHelper(); private static SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> TERMINATED_AFTER_SUCCESS_HELPER = new TerminatedAfterSuccessHelper(KILLED_HELPER); private static SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> STATUS_UPDATER = new StatusUpdaterTransition(); private final StateMachine<TaskAttemptStateInternal, TaskAttemptEventType, TaskAttemptEvent> stateMachine; private static StateMachineFactory <TaskAttemptImpl, TaskAttemptStateInternal, TaskAttemptEventType, TaskAttemptEvent> stateMachineFactory = new StateMachineFactory <TaskAttemptImpl, TaskAttemptStateInternal, TaskAttemptEventType, TaskAttemptEvent> (TaskAttemptStateInternal.NEW) .addTransition(TaskAttemptStateInternal.NEW, EnumSet.of(TaskAttemptStateInternal.START_WAIT, TaskAttemptStateInternal.FAILED), TaskAttemptEventType.TA_SCHEDULE, new ScheduleTaskattemptTransition()) .addTransition(TaskAttemptStateInternal.NEW, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_KILL_REQUEST, new TerminateTransition(KILLED_HELPER)) .addTransition(TaskAttemptStateInternal.NEW, EnumSet.of(TaskAttemptStateInternal.NEW, TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.KILLED, TaskAttemptStateInternal.FAILED, TaskAttemptStateInternal.SUCCEEDED), TaskAttemptEventType.TA_RECOVER, new RecoverTransition()) .addTransition(TaskAttemptStateInternal.START_WAIT, TaskAttemptStateInternal.RUNNING, TaskAttemptEventType.TA_STARTED_REMOTELY, new StartedTransition()) .addTransition(TaskAttemptStateInternal.START_WAIT, TaskAttemptStateInternal.KILL_IN_PROGRESS, TaskAttemptEventType.TA_KILL_REQUEST, new TerminatedBeforeRunningTransition(KILLED_HELPER)) .addTransition(TaskAttemptStateInternal.START_WAIT, TaskAttemptStateInternal.KILL_IN_PROGRESS, TaskAttemptEventType.TA_NODE_FAILED, new NodeFailedBeforeRunningTransition()) .addTransition(TaskAttemptStateInternal.START_WAIT, TaskAttemptStateInternal.FAIL_IN_PROGRESS, TaskAttemptEventType.TA_CONTAINER_TERMINATING, new ContainerTerminatingBeforeRunningTransition()) .addTransition(TaskAttemptStateInternal.START_WAIT, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CONTAINER_TERMINATED, new ContainerCompletedBeforeRunningTransition()) .addTransition(TaskAttemptStateInternal.START_WAIT, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_CONTAINER_TERMINATED_BY_SYSTEM, new ContainerCompletedBeforeRunningTransition(KILLED_HELPER)) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.RUNNING, TaskAttemptEventType.TA_STATUS_UPDATE, STATUS_UPDATER) // Optional, may not come in for all tasks. .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.SUCCEEDED, TaskAttemptEventType.TA_DONE, new SucceededTransition()) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.FAIL_IN_PROGRESS, TaskAttemptEventType.TA_FAILED, new TerminatedWhileRunningTransition(FAILED_HELPER)) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.FAIL_IN_PROGRESS, TaskAttemptEventType.TA_TIMED_OUT, new TerminatedWhileRunningTransition(FAILED_HELPER)) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.KILL_IN_PROGRESS, TaskAttemptEventType.TA_KILL_REQUEST, new TerminatedWhileRunningTransition(KILLED_HELPER)) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.KILL_IN_PROGRESS, TaskAttemptEventType.TA_NODE_FAILED, new TerminatedWhileRunningTransition(KILLED_HELPER)) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.FAIL_IN_PROGRESS, TaskAttemptEventType.TA_CONTAINER_TERMINATING, new TerminatedWhileRunningTransition(FAILED_HELPER)) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CONTAINER_TERMINATED, new ContainerCompletedWhileRunningTransition()) .addTransition(TaskAttemptStateInternal.RUNNING, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_CONTAINER_TERMINATED_BY_SYSTEM, new ContainerCompletedWhileRunningTransition(KILLED_HELPER)) .addTransition( TaskAttemptStateInternal.RUNNING, EnumSet.of(TaskAttemptStateInternal.FAIL_IN_PROGRESS, TaskAttemptStateInternal.RUNNING), TaskAttemptEventType.TA_OUTPUT_FAILED, new OutputReportedFailedTransition()) .addTransition(TaskAttemptStateInternal.KILL_IN_PROGRESS, TaskAttemptStateInternal.KILLED, TaskAttemptEventType.TA_CONTAINER_TERMINATED, new ContainerCompletedWhileTerminating()) .addTransition( TaskAttemptStateInternal.KILL_IN_PROGRESS, TaskAttemptStateInternal.KILL_IN_PROGRESS, EnumSet.of(TaskAttemptEventType.TA_STARTED_REMOTELY, TaskAttemptEventType.TA_CONTAINER_TERMINATED_BY_SYSTEM, TaskAttemptEventType.TA_STATUS_UPDATE, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_FAILED, TaskAttemptEventType.TA_TIMED_OUT, TaskAttemptEventType.TA_KILL_REQUEST, TaskAttemptEventType.TA_NODE_FAILED, TaskAttemptEventType.TA_CONTAINER_TERMINATING, TaskAttemptEventType.TA_OUTPUT_FAILED)) .addTransition(TaskAttemptStateInternal.FAIL_IN_PROGRESS, TaskAttemptStateInternal.FAILED, TaskAttemptEventType.TA_CONTAINER_TERMINATED, new ContainerCompletedWhileTerminating()) .addTransition( TaskAttemptStateInternal.FAIL_IN_PROGRESS, TaskAttemptStateInternal.FAIL_IN_PROGRESS, EnumSet.of(TaskAttemptEventType.TA_STARTED_REMOTELY, TaskAttemptEventType.TA_CONTAINER_TERMINATED_BY_SYSTEM, TaskAttemptEventType.TA_STATUS_UPDATE, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_FAILED, TaskAttemptEventType.TA_TIMED_OUT, TaskAttemptEventType.TA_KILL_REQUEST, TaskAttemptEventType.TA_NODE_FAILED, TaskAttemptEventType.TA_CONTAINER_TERMINATING, TaskAttemptEventType.TA_OUTPUT_FAILED)) .addTransition( TaskAttemptStateInternal.KILLED, TaskAttemptStateInternal.KILLED, EnumSet.of(TaskAttemptEventType.TA_STARTED_REMOTELY, TaskAttemptEventType.TA_SCHEDULE, TaskAttemptEventType.TA_CONTAINER_TERMINATED_BY_SYSTEM, TaskAttemptEventType.TA_STATUS_UPDATE, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_FAILED, TaskAttemptEventType.TA_TIMED_OUT, TaskAttemptEventType.TA_KILL_REQUEST, TaskAttemptEventType.TA_NODE_FAILED, TaskAttemptEventType.TA_CONTAINER_TERMINATING, TaskAttemptEventType.TA_CONTAINER_TERMINATED, TaskAttemptEventType.TA_OUTPUT_FAILED)) .addTransition( TaskAttemptStateInternal.FAILED, TaskAttemptStateInternal.FAILED, EnumSet.of(TaskAttemptEventType.TA_STARTED_REMOTELY, TaskAttemptEventType.TA_SCHEDULE, TaskAttemptEventType.TA_CONTAINER_TERMINATED_BY_SYSTEM, TaskAttemptEventType.TA_STATUS_UPDATE, TaskAttemptEventType.TA_DONE, TaskAttemptEventType.TA_FAILED, TaskAttemptEventType.TA_TIMED_OUT, TaskAttemptEventType.TA_KILL_REQUEST, TaskAttemptEventType.TA_NODE_FAILED, TaskAttemptEventType.TA_CONTAINER_TERMINATING, TaskAttemptEventType.TA_CONTAINER_TERMINATED, TaskAttemptEventType.TA_OUTPUT_FAILED)) // How will duplicate history events be handled ? // TODO Maybe consider not failing REDUCE tasks in this case. Also, // MAP_TASKS in case there's only one phase in the job. .addTransition( TaskAttemptStateInternal.SUCCEEDED, EnumSet.of(TaskAttemptStateInternal.KILLED, TaskAttemptStateInternal.SUCCEEDED), TaskAttemptEventType.TA_KILL_REQUEST, new TerminatedAfterSuccessTransition()) .addTransition( TaskAttemptStateInternal.SUCCEEDED, EnumSet.of(TaskAttemptStateInternal.KILLED, TaskAttemptStateInternal.SUCCEEDED), TaskAttemptEventType.TA_NODE_FAILED, new TerminatedAfterSuccessTransition()) .addTransition( TaskAttemptStateInternal.SUCCEEDED, EnumSet.of(TaskAttemptStateInternal.FAILED, TaskAttemptStateInternal.SUCCEEDED), TaskAttemptEventType.TA_OUTPUT_FAILED, new OutputReportedFailedTransition()) .addTransition( TaskAttemptStateInternal.SUCCEEDED, TaskAttemptStateInternal.SUCCEEDED, EnumSet.of(TaskAttemptEventType.TA_TIMED_OUT, TaskAttemptEventType.TA_CONTAINER_TERMINATING, TaskAttemptEventType.TA_CONTAINER_TERMINATED, TaskAttemptEventType.TA_CONTAINER_TERMINATED_BY_SYSTEM)) .installTopology(); private TaskAttemptState recoveredState = TaskAttemptState.NEW; private boolean recoveryStartEventSeen = false; @SuppressWarnings("rawtypes") public TaskAttemptImpl(TezTaskID taskId, int attemptNumber, EventHandler eventHandler, TaskAttemptListener taskAttemptListener, Configuration conf, Clock clock, TaskHeartbeatHandler taskHeartbeatHandler, AppContext appContext, boolean isRescheduled, Resource resource, ContainerContext containerContext, boolean leafVertex, Task task) { this.MAX_ALLOWED_OUTPUT_FAILURES = conf.getInt(TezConfiguration .TEZ_TASK_MAX_ALLOWED_OUTPUT_FAILURES, TezConfiguration .TEZ_TASK_MAX_ALLOWED_OUTPUT_FAILURES_DEFAULT); this.MAX_ALLOWED_OUTPUT_FAILURES_FRACTION = conf.getDouble(TezConfiguration .TEZ_TASK_MAX_ALLOWED_OUTPUT_FAILURES_FRACTION, TezConfiguration .TEZ_TASK_MAX_ALLOWED_OUTPUT_FAILURES_FRACTION_DEFAULT); ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); this.readLock = rwLock.readLock(); this.writeLock = rwLock.writeLock(); this.attemptId = TezBuilderUtils.newTaskAttemptId(taskId, attemptNumber); this.eventHandler = eventHandler; //Reported status this.conf = conf; this.clock = clock; this.taskHeartbeatHandler = taskHeartbeatHandler; this.appContext = appContext; this.task = task; this.vertex = this.task.getVertex(); this.reportedStatus = new TaskAttemptStatus(this.attemptId); initTaskAttemptStatus(reportedStatus); RackResolver.init(conf); this.stateMachine = stateMachineFactory.make(this); this.isRescheduled = isRescheduled; this.taskResource = resource; this.containerContext = containerContext; this.leafVertex = leafVertex; } @Override public TezTaskAttemptID getID() { return attemptId; } @Override public TezTaskID getTaskID() { return attemptId.getTaskID(); } @Override public TezVertexID getVertexID() { return attemptId.getTaskID().getVertexID(); } @Override public TezDAGID getDAGID() { return getVertexID().getDAGId(); } TaskSpec createRemoteTaskSpec() throws AMUserCodeException { TaskSpec baseTaskSpec = task.getBaseTaskSpec(); if (baseTaskSpec == null) { // since recovery does not follow normal transitions, TaskEventScheduleTask // is not being honored by the recovery code path. Using this to workaround // until recovery is fixed. Calling the non-locking internal method of the vertex // to get the taskSpec directly. Since everything happens on the central dispatcher // during recovery this is deadlock free for now. TEZ-1019 should remove the need for this. baseTaskSpec = ((VertexImpl) vertex).createRemoteTaskSpec(getID().getTaskID().getId()); } return new TaskSpec(getID(), baseTaskSpec.getDAGName(), baseTaskSpec.getVertexName(), baseTaskSpec.getVertexParallelism(), baseTaskSpec.getProcessorDescriptor(), baseTaskSpec.getInputs(), baseTaskSpec.getOutputs(), baseTaskSpec.getGroupInputs()); } @Override public TaskAttemptReport getReport() { TaskAttemptReport result = Records.newRecord(TaskAttemptReport.class); readLock.lock(); try { result.setTaskAttemptId(attemptId); //take the LOCAL state of attempt //DO NOT take from reportedStatus result.setTaskAttemptState(getState()); result.setProgress(reportedStatus.progress); result.setStartTime(launchTime); result.setFinishTime(finishTime); //result.setShuffleFinishTime(this.reportedStatus.shuffleFinishTime); result.setDiagnosticInfo(StringUtils.join(getDiagnostics(), LINE_SEPARATOR)); //result.setPhase(reportedStatus.phase); //result.setStateString(reportedStatus.statef); result.setCounters(getCounters()); result.setContainerId(this.getAssignedContainerID()); result.setNodeManagerHost(trackerName); result.setNodeManagerHttpPort(httpPort); if (this.containerNodeId != null) { result.setNodeManagerPort(this.containerNodeId.getPort()); } return result; } finally { readLock.unlock(); } } @Override public List<String> getDiagnostics() { List<String> result = new ArrayList<String>(); readLock.lock(); try { result.addAll(diagnostics); return result; } finally { readLock.unlock(); } } @Override public TaskAttemptTerminationCause getTerminationCause() { return terminationCause; } @Override public TezCounters getCounters() { readLock.lock(); try { reportedStatus.setLocalityCounter(this.localityCounter); TezCounters counters = reportedStatus.counters; if (counters == null) { counters = EMPTY_COUNTERS; } return counters; } finally { readLock.unlock(); } } TaskStatistics getStatistics() { return this.statistics; } @Override public float getProgress() { readLock.lock(); try { return reportedStatus.progress; } finally { readLock.unlock(); } } @Override public TaskAttemptState getState() { readLock.lock(); try { return getStateNoLock(); } finally { readLock.unlock(); } } @Override public TaskAttemptState getStateNoLock() { return getExternalState(stateMachine.getCurrentState()); } @Override public boolean isFinished() { readLock.lock(); try { return (EnumSet.of(TaskAttemptStateInternal.SUCCEEDED, TaskAttemptStateInternal.FAILED, TaskAttemptStateInternal.FAIL_IN_PROGRESS, TaskAttemptStateInternal.KILLED, TaskAttemptStateInternal.KILL_IN_PROGRESS) .contains(getInternalState())); } finally { readLock.unlock(); } } @Override public ContainerId getAssignedContainerID() { readLock.lock(); try { return containerId; } finally { readLock.unlock(); } } @Override public Container getAssignedContainer() { readLock.lock(); try { return container; } finally { readLock.unlock(); } } @Override public String getAssignedContainerMgrAddress() { readLock.lock(); try { return containerNodeId.toString(); } finally { readLock.unlock(); } } @Override public NodeId getNodeId() { readLock.lock(); try { return containerNodeId; } finally { readLock.unlock(); } } /**If container Assigned then return the node's address, otherwise null. */ @Override public String getNodeHttpAddress() { readLock.lock(); try { return nodeHttpAddress; } finally { readLock.unlock(); } } /** * If container Assigned then return the node's rackname, otherwise null. */ @Override public String getNodeRackName() { this.readLock.lock(); try { return this.nodeRackName; } finally { this.readLock.unlock(); } } @Override public long getLaunchTime() { readLock.lock(); try { return launchTime; } finally { readLock.unlock(); } } @Override public long getFinishTime() { readLock.lock(); try { return finishTime; } finally { readLock.unlock(); } } Vertex getVertex() { return vertex; } @SuppressWarnings("unchecked") @Override public void handle(TaskAttemptEvent event) { if (LOG.isDebugEnabled()) { LOG.debug("Processing TaskAttemptEvent " + event.getTaskAttemptID() + " of type " + event.getType() + " while in state " + getInternalState() + ". Event: " + event); } writeLock.lock(); try { final TaskAttemptStateInternal oldState = getInternalState(); try { stateMachine.doTransition(event.getType(), event); } catch (InvalidStateTransitonException e) { LOG.error("Can't handle this event at current state for " + this.attemptId, e); eventHandler.handle(new DAGEventDiagnosticsUpdate( this.attemptId.getTaskID().getVertexID().getDAGId(), "Invalid event " + event.getType() + " on TaskAttempt " + this.attemptId)); eventHandler.handle( new DAGEvent( this.attemptId.getTaskID().getVertexID().getDAGId(), DAGEventType.INTERNAL_ERROR) ); } if (oldState != getInternalState()) { LOG.info(attemptId + " TaskAttempt Transitioned from " + oldState + " to " + getInternalState() + " due to event " + event.getType()); } } finally { writeLock.unlock(); } } @VisibleForTesting public TaskAttemptStateInternal getInternalState() { readLock.lock(); try { return stateMachine.getCurrentState(); } finally { readLock.unlock(); } } private static TaskAttemptState getExternalState( TaskAttemptStateInternal smState) { switch (smState) { case NEW: case START_WAIT: return TaskAttemptState.STARTING; case RUNNING: return TaskAttemptState.RUNNING; case FAILED: case FAIL_IN_PROGRESS: return TaskAttemptState.FAILED; case KILLED: case KILL_IN_PROGRESS: return TaskAttemptState.KILLED; case SUCCEEDED: return TaskAttemptState.SUCCEEDED; default: throw new TezUncheckedException("Attempt to convert invalid " + "stateMachineTaskAttemptState to externalTaskAttemptState: " + smState); } } @Override public TaskAttemptState restoreFromEvent(HistoryEvent historyEvent) { writeLock.lock(); try { switch (historyEvent.getEventType()) { case TASK_ATTEMPT_STARTED: { TaskAttemptStartedEvent tEvent = (TaskAttemptStartedEvent) historyEvent; this.launchTime = tEvent.getStartTime(); recoveryStartEventSeen = true; recoveredState = TaskAttemptState.RUNNING; this.containerId = tEvent.getContainerId(); sendEvent(createDAGCounterUpdateEventTALaunched(this)); return recoveredState; } case TASK_ATTEMPT_FINISHED: { TaskAttemptFinishedEvent tEvent = (TaskAttemptFinishedEvent) historyEvent; this.finishTime = tEvent.getFinishTime(); this.reportedStatus.counters = tEvent.getCounters(); this.reportedStatus.progress = 1f; this.reportedStatus.state = tEvent.getState(); this.terminationCause = tEvent.getTaskAttemptError() != null ? tEvent.getTaskAttemptError() : TaskAttemptTerminationCause.UNKNOWN_ERROR; this.diagnostics.add(tEvent.getDiagnostics()); this.recoveredState = tEvent.getState(); sendEvent(createDAGCounterUpdateEventTAFinished(this, tEvent.getState())); return recoveredState; } default: throw new RuntimeException("Unexpected event received for restoring" + " state, eventType=" + historyEvent.getEventType()); } } finally { writeLock.unlock(); } } @SuppressWarnings("unchecked") private void sendEvent(Event<?> event) { this.eventHandler.handle(event); } // always called in write lock private void setFinishTime() { // set the finish time only if launch time is set if (launchTime != 0 && finishTime == 0) { finishTime = clock.getTime(); } } // TOOD Merge some of these JobCounter events. private static DAGEventCounterUpdate createDAGCounterUpdateEventTALaunched( TaskAttemptImpl ta) { DAGEventCounterUpdate dagCounterEvent = new DAGEventCounterUpdate( ta.getDAGID() ); dagCounterEvent.addCounterUpdate(DAGCounter.TOTAL_LAUNCHED_TASKS, 1); return dagCounterEvent; } private static DAGEventCounterUpdate createDAGCounterUpdateEventTAFinished( TaskAttemptImpl taskAttempt, TaskAttemptState taState) { DAGEventCounterUpdate jce = new DAGEventCounterUpdate(taskAttempt.getDAGID()); if (taState == TaskAttemptState.FAILED) { jce.addCounterUpdate(DAGCounter.NUM_FAILED_TASKS, 1); } else if (taState == TaskAttemptState.KILLED) { jce.addCounterUpdate(DAGCounter.NUM_KILLED_TASKS, 1); } else if (taState == TaskAttemptState.SUCCEEDED ) { jce.addCounterUpdate(DAGCounter.NUM_SUCCEEDED_TASKS, 1); } return jce; } // private static long computeSlotMillis(TaskAttemptImpl taskAttempt) { // int slotMemoryReq = // taskAttempt.taskResource.getMemory(); // // int minSlotMemSize = // taskAttempt.appContext.getClusterInfo().getMinContainerCapability() // .getMemory(); // // int simSlotsRequired = // minSlotMemSize == 0 ? 0 : (int) Math.ceil((float) slotMemoryReq // / minSlotMemSize); // // long slotMillisIncrement = // simSlotsRequired // * (taskAttempt.getFinishTime() - taskAttempt.getLaunchTime()); // return slotMillisIncrement; // } // TODO: JobHistory // TODO Change to return a JobHistoryEvent. /* private static TaskAttemptUnsuccessfulCompletionEvent createTaskAttemptUnsuccessfulCompletionEvent(TaskAttemptImpl taskAttempt, TaskAttemptStateInternal attemptState) { TaskAttemptUnsuccessfulCompletionEvent tauce = new TaskAttemptUnsuccessfulCompletionEvent( TypeConverter.fromYarn(taskAttempt.attemptId), TypeConverter.fromYarn(taskAttempt.attemptId.getTaskId() .getTaskType()), attemptState.toString(), taskAttempt.finishTime, taskAttempt.containerNodeId == null ? "UNKNOWN" : taskAttempt.containerNodeId.getHost(), taskAttempt.containerNodeId == null ? -1 : taskAttempt.containerNodeId.getPort(), taskAttempt.nodeRackName == null ? "UNKNOWN" : taskAttempt.nodeRackName, StringUtils.join( taskAttempt.getDiagnostics(), LINE_SEPARATOR), taskAttempt .getProgressSplitBlock().burst()); return tauce; } // TODO Incorporate MAPREDUCE-4838 private JobHistoryEvent createTaskAttemptStartedEvent() { TaskAttemptStartedEvent tase = new TaskAttemptStartedEvent( TypeConverter.fromYarn(attemptId), TypeConverter.fromYarn(taskId .getTaskType()), launchTime, trackerName, httpPort, shufflePort, containerId, "", ""); return new JobHistoryEvent(jobId, tase); } */ // private WrappedProgressSplitsBlock getProgressSplitBlock() { // return null; // // TODO // /* // readLock.lock(); // try { // if (progressSplitBlock == null) { // progressSplitBlock = new WrappedProgressSplitsBlock(conf.getInt( // MRJobConfig.MR_AM_NUM_PROGRESS_SPLITS, // MRJobConfig.DEFAULT_MR_AM_NUM_PROGRESS_SPLITS)); // } // return progressSplitBlock; // } finally { // readLock.unlock(); // } // */ // } private void updateProgressSplits() { // double newProgress = reportedStatus.progress; // newProgress = Math.max(Math.min(newProgress, 1.0D), 0.0D); // TezCounters counters = reportedStatus.counters; // if (counters == null) // return; // // WrappedProgressSplitsBlock splitsBlock = getProgressSplitBlock(); // if (splitsBlock != null) { // long now = clock.getTime(); // long start = getLaunchTime(); // // if (start == 0) // return; // // if (start != 0 && now - start <= Integer.MAX_VALUE) { // splitsBlock.getProgressWallclockTime().extend(newProgress, // (int) (now - start)); // } // // TezCounter cpuCounter = counters.findCounter(TaskCounter.CPU_MILLISECONDS); // if (cpuCounter != null && cpuCounter.getValue() <= Integer.MAX_VALUE) { // splitsBlock.getProgressCPUTime().extend(newProgress, // (int) cpuCounter.getValue()); // long to int? TODO: FIX. Same below // } // // TezCounter virtualBytes = counters // .findCounter(TaskCounter.VIRTUAL_MEMORY_BYTES); // if (virtualBytes != null) { // splitsBlock.getProgressVirtualMemoryKbytes().extend(newProgress, // (int) (virtualBytes.getValue() / (MEMORY_SPLITS_RESOLUTION))); // } // // TezCounter physicalBytes = counters // .findCounter(TaskCounter.PHYSICAL_MEMORY_BYTES); // if (physicalBytes != null) { // splitsBlock.getProgressPhysicalMemoryKbytes().extend(newProgress, // (int) (physicalBytes.getValue() / (MEMORY_SPLITS_RESOLUTION))); // } // } } private void sendTaskAttemptCleanupEvent() { // TaskAttemptContext taContext = // new TaskAttemptContextImpl(this.conf, // TezMRTypeConverter.fromTez(this.attemptId)); // sendEvent(new TaskCleanupEvent(this.attemptId, this.committer, taContext)); } private TaskLocationHint getTaskLocationHint() { return task.getTaskLocationHint(); } protected String[] resolveHosts(String[] src) { return TaskAttemptImplHelpers.resolveHosts(src); } protected void logJobHistoryAttemptStarted() { final String containerIdStr = containerId.toString(); String inProgressLogsUrl = nodeHttpAddress + "/" + "node/containerlogs" + "/" + containerIdStr + "/" + this.appContext.getUser(); String completedLogsUrl = ""; if (conf.getBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, YarnConfiguration.DEFAULT_LOG_AGGREGATION_ENABLED) && conf.get(YarnConfiguration.YARN_LOG_SERVER_URL) != null) { String contextStr = "v_" + getVertex().getName() + "_" + this.attemptId.toString(); completedLogsUrl = conf.get(YarnConfiguration.YARN_LOG_SERVER_URL) + "/" + containerNodeId.toString() + "/" + containerIdStr + "/" + contextStr + "/" + this.appContext.getUser(); } TaskAttemptStartedEvent startEvt = new TaskAttemptStartedEvent( attemptId, getVertex().getName(), launchTime, containerId, containerNodeId, inProgressLogsUrl, completedLogsUrl, nodeHttpAddress); this.appContext.getHistoryHandler().handle( new DAGHistoryEvent(getDAGID(), startEvt)); } protected void logJobHistoryAttemptFinishedEvent(TaskAttemptStateInternal state) { //Log finished events only if an attempt started. if (getLaunchTime() == 0) return; TaskAttemptFinishedEvent finishEvt = new TaskAttemptFinishedEvent( attemptId, getVertex().getName(), getLaunchTime(), getFinishTime(), TaskAttemptState.SUCCEEDED, null, "", getCounters()); // FIXME how do we store information regd completion events this.appContext.getHistoryHandler().handle( new DAGHistoryEvent(getDAGID(), finishEvt)); } protected void logJobHistoryAttemptUnsuccesfulCompletion( TaskAttemptState state) { TaskAttemptFinishedEvent finishEvt = new TaskAttemptFinishedEvent( attemptId, getVertex().getName(), getLaunchTime(), clock.getTime(), state, terminationCause, StringUtils.join( getDiagnostics(), LINE_SEPARATOR), getCounters()); // FIXME how do we store information regd completion events this.appContext.getHistoryHandler().handle( new DAGHistoryEvent(getDAGID(), finishEvt)); } ////////////////////////////////////////////////////////////////////////////// // Start of Transition Classes // ////////////////////////////////////////////////////////////////////////////// protected static class ScheduleTaskattemptTransition implements MultipleArcTransition<TaskAttemptImpl, TaskAttemptEvent, TaskAttemptStateInternal> { @Override public TaskAttemptStateInternal transition(TaskAttemptImpl ta, TaskAttemptEvent event) { TaskAttemptEventSchedule scheduleEvent = (TaskAttemptEventSchedule) event; // TODO Creating the remote task here may not be required in case of // recovery. // Create the remote task. TaskSpec remoteTaskSpec; try { remoteTaskSpec = ta.createRemoteTaskSpec(); LOG.info("remoteTaskSpec:" + remoteTaskSpec); } catch (AMUserCodeException e) { String msg = "Exception in " + e.getSource() + ", taskAttempt=" + ta; LOG.error(msg, e); String diag = msg + ", " + e.getMessage() + ", " + ExceptionUtils.getStackTrace(e.getCause()); new TerminateTransition(FAILED_HELPER).transition(ta, new TaskAttemptEventAttemptFailed(ta.getID(), TaskAttemptEventType.TA_FAILED, diag, TaskAttemptTerminationCause.APPLICATION_ERROR)); return TaskAttemptStateInternal.FAILED; } // Create startTaskRequest String[] requestHosts = new String[0]; // Compute node/rack location request even if re-scheduled. Set<String> racks = new HashSet<String>(); TaskLocationHint locationHint = ta.getTaskLocationHint(); if (locationHint != null) { if (locationHint.getRacks() != null) { racks.addAll(locationHint.getRacks()); } if (locationHint.getHosts() != null) { for (String host : locationHint.getHosts()) { racks.add(RackResolver.resolve(host).getNetworkLocation()); } requestHosts = ta.resolveHosts(locationHint.getHosts() .toArray(new String[locationHint.getHosts().size()])); } } ta.taskHosts.addAll(Arrays.asList(requestHosts)); ta.taskRacks = racks; // Ask for hosts / racks only if not a re-scheduled task. if (ta.isRescheduled) { locationHint = null; } if (LOG.isDebugEnabled()) { LOG.debug("Asking for container launch with taskAttemptContext: " + remoteTaskSpec); } // Send out a launch request to the scheduler. int priority; if (ta.isRescheduled) { // higher priority for rescheduled attempts priority = scheduleEvent.getPriorityHighLimit(); } else { priority = (scheduleEvent.getPriorityHighLimit() + scheduleEvent.getPriorityLowLimit()) / 2; } AMSchedulerEventTALaunchRequest launchRequestEvent = new AMSchedulerEventTALaunchRequest( ta.attemptId, ta.taskResource, remoteTaskSpec, ta, locationHint, priority, ta.containerContext); ta.sendEvent(launchRequestEvent); return TaskAttemptStateInternal.START_WAIT; } } protected static class TerminateTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { TerminatedTransitionHelper helper; public TerminateTransition(TerminatedTransitionHelper helper) { this.helper = helper; } @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { ta.setFinishTime(); if (event instanceof DiagnosableEvent) { ta.addDiagnosticInfo(((DiagnosableEvent) event).getDiagnosticInfo()); } if (event instanceof TaskAttemptEventTerminationCauseEvent) { ta.trySetTerminationCause(((TaskAttemptEventTerminationCauseEvent) event).getTerminationCause()); } else { throw new TezUncheckedException("Invalid event received in TerminateTransition" + ", requiredClass=TaskAttemptEventTerminationCauseEvent" + ", eventClass=" + event.getClass().getName()); } ta.sendEvent(createDAGCounterUpdateEventTAFinished(ta, helper.getTaskAttemptState())); ta.logJobHistoryAttemptUnsuccesfulCompletion(helper .getTaskAttemptState()); // Send out events to the Task - indicating TaskAttemptTermination(F/K) ta.sendEvent(new TaskEventTAUpdate(ta.attemptId, helper .getTaskEventType())); } } protected static class StartedTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent origEvent) { TaskAttemptEventStartedRemotely event = (TaskAttemptEventStartedRemotely) origEvent; Container container = ta.appContext.getAllContainers() .get(event.getContainerId()).getContainer(); ta.container = container; ta.containerId = event.getContainerId(); ta.containerNodeId = container.getNodeId(); ta.nodeHttpAddress = StringInterner.weakIntern(container.getNodeHttpAddress()); ta.nodeRackName = StringInterner.weakIntern(RackResolver.resolve(ta.containerNodeId.getHost()) .getNetworkLocation()); ta.launchTime = ta.clock.getTime(); // TODO Resolve to host / IP in case of a local address. InetSocketAddress nodeHttpInetAddr = NetUtils .createSocketAddr(ta.nodeHttpAddress); // TODO: Costly? ta.trackerName = StringInterner.weakIntern(nodeHttpInetAddr.getHostName()); ta.httpPort = nodeHttpInetAddr.getPort(); ta.sendEvent(createDAGCounterUpdateEventTALaunched(ta)); LOG.info("TaskAttempt: [" + ta.attemptId + "] started." + " Is using containerId: [" + ta.containerId + "]" + " on NM: [" + ta.containerNodeId + "]"); // JobHistoryEvent ta.logJobHistoryAttemptStarted(); // TODO Remove after HDFS-5098 // Compute LOCALITY counter for this task. if (ta.taskHosts.contains(ta.containerNodeId.getHost())) { ta.localityCounter = DAGCounter.DATA_LOCAL_TASKS; } else if (ta.taskRacks.contains(ta.nodeRackName)) { ta.localityCounter = DAGCounter.RACK_LOCAL_TASKS; } else { // Not computing this if the task does not have locality information. if (ta.getTaskLocationHint() != null) { ta.localityCounter = DAGCounter.OTHER_LOCAL_TASKS; } } // Inform the Task ta.sendEvent(new TaskEventTAUpdate(ta.attemptId, TaskEventType.T_ATTEMPT_LAUNCHED)); if (ta.isSpeculationEnabled()) { ta.sendEvent(new SpeculatorEventTaskAttemptStatusUpdate(ta.attemptId, TaskAttemptState.RUNNING, ta.launchTime, true)); } ta.taskHeartbeatHandler.register(ta.attemptId); } } private boolean isSpeculationEnabled() { return conf.getBoolean(TezConfiguration.TEZ_AM_SPECULATION_ENABLED, TezConfiguration.TEZ_AM_SPECULATION_ENABLED_DEFAULT); } protected static class TerminatedBeforeRunningTransition extends TerminateTransition { public TerminatedBeforeRunningTransition( TerminatedTransitionHelper helper) { super(helper); } protected boolean sendSchedulerEvent() { return true; } @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { super.transition(ta, event); // Inform the scheduler if (sendSchedulerEvent()) { ta.sendEvent(new AMSchedulerEventTAEnded(ta, ta.containerId, helper .getTaskAttemptState())); } } } protected static class NodeFailedBeforeRunningTransition extends TerminatedBeforeRunningTransition { public NodeFailedBeforeRunningTransition() { super(KILLED_HELPER); } @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { super.transition(ta, event); } } protected static class ContainerTerminatingBeforeRunningTransition extends TerminatedBeforeRunningTransition { public ContainerTerminatingBeforeRunningTransition() { super(FAILED_HELPER); } @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { super.transition(ta, event); } } protected static class ContainerCompletedBeforeRunningTransition extends TerminatedBeforeRunningTransition { public ContainerCompletedBeforeRunningTransition() { super(FAILED_HELPER); } public ContainerCompletedBeforeRunningTransition(TerminatedTransitionHelper helper) { super(helper); } @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { super.transition(ta, event); ta.sendTaskAttemptCleanupEvent(); } } protected static class StatusUpdaterTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { TaskStatusUpdateEvent statusEvent = ((TaskAttemptEventStatusUpdate) event) .getStatusEvent(); ta.reportedStatus.state = ta.getState(); ta.reportedStatus.progress = statusEvent.getProgress(); ta.reportedStatus.counters = statusEvent.getCounters(); ta.statistics = statusEvent.getStatistics(); ta.updateProgressSplits(); if (ta.isSpeculationEnabled()) { ta.sendEvent(new SpeculatorEventTaskAttemptStatusUpdate(ta.attemptId, ta.getState(), ta.clock.getTime())); } } } protected static class SucceededTransition implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { ta.setFinishTime(); // Send out history event. ta.logJobHistoryAttemptFinishedEvent(TaskAttemptStateInternal.SUCCEEDED); ta.sendEvent(createDAGCounterUpdateEventTAFinished(ta, TaskAttemptState.SUCCEEDED)); // Inform the Scheduler. ta.sendEvent(new AMSchedulerEventTAEnded(ta, ta.containerId, TaskAttemptState.SUCCEEDED)); // Inform the task. ta.sendEvent(new TaskEventTAUpdate(ta.attemptId, TaskEventType.T_ATTEMPT_SUCCEEDED)); // Unregister from the TaskHeartbeatHandler. ta.taskHeartbeatHandler.unregister(ta.attemptId); ta.reportedStatus.state = TaskAttemptState.SUCCEEDED; ta.reportedStatus.progress = 1.0f; if (ta.isSpeculationEnabled()) { ta.sendEvent(new SpeculatorEventTaskAttemptStatusUpdate(ta.attemptId, TaskAttemptState.SUCCEEDED, ta.clock.getTime())); } // TODO maybe. For reuse ... Stacking pulls for a reduce task, even if the // TA finishes independently. // Will likely be the Job's responsibility. } } protected static class TerminatedWhileRunningTransition extends TerminatedBeforeRunningTransition { public TerminatedWhileRunningTransition( TerminatedTransitionHelper helper) { super(helper); } @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { super.transition(ta, event); ta.taskHeartbeatHandler.unregister(ta.attemptId); ta.reportedStatus.state = helper.getTaskAttemptState(); // FAILED or KILLED if (ta.isSpeculationEnabled()) { ta.sendEvent(new SpeculatorEventTaskAttemptStatusUpdate(ta.attemptId, helper.getTaskAttemptState(), ta.clock.getTime())); } } } protected static class ContainerCompletedWhileRunningTransition extends TerminatedWhileRunningTransition { public ContainerCompletedWhileRunningTransition() { super(FAILED_HELPER); } public ContainerCompletedWhileRunningTransition(TerminatedTransitionHelper helper) { super(helper); } @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { super.transition(ta, event); ta.sendTaskAttemptCleanupEvent(); } } protected static class ContainerCompletedWhileTerminating implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { ta.sendTaskAttemptCleanupEvent(); TaskAttemptEventContainerTerminated tEvent = (TaskAttemptEventContainerTerminated) event; ta.addDiagnosticInfo(tEvent.getDiagnosticInfo()); } } protected static class TerminatedAfterSuccessHelper extends TerminatedBeforeRunningTransition { @Override protected boolean sendSchedulerEvent() { // since the success transition would have sent the event // there is no need to send it again return false; } public TerminatedAfterSuccessHelper(TerminatedTransitionHelper helper) { super(helper); } @Override public void transition(TaskAttemptImpl ta, TaskAttemptEvent event) { super.transition(ta, event); ta.sendTaskAttemptCleanupEvent(); } } protected static class RecoverTransition implements MultipleArcTransition<TaskAttemptImpl, TaskAttemptEvent, TaskAttemptStateInternal> { @Override public TaskAttemptStateInternal transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent taskAttemptEvent) { TaskAttemptStateInternal endState = TaskAttemptStateInternal.FAILED; switch(taskAttempt.recoveredState) { case NEW: case RUNNING: // FIXME once running containers can be recovered, this // should be handled differently // TODO abort taskattempt taskAttempt.sendEvent(new TaskEventTAUpdate(taskAttempt.attemptId, TaskEventType.T_ATTEMPT_KILLED)); taskAttempt.sendEvent(createDAGCounterUpdateEventTAFinished(taskAttempt, getExternalState(TaskAttemptStateInternal.KILLED))); taskAttempt.logJobHistoryAttemptUnsuccesfulCompletion(TaskAttemptState.KILLED); endState = TaskAttemptStateInternal.KILLED; break; case SUCCEEDED: // Do not inform Task as it already knows about completed attempts endState = TaskAttemptStateInternal.SUCCEEDED; break; case FAILED: // Do not inform Task as it already knows about completed attempts endState = TaskAttemptStateInternal.FAILED; break; case KILLED: // Do not inform Task as it already knows about completed attempts endState = TaskAttemptStateInternal.KILLED; break; default: throw new RuntimeException("Failed to recover from non-handled state" + ", taskAttemptId=" + taskAttempt.getID() + ", state=" + taskAttempt.recoveredState); } return endState; } } protected static class TerminatedAfterSuccessTransition implements MultipleArcTransition<TaskAttemptImpl, TaskAttemptEvent, TaskAttemptStateInternal> { @Override public TaskAttemptStateInternal transition(TaskAttemptImpl attempt, TaskAttemptEvent event) { if (attempt.leafVertex) { return TaskAttemptStateInternal.SUCCEEDED; } // TODO - TEZ-834. This assumes that the outputs were on that node attempt.sendInputFailedToConsumers(); TaskAttemptImpl.TERMINATED_AFTER_SUCCESS_HELPER.transition(attempt, event); return TaskAttemptStateInternal.KILLED; } } protected static class OutputReportedFailedTransition implements MultipleArcTransition<TaskAttemptImpl, TaskAttemptEvent, TaskAttemptStateInternal> { @Override public TaskAttemptStateInternal transition(TaskAttemptImpl attempt, TaskAttemptEvent event) { TaskAttemptEventOutputFailed outputFailedEvent = (TaskAttemptEventOutputFailed) event; TezEvent tezEvent = outputFailedEvent.getInputFailedEvent(); TezTaskAttemptID failedDestTaId = tezEvent.getSourceInfo().getTaskAttemptID(); InputReadErrorEvent readErrorEvent = (InputReadErrorEvent)tezEvent.getEvent(); int failedInputIndexOnDestTa = readErrorEvent.getIndex(); if (readErrorEvent.getVersion() != attempt.getID().getId()) { throw new TezUncheckedException(attempt.getID() + " incorrectly blamed for read error from " + failedDestTaId + " at inputIndex " + failedInputIndexOnDestTa + " version" + readErrorEvent.getVersion()); } LOG.info(attempt.getID() + " blamed for read error from " + failedDestTaId + " at inputIndex " + failedInputIndexOnDestTa); attempt.uniquefailedOutputReports.add(failedDestTaId); float failureFraction = ((float) attempt.uniquefailedOutputReports.size()) / outputFailedEvent.getConsumerTaskNumber(); boolean withinFailureFractionLimits = (failureFraction <= MAX_ALLOWED_OUTPUT_FAILURES_FRACTION); boolean withinOutputFailureLimits = (attempt.uniquefailedOutputReports.size() < MAX_ALLOWED_OUTPUT_FAILURES); // If needed we can launch a background task without failing this task // to generate a copy of the output just in case. // If needed we can consider only running consumer tasks if (withinFailureFractionLimits && withinOutputFailureLimits) { return attempt.getInternalState(); } String message = attempt.getID() + " being failed for too many output errors. " + "failureFraction=" + failureFraction + ", " + "MAX_ALLOWED_OUTPUT_FAILURES_FRACTION=" + MAX_ALLOWED_OUTPUT_FAILURES_FRACTION + ", " + "uniquefailedOutputReports=" + attempt.uniquefailedOutputReports.size() + ", " + "MAX_ALLOWED_OUTPUT_FAILURES=" + MAX_ALLOWED_OUTPUT_FAILURES; LOG.info(message); attempt.addDiagnosticInfo(message); // send input failed event attempt.sendInputFailedToConsumers(); // Not checking for leafVertex since a READ_ERROR should only be reported for intermediate tasks. if (attempt.getInternalState() == TaskAttemptStateInternal.SUCCEEDED) { (new TerminatedAfterSuccessHelper(FAILED_HELPER)).transition( attempt, event); return TaskAttemptStateInternal.FAILED; } else { (new TerminatedWhileRunningTransition(FAILED_HELPER)).transition( attempt, event); return TaskAttemptStateInternal.FAIL_IN_PROGRESS; } // TODO at some point. Nodes may be interested in FetchFailure info. // Can be used to blacklist nodes. } } @VisibleForTesting protected void sendInputFailedToConsumers() { Vertex vertex = getVertex(); Map<Vertex, Edge> edges = vertex.getOutputVertices(); if (edges != null && !edges.isEmpty()) { List<TezEvent> tezIfEvents = Lists.newArrayListWithCapacity(edges.size()); for (Vertex edgeVertex : edges.keySet()) { tezIfEvents.add(new TezEvent(new InputFailedEvent(), new EventMetaData(EventProducerConsumerType.SYSTEM, vertex.getName(), edgeVertex.getName(), getID()))); } sendEvent(new VertexEventRouteEvent(vertex.getVertexId(), tezIfEvents)); } } private void trySetTerminationCause(TaskAttemptTerminationCause err) { // keep only the first error cause if (terminationCause == TaskAttemptTerminationCause.UNKNOWN_ERROR) { terminationCause = err; } } private void initTaskAttemptStatus(TaskAttemptStatus result) { result.progress = 0.0f; // result.phase = Phase.STARTING; //result.stateString = "NEW"; result.state = TaskAttemptState.NEW; //TezCounters counters = EMPTY_COUNTERS; //result.counters = counters; } private void addDiagnosticInfo(String diag) { if (diag != null && !diag.equals("")) { diagnostics.add(diag); } } protected interface TerminatedTransitionHelper { public TaskAttemptStateInternal getTaskAttemptStateInternal(); public TaskAttemptState getTaskAttemptState(); public TaskEventType getTaskEventType(); } protected static class FailedTransitionHelper implements TerminatedTransitionHelper { public TaskAttemptStateInternal getTaskAttemptStateInternal() { return TaskAttemptStateInternal.FAILED; } @Override public TaskAttemptState getTaskAttemptState() { return TaskAttemptState.FAILED; } @Override public TaskEventType getTaskEventType() { return TaskEventType.T_ATTEMPT_FAILED; } } protected static class KilledTransitionHelper implements TerminatedTransitionHelper { @Override public TaskAttemptStateInternal getTaskAttemptStateInternal() { return TaskAttemptStateInternal.KILLED; } @Override public TaskAttemptState getTaskAttemptState() { return TaskAttemptState.KILLED; } @Override public TaskEventType getTaskEventType() { return TaskEventType.T_ATTEMPT_KILLED; } } @Override public String toString() { return getID().toString(); } }
bernhardschaefer/tez
tez-dag/src/main/java/org/apache/tez/dag/app/dag/impl/TaskAttemptImpl.java
Java
apache-2.0
57,692
package biz.brainpowered.plane.comp; import biz.brainpowered.plane.comp.interfaces.ComponentInterface; import biz.brainpowered.plane.comp.interfaces.EntityInterface; /** * Created by sebastian on 2014/07/28. */ public class DemoInputComponent extends BaseComponent implements ComponentInterface { public DemoInputComponent(EntityInterface entity) { super("Input", entity); // todo: inject custom callbacks into InputComponents // and then init AI } public void update( Object... params ) { // detect input and update velocity on entity // input detection and setting Entity properties // AI. execute/update/smoothstep } }
sscholle/PlanePilot
core/src/biz/brainpowered/plane/comp/DemoInputComponent.java
Java
apache-2.0
693
package com.playground.datastructures; /** * This class represents the node of LinkedList. It extends Node to add additional feilds to * indicate the next feild. */ public class LinkedListNode extends Node { private LinkedListNode next; /** * Constructor to create a linked list node. * * @param pObject Object to be stored in the node. */ public LinkedListNode(Object pObject) { super(pObject); } /** * This function is used to retreive the next feild of a linked list. * * @return The next node of the current node */ public LinkedListNode getNext() { return next; } /** * This function is used to set the next node to the given node. * * @param pNext The next node to the given node. */ public void setNext(LinkedListNode pNext) { next = pNext; } }
ashishkumarshah/problemsolving
src/main/java/com/playground/datastructures/LinkedListNode.java
Java
apache-2.0
824
package org.sakaiproject.gradebookng.business; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.JAXBException; import lombok.Setter; import lombok.extern.apachecommons.CommonsLog; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.CompareToBuilder; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang.time.StopWatch; import org.sakaiproject.coursemanagement.api.CourseManagementService; import org.sakaiproject.coursemanagement.api.Section; import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.gradebookng.business.dto.AssignmentOrder; import org.sakaiproject.gradebookng.business.exception.GbException; import org.sakaiproject.gradebookng.business.model.GbAssignmentGradeSortOrder; import org.sakaiproject.gradebookng.business.model.GbGradeCell; import org.sakaiproject.gradebookng.business.model.GbGradeInfo; import org.sakaiproject.gradebookng.business.model.GbGradeLog; import org.sakaiproject.gradebookng.business.model.GbGroup; import org.sakaiproject.gradebookng.business.model.GbGroupType; import org.sakaiproject.gradebookng.business.model.GbStudentGradeInfo; import org.sakaiproject.gradebookng.business.model.GbUser; import org.sakaiproject.gradebookng.business.util.Temp; import org.sakaiproject.gradebookng.business.util.XmlList; import org.sakaiproject.memory.api.Cache; import org.sakaiproject.memory.api.MemoryService; import org.sakaiproject.service.gradebook.shared.AssessmentNotFoundException; import org.sakaiproject.service.gradebook.shared.Assignment; import org.sakaiproject.service.gradebook.shared.CommentDefinition; import org.sakaiproject.service.gradebook.shared.GradeDefinition; import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.service.gradebook.shared.InvalidGradeException; import org.sakaiproject.service.gradebook.shared.SortType; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.tool.api.ToolManager; import org.sakaiproject.tool.gradebook.Gradebook; import org.sakaiproject.tool.gradebook.GradingEvent; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.UserNotDefinedException; /** * Business service for GradebookNG * * This is not designed to be consumed outside of the application or supplied entityproviders. * Use at your own risk. * * @author Steve Swinsburg (steve.swinsburg@gmail.com) * */ // TODO add permission checks! Remove logic from entityprovider if there is a double up // TODO some of these methods pass in empty lists and its confusing. If we aren't doing paging, remove this. @CommonsLog public class GradebookNgBusinessService { @Setter private SiteService siteService; @Setter private UserDirectoryService userDirectoryService; @Setter private ToolManager toolManager; @Setter private GradebookService gradebookService; @Setter private CourseManagementService courseManagementService; @Setter private MemoryService memoryService; public static final String ASSIGNMENT_ORDER_PROP = "gbng_assignment_order"; private Cache cache; private static final String NOTIFICATIONS_CACHE_NAME = "org.sakaiproject.gradebookng.cache.notifications"; @SuppressWarnings("unchecked") public void init() { //max entries unbounded, no TTL eviction (TODO set this to 10 seconds?), TTI 10 seconds //TODO this should be configured in sakai.properties so we dont have redundant config code here cache = memoryService.getCache(NOTIFICATIONS_CACHE_NAME); if(cache == null) { cache = memoryService.createCache("org.sakaiproject.gradebookng.cache.notifications", null); } } /** * Get a list of all users in the current site that can have grades * * @return a list of users as uuids or null if none */ private List<String> getGradeableUsers() { try { String siteId = this.getCurrentSiteId(); Set<String> userUuids = siteService.getSite(siteId).getUsersIsAllowed(Permissions.VIEW_OWN_GRADES.getValue()); return new ArrayList<>(userUuids); } catch (IdUnusedException e) { e.printStackTrace(); return null; } } /** * Given a list of uuids, get a list of Users * * @param userUuids list of user uuids * @return */ private List<User> getUsers(List<String> userUuids) throws GbException { try { List<User> users = userDirectoryService.getUsers(userUuids); Collections.sort(users, new LastNameComparator()); //TODO this needs to take into account the GbStudentSortType return users; } catch (RuntimeException e) { //an LDAP exception can sometimes be thrown here, catch and rethrow throw new GbException("An error occurred getting the list of users.", e); } } /** * Helper to get a reference to the gradebook for the current site * * @return the gradebook for the site */ private Gradebook getGradebook() { return getGradebook(this.getCurrentSiteId()); } /** * Helper to get a reference to the gradebook for the specified site * * @param siteId the siteId * @return the gradebook for the site */ private Gradebook getGradebook(String siteId) { try { Gradebook gradebook = (Gradebook)gradebookService.getGradebook(siteId); return gradebook; } catch (GradebookNotFoundException e) { log.error("No gradebook in site: " + siteId); return null; } } /** * Get a list of assignments in the gradebook in the current site * * @return a list of assignments or null if no gradebook */ public List<Assignment> getGradebookAssignments() { return getGradebookAssignments(this.getCurrentSiteId()); } /** * Get a list of assignments in the gradebook in the specified site, sorted by sort order * * @param siteId the siteId * @return a list of assignments or null if no gradebook */ public List<Assignment> getGradebookAssignments(String siteId) { Gradebook gradebook = getGradebook(siteId); if(gradebook != null) { return gradebookService.getAssignments(gradebook.getUid(), SortType.SORT_BY_SORTING); } return null; } /** * Get a map of course grades for all users in the site, using a grade override preferentially over a calculated one * key = student eid * value = course grade * * Note that his mpa is keyed on EID. Since the business service does not have a list of eids, to save an iteration, the calling service needs to do the filtering * * @param userUuids * @return the map of course grades for students, or an empty map */ @SuppressWarnings("unchecked") public Map<String,String> getSiteCourseGrades() { Map<String,String> courseGrades = new HashMap<>(); Gradebook gradebook = this.getGradebook(); if(gradebook != null) { //get course grades. THis new method for Sakai 11 does the override automatically, so GB1 data is preserved //note that this DOES not have the course grade points earned because that is in GradebookManagerHibernateImpl courseGrades = gradebookService.getImportCourseGrade(gradebook.getUid()); } return courseGrades; } /** * Save the grade and comment for a student's assignment. Ignores the concurrency check. * * @param assignmentId id of the gradebook assignment * @param studentUuid uuid of the user * @param grade grade for the assignment/user * @param comment optional comment for the grade. Can be null. * * @return */ public GradeSaveResponse saveGrade(final Long assignmentId, final String studentUuid, final String grade, final String comment) { Gradebook gradebook = this.getGradebook(); if(gradebook == null) { return GradeSaveResponse.ERROR; } return this.saveGrade(assignmentId, studentUuid, null, grade, comment); } /** * Save the grade and comment for a student's assignment and do concurrency checking * * @param assignmentId id of the gradebook assignment * @param studentUuid uuid of the user * @param oldGrade old grade, passed in for concurrency checking/ If null, concurrency checking is skipped. * @param newGrade new grade for the assignment/user * @param comment optional comment for the grade. Can be null. * * @return * * TODO make the concurrency check a boolean instead of the null oldGrade */ public GradeSaveResponse saveGrade(final Long assignmentId, final String studentUuid, String oldGrade, String newGrade, final String comment) { Gradebook gradebook = this.getGradebook(); if(gradebook == null) { return GradeSaveResponse.ERROR; } //get current grade String storedGrade = gradebookService.getAssignmentScoreString(gradebook.getUid(), assignmentId, studentUuid); //trim the .0 from the grades if present. UI removes it so lets standardise. storedGrade = StringUtils.removeEnd(storedGrade, ".0"); oldGrade = StringUtils.removeEnd(oldGrade, ".0"); newGrade = StringUtils.removeEnd(newGrade, ".0"); //trim to null so we can better compare against no previous grade being recorded (as it will be null) //note that we also trim newGrade so that don't add the grade if the new grade is blank and there was no grade previously storedGrade = StringUtils.trimToNull(storedGrade); oldGrade = StringUtils.trimToNull(oldGrade); newGrade = StringUtils.trimToNull(newGrade); if(log.isDebugEnabled()) { log.debug("storedGrade: " + storedGrade); log.debug("oldGrade: " + oldGrade); log.debug("newGrade: " + newGrade); } //no change if(StringUtils.equals(storedGrade, newGrade)){ return GradeSaveResponse.NO_CHANGE; } //concurrency check, if stored grade != old grade that was passed in, someone else has edited. //if oldGrade == null, ignore concurrency check if(oldGrade != null && !StringUtils.equals(storedGrade, oldGrade)) { return GradeSaveResponse.CONCURRENT_EDIT; } //about to edit so push a notification pushEditingNotification(gradebook.getUid(), this.getCurrentUser(), studentUuid, assignmentId); //over limit check, get max points for assignment and check if the newGrade is over limit //we still save it but we return the warning Assignment assignment = this.getAssignment(assignmentId); Double maxPoints = assignment.getPoints(); Double newGradePoints = NumberUtils.toDouble(newGrade); GradeSaveResponse rval = null; if(newGradePoints.compareTo(maxPoints) > 0) { log.debug("over limit. Max: " + maxPoints); rval = GradeSaveResponse.OVER_LIMIT; } //save try { //note, you must pass in the comment or it wil lbe nulled out by the GB service gradebookService.saveGradeAndCommentForStudent(gradebook.getUid(), assignmentId, studentUuid, newGrade, comment); if(rval == null) { //if we don't have some other warning, it was all OK rval = GradeSaveResponse.OK; } } catch (InvalidGradeException | GradebookNotFoundException | AssessmentNotFoundException e) { log.error("An error occurred saving the grade. " + e.getClass() + ": " + e.getMessage()); rval = GradeSaveResponse.ERROR; } return rval; } /** * Build the matrix of assignments, students and grades for all students * * @param assignments list of assignments * @return */ public List<GbStudentGradeInfo> buildGradeMatrix(List<Assignment> assignments) throws GbException { return this.buildGradeMatrix(assignments, this.getGradeableUsers()); } /** * Build the matrix of assignments and grades for the given users. * In general this is just one, as we use it for the student summary but could be more for paging etc * * @param assignments list of assignments * @param list of uuids * @return */ public List<GbStudentGradeInfo> buildGradeMatrix(List<Assignment> assignments, List<String> studentUuids) throws GbException { return this.buildGradeMatrix(assignments, studentUuids, null); } /** * Build the matrix of assignments, students and grades for all students, with the specified sortOrder * * @param assignments list of assignments * @param sortOrder the sort order * @return */ public List<GbStudentGradeInfo> buildGradeMatrix(List<Assignment> assignments, GbAssignmentGradeSortOrder sortOrder) throws GbException { return this.buildGradeMatrix(assignments, this.getGradeableUsers(), sortOrder); } /** * Build the matrix of assignments and grades for the given users with the specified sort order * * @param assignments list of assignments * @param list of uuids * @Param sortOrder the type of sort we want. Wraps assignmentId and direction. * @return */ public List<GbStudentGradeInfo> buildGradeMatrix(List<Assignment> assignments, List<String> studentUuids, GbAssignmentGradeSortOrder sortOrder) throws GbException { StopWatch stopwatch = new StopWatch(); stopwatch.start(); Temp.timeWithContext("buildGradeMatrix", "buildGradeMatrix start", stopwatch.getTime()); Gradebook gradebook = this.getGradebook(); if(gradebook == null) { return null; } Temp.timeWithContext("buildGradeMatrix", "getGradebook", stopwatch.getTime()); //get uuids as list of Users. //this gives us our base list and will be sorted as per our desired sort method List<User> students = this.getUsers(studentUuids); //because this map is based on eid not uuid, we do the filtering later so we can save an iteration Map<String,String> courseGrades = this.getSiteCourseGrades(); Temp.timeWithContext("buildGradeMatrix", "getSiteCourseGrades", stopwatch.getTime()); //setup a map as we progressively build this up by adding grades to a student's entry Map<String, GbStudentGradeInfo> matrix = new LinkedHashMap<String, GbStudentGradeInfo>(); //seed the map for all students so we can progresseively add grades to it //also add the course grade here, to save an iteration later for(User student: students) { //create and add the user info GbStudentGradeInfo sg = new GbStudentGradeInfo(student); //add the course grade sg.setCourseGrade(courseGrades.get(student.getEid())); //add to map so we can build on it later matrix.put(student.getId(), sg); } Temp.timeWithContext("buildGradeMatrix", "matrix seeded", stopwatch.getTime()); //iterate over assignments and get the grades for each //note, the returned list only includes entries where there is a grade for the user //TODO maybe a new gb service method to do this, so we save iterating here? for(Assignment assignment: assignments) { try { List<GradeDefinition> defs = this.gradebookService.getGradesForStudentsForItem(gradebook.getUid(), assignment.getId(), studentUuids); Temp.timeWithContext("buildGradeMatrix", "getGradesForStudentsForItem: " + assignment.getId(), stopwatch.getTime()); //iterate the definitions returned and update the record for each student with any grades for(GradeDefinition def: defs) { GbStudentGradeInfo sg = matrix.get(def.getStudentUid()); if(sg == null) { log.warn("No matrix entry seeded for: " + def.getStudentUid() + ". This user may be been removed from the site"); } else { sg.addGrade(assignment.getId(), new GbGradeInfo(def)); } } Temp.timeWithContext("buildGradeMatrix", "updatedStudentGradeInfo: " + assignment.getId(), stopwatch.getTime()); } catch (SecurityException e) { //tried to access info for a user that we aren't allowed to get for. Skip this user. //consider rethrowing this? Or should the UI not care. log.error("Error retrieving grades. Skipping.", e); } } //get the matrix as a list of GbStudentGradeInfo ArrayList<GbStudentGradeInfo> items = new ArrayList<>(matrix.values()); //sort the matrix based on the supplied sort order (if any) if(sortOrder != null) { GradeComparator comparator = new GradeComparator(); comparator.setAssignmentId(sortOrder.getAssignmentId()); SortDirection direction = sortOrder.getDirection(); //sort Collections.sort(items, comparator); //reverse if required if(direction == SortDirection.DESCENDING) { Collections.reverse(items); } } return items; } /** * Get a list of sections and groups in a site * @return */ public List<GbGroup> getSiteSectionsAndGroups() { String siteId = this.getCurrentSiteId(); List<GbGroup> rval = new ArrayList<>(); //get sections try { Set<Section> sections = courseManagementService.getSections(siteId); for(Section section: sections){ rval.add(new GbGroup(section.getEid(), section.getTitle(), GbGroupType.SECTION)); } } catch (IdNotFoundException e) { //not a course site or no sections, ignore } //get groups try { Site site = siteService.getSite(siteId); Collection<Group> groups = site.getGroups(); for(Group group: groups) { rval.add(new GbGroup(group.getId(), group.getTitle(), GbGroupType.GROUP)); } } catch (IdUnusedException e) { //essentially ignore and use what we have log.error("Error retrieving groups", e); } Collections.sort(rval); //add the default ALL (this is a UI thing, it might not be appropriate here) //TODO also need to internationalse ths string rval.add(0, new GbGroup(null, "All Sections/Groups", GbGroupType.ALL)); return rval; } /** * Get a list of section memberships for the users in the site * @return */ /* public List<String> getSectionMemberships() { List<Section> sections = getSiteSections(); for(Section s: sections) { EnrollmentSet enrollmentSet = s.getEnrollmentSet(); Set<Enrollment> enrollments = courseManagementService.getEnrollments(enrollmentSet.getEid()); for(Enrollment e: enrollments) { //need to create a DTO for this //a user can be in multiple sections, need a list of sections per user //s.getTitle(); section title //e.getUserId(); user uuid } } return null; } */ /** * Helper to get siteid. * This will ONLY work in a portal site context, it will return null otherwise (ie via an entityprovider). * @return */ public String getCurrentSiteId() { try { return this.toolManager.getCurrentPlacement().getContext(); } catch (Exception e){ return null; } } /** * Get the placement id of the gradebookNG tool in the site. * This will ONLY work in a portal site context, null otherwise * @return */ private String getToolPlacementId() { try { return this.toolManager.getCurrentPlacement().getId(); } catch (Exception e){ return null; } } /** * Helper to get user * @return */ public User getCurrentUser() { return this.userDirectoryService.getCurrentUser(); } /** * Add a new assignment definition to the gradebook * @param assignment */ public void addAssignment(Assignment assignment) { Gradebook gradebook = getGradebook(); if(gradebook != null) { String gradebookId = gradebook.getUid(); this.gradebookService.addAssignment(gradebookId, assignment); //TODO wrap this so we can catch any runtime exceptions } } /** * Update the order of an assignment for the current site. * * @param assignmentId * @param order */ public void updateAssignmentOrder(long assignmentId, int order) { String siteId = this.getCurrentSiteId(); this.updateAssignmentOrder(siteId, assignmentId, order); } /** * Update the order of an assignment. If calling outside of GBNG, use this method as you can provide the site id. * * @param siteId the siteId * @param assignmentId the assignment we are reordering * @param order the new order * @throws IdUnusedException * @throws PermissionException */ public void updateAssignmentOrder(String siteId, long assignmentId, int order) { Gradebook gradebook = this.getGradebook(siteId); this.gradebookService.updateAssignmentOrder(gradebook.getUid(), assignmentId, order); } /** * Update the categorized order of an assignment. * * @param assignmentId the assignment we are reordering * @param order the new order * @throws JAXBException * @throws IdUnusedException * @throws PermissionException */ public void updateCategorizedAssignmentOrder(long assignmentId, int order) throws JAXBException, IdUnusedException, PermissionException { String siteId = this.getCurrentSiteId(); updateCategorizedAssignmentOrder(siteId, assignmentId, order); } /** * Update the categorized order of an assignment. * * @param siteId the site's id * @param assignmentId the assignment we are reordering * @param order the new order * @throws JAXBException * @throws IdUnusedException * @throws PermissionException */ public void updateCategorizedAssignmentOrder(String siteId, long assignmentId, int order) throws JAXBException, IdUnusedException, PermissionException { Site site = null; try { site = this.siteService.getSite(siteId); } catch (IdUnusedException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } Gradebook gradebook = (Gradebook)gradebookService.getGradebook(siteId); if (gradebook == null) { log.error(String.format("Gradebook not in site %s", siteId)); return; } Assignment assignmentToMove = gradebookService.getAssignment(gradebook.getUid(), assignmentId); if (assignmentToMove == null) { // TODO Handle assignment not in gradebook log.error(String.format("Assignment %d not in site %s", assignmentId, siteId)); return; } String category = assignmentToMove.getCategoryName(); Map<String, List<Long>> orderedAssignments = getCategorizedAssignmentsOrder(siteId); if (!orderedAssignments.containsKey(category)) { orderedAssignments.put(category, new ArrayList<Long>()); } else { orderedAssignments.get(category).remove(assignmentToMove.getId()); } orderedAssignments.get(category).add(order, assignmentToMove.getId()); storeCategorizedAssignmentsOrder(siteId, orderedAssignments); } /** * Get the ordered categorized assignment ids for the current site */ public Map<String, List<Long>> getCategorizedAssignmentsOrder() { try { return getCategorizedAssignmentsOrder(getCurrentSiteId()); } catch (JAXBException e) { e.printStackTrace(); } catch(IdUnusedException e) { e.printStackTrace(); } catch(PermissionException e) { e.printStackTrace(); } return null; } /** * Get the ordered categorized assignment ids for the siteId * * @param siteId the siteId * @throws JAXBException * @throws IdUnusedException * @throws PermissionException */ private Map<String, List<Long>> getCategorizedAssignmentsOrder(String siteId) throws JAXBException, IdUnusedException, PermissionException { Site site = null; try { site = this.siteService.getSite(siteId); } catch (IdUnusedException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } Gradebook gradebook = (Gradebook)gradebookService.getGradebook(siteId); if (gradebook == null) { log.error(String.format("Gradebook not in site %s", siteId)); return null; } ResourceProperties props = site.getProperties(); String xml = props.getProperty(ASSIGNMENT_ORDER_PROP); if(StringUtils.isNotBlank(xml)) { try { //goes via the xml list wrapper as that is serialisable XmlList<AssignmentOrder> xmlList = (XmlList<AssignmentOrder>) XmlMarshaller.unmarshall(xml); Map<String, List<Long>> result = new HashMap<String, List<Long>>(); List<AssignmentOrder> assignmentOrders = xmlList.getItems(); // Sort the assignments by their category and then order Collections.sort(assignmentOrders, new AssignmentOrderComparator()); for (AssignmentOrder ao : assignmentOrders) { // add the category if the XML doesn't have it already if (!result.containsKey(ao.getCategory())) { result.put(ao.getCategory(), new ArrayList<Long>()); } result.get(ao.getCategory()).add(ao.getAssignmentId()); } return result; } catch (JAXBException e) { e.printStackTrace(); } } else { return initializeCategorizedAssignmentOrder(siteId); } return null; } /** * Get the categorized order for an assignment * * @param assignmentId the assignment id * @throws JAXBException * @throws IdUnusedException * @throws PermissionException */ public int getCategorizedSortOrder(Long assignmentId) throws JAXBException, IdUnusedException, PermissionException { String siteId = this.getCurrentSiteId(); Gradebook gradebook = getGradebook(siteId); if(gradebook != null) { Assignment assignment = gradebookService.getAssignment(gradebook.getUid(), assignmentId); Map<String, List<Long>> categorizedOrder = getCategorizedAssignmentsOrder(siteId); return categorizedOrder.get(assignment.getCategoryName()).indexOf(assignmentId); } return -1; } /** * Set up initial Categorized Assignment Order */ private Map<String, List<Long>> initializeCategorizedAssignmentOrder(String siteId) throws JAXBException, IdUnusedException, PermissionException { Gradebook gradebook = getGradebook(siteId); List<Assignment> assignments = getGradebookAssignments(); Map<String, List<Long>> categoriesToAssignments = new HashMap<String, List<Long>>(); Iterator<Assignment> assignmentsIterator = assignments.iterator(); while (assignmentsIterator.hasNext()) { Assignment assignment = assignmentsIterator.next(); String category = assignment.getCategoryName(); if (!categoriesToAssignments.containsKey(category)) { categoriesToAssignments.put(category, new ArrayList<Long>()); } categoriesToAssignments.get(category).add(assignment.getId()); } storeCategorizedAssignmentsOrder(siteId, categoriesToAssignments); return categoriesToAssignments; } /** * Store categorized assignment order as XML on a site property * * @param siteId the site's id * @param assignments a list of assignments in their new order * @throws JAXBException * @throws IdUnusedException * @throws PermissionException */ private void storeCategorizedAssignmentsOrder(String siteId, Map<String, List<Long>> categoriesToAssignments) throws JAXBException, IdUnusedException, PermissionException { Site site = null; try { site = this.siteService.getSite(siteId); } catch (IdUnusedException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } List<AssignmentOrder> assignmentOrders = new ArrayList<AssignmentOrder>(); for (String category : categoriesToAssignments.keySet()) { List<Long> assignmentIds = categoriesToAssignments.get(category); for (int i = 0; i < assignmentIds.size(); i++) { assignmentOrders.add(new AssignmentOrder(assignmentIds.get(i), category, i)); } } XmlList<AssignmentOrder> newXmlList = new XmlList<AssignmentOrder>(assignmentOrders); String newXml = XmlMarshaller.marshal(newXmlList); ResourcePropertiesEdit props = site.getPropertiesEdit(); props.addProperty(ASSIGNMENT_ORDER_PROP, newXml); log.debug("Updated assignment order: " + newXml); this.siteService.save(site); } /** * Comparator class for sorting a list of users by last name */ class LastNameComparator implements Comparator<User> { @Override public int compare(User u1, User u2) { return u1.getLastName().compareTo(u2.getLastName()); } } /** * Comparator class for sorting a list of users by first name */ class FirstNameComparator implements Comparator<User> { @Override public int compare(User u1, User u2) { return u1.getFirstName().compareTo(u2.getFirstName()); } } /** * Push a an notification into the cache that someone is editing this gradebook. * We store one entry in the cache per gradebook. This allows fast lookup for a given gradebookUid. * Within the cached object we store a map keyed on the user (eid) that performed the edit (ie could be several instructors editing at once) * The value of the map is a map wih a special key of assignmentid+studentUuid, again for fast lookup. We can then access the data object directly and update it. It holds the coords of a grade cell that has been edited. * So for a given user editing many cells there will be many GbGradeCells associated with that user. * These have a time associated with each so we can discard manually if desired, on lookup. * * @param gradebookUid */ private void pushEditingNotification(final String gradebookUid, final User currentUser, final String studentUuid, final long assignmentId) { //TODO Tie into the event system so other edits also participate in this //get the notifications for this gradebook Map<String,Map<String,GbGradeCell>> notifications = (Map<String,Map<String,GbGradeCell>>) cache.get(gradebookUid); Map<String,GbGradeCell> cells = null; //get or create cell map if(notifications != null) { cells = notifications.get(currentUser.getId()); } else { notifications = new HashMap<>(); } if(cells == null) { cells = new LinkedHashMap<>(); } //push the edited cell into the map. It will add/update as required cells.put(buildCellKey(studentUuid, assignmentId), new GbGradeCell(studentUuid, assignmentId)); //push the new/updated cell map into the main map notifications.put(currentUser.getEid(), cells); //update the map in the cache cache.put(gradebookUid, notifications); } /** * Get a list of editing notifications for this gradebook. Excludes any notifications for the current user * * @param gradebookUid the gradebook that we are interested in * @return */ public List<GbGradeCell> getEditingNotifications(String gradebookUid) { String currentUserId = this.getCurrentUser().getEid(); //get the notifications for this gradebook Map<String,Map<String,GbGradeCell>> notifications = (Map<String,Map<String,GbGradeCell>>) cache.get(gradebookUid); List<GbGradeCell> rval = new ArrayList<>(); if(notifications != null) { notifications.remove(currentUserId); //join the rest of the maps to get a flat list of GbGradeCells for(Map<String, GbGradeCell> cells : notifications.values()) { rval.addAll(cells.values()); } } //TODO accept a timestamp and filter the list. We are only itnerested in notifications after the given timestamp //this solves the problem where old editing notifications are returned even though the user has recently refreshed the list return rval; } /** * Get an Assignment in the current site given the assignment id * * @param siteId * @param assignmentId * @return */ public Assignment getAssignment(long assignmentId) { String siteId = this.getCurrentSiteId(); return this.getAssignment(siteId, assignmentId); } /** * Get an Assignment in the specified site given the assignment id * * @param siteId * @param assignmentId * @return */ public Assignment getAssignment(String siteId, long assignmentId) { Gradebook gradebook = getGradebook(siteId); if(gradebook != null) { return gradebookService.getAssignment(gradebook.getUid(), assignmentId); } return null; } /** * Get the sort order of an assignment. If the assignment has a sort order, use that. * Otherwise we determine the order of the assignment in the list of assignments * * This means that we can always determine the most current sort order for an assignment, even if the list has never been sorted. * * * @param assignmentId * @return sort order if set, or calculated, or -1 if cannot determine at all. */ public int getAssignmentSortOrder(long assignmentId) { String siteId = this.getCurrentSiteId(); Gradebook gradebook = getGradebook(siteId); if(gradebook != null) { Assignment assignment = gradebookService.getAssignment(gradebook.getUid(), assignmentId); //if the assignment has a sort order, return that if(assignment.getSortOrder() != null) { return assignment.getSortOrder(); } //otherwise we need to determine the assignment sort order within the list of assignments List<Assignment> assignments = this.getGradebookAssignments(siteId); for(int i=0; i<assignments.size(); i++) { Assignment a = assignments.get(i); if(assignmentId == a.getId()) { return a.getSortOrder(); } } } return -1; } /** * Update the details of an assignment * * @param assignment * @return */ public boolean updateAssignment(Assignment assignment) { String siteId = this.getCurrentSiteId(); Gradebook gradebook = getGradebook(siteId); //need the original name as the service needs that as the key... Assignment original = this.getAssignment(assignment.getId()); try { gradebookService.updateAssignment(gradebook.getUid(), original.getId(), assignment); return true; } catch (Exception e) { log.error("An error occurred updating the assignment", e); } return false; } /** * Updates ungraded items in the given assignment with the given grade * * @param assignmentId * @param grade * @return */ public boolean updateUngradedItems(long assignmentId, double grade) { String siteId = this.getCurrentSiteId(); Gradebook gradebook = getGradebook(siteId); //get students List<String> studentUuids = this.getGradeableUsers(); //get grades (only returns those where there is a grade) List<GradeDefinition> defs = this.gradebookService.getGradesForStudentsForItem(gradebook.getUid(), assignmentId, studentUuids); //iterate and trim the studentUuids list down to those that don't have grades for(GradeDefinition def: defs) { //don't remove those where the grades are blank, they need to be updated too if(StringUtils.isNotBlank(def.getGrade())) { studentUuids.remove(def.getStudentUid()); } } if(studentUuids.isEmpty()) { log.debug("Setting default grade. No students are ungraded."); } try { //for each student remaining, add the grade for(String studentUuid : studentUuids) { log.debug("Setting default grade. Values of assignmentId: " + assignmentId + ", studentUuid: " + studentUuid + ", grade: " + grade); //TODO if this is slow doing it one by one, might be able to batch it gradebookService.saveGradeAndCommentForStudent(gradebook.getUid(), assignmentId, studentUuid, String.valueOf(grade), null); } return true; } catch (Exception e) { log.error("An error occurred updating the assignment", e); } return false; } /** * Get the grade log for the given student and assignment * * @param studentUuid * @param assignmentId * @return */ public List<GbGradeLog> getGradeLog(final String studentUuid, final long assignmentId) { List<GradingEvent> gradingEvents = this.gradebookService.getGradingEvents(studentUuid, assignmentId); List<GbGradeLog> rval = new ArrayList<>(); for(GradingEvent ge: gradingEvents) { rval.add(new GbGradeLog(ge)); } Collections.reverse(rval); return rval; } /** * Get the user given a uuid * @param userUuid * @return GbUser or null if cannot be found */ public GbUser getUser(String userUuid) { try { User u = userDirectoryService.getUser(userUuid); return new GbUser(u); } catch (UserNotDefinedException e) { return null; } } /** * Get the comment for a given student assignment grade * * @param assignmentId id of assignment * @param studentUuid uuid of student * @return the comment or null if none */ public String getAssignmentGradeComment(final long assignmentId, final String studentUuid){ String siteId = this.getCurrentSiteId(); Gradebook gradebook = getGradebook(siteId); try { CommentDefinition def = this.gradebookService.getAssignmentScoreComment(gradebook.getUid(), assignmentId, studentUuid); if(def != null){ return def.getCommentText(); } } catch (GradebookNotFoundException | AssessmentNotFoundException e) { log.error("An error occurred retrieving the comment. " + e.getClass() + ": " + e.getMessage()); } return null; } /** * Update (or set) the comment for a student's assignment * * @param assignmentId id of assignment * @param studentUuid uuid of student * @param comment the comment * @return true/false */ public boolean updateAssignmentGradeComment(final long assignmentId, final String studentUuid, final String comment) { String siteId = this.getCurrentSiteId(); Gradebook gradebook = getGradebook(siteId); try { //could do a check here to ensure we aren't overwriting someone else's comment that has been updated in the interim... this.gradebookService.setAssignmentScoreComment(gradebook.getUid(), assignmentId, studentUuid, comment); return true; } catch (GradebookNotFoundException | AssessmentNotFoundException | IllegalArgumentException e) { log.error("An error occurred saving the comment. " + e.getClass() + ": " + e.getMessage()); } return false; } /** * Comparator class for sorting a list of AssignmentOrders */ class AssignmentOrderComparator implements Comparator<AssignmentOrder> { @Override public int compare(AssignmentOrder ao1, AssignmentOrder ao2) { // Deal with uncategorized assignments (nulls!) if (ao1.getCategory() == null && ao2.getCategory() == null) { return ((Integer) ao1.getOrder()).compareTo(ao2.getOrder()); } else if (ao1.getCategory() == null) { return 1; } else if (ao2.getCategory() == null) { return -1; } // Deal with friendly categorized assignments if (ao1.getCategory().equals(ao2.getCategory())) { return ((Integer) ao1.getOrder()).compareTo(ao2.getOrder()); } else { return ((String) ao1.getCategory()).compareTo(ao2.getCategory()); } } } /** * Build the key to identify the cell. Used in the notifications cache. * @param studentUuid * @param assignmentId * @return */ private String buildCellKey(String studentUuid, long assignmentId) { return studentUuid + "-" + assignmentId; } /** * Comparator class for sorting an assignment by the grades * Note that this must have the assignmentId set into it so we can extract the appropriate grade entry from the map that each student has * */ class GradeComparator implements Comparator<GbStudentGradeInfo> { @Setter private long assignmentId; @Override public int compare(GbStudentGradeInfo g1, GbStudentGradeInfo g2) { GbGradeInfo info1 = g1.getGrades().get(assignmentId); GbGradeInfo info2 = g2.getGrades().get(assignmentId); //for proper number ordering, these have to be numerical Double grade1 = (info1 != null) ? NumberUtils.toDouble(info1.getGrade()) : null; Double grade2 = (info2 != null) ? NumberUtils.toDouble(info2.getGrade()) : null; return new CompareToBuilder() .append(grade1, grade2) .toComparison(); } } }
maurercw/gradebookNG
tool/src/java/org/sakaiproject/gradebookng/business/GradebookNgBusinessService.java
Java
apache-2.0
41,343
package mealplanner.view.diet; import javafx.fxml.FXML; import javafx.scene.control.TableColumn; import mealplanner.domain.Data; import mealplanner.domain.Diet; import mealplanner.domain.Dish; import mealplanner.view.ListController; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.OptionalLong; public class DietListController extends ListController<Diet> { @FXML private TableColumn<Diet, Long> idColumn; @FXML private TableColumn<Diet, String> nameColumn; private Data data; public static final URL DIALOG_LOCATION = DietListController.class.getResource("DietListDialog.fxml"); public DietListController() { super(DietEditController.DIALOG_LOCATION, "Diet"); } @Override protected void initialize() { super.initialize(); assert idColumn != null; assert nameColumn != null; idColumn.setCellValueFactory(cellData -> cellData.getValue().idProperty().asObject()); nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); } @Override public void setData(Data data) { table.setItems(data.getDiets()); this.data = data; } @Override protected List<String> findUsages(Diet diet) { List<String> result = new ArrayList<>(); for (Dish dish : data.getDishes()) { if (dish.getDiets().contains(diet)) { result.add(dish.getName()); } } return result; } @Override protected boolean removeUsages(Diet diet) { for (Dish dish : data.getDishes()) { dish.getDiets().remove(diet); } return true; } }
kokorin/MealPlanner
src/java/mealplanner/view/diet/DietListController.java
Java
apache-2.0
1,739
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mediaconvert.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.mediaconvert.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CaptionDescriptionPreset JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CaptionDescriptionPresetJsonUnmarshaller implements Unmarshaller<CaptionDescriptionPreset, JsonUnmarshallerContext> { public CaptionDescriptionPreset unmarshall(JsonUnmarshallerContext context) throws Exception { CaptionDescriptionPreset captionDescriptionPreset = new CaptionDescriptionPreset(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("customLanguageCode", targetDepth)) { context.nextToken(); captionDescriptionPreset.setCustomLanguageCode(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("destinationSettings", targetDepth)) { context.nextToken(); captionDescriptionPreset.setDestinationSettings(CaptionDestinationSettingsJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("languageCode", targetDepth)) { context.nextToken(); captionDescriptionPreset.setLanguageCode(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("languageDescription", targetDepth)) { context.nextToken(); captionDescriptionPreset.setLanguageDescription(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return captionDescriptionPreset; } private static CaptionDescriptionPresetJsonUnmarshaller instance; public static CaptionDescriptionPresetJsonUnmarshaller getInstance() { if (instance == null) instance = new CaptionDescriptionPresetJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/transform/CaptionDescriptionPresetJsonUnmarshaller.java
Java
apache-2.0
3,686
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ivs.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.ivs.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * BatchGetStreamKeyRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class BatchGetStreamKeyRequestProtocolMarshaller implements Marshaller<Request<BatchGetStreamKeyRequest>, BatchGetStreamKeyRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/BatchGetStreamKey") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).serviceName("AmazonIVS").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public BatchGetStreamKeyRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<BatchGetStreamKeyRequest> marshall(BatchGetStreamKeyRequest batchGetStreamKeyRequest) { if (batchGetStreamKeyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<BatchGetStreamKeyRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, batchGetStreamKeyRequest); protocolMarshaller.startMarshalling(); BatchGetStreamKeyRequestMarshaller.getInstance().marshall(batchGetStreamKeyRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-ivs/src/main/java/com/amazonaws/services/ivs/model/transform/BatchGetStreamKeyRequestProtocolMarshaller.java
Java
apache-2.0
2,659
package no.noen.server.commond; /** * Alarm data. */ public class AlarmData { private int portNr; private int portState; private java.util.Date timestamp; private String text; /** Constructor. */ public AlarmData(int port, int state, java.util.Date ts, String txt) { this.portNr = port; this.portState = state; this.timestamp = ts; this.text = txt; } /** @return port nr */ public final int getPortNr() { return portNr; } /** @return port state as an integer.) */ public final int getPortState() { return portState; } /** @return timestamp for the alarm */ public final java.util.Date getTimestamp() { return timestamp; } /** @return alarm text */ public final String getText() { return text; } }
haakom/EnergiWeb-remake
energiweb/src/no/noen/server/commond/AlarmData.java
Java
apache-2.0
850
package com.lee.hooker; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.lee.architecture", appContext.getPackageName()); } }
noobyang/AndroidStudy
hooker/src/androidTest/java/com/lee/hooker/ExampleInstrumentedTest.java
Java
apache-2.0
718
package com.yammer.breakerbox.service.comparable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Ordering; import com.yammer.breakerbox.azure.model.DependencyEntity; import com.yammer.breakerbox.store.DependencyId; import com.yammer.breakerbox.store.ServiceId; import com.yammer.breakerbox.store.model.DependencyModel; import org.joda.time.DateTime; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; public class SortRowFirstTest { @Test public void testOrdering() throws Exception { final DependencyId dependencyId = DependencyId.from("foo"); final ServiceId serviceId = ServiceId.from("testService"); final ImmutableList<DependencyModel> items = ImmutableList.of( new DependencyModel(dependencyId, new DateTime(10), DependencyEntity.defaultConfiguration(), "testUser", serviceId), new DependencyModel(dependencyId, new DateTime(8), DependencyEntity.defaultConfiguration(), "testUser", serviceId), new DependencyModel(dependencyId, new DateTime(12), DependencyEntity.defaultConfiguration(), "testUser", serviceId), new DependencyModel(dependencyId, new DateTime(14), DependencyEntity.defaultConfiguration(), "testUser", serviceId), new DependencyModel(dependencyId, new DateTime(13), DependencyEntity.defaultConfiguration(), "testUser", serviceId), new DependencyModel(dependencyId, new DateTime(200), DependencyEntity.defaultConfiguration(), "testUser", serviceId)); final ImmutableList<DependencyModel> sortedItems = Ordering.from(new SortRowFirst()) .reverse() .immutableSortedCopy(items); assertThat(sortedItems.size()).isEqualTo(items.size()); assertThat(sortedItems.get(0).getDateTime()).isEqualTo(new DateTime(200)); assertThat(sortedItems.get(1).getDateTime()).isEqualTo(new DateTime(14)); assertThat(sortedItems.get(2).getDateTime()).isEqualTo(new DateTime(13)); assertThat(sortedItems.get(3).getDateTime()).isEqualTo(new DateTime(12)); assertThat(sortedItems.get(4).getDateTime()).isEqualTo(new DateTime(10)); assertThat(sortedItems.get(5).getDateTime()).isEqualTo(new DateTime(8)); } }
guggens/log-dropwizard-eureka-mongo-sample
breakerbox/breakerbox-service/src/test/java/com/yammer/breakerbox/service/comparable/SortRowFirstTest.java
Java
apache-2.0
2,300
package org.visallo.web.routes.edge; import com.google.inject.Inject; import com.google.inject.Singleton; import org.visallo.webster.ParameterizedHandler; import org.visallo.webster.annotations.Handle; import org.visallo.webster.annotations.Optional; import org.visallo.webster.annotations.Required; import org.vertexium.*; import org.visallo.core.exception.VisalloResourceNotFoundException; import org.visallo.core.model.termMention.TermMentionRepository; import org.visallo.core.security.VisalloVisibility; import org.visallo.core.security.VisibilityTranslator; import org.visallo.core.user.User; import org.visallo.core.util.VisalloLogger; import org.visallo.core.util.VisalloLoggerFactory; import org.visallo.web.clientapi.model.ClientApiEdgePropertyDetails; import org.visallo.web.clientapi.model.ClientApiSourceInfo; import org.visallo.web.clientapi.model.VisibilityJson; import org.visallo.web.parameterProviders.ActiveWorkspaceId; import org.visallo.web.util.VisibilityValidator; import java.util.ResourceBundle; @Singleton public class EdgePropertyDetails implements ParameterizedHandler { private static final VisalloLogger LOGGER = VisalloLoggerFactory.getLogger(EdgePropertyDetails.class); private final Graph graph; private final TermMentionRepository termMentionRepository; private final VisibilityTranslator visibilityTranslator; @Inject public EdgePropertyDetails( Graph graph, TermMentionRepository termMentionRepository, VisibilityTranslator visibilityTranslator ) { this.graph = graph; this.termMentionRepository = termMentionRepository; this.visibilityTranslator = visibilityTranslator; } @Handle public ClientApiEdgePropertyDetails handle( @Required(name = "edgeId") String edgeId, @Optional(name = "propertyKey") String propertyKey, @Required(name = "propertyName") String propertyName, @Required(name = "visibilitySource") String visibilitySource, @ActiveWorkspaceId String workspaceId, ResourceBundle resourceBundle, User user, Authorizations authorizations ) throws Exception { Visibility visibility = VisibilityValidator.validate( graph, visibilityTranslator, resourceBundle, visibilitySource, user, authorizations ); Edge edge = this.graph.getEdge(edgeId, authorizations); if (edge == null) { throw new VisalloResourceNotFoundException("Could not find edge with id: " + edgeId, edgeId); } Property property = edge.getProperty(propertyKey, propertyName, visibility); if (property == null) { VisibilityJson visibilityJson = new VisibilityJson(); visibilityJson.setSource(visibilitySource); visibilityJson.addWorkspace(workspaceId); VisalloVisibility v2 = visibilityTranslator.toVisibility(visibilityJson); property = edge.getProperty(propertyKey, propertyName, v2.getVisibility()); if (property == null) { throw new VisalloResourceNotFoundException("Could not find property " + propertyKey + ":" + propertyName + ":" + visibility + " on edge with id: " + edgeId, edgeId); } } ClientApiSourceInfo sourceInfo = termMentionRepository.getSourceInfoForEdgeProperty(edge, property, authorizations); ClientApiEdgePropertyDetails result = new ClientApiEdgePropertyDetails(); result.sourceInfo = sourceInfo; return result; } }
visallo/visallo
web/web-base/src/main/java/org/visallo/web/routes/edge/EdgePropertyDetails.java
Java
apache-2.0
3,660
/* * Copyright 2015, Alexandre Lewandowski * * 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.sonar.plugins.oauth2.provider; import org.apache.oltu.oauth2.client.request.OAuthClientRequest; import org.apache.oltu.oauth2.common.OAuthProviderType; import org.apache.oltu.oauth2.common.message.types.GrantType; import org.sonar.api.config.Settings; import org.sonar.plugins.oauth2.OAuth2Client; public class GenericProvider implements OAuth2Provider { private OAuthProviderType provider; public GenericProvider(OAuthProviderType provider) { this.provider = provider; } @Override public String getAuthzEndpoint() { return this.provider.getAuthzEndpoint(); } @Override public String getProviderName() { return this.provider.getProviderName(); } @Override public String getTokenEndpoint() { return this.provider.getTokenEndpoint(); } @Override public OAuthClientRequest.AuthenticationRequestBuilder createRedirectRequestBuilder(Settings settings) { final String callback = getRedirectUri(settings); return OAuthClientRequest.authorizationLocation(getAuthzEndpoint()) .setClientId(settings.getString(OAuth2Client.PROPERTY_CLIENT_ID)) .setRedirectURI(callback) .setParameter("scope", "email"); } @Override public OAuthClientRequest.TokenRequestBuilder createTokenRequestBuilder(Settings settings, String code) { final String callback = getRedirectUri(settings); return OAuthClientRequest.tokenLocation(getTokenEndpoint()) .setClientId(settings.getString(OAuth2Client.PROPERTY_CLIENT_ID)) .setClientSecret(settings.getString(OAuth2Client.PROPERTY_SECRET)) .setCode(code) .setRedirectURI(callback) .setGrantType(GrantType.AUTHORIZATION_CODE); } private String getRedirectUri(Settings settings) { final String baseUrl = settings.getString(OAuth2Client.PROPERTY_SONAR_URL); return baseUrl + (baseUrl.endsWith("/") ? "" : "/") + OAuth2Client.PROPERTY_CALLBACK_URI; } }
alexlew/sonar-oauth2
src/main/java/org/sonar/plugins/oauth2/provider/GenericProvider.java
Java
apache-2.0
2,567
package edu.cmu.sv.ws.ssnoc.data.po; import com.google.gson.Gson; /** * This is the persistence class to save all user information in the system. * This contains information like the user's name, his role, his account status * and the password information entered by the user when signing up. <br/> * Information is saved in SSN_USERS table. * */ public class UserPO { private long userId; private String userName; private String password; private String salt; public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } @Override public String toString() { return new Gson().toJson(this); } }
seckcoder/SSNoC-Java-REST
src/main/java/edu/cmu/sv/ws/ssnoc/data/po/UserPO.java
Java
apache-2.0
1,034
/* * Copyright 2017 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.terminal; import com.google.idea.blaze.base.model.primitives.WorkspaceRoot; import com.intellij.openapi.project.Project; import javax.annotation.Nullable; import org.jetbrains.plugins.terminal.LocalTerminalCustomizer; /** Set the default terminal path to the workspace root. */ public class DefaultTerminalLocationCustomizer extends LocalTerminalCustomizer { // added in 2017.1, so foregoing the override annotation for backwards compatibility. @SuppressWarnings("Overrides") @Nullable protected String getDefaultFolder(Project project) { WorkspaceRoot root = WorkspaceRoot.fromProjectSafe(project); return root != null ? root.toString() : null; } }
brendandouglas/intellij
terminal/src/com/google/idea/blaze/terminal/DefaultTerminalLocationCustomizer.java
Java
apache-2.0
1,322
/** * Copyright [2016] Gaurav Gupta * * 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.netbeans.modeler.properties.enumtype; import java.util.Map; import org.netbeans.modeler.config.element.Attribute; import org.netbeans.modeler.core.ModelerFile; import org.netbeans.modeler.specification.model.document.widget.IBaseElementWidget; import org.netbeans.modeler.widget.properties.handler.PropertyChangeListener; import org.openide.nodes.PropertySupport; /** * * @author jGauravGupta <gaurav.gupta.jc@gmail.com> */ public interface EnumComboBoxResolver { PropertySupport getPropertySupport(ModelerFile modelerFile, Attribute attribute, IBaseElementWidget baseElementWidget, Object object, Map<String, PropertyChangeListener> propertyChangeHandlers); }
jGauravGupta/nbmodeler
modeler-api/src/main/java/org/netbeans/modeler/properties/enumtype/EnumComboBoxResolver.java
Java
apache-2.0
1,310
package com.ext.portlet.epsos.gateway; import java.io.Serializable; import java.util.List; import org.opensaml.saml2.core.Assertion; import com.spirit.ehr.ws.client.generated.SpiritUserClientDto; public class InitUserObj implements Serializable { private static final long serialVersionUID = 1L; SpiritUserClientDto usr; Assertion assertion; public SpiritUserClientDto getUsr() { return usr; } public void setUsr(SpiritUserClientDto usr) { this.usr = usr; } public Assertion getAssertion() { return assertion; } public void setAssertion(Assertion assertion) { this.assertion = assertion; } }
WilliamGoossen/epsos-common-components.gnomonportal
webapps/ROOT/WEB-INF/src/com/ext/portlet/epsos/gateway/InitUserObj.java
Java
apache-2.0
653
package com.github.ftrossbach.kiqr.client.service.rest; import com.github.ftrossbach.kiqr.client.service.GenericBlockingKiqrClient; import com.github.ftrossbach.kiqr.client.service.QueryExecutionException; import com.github.ftrossbach.kiqr.commons.config.querymodel.requests.*; import com.github.ftrossbach.kiqr.core.RuntimeVerticle; import com.github.ftrossbach.kiqr.rest.server.RestKiqrServerVerticle; import io.vertx.core.AbstractVerticle; import io.vertx.core.Vertx; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.kstream.*; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; /** * Created by ftr on 08/03/2017. */ public class GenericClientIntegrationITCase { private final static String KAFKA_HOST = "localhost"; private final static String KAFKA_PORT; static { if(System.getenv("KAFKA_PORT") != null){ KAFKA_PORT = System.getenv("KAFKA_PORT"); } else { KAFKA_PORT = "9092"; } } private static String TOPIC = UUID.randomUUID().toString(); private static final Vertx VERTX = Vertx.vertx(); @BeforeClass public static void produceMessages() throws Exception{ Properties producerProps = new Properties(); producerProps.put("bootstrap.servers", KAFKA_HOST + ":" + KAFKA_PORT); producerProps.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); producerProps.put("value.serializer", "org.apache.kafka.common.serialization.LongSerializer"); producerProps.put("linger.ms", 0); try(KafkaProducer<String, Long> producer = new KafkaProducer<>(producerProps)){ producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 0L, "key1", 1L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 100L, "key1", 2L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 100000L, "key1", 3L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 0L, "key2", 4L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 100000L, "key2", 5L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 100001L, "key2", 6L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 0L, "key3", 7L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 50000L, "key3", 8L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 100001L, "key3", 9L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 0L, "key4", 10L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 1L, "key4", 11L)); producer.send(new ProducerRecord<String, Long>(TOPIC, 0, 2L, "key4", 12L)); } CountDownLatch cdl = new CountDownLatch(12); Properties consumerProps = new Properties(); consumerProps.put("bootstrap.servers", KAFKA_HOST + ":" + KAFKA_PORT); consumerProps.put("group.id", UUID.randomUUID().toString()); consumerProps.put("enable.auto.commit", "true"); consumerProps.put("auto.offset.reset", "earliest"); consumerProps.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); consumerProps.put("value.deserializer", "org.apache.kafka.common.serialization.LongDeserializer"); Runnable consumerRunnable = () -> { KafkaConsumer<String, Long> consumer = new KafkaConsumer<>(consumerProps); consumer.subscribe(Collections.singleton(TOPIC)); int tryCount = 10; while(true){ ConsumerRecords<String, Long> records = consumer.poll(500); records.forEach(rec -> cdl.countDown()); tryCount--; if(cdl.getCount() == 0){ consumer.close(); return; } else if(tryCount == 0){ throw new RuntimeException("times up"); } } }; consumerRunnable.run(); cdl.await(10000, TimeUnit.MILLISECONDS); KStreamBuilder builder = new KStreamBuilder(); KStream<String, Long> kv = builder.stream(Serdes.String(), Serdes.Long(), TOPIC); KGroupedStream<String, Long> group = kv.groupBy((k, v) -> k, Serdes.String(), Serdes.Long()); group.reduce((a,b) -> b, "kv"); group.count(SessionWindows.with(60 * 1000), "session"); group.count(TimeWindows.of(10000L), "window"); Properties streamProps = new Properties(); streamProps.put(StreamsConfig.APPLICATION_ID_CONFIG, UUID.randomUUID().toString()); streamProps.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_HOST + ":" + KAFKA_PORT); streamProps.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0); streamProps.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); streamProps.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.Long().getClass().getName()); CountDownLatch streamCdl = new CountDownLatch(2); RestKiqrServerVerticle.Builder verticleBuilder = RestKiqrServerVerticle.Builder.serverBuilder(builder, streamProps); RuntimeVerticle.Builder builder1 = verticleBuilder.withPort(44321).withStateListener((newState, oldState) -> { if (newState == KafkaStreams.State.RUNNING) streamCdl.countDown(); System.out.println(oldState + " - " + newState); }); AbstractVerticle verticle = verticleBuilder.build(); CountDownLatch verticleCdl = new CountDownLatch(1); VERTX.deployVerticle(verticle, handler -> { verticleCdl.countDown(); }); streamCdl.await(100000, TimeUnit.MILLISECONDS); verticleCdl.await(100000, TimeUnit.MILLISECONDS); } @Test public void successfulScalarQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Optional<Long> resultKey1 = client.getScalarKeyValue("kv", String.class, "key1", Long.class, Serdes.String(), Serdes.Long()); assertTrue(resultKey1.isPresent()); assertThat(resultKey1.get(), is(equalTo(3L))); Optional<Long> resultKey2 = client.getScalarKeyValue("kv", String.class, "key3", Long.class, Serdes.String(), Serdes.Long()); assertTrue(resultKey2.isPresent()); assertThat(resultKey2.get(), is(equalTo(9L))); } @Test public void notFoundScalarQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Optional<Long> resultKey1 = client.getScalarKeyValue("kv", String.class, "key5", Long.class, Serdes.String(), Serdes.Long()); assertFalse(resultKey1.isPresent()); } @Test public void noSuchStoreScalarQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Optional<Long> resultKey1 = client.getScalarKeyValue("idontexist", String.class, "key1", Long.class, Serdes.String(), Serdes.Long()); assertFalse(resultKey1.isPresent()); } @Test(expected = QueryExecutionException.class) public void wrongStoreTypeScalarQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Optional<Long> resultKey1 = client.getScalarKeyValue("window", String.class, "key1", Long.class, Serdes.String(), Serdes.Long()); } @Test public void successfulAllQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<String, Long> result = client.getAllKeyValues("kv", String.class, Long.class, Serdes.String(), Serdes.Long()); assertThat(result.entrySet(),hasSize(4)); assertThat(result, hasEntry("key1", 3L)); assertThat(result, hasEntry("key2", 6L)); assertThat(result, hasEntry("key3", 9L)); assertThat(result, hasEntry("key4", 12L)); } @Test public void noSuchStoreAllQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<String, Long> result = client.getAllKeyValues("idontexist", String.class, Long.class, Serdes.String(), Serdes.Long()); assertTrue(result.isEmpty()); } @Test(expected = QueryExecutionException.class) public void wrongStoreTypeAllQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<String, Long> result = client.getAllKeyValues("window", String.class, Long.class, Serdes.String(), Serdes.Long()); } @Test public void successfulRangeQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<String, Long> result = client.getRangeKeyValues("kv", String.class, Long.class, Serdes.String(), Serdes.Long(), "key1", "key2"); assertThat(result.entrySet(),hasSize(2)); assertThat(result, hasEntry("key1", 3L)); assertThat(result, hasEntry("key2", 6L)); } @Test public void emptyRangeQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<String, Long> result = client.getRangeKeyValues("kv", String.class, Long.class, Serdes.String(), Serdes.Long(), "key6", "key7"); assertThat(result.entrySet(),is(empty())); } @Test(expected = QueryExecutionException.class) public void invertedRangeQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<String, Long> result = client.getRangeKeyValues("kv", String.class, Long.class, Serdes.String(), Serdes.Long(), "key3", "key1"); assertThat(result.entrySet(),is(empty())); } @Test public void noSuchStoreRangeQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<String, Long> result = client.getRangeKeyValues("idontexist", String.class, Long.class, Serdes.String(), Serdes.Long(), "key1", "key2"); assertTrue(result.isEmpty()); } @Test(expected = QueryExecutionException.class) public void wrongStoreTypeRangeQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<String, Long> result = client.getRangeKeyValues("window", String.class, Long.class, Serdes.String(), Serdes.Long(), "key1", "key2"); } @Test public void successfulWindowQuery() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<Long, Long> result = client.getWindow("window", String.class, "key1", Long.class, Serdes.String(), Serdes.Long(), 0L, 100001L); assertThat(result.entrySet(),hasSize(2)); assertThat(result, hasEntry(0L, 2L)); assertThat(result, hasEntry(100000L, 1L)); Map<Long, Long> resultKey2 = client.getWindow("window", String.class, "key2", Long.class, Serdes.String(), Serdes.Long(), 0L, 100001L); assertThat(resultKey2.entrySet(),hasSize(2)); assertThat(resultKey2, hasEntry(0L, 1L)); assertThat(resultKey2, hasEntry(100000L, 2L)); Map<Long, Long> resultKey3 = client.getWindow("window", String.class, "key3", Long.class, Serdes.String(), Serdes.Long(), 0L, 100001L); assertThat(resultKey3.entrySet(),hasSize(3)); assertThat(resultKey3, hasEntry(0L, 1L)); assertThat(resultKey3, hasEntry(50000L, 1L)); assertThat(resultKey3, hasEntry(100000L, 1L)); Map<Long, Long> resultKey4 = client.getWindow("window", String.class, "key4", Long.class, Serdes.String(), Serdes.Long(), 0L, 100001L); assertThat(resultKey4.entrySet(),hasSize(1)); assertThat(resultKey4, hasEntry(0L, 3L)); } @Test public void successfulCount() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Optional<Long> count = client.count("kv"); assertTrue(count.isPresent());; assertThat(count.get(), is(greaterThan(0L))); } @Test public void successfulSession() throws Exception{ GenericBlockingKiqrClient client = new GenericBlockingRestKiqrClientImpl("localhost", 44321); Map<com.github.ftrossbach.kiqr.commons.config.querymodel.requests.Window, Long> session = client.getSession("session", String.class, "key1", Long.class, Serdes.String(), Serdes.Long()); assertThat(session.size(), is(equalTo(2)) ); } @AfterClass public static void tearDown() throws Exception{ CountDownLatch cdl = new CountDownLatch(1); VERTX.close(handler -> cdl.countDown()); cdl.await(30000, TimeUnit.MILLISECONDS); } }
ftrossbach/kiqr
rest-client/src/test/java/com/github/ftrossbach/kiqr/client/service/rest/GenericClientIntegrationITCase.java
Java
apache-2.0
13,686
package ar.com.larreta.prode.domain; public class LocalGameState extends GameState { public LocalGameState() { super(new Long(1)); } }
llarreta/larretasources
ProdeWeb/src/main/java/ar/com/larreta/prode/domain/LocalGameState.java
Java
apache-2.0
151
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.nodemanager; public enum ContainerManagerEventType { FINISH_APPS, FINISH_CONTAINERS, }
srijeyanthan/hops
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerManagerEventType.java
Java
apache-2.0
938
/* 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.flowable.ui.modeler.conf; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.flowable.common.engine.api.FlowableException; import org.flowable.ui.common.service.exception.InternalServerErrorException; import org.flowable.ui.modeler.properties.FlowableModelerAppProperties; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.ResourcePatternUtils; import liquibase.Liquibase; import liquibase.database.Database; import liquibase.database.DatabaseConnection; import liquibase.database.DatabaseFactory; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.DatabaseException; import liquibase.resource.ClassLoaderResourceAccessor; @Configuration(proxyBeanMethods = false) public class ModelerDatabaseConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(ModelerDatabaseConfiguration.class); protected static final String LIQUIBASE_CHANGELOG_PREFIX = "ACT_DE_"; @Autowired protected FlowableModelerAppProperties modelerAppProperties; @Autowired protected ResourceLoader resourceLoader; protected static Properties databaseTypeMappings = getDefaultDatabaseTypeMappings(); public static final String DATABASE_TYPE_H2 = "h2"; public static final String DATABASE_TYPE_HSQL = "hsql"; public static final String DATABASE_TYPE_MYSQL = "mysql"; public static final String DATABASE_TYPE_ORACLE = "oracle"; public static final String DATABASE_TYPE_POSTGRES = "postgres"; public static final String DATABASE_TYPE_MSSQL = "mssql"; public static final String DATABASE_TYPE_DB2 = "db2"; public static Properties getDefaultDatabaseTypeMappings() { Properties databaseTypeMappings = new Properties(); databaseTypeMappings.setProperty("H2", DATABASE_TYPE_H2); databaseTypeMappings.setProperty("HSQL Database Engine", DATABASE_TYPE_HSQL); databaseTypeMappings.setProperty("MySQL", DATABASE_TYPE_MYSQL); databaseTypeMappings.setProperty("MariaDB", DATABASE_TYPE_MYSQL); databaseTypeMappings.setProperty("Oracle", DATABASE_TYPE_ORACLE); databaseTypeMappings.setProperty("PostgreSQL", DATABASE_TYPE_POSTGRES); databaseTypeMappings.setProperty("Microsoft SQL Server", DATABASE_TYPE_MSSQL); databaseTypeMappings.setProperty(DATABASE_TYPE_DB2, DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/NT", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/NT64", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2 UDP", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/LINUX", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/LINUX390", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/LINUXX8664", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/LINUXZ64", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/LINUXPPC64", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/400 SQL", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/6000", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2 UDB iSeries", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/AIX64", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/HPUX", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/HP64", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/SUN", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/SUN64", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/PTX", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2/2", DATABASE_TYPE_DB2); databaseTypeMappings.setProperty("DB2 UDB AS400", DATABASE_TYPE_DB2); return databaseTypeMappings; } @Bean @Qualifier("flowableModeler") public SqlSessionFactory modelerSqlSessionFactory(DataSource dataSource) { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); String databaseType = initDatabaseType(dataSource); if (databaseType == null) { throw new FlowableException("couldn't deduct database type"); } try { Properties properties = new Properties(); properties.put("prefix", modelerAppProperties.getDataSourcePrefix()); properties.put("blobType", "BLOB"); properties.put("boolValue", "TRUE"); properties.load(this.getClass().getClassLoader().getResourceAsStream("org/flowable/db/properties/" + databaseType + ".properties")); sqlSessionFactoryBean.setConfigurationProperties(properties); sqlSessionFactoryBean .setMapperLocations(ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:/META-INF/modeler-mybatis-mappings/*.xml")); sqlSessionFactoryBean.afterPropertiesSet(); return sqlSessionFactoryBean.getObject(); } catch (Exception e) { throw new FlowableException("Could not create sqlSessionFactory", e); } } @Bean(destroyMethod = "clearCache") // destroyMethod: see https://github.com/mybatis/old-google-code-issues/issues/778 @Qualifier("flowableModeler") public SqlSessionTemplate modelerSqlSessionTemplate(@Qualifier("flowableModeler") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean @Qualifier("flowableModeler") public Liquibase modelerLiquibase(DataSource dataSource) { LOGGER.info("Configuring Liquibase"); Liquibase liquibase = null; try { DatabaseConnection connection = new JdbcConnection(dataSource.getConnection()); Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection); database.setDatabaseChangeLogTableName(LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogTableName()); database.setDatabaseChangeLogLockTableName(LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogLockTableName()); liquibase = new Liquibase("META-INF/liquibase/flowable-modeler-app-db-changelog.xml", new ClassLoaderResourceAccessor(), database); liquibase.update("flowable"); return liquibase; } catch (Exception e) { throw new InternalServerErrorException("Error creating liquibase database", e); } finally { closeDatabase(liquibase); } } protected String initDatabaseType(DataSource dataSource) { String databaseType = null; Connection connection = null; try { connection = dataSource.getConnection(); DatabaseMetaData databaseMetaData = connection.getMetaData(); String databaseProductName = databaseMetaData.getDatabaseProductName(); LOGGER.info("database product name: '{}'", databaseProductName); databaseType = databaseTypeMappings.getProperty(databaseProductName); if (databaseType == null) { throw new FlowableException("couldn't deduct database type from database product name '" + databaseProductName + "'"); } LOGGER.info("using database type: {}", databaseType); } catch (SQLException e) { LOGGER.error("Exception while initializing Database connection", e); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException e) { LOGGER.error("Exception while closing the Database connection", e); } } return databaseType; } private void closeDatabase(Liquibase liquibase) { if (liquibase != null) { Database database = liquibase.getDatabase(); if (database != null) { try { database.close(); } catch (DatabaseException e) { LOGGER.warn("Error closing database", e); } } } } }
paulstapleton/flowable-engine
modules/flowable-ui/flowable-ui-modeler-conf/src/main/java/org/flowable/ui/modeler/conf/ModelerDatabaseConfiguration.java
Java
apache-2.0
9,418
package org.redisson.spring.support; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.Executor; import org.junit.Test; import org.redisson.ClusterRunner; import org.redisson.RedisRunner; import org.redisson.api.RedissonClient; import org.redisson.client.RedisClient; import org.redisson.client.RedisConnection; import org.redisson.client.codec.Codec; import org.redisson.client.protocol.RedisCommands; import org.redisson.config.Config; import org.redisson.config.SingleServerConfig; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import io.netty.channel.EventLoopGroup; /** * * @author Rui Gu (https://github.com/jackygurui) */ public class SpringNamespaceWikiTest { @Test public void testSingle() throws Exception { RedisRunner.RedisProcess run = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .nosave() .randomDir() .run(); try { ((ConfigurableApplicationContext) new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_single.xml")) .close(); } finally { run.stop(); } } @Test public void testRedisClient() throws Exception { RedisRunner.RedisProcess run = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .nosave() .randomDir() .run(); try { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_redis_client.xml"); RedisClient redisClient = context.getBean(RedisClient.class); RedisConnection connection = redisClient.connect(); Map<String, String> info = connection.sync(RedisCommands.INFO_ALL); assertThat(info, notNullValue()); assertThat(info, not(info.isEmpty())); ((ConfigurableApplicationContext) context).close(); } finally { run.stop(); } } @Test public void testSingleWithPlaceholder() throws Exception { RedisRunner.RedisProcess run = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .nosave() .randomDir() .run(); System.setProperty("redisson.redisAddress", run.getRedisServerAddressAndPort()); System.setProperty("redisson.threads", "1"); System.setProperty("redisson.nettyThreads", "2"); System.setProperty("redisson.codecRef", "myCodec"); System.setProperty("redisson.useLinuxNativeEpoll", "false"); System.setProperty("redisson.redissonReferenceEnabled", "false"); System.setProperty("redisson.codecProviderRef", "myCodecProvider"); System.setProperty("redisson.resolverProviderRef", "myResolverProvider"); System.setProperty("redisson.executorRef", "myExecutor"); System.setProperty("redisson.eventLoopGroupRef", "myEventLoopGroup"); System.setProperty("redisson.idleConnectionTimeout", "10000"); System.setProperty("redisson.pingTimeout", "20000"); System.setProperty("redisson.connectTimeout", "30000"); System.setProperty("redisson.timeout", "40000"); System.setProperty("redisson.retryAttempts", "5"); System.setProperty("redisson.retryInterval", "60000"); System.setProperty("redisson.reconnectionTimeout", "70000"); System.setProperty("redisson.failedAttempts", "8"); System.setProperty("redisson.password", "do_not_use_if_it_is_not_set"); System.setProperty("redisson.subscriptionsPerConnection", "10"); System.setProperty("redisson.clientName", "client_name"); System.setProperty("redisson.sslEnableEndpointIdentification", "true"); System.setProperty("redisson.sslProvider", "JDK"); System.setProperty("redisson.sslTruststore", "/tmp/truststore.p12"); System.setProperty("redisson.sslTruststorePassword", "not_set"); System.setProperty("redisson.sslKeystore", "/tmp/keystore.p12"); System.setProperty("redisson.sslKeystorePassword", "not_set"); System.setProperty("redisson.subscriptionConnectionMinimumIdleSize", "11"); System.setProperty("redisson.subscriptionConnectionPoolSize", "12"); System.setProperty("redisson.connectionMinimumIdleSize", "13"); System.setProperty("redisson.connectionPoolSize", "14"); System.setProperty("redisson.database", "15"); System.setProperty("redisson.dnsMonitoring", "false"); System.setProperty("redisson.dnsMonitoringInterval", "80000"); try { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_single_with_placeholder.xml"); RedissonClient redisson = context.getBean("myId", RedissonClient.class); assertNotNull(redisson); Config config = redisson.getConfig(); assertEquals(1, config.getThreads()); assertEquals(2, config.getNettyThreads()); assertSame(context.getBean("myCodec", Codec.class), config.getCodec()); assertEquals(false, config.isReferenceEnabled()); assertSame(context.getBean("myExecutor", Executor.class), config.getExecutor()); assertSame(context.getBean("myEventLoopGroup", EventLoopGroup.class), config.getEventLoopGroup()); Method method = Config.class.getDeclaredMethod("getSingleServerConfig", (Class<?>[]) null); method.setAccessible(true); SingleServerConfig single = (SingleServerConfig) method.invoke(config, (Object[]) null); assertEquals(10000, single.getIdleConnectionTimeout()); assertEquals(30000, single.getConnectTimeout()); assertEquals(40000, single.getTimeout()); assertEquals(5, single.getRetryAttempts()); assertEquals(60000, single.getRetryInterval()); assertEquals("do_not_use_if_it_is_not_set", single.getPassword()); assertEquals(10, single.getSubscriptionsPerConnection()); assertEquals("client_name", single.getClientName()); assertEquals(11, single.getSubscriptionConnectionMinimumIdleSize()); assertEquals(12, single.getSubscriptionConnectionPoolSize()); assertEquals(13, single.getConnectionMinimumIdleSize()); assertEquals(14, single.getConnectionPoolSize()); assertEquals(15, single.getDatabase()); assertEquals(80000, single.getDnsMonitoringInterval()); ((ConfigurableApplicationContext) context).close(); } finally { run.stop(); } } @Test public void testMasterSlave() throws Exception { RedisRunner.RedisProcess master = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .nosave() .randomDir() .run(); RedisRunner.RedisProcess slave1 = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .masterauth("do_not_use_if_it_is_not_set") .port(6380) .nosave() .randomDir() .slaveof("127.0.0.1", 6379) .run(); RedisRunner.RedisProcess slave2 = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .masterauth("do_not_use_if_it_is_not_set") .port(6381) .nosave() .randomDir() .slaveof("127.0.0.1", 6379) .run(); try { ((ConfigurableApplicationContext) new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_master_slave.xml")) .close(); } finally { master.stop(); slave1.stop(); slave2.stop(); } } @Test public void testSentinel() throws Exception { RedisRunner.RedisProcess master = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .nosave() .randomDir() .run(); RedisRunner.RedisProcess slave1 = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .masterauth("do_not_use_if_it_is_not_set") .port(6380) .nosave() .randomDir() .slaveof("127.0.0.1", 6379) .run(); RedisRunner.RedisProcess slave2 = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .masterauth("do_not_use_if_it_is_not_set") .port(6381) .nosave() .randomDir() .slaveof("127.0.0.1", 6379) .run(); RedisRunner.RedisProcess sentinel1 = new RedisRunner() // .requirepass("do_not_use_if_it_is_not_set") .nosave() .randomDir() .port(26379) .sentinel() .sentinelMonitor("myMaster", "127.0.0.1", 6379, 2) .sentinelAuthPass("myMaster", "do_not_use_if_it_is_not_set") .run(); RedisRunner.RedisProcess sentinel2 = new RedisRunner() // .requirepass("do_not_use_if_it_is_not_set") .nosave() .randomDir() .port(26380) .sentinel() .sentinelMonitor("myMaster", "127.0.0.1", 6379, 2) .sentinelAuthPass("myMaster", "do_not_use_if_it_is_not_set") .run(); RedisRunner.RedisProcess sentinel3 = new RedisRunner() // .requirepass("do_not_use_if_it_is_not_set") .nosave() .randomDir() .port(26381) .sentinel() .sentinelMonitor("myMaster", "127.0.0.1", 6379, 2) .sentinelAuthPass("myMaster", "do_not_use_if_it_is_not_set") .run(); try { ((ConfigurableApplicationContext) new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_sentinel.xml")) .close(); } finally { master.stop(); slave1.stop(); slave2.stop(); sentinel1.stop(); sentinel2.stop(); sentinel3.stop(); } } @Test public void testReplicated() throws Exception { RedisRunner.RedisProcess master = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .nosave() .randomDir() .run(); RedisRunner.RedisProcess slave1 = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .masterauth("do_not_use_if_it_is_not_set") .port(6380) .nosave() .randomDir() .slaveof("127.0.0.1", 6379) .run(); RedisRunner.RedisProcess slave2 = new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .masterauth("do_not_use_if_it_is_not_set") .port(6381) .nosave() .randomDir() .slaveof("127.0.0.1", 6379) .run(); try { ((ConfigurableApplicationContext) new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_replicated.xml")) .close(); } finally { master.stop(); slave1.stop(); slave2.stop(); } } @Test public void testCluster() throws Exception { ClusterRunner clusterRunner = new ClusterRunner() .addNode(new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .port(6379) .randomDir() .nosave()) .addNode(new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .port(6380) .randomDir() .nosave()) .addNode(new RedisRunner() .requirepass("do_not_use_if_it_is_not_set") .port(6381) .randomDir() .nosave()); ClusterRunner.ClusterProcesses cluster = clusterRunner.run(); try { ((ConfigurableApplicationContext) new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_cluster.xml")) .close(); } finally { cluster.shutdown(); } } }
mrniko/redisson
redisson/src/test/java/org/redisson/spring/support/SpringNamespaceWikiTest.java
Java
apache-2.0
13,484
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.conversion.impl; import com.intellij.conversion.CannotConvertException; import com.intellij.conversion.ConversionListener; import com.intellij.conversion.ConversionService; import com.intellij.conversion.ConverterProvider; import com.intellij.conversion.impl.ui.ConvertProjectDialog; import com.intellij.ide.IdeBundle; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.impl.stores.IProjectStore; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.PathUtil; import com.intellij.util.SystemProperties; import com.intellij.util.graph.CachingSemiGraph; import com.intellij.util.graph.DFSTBuilder; import com.intellij.util.graph.GraphGenerator; import com.intellij.util.xmlb.XmlSerializer; import com.intellij.util.xmlb.annotations.AbstractCollection; import com.intellij.util.xmlb.annotations.MapAnnotation; import com.intellij.util.xmlb.annotations.Tag; import org.jdom.Document; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.util.*; /** * @author nik */ public class ConversionServiceImpl extends ConversionService { private static final Logger LOG = Logger.getInstance("#com.intellij.conversion.impl.ConversionServiceImpl"); @Override public boolean convertSilently(@NotNull String projectPath) { return convertSilently(projectPath, new ConversionListener() { public void conversionNeeded() { } public void successfullyConverted(File backupDir) { } public void error(String message) { } public void cannotWriteToFiles(List<File> readonlyFiles) { } }); } @Override public boolean convertSilently(@NotNull String projectPath, @NotNull ConversionListener listener) { try { if (!isConversionNeeded(projectPath)) { return true; } listener.conversionNeeded(); ConversionContextImpl context = new ConversionContextImpl(projectPath); final List<ConversionRunner> runners = getConversionRunners(context); Set<File> affectedFiles = new HashSet<File>(); for (ConversionRunner runner : runners) { affectedFiles.addAll(runner.getAffectedFiles()); } final List<File> readOnlyFiles = ConversionRunner.getReadOnlyFiles(affectedFiles); if (!readOnlyFiles.isEmpty()) { listener.cannotWriteToFiles(readOnlyFiles); return false; } final File backupDir = ProjectConversionUtil.backupFiles(affectedFiles, context.getProjectBaseDir()); for (ConversionRunner runner : runners) { runner.preProcess(); runner.process(); runner.postProcess(); } context.saveFiles(affectedFiles); listener.successfullyConverted(backupDir); saveConversionResult(context); return true; } catch (CannotConvertException e) { listener.error(e.getMessage()); } catch (IOException e) { listener.error(e.getMessage()); } return false; } @Override public boolean convert(@NotNull String projectPath) { try { if (!isConversionNeeded(projectPath)) { return true; } final ConversionContextImpl context = new ConversionContextImpl(projectPath); final List<ConversionRunner> converters = getConversionRunners(context); ConvertProjectDialog dialog = new ConvertProjectDialog(context, converters); dialog.show(); if (dialog.isConverted()) { saveConversionResult(context); return true; } return false; } catch (CannotConvertException e) { LOG.info(e); Messages.showErrorDialog(IdeBundle.message("error.cannot.convert.project", e.getMessage()), IdeBundle.message("title.cannot.convert.project")); return false; } } private List<ConversionRunner> getConversionRunners(ConversionContextImpl context) throws CannotConvertException { final List<ConversionRunner> converters = getSortedConverters(context); final Iterator<ConversionRunner> iterator = converters.iterator(); Set<String> convertersToRunIds = new HashSet<String>(); while (iterator.hasNext()) { ConversionRunner runner = iterator.next(); if (!runner.isConversionNeeded() && !convertersToRunIds.contains(runner.getProvider().getId())) { iterator.remove(); } else { convertersToRunIds.add(runner.getProvider().getId()); } } return converters; } public boolean isConversionNeeded(String projectPath) throws CannotConvertException { final ConversionContextImpl context = new ConversionContextImpl(projectPath); final List<ConversionRunner> runners = getSortedConverters(context); if (runners.isEmpty()) { return false; } for (ConversionRunner runner : runners) { if (runner.isConversionNeeded()) { return true; } } saveConversionResult(context); return false; } private List<ConversionRunner> getSortedConverters(final ConversionContextImpl context) throws CannotConvertException { final CachedConversionResult conversionResult = loadCachedConversionResult(context.getProjectFile()); final Map<String, Long> oldMap = conversionResult.myProjectFilesTimestamps; Map<String, Long> newMap = getProjectFilesMap(context); boolean changed = false; LOG.debug("Checking project files"); for (Map.Entry<String, Long> entry : newMap.entrySet()) { final String path = entry.getKey(); final Long oldValue = oldMap.get(path); if (oldValue == null) { LOG.debug(" new file: " + path); changed = true; } else if (!entry.getValue().equals(oldValue)) { LOG.debug(" changed file: " + path); changed = true; } } final Set<String> performedConversionIds; if (changed) { performedConversionIds = Collections.emptySet(); LOG.debug("Project files were modified."); } else { performedConversionIds = conversionResult.myAppliedConverters; LOG.debug("Project files are up to date. Applied converters: " + performedConversionIds); } return createConversionRunners(context, performedConversionIds); } private static Map<String, Long> getProjectFilesMap(ConversionContextImpl context) { final Map<String, Long> map = new HashMap<String, Long>(); for (File file : context.getAllProjectFiles()) { if (file.exists()) { map.put(file.getAbsolutePath(), file.lastModified()); } } return map; } private List<ConversionRunner> createConversionRunners(ConversionContextImpl context, final Set<String> performedConversionIds) { List<ConversionRunner> runners = new ArrayList<ConversionRunner>(); final ConverterProvider[] providers = ConverterProvider.EP_NAME.getExtensions(); for (ConverterProvider provider : providers) { if (!performedConversionIds.contains(provider.getId())) { runners.add(new ConversionRunner(provider, context)); } } final CachingSemiGraph<ConverterProvider> graph = CachingSemiGraph.create(new ConverterProvidersGraph(providers)); final DFSTBuilder<ConverterProvider> builder = new DFSTBuilder<ConverterProvider>(GraphGenerator.create(graph)); if (!builder.isAcyclic()) { final Pair<ConverterProvider,ConverterProvider> pair = builder.getCircularDependency(); LOG.error("cyclic dependencies between converters: " + pair.getFirst().getId() + " and " + pair.getSecond().getId()); } final Comparator<ConverterProvider> comparator = builder.comparator(); Collections.sort(runners, new Comparator<ConversionRunner>() { public int compare(ConversionRunner o1, ConversionRunner o2) { return comparator.compare(o1.getProvider(), o2.getProvider()); } }); return runners; } public void saveConversionResult(String projectPath) { try { saveConversionResult(new ConversionContextImpl(projectPath)); } catch (CannotConvertException e) { LOG.info(e); } } private void saveConversionResult(ConversionContextImpl context) { final CachedConversionResult conversionResult = new CachedConversionResult(); for (ConverterProvider provider : ConverterProvider.EP_NAME.getExtensions()) { conversionResult.myAppliedConverters.add(provider.getId()); } conversionResult.myProjectFilesTimestamps = getProjectFilesMap(context); final File infoFile = getConversionInfoFile(context.getProjectFile()); infoFile.getParentFile().mkdirs(); try { JDOMUtil.writeDocument(new Document(XmlSerializer.serialize(conversionResult)), infoFile, SystemProperties.getLineSeparator()); } catch (IOException e) { LOG.info(e); } } @NotNull private CachedConversionResult loadCachedConversionResult(File projectFile) { try { final File infoFile = getConversionInfoFile(projectFile); if (!infoFile.exists()) { return new CachedConversionResult(); } final Document document = JDOMUtil.loadDocument(infoFile); final CachedConversionResult result = XmlSerializer.deserialize(document, CachedConversionResult.class); return result != null ? result : new CachedConversionResult(); } catch (Exception e) { LOG.info(e); return new CachedConversionResult(); } } private File getConversionInfoFile(@NotNull File projectFile) { String dirName = PathUtil.suggestFileName(projectFile.getName() + Integer.toHexString(projectFile.getAbsolutePath().hashCode())); return new File(PathManager.getSystemPath() + File.separator + "conversion" + File.separator + dirName + ".xml"); } public boolean convertModule(@NotNull final Project project, @NotNull final File moduleFile) { final IProjectStore stateStore = ((ProjectImpl)project).getStateStore(); String projectPath = FileUtil.toSystemDependentName(stateStore.getLocation()); if (!isConversionNeeded(projectPath, moduleFile)) { return true; } final int res = Messages.showYesNoDialog(project, IdeBundle.message("message.module.file.has.an.older.format.do.you.want.to.convert.it"), IdeBundle.message("dialog.title.convert.module"), Messages.getQuestionIcon()); if (res != 0) { return false; } if (!moduleFile.canWrite()) { Messages.showErrorDialog(project, IdeBundle.message("error.message.cannot.modify.file.0", moduleFile.getAbsolutePath()), IdeBundle.message("dialog.title.convert.module")); return false; } try { ConversionContextImpl context = new ConversionContextImpl(projectPath); final List<ConversionRunner> runners = createConversionRunners(context, Collections.<String>emptySet()); final File backupFile = ProjectConversionUtil.backupFile(moduleFile); for (ConversionRunner runner : runners) { if (runner.isModuleConversionNeeded(moduleFile)) { runner.convertModule(moduleFile); } } context.saveFiles(Collections.singletonList(moduleFile)); Messages.showInfoMessage(project, IdeBundle.message("message.your.module.was.succesfully.converted.br.old.version.was.saved.to.0", backupFile.getAbsolutePath()), IdeBundle.message("dialog.title.convert.module")); return true; } catch (CannotConvertException e) { Messages.showErrorDialog(IdeBundle.message("error.cannot.load.project", e.getMessage()), "Cannot Convert Module"); return false; } catch (IOException e) { return false; } } private boolean isConversionNeeded(String projectPath, File moduleFile) { try { ConversionContextImpl context = new ConversionContextImpl(projectPath); final List<ConversionRunner> runners = createConversionRunners(context, Collections.<String>emptySet()); for (ConversionRunner runner : runners) { if (runner.isModuleConversionNeeded(moduleFile)) { return true; } } return false; } catch (CannotConvertException e) { LOG.info(e); return false; } } @Tag("conversion") public static class CachedConversionResult { @Tag("applied-converters") @AbstractCollection(surroundWithTag = false, elementTag = "converter", elementValueAttribute = "id") public Set<String> myAppliedConverters = new HashSet<String>(); @Tag("project-files") @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false, entryTagName = "file", keyAttributeName = "path", valueAttributeName = "timestamp") public Map<String, Long> myProjectFilesTimestamps = new HashMap<String, Long>(); } private class ConverterProvidersGraph implements GraphGenerator.SemiGraph<ConverterProvider> { private final ConverterProvider[] myProviders; public ConverterProvidersGraph(ConverterProvider[] providers) { myProviders = providers; } public Collection<ConverterProvider> getNodes() { return Arrays.asList(myProviders); } public Iterator<ConverterProvider> getIn(ConverterProvider n) { List<ConverterProvider> preceding = new ArrayList<ConverterProvider>(); for (String id : n.getPrecedingConverterIds()) { for (ConverterProvider provider : myProviders) { if (provider.getId().equals(id)) { preceding.add(provider); } } } return preceding.iterator(); } } }
jexp/idea2
platform/lang-impl/src/com/intellij/conversion/impl/ConversionServiceImpl.java
Java
apache-2.0
14,413
/** * Copyright 2012 Neil Borle, Mitchell Home, Bronte Lee, Aaron * Padlesky, Eddie Santos * * 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 ca.ualberta.cs.c301f12t01.gui; import java.util.ArrayList; import java.util.UUID; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import ca.ualberta.cs.c301f12t01.R; import ca.ualberta.cs.c301f12t01.common.Report; import ca.ualberta.cs.c301f12t01.common.Request; import ca.ualberta.cs.c301f12t01.common.Sharing; import ca.ualberta.cs.c301f12t01.common.Task; import ca.ualberta.cs.c301f12t01.gui.helper.ResponseObtainer; import ca.ualberta.cs.c301f12t01.gui.helper.ResponseObtainerObtainer; /** * FulfillTaskActivity -- Displays the user interface for Fulfilling a Task. * * Displays the layout for activity_fulfill_task. * * @author Eddie Antonio Santos <easantos@ualberta.ca> * @author Bronte Lee <bronte@ualberta.ca> * */ public class FulfillTaskActivity extends Activity { /* TODO: Get some more global place to store the following string. */ public static final String ARG_TASK_ID = "task_id"; private Task task; ArrayList<ResponseObtainer> obtainers = new ArrayList<ResponseObtainer>(); /** * onCreate - get taskId from the TaskDetailActivity and display fulfill * fields */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fulfill_task); getActionBar().setDisplayHomeAsUpEnabled(true); /* The list of tasks Activity passed us a taskID, so we should get it */ Bundle taskBundle = getIntent().getExtras(); if (taskBundle != null) { UUID taskId = (UUID) taskBundle.getSerializable(ARG_TASK_ID); task = TaskSourceApplication.getTask(taskId); } /* Display Fulfilling Task information */ displayFulfillTaskInformation(); android.util.Log.d("Act-LIFECYCLE", "FulfillTaskActivity - onCreate"); } /** * displayFulfillTaskInformation - Display the proper fulfill fields based * on the requests of the task. * */ protected void displayFulfillTaskInformation() { /* Sets the simple text views. */ ((TextView) findViewById(R.id.task_summary)).setText(task.getSummary()); String descriptionText = task.getDescription(); TextView descripionView = (TextView) findViewById(R.id.task_description); if (descriptionText.equals("")) { /* No description? Don't show the text widget at all! */ descripionView.setVisibility(View.GONE); } else { descripionView.setText(descriptionText); } /* Get the container for the responses. */ ViewGroup responseContainer = (ViewGroup) findViewById(R.id.task_responses); LayoutInflater inflater = getLayoutInflater(); /* * Creates a response field for each respective request, and remember * them. */ for (Request request : task) { obtainers.add(ResponseObtainerObtainer.getResponseObtainer( request.getType(), inflater, responseContainer)); } } /** * onFormCompletion - Called when the user decides they are done fulfilling * the task. * * @returns false is the form was completed incorrectly, else true. */ protected Boolean onFormCompletion() { if (hasNoResponse()) { return false; } Report report = new Report(task); attachReportSharingMode(report); attachResponsesToReport(report); TaskSourceApplication.addReport(report); android.util.Log.d("Act-LIFECYCLE", "FulfillTaskActivity - onFormCompletion"); android.util.Log.d("Act-LIFECYCLE", "Response TYPE - " + report.responseTypes()); android.util.Log.d("Act-LIFECYCLE", "Response COUNT - " + report.responseCount()); android.util.Log.d("Act-LIFECYCLE", "New number of reports for the task - " + TaskSourceApplication.getReportsForTask(task.getId()) .size()); return true; } /** * Returns true if the report has no responses (and thus, invalid). * @return */ private boolean hasNoResponse() { for (ResponseObtainer obtainer : obtainers) { if (obtainer.hasBeenFulfilled()) { return false; } } return true; } /** * Attaches the sharing mode on the current activity to the given Report. * * @param report */ private void attachReportSharingMode(Report report) { android.util.Log.d("Act-LIFECYCLE", "FulfillTaskActivity - attachReportSharingMode"); RadioGroup sharingButtons = (RadioGroup) findViewById(R.id.radio_group_send_options); Sharing selectedSharing = Sharing.TASK_CREATOR; switch (sharingButtons.getCheckedRadioButtonId()) { case R.id.radio_send_to_owner: selectedSharing = Sharing.TASK_CREATOR; break; case R.id.radio_send_to_server: selectedSharing = Sharing.GLOBAL; break; case R.id.radio_do_not_send: selectedSharing = Sharing.LOCAL; break; } report.setSharing(selectedSharing); } /** * Attaches every Response on the current activity to the given Report and * returns the amount attached. * * @param report */ private void attachResponsesToReport(Report report) { android.util.Log.d("Act-LIFECYCLE", "FulfillTaskActivity - attachResponsesToReport"); for (ResponseObtainer obtainer : obtainers) { report.addResponse(obtainer.getResponse()); } } /* Display menu */ public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_fulfill_task, menu); return true; } /* When a menu option is selected */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.menu_done: if (onFormCompletion()) { Toast.makeText(getBaseContext(), R.string.fulfill_success, Toast.LENGTH_SHORT).show(); finish(); } else { Toast.makeText(getBaseContext(), R.string.error_zero_responses, Toast.LENGTH_SHORT).show(); } return true; } return super.onOptionsItemSelected(item); } }
CMPUT301F12T01/classproject
src/ca/ualberta/cs/c301f12t01/gui/FulfillTaskActivity.java
Java
apache-2.0
6,730
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iotsitewise.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Contains asset property value notification information. When the notification state is enabled, IoT SiteWise * publishes property value updates to a unique MQTT topic. For more information, see <a * href="https://docs.aws.amazon.com/iot-sitewise/latest/userguide/interact-with-other-services.html">Interacting with * other services</a> in the <i>IoT SiteWise User Guide</i>. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotsitewise-2019-12-02/PropertyNotification" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PropertyNotification implements Serializable, Cloneable, StructuredPojo { /** * <p> * The MQTT topic to which IoT SiteWise publishes property value update notifications. * </p> */ private String topic; /** * <p> * The current notification state. * </p> */ private String state; /** * <p> * The MQTT topic to which IoT SiteWise publishes property value update notifications. * </p> * * @param topic * The MQTT topic to which IoT SiteWise publishes property value update notifications. */ public void setTopic(String topic) { this.topic = topic; } /** * <p> * The MQTT topic to which IoT SiteWise publishes property value update notifications. * </p> * * @return The MQTT topic to which IoT SiteWise publishes property value update notifications. */ public String getTopic() { return this.topic; } /** * <p> * The MQTT topic to which IoT SiteWise publishes property value update notifications. * </p> * * @param topic * The MQTT topic to which IoT SiteWise publishes property value update notifications. * @return Returns a reference to this object so that method calls can be chained together. */ public PropertyNotification withTopic(String topic) { setTopic(topic); return this; } /** * <p> * The current notification state. * </p> * * @param state * The current notification state. * @see PropertyNotificationState */ public void setState(String state) { this.state = state; } /** * <p> * The current notification state. * </p> * * @return The current notification state. * @see PropertyNotificationState */ public String getState() { return this.state; } /** * <p> * The current notification state. * </p> * * @param state * The current notification state. * @return Returns a reference to this object so that method calls can be chained together. * @see PropertyNotificationState */ public PropertyNotification withState(String state) { setState(state); return this; } /** * <p> * The current notification state. * </p> * * @param state * The current notification state. * @return Returns a reference to this object so that method calls can be chained together. * @see PropertyNotificationState */ public PropertyNotification withState(PropertyNotificationState state) { this.state = state.toString(); 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 (getTopic() != null) sb.append("Topic: ").append(getTopic()).append(","); if (getState() != null) sb.append("State: ").append(getState()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PropertyNotification == false) return false; PropertyNotification other = (PropertyNotification) obj; if (other.getTopic() == null ^ this.getTopic() == null) return false; if (other.getTopic() != null && other.getTopic().equals(this.getTopic()) == false) return false; if (other.getState() == null ^ this.getState() == null) return false; if (other.getState() != null && other.getState().equals(this.getState()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getTopic() == null) ? 0 : getTopic().hashCode()); hashCode = prime * hashCode + ((getState() == null) ? 0 : getState().hashCode()); return hashCode; } @Override public PropertyNotification clone() { try { return (PropertyNotification) 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.iotsitewise.model.transform.PropertyNotificationMarshaller.getInstance().marshall(this, protocolMarshaller); } }
aws/aws-sdk-java
aws-java-sdk-iotsitewise/src/main/java/com/amazonaws/services/iotsitewise/model/PropertyNotification.java
Java
apache-2.0
6,515
package com.f2prateek.rx.preferences2; import static com.f2prateek.rx.preferences2.Preconditions.checkNotNull; import android.content.SharedPreferences; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import io.reactivex.Observable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate; final class RealPreference<T> implements Preference<T> { /** Stores and retrieves instances of {@code T} in {@link SharedPreferences}. */ interface Adapter<T> { /** Retrieve the value for {@code key} from {@code preferences}. */ T get(@NonNull String key, @NonNull SharedPreferences preferences); /** * Store non-null {@code value} for {@code key} in {@code editor}. * <p> * Note: Implementations <b>must not</b> call {@code commit()} or {@code apply()} on * {@code editor}. */ void set(@NonNull String key, @NonNull T value, @NonNull SharedPreferences.Editor editor); } private final SharedPreferences preferences; private final String key; private final T defaultValue; private final Adapter<T> adapter; private final Observable<T> values; RealPreference(SharedPreferences preferences, final String key, T defaultValue, Adapter<T> adapter, Observable<String> keyChanges) { this.preferences = preferences; this.key = key; this.defaultValue = defaultValue; this.adapter = adapter; this.values = keyChanges // .filter(new Predicate<String>() { @Override public boolean test(String changedKey) throws Exception { return key.equals(changedKey); } }) // .startWith("<init>") // Dummy value to trigger initial load. .map(new Function<String, T>() { @Override public T apply(String s) throws Exception { return get(); } }); } @Override @NonNull public String key() { return key; } @Override @NonNull public T defaultValue() { return defaultValue; } @Override @NonNull public synchronized T get() { if (!preferences.contains(key)) { return defaultValue; } return adapter.get(key, preferences); } @Override public void set(@NonNull T value) { checkNotNull(value, "value == null"); SharedPreferences.Editor editor = preferences.edit(); adapter.set(key, value, editor); editor.apply(); } @Override public boolean isSet() { return preferences.contains(key); } @Override public synchronized void delete() { preferences.edit().remove(key).apply(); } @Override @CheckResult @NonNull public Observable<T> asObservable() { return values; } @Override @CheckResult @NonNull public Consumer<? super T> asConsumer() { return new Consumer<T>() { @Override public void accept(T value) throws Exception { set(value); } }; } }
MaTriXy/rx-preferences
rx-preferences/src/main/java/com/f2prateek/rx/preferences2/RealPreference.java
Java
apache-2.0
2,919
/* * Copyright (C) 2015 Jack Jiang(cngeeker.com) The BeautyEye Project. * All rights reserved. * Project URL:https://github.com/JackJiang2011/beautyeye * Version 3.6 * * Jack Jiang PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * BEMenuItemUI.java at 2015-2-1 20:25:38, original version by Jack Jiang. * You can contact author with jb2011@163.com. */ package org.jb2011.lnf.beautyeye.menu; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.ButtonModel; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicMenuItemUI; /** * JMenuItem的UI实现类. * * 特别注意:BasicMenuItemUI中针对Vista及后来的Windows版本预设了很多其它LNF不需要的属性, * 预设的属性详见BasicMenuItemUI及WindowsLookAndFeel中的initVistaComponentDefaults(..)方法. * 这些属性只能会在vista及更新的windows平台上过运行时才会起效,所以除此之外的windows测不出来, * 容易出现ui视觉差异. * * @author Jack Jiang(jb2011@163.com) */ public class BEMenuItemUI extends BasicMenuItemUI { /** * 是否强制单项透明(当强制不透明时,在普通状态下该item将不会被绘制背景). */ private static boolean enforceTransparent = true;// TODO 可以提炼成UI属性 public static ComponentUI createUI(JComponent c) { return new BEMenuItemUI(); } /** * {@inheritDoc} * * @see com.sun.java.swing.plaf.windows.WindowsMenuItemUI#paintBackground(java.awt.Graphics, javax.swing.JMenuItem, java.awt.Color) * @see javax.swing.plaf.basic.BasicMenuItemUI#paintBackground(java.awt.Graphics, javax.swing.JMenuItem, java.awt.Color) */ @Override protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) { ButtonModel model = menuItem.getModel(); Color oldColor = g.getColor(); int menuWidth = menuItem.getWidth(); int menuHeight = menuItem.getHeight(); Graphics2D g2 = (Graphics2D) g; if (model.isArmed() || (menuItem instanceof JMenu && model.isSelected())) //菜单项的样式绘制(用NinePatch图来填充) BEMenuUI.ICON_9.get("selected") .draw(g2, 0, 0, menuWidth, menuHeight); else if (!enforceTransparent) { g.setColor(menuItem.getBackground()); g.fillRect(0, 0, menuWidth, menuHeight); } g.setColor(oldColor); } }
huanghongxun/beautyeye
beautyeye/src/org/jb2011/lnf/beautyeye/menu/BEMenuItemUI.java
Java
apache-2.0
2,609
package com.spacetimecat.build.java; import com.spacetimecat.build.files.FilesUnder; import com.spacetimecat.build.files.Paths; public final class BuildExampleMain { public static void main (String[] args) throws Exception { final String root = "/home/erik/web/build-test"; System.out.println(new FilesUnder("").endingWith(".java").get()); final Paths projects = Paths.under(root).whichLooksLikeMavenProject(); System.out.println(projects); System.out.println(Paths.under("").whoseNameEndsWith(".java")); } }
edom/web
java-build/src/main/java/com/spacetimecat/build/java/BuildExampleMain.java
Java
apache-2.0
563
/* * #! * Ontopia Engine * #- * Copyright (C) 2001 - 2013 The Ontopia 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 net.ontopia.persistence.proxy; import java.sql.PreparedStatement; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * INTERNAL: Class that performs the task of accessing and * manipulating M:M reference fields in the database. */ public class SQLBatchManyToManyReference extends SQLManyToManyReference implements FlushableIF { // Define a logging category. private static final Logger log = LoggerFactory.getLogger(SQLBatchManyToManyReference.class.getName()); protected boolean debug = log.isDebugEnabled(); protected PreparedStatement stm_add; protected PreparedStatement stm_remove; protected PreparedStatement stm_clear; public SQLBatchManyToManyReference(RDBMSAccess access, FieldInfoIF field) { super(access, field); close_stm = false; } //! protected void add(IdentityIF identity, Object[] values) throws Exception { //! // Get batch statement //! PreparedStatement stm = add_getStatement(); //! //! // Loop over the values //! for (int i=0; i < values.length; i++) { //! //! // Bind parameters //! add_bindParameters(stm, identity, values[i]); //! //! // Add batch update //! if (debug) log.debug("Adding batch: " + sql_add); //! stm.addBatch(); //! } //! } @Override protected PreparedStatement add_getStatement() throws SQLException { if (stm_add == null) { // Create statement and set statement field stm_add = super.add_getStatement(); // Register as flushable access.needsFlushing(this); } return stm_add; } //! protected void remove(IdentityIF identity, Object[] values) throws Exception { //! // Get batch statement //! PreparedStatement stm = remove_getStatement(); //! //! // Loop over the values //! for (int i=0; i < values.length; i++) { //! //! // Bind parameters //! remove_bindParameters(stm, identity, values[i]); //! //! // Add batch update //! if (debug) log.debug("Adding batch: " + sql_remove); //! stm.addBatch(); //! } //! } @Override protected PreparedStatement remove_getStatement() throws SQLException { if (stm_remove == null) { // Create statement and set statement field stm_remove = super.remove_getStatement(); // Register as flushable access.needsFlushing(this); } return stm_remove; } //! public void clear(IdentityIF identity) throws Exception { //! // Get batch statement //! PreparedStatement stm = clear_getStatement(); //! //! // Bind parameters //! clear_bindParameters(stm, identity); //! //! // Add batch update //! if (debug) log.debug("Adding batch: " + sql_clear); //! stm.addBatch(); //! } @Override protected PreparedStatement clear_getStatement() throws SQLException { if (stm_clear == null) { // Create statement and set statement field stm_clear = super.clear_getStatement(); // Register as flushable access.needsFlushing(this); } return stm_clear; } @Override protected void executeUpdate(PreparedStatement stm, String sql) throws Exception { // Add batch update if (debug) log.debug("Adding batch: " + sql); stm.addBatch(); } @Override public void flush() throws Exception { // Handle add batch if (stm_add != null) { try { // Execute batch statements stm_add.executeBatch(); } finally { stm_add.close(); stm_add = null; } } // Handle remove batch if (stm_remove != null) { try { // Execute batch statements stm_remove.executeBatch(); } finally { stm_remove.close(); stm_remove = null; } } // Handle clear batch if (stm_clear != null) { try { // Execute batch statements stm_clear.executeBatch(); } finally { stm_clear.close(); stm_clear = null; } } } }
ontopia/ontopia
ontopia-engine/src/main/java/net/ontopia/persistence/proxy/SQLBatchManyToManyReference.java
Java
apache-2.0
4,713
package com.ansteel.dhtmlx.widget.form; import java.util.Map; import com.ansteel.core.constant.DHtmlxConstants; /** * 创 建 人:gugu * 创建日期:2015-06-18 * 修 改 人: * 修改日 期: * 描 述:dhtmlx表单类。 */ public class Label extends Form{ public Label() { super(DHtmlxConstants.LABEL); } private String className; private Boolean disabled ; private Boolean hidden ; private String label; private Integer labelHeight ; private Integer labelLeft ; private Integer labelTop ; private Integer labelWidth ; private String name; private Integer offsetLeft ; private Integer offsetTop ; private String position; private Map<String, Object> userdata; public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public Boolean getDisabled() { return disabled; } public void setDisabled(Boolean disabled) { this.disabled = disabled; } public Boolean getHidden() { return hidden; } public void setHidden(Boolean hidden) { this.hidden = hidden; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Integer getLabelHeight() { return labelHeight; } public void setLabelHeight(Integer labelHeight) { this.labelHeight = labelHeight; } public Integer getLabelLeft() { return labelLeft; } public void setLabelLeft(Integer labelLeft) { this.labelLeft = labelLeft; } public Integer getLabelTop() { return labelTop; } public void setLabelTop(Integer labelTop) { this.labelTop = labelTop; } public Integer getLabelWidth() { return labelWidth; } public void setLabelWidth(Integer labelWidth) { this.labelWidth = labelWidth; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getOffsetLeft() { return offsetLeft; } public void setOffsetLeft(Integer offsetLeft) { this.offsetLeft = offsetLeft; } public Integer getOffsetTop() { return offsetTop; } public void setOffsetTop(Integer offsetTop) { this.offsetTop = offsetTop; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Map<String, Object> getUserdata() { return userdata; } public void setUserdata(Map<String, Object> userdata) { this.userdata = userdata; } }
LittleLazyCat/TXEYXXK
2017workspace/go-public/go-core/src/main/java/com/ansteel/dhtmlx/widget/form/Label.java
Java
apache-2.0
2,421
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.plugin.groovy; import org.elasticsearch.plugins.AbstractPlugin; import org.elasticsearch.script.ScriptModule; import org.elasticsearch.script.groovy.GroovyScriptEngineService; /** * */ public class GroovyPlugin extends AbstractPlugin { @Override public String name() { return "lang-groovy"; } @Override public String description() { return "Groovy plugin allowing to add groovy scripting support"; } public void onModule(ScriptModule module) { module.addScriptEngine(GroovyScriptEngineService.class); } }
umangmehta12/elasticsearch-server
elasticsearch-lang-groovy/src/main/java/org/elasticsearch/plugin/groovy/GroovyPlugin.java
Java
apache-2.0
1,401
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ccreanga.webserver.ioutil; import java.io.*; import static com.ccreanga.webserver.common.Constants.*; import static java.lang.String.format; /** * <p> Low level API for processing file uploads. * <p> * <p> This class can be used to process data streams conforming to MIME * 'multipart' format as defined in * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>. Arbitrarily * large amounts of data in the stream can be processed under constant * memory usage. * <p> * <p> The format of the stream is defined in the following way:<br> * <p> * <code> * multipart-body := preamble 1*encapsulation close-delimiter epilogue<br> * encapsulation := delimiter body CRLF<br> * delimiter := "--" boundary CRLF<br> * close-delimiter := "--" boundary "--"<br> * preamble := &lt;ignore&gt;<br> * epilogue := &lt;ignore&gt;<br> * body := header-part CRLF body-part<br> * header-part := 1*header CRLF<br> * header := header-name ":" header-value<br> * header-name := &lt;printable ascii characters except ":"&gt;<br> * header-value := &lt;any ascii characters except CR &amp; LF&gt;<br> * body-data := &lt;arbitrary data&gt;<br> * </code> * <p> * <p>Note that body-data can contain another mulipart entity. There * is limited support for single pass processing of such nested * streams. The nested stream is <strong>required</strong> to have a * boundary token of the same length as the parent stream (see {@link * #setBoundary(byte[])}). * <p> * <p>Here is an example of usage of this class.<br> * <p> * <pre> * try { * MultipartStream multipartStream = new MultipartStream(input, boundary); * boolean nextPart = multipartStream.skipPreamble(); * OutputStream output; * while(nextPart) { * String header = multipartStream.readHeaders(); * // process headers * // create some output stream * multipartStream.readBodyData(output); * nextPart = multipartStream.readBoundary(); * } * } catch(MultipartStream.MalformedStreamException e) { * // the stream failed to follow required syntax * } catch(IOException e) { * // a read or write error occurred * } * </pre> * * @version $Id$ */ public class MultipartStream { private static final int HEADER_PART_SIZE_MAX = 10240; private static final int DEFAULT_BUFSIZE = 4096; private static final byte[] HEADER_SEPARATOR = {CR, LF, CR, LF}; private static final byte[] FIELD_SEPARATOR = CRLF; private static final byte[] STREAM_TERMINATOR = {DASH, DASH}; private static final byte[] BOUNDARY_PREFIX = {CR, LF, DASH, DASH}; // ----------------------------------------------------------- Data members private final InputStream input; /** * The length of the boundary token plus the leading <code>CRLF--</code>. */ private int boundaryLength; private final int keepRegion; private final byte[] boundary; private final int bufSize; private final byte[] buffer; private int head; private int tail; private String headerEncoding; public MultipartStream(InputStream input, byte[] boundary, int bufSize) { if (boundary == null) { throw new IllegalArgumentException("boundary may not be null"); } // We prepend CR/LF to the boundary to chop trailing CR/LF from // body-data tokens. this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length; if (bufSize < this.boundaryLength + 1) { throw new IllegalArgumentException( "The buffer size specified for the MultipartStream is too small"); } this.input = input; this.bufSize = Math.max(bufSize, boundaryLength * 2); this.buffer = new byte[this.bufSize]; this.boundary = new byte[this.boundaryLength]; this.keepRegion = this.boundary.length; System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0, BOUNDARY_PREFIX.length); System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); head = 0; tail = 0; } public MultipartStream(InputStream input, byte[] boundary) { this(input, boundary, DEFAULT_BUFSIZE); } public void setHeaderEncoding(String encoding) { headerEncoding = encoding; } /** * Reads a byte from the <code>buffer</code>, and refills it as * necessary. * * @return The next byte from the input stream. * @throws IOException if there is no more data available. */ public byte readByte() throws IOException { // Buffer depleted ? if (head == tail) { head = 0; // Refill. tail = input.read(buffer, head, bufSize); if (tail == -1) { // No more data available. throw new IOException("No more data is available"); } } return buffer[head++]; } /** * Skips a <code>boundary</code> token, and checks whether more * <code>encapsulations</code> are contained in the stream. * * @return <code>true</code> if there are more encapsulations in * this stream; <code>false</code> otherwise. * @throws MalformedStreamException if the stream ends unexpectedly or * fails to follow required syntax. */ public boolean readBoundary() throws MalformedStreamException { byte[] marker = new byte[2]; boolean nextChunk = false; head += boundaryLength; try { marker[0] = readByte(); if (marker[0] == LF) { // Work around IE5 Mac bug with input type=image. // Because the boundary delimiter, not including the trailing // CRLF, must not appear within any file (RFC 2046, section // 5.1.1), we know the missing CR is due to a buggy browser // rather than a file containing something similar to a // boundary. return true; } marker[1] = readByte(); if (arrayequals(marker, STREAM_TERMINATOR, 2)) { nextChunk = false; } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) { nextChunk = true; } else { throw new MalformedStreamException( "Unexpected characters follow a boundary"); } } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } return nextChunk; } /** * <p>Changes the boundary token used for partitioning the stream. * <p> * <p>This method allows single pass processing of nested multipart * streams. * <p> * <p>The boundary token of the nested stream is <code>required</code> * to be of the same length as the boundary token in parent stream. * <p> * <p>Restoring the parent stream boundary token after processing of a * nested stream is left to the application. * * @param boundary The boundary to be used for parsing of the nested * stream. * @throws IllegalBoundaryException if the <code>boundary</code> * has a different length than the one * being currently parsed. */ public void setBoundary(byte[] boundary) throws IllegalBoundaryException { if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) { throw new IllegalBoundaryException( "The length of a boundary token can not be changed"); } System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); } /** * <p>Reads the <code>header-part</code> of the current * <code>encapsulation</code>. * <p> * <p>Headers are returned verbatim to the input stream, including the * trailing <code>CRLF</code> marker. Parsing is left to the * application. * <p> * <p><strong>TODO</strong> allow limiting maximum header size to * protect against abuse. * * @return The <code>header-part</code> of the current encapsulation. * @throws MalformedStreamException if the stream ends unexpectedly. */ public String readHeaders() throws MalformedStreamException { int i = 0; byte b; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); int size = 0; while (i < HEADER_SEPARATOR.length) { try { b = readByte(); } catch (IOException e) { throw new MalformedStreamException("Stream ended unexpectedly"); } if (++size > HEADER_PART_SIZE_MAX) { throw new MalformedStreamException(format("Header section has more than %s bytes (maybe it is not properly terminated)", HEADER_PART_SIZE_MAX)); } if (b == HEADER_SEPARATOR[i]) { i++; } else { i = 0; } baos.write(b); } String headers = null; if (headerEncoding != null) { try { headers = baos.toString(headerEncoding); } catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); } } else { headers = baos.toString(); } return headers; } public long readBodyData(OutputStream output) throws IOException { return IOUtil.copy(newInputStream(), output); } /** * Creates a new {@link ItemInputStream}. * * @return A new instance of {@link ItemInputStream}. */ ItemInputStream newInputStream() { return new ItemInputStream(); } /** * <p> Reads <code>body-data</code> from the current * <code>encapsulation</code> and discards it. * <p> * <p>Use this method to skip encapsulations you don't need or don't * understand. * * @return The amount of data discarded. * @throws MalformedStreamException if the stream ends unexpectedly. * @throws IOException if an i/o error occurs. */ public long discardBodyData() throws MalformedStreamException, IOException { return readBodyData(null); } /** * Finds the beginning of the first <code>encapsulation</code>. * * @return <code>true</code> if an <code>encapsulation</code> was found in * the stream. * @throws IOException if an i/o error occurs. */ public boolean skipPreamble() throws IOException { // First delimiter may be not preceeded with a CRLF. System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2); boundaryLength = boundary.length - 2; try { // Discard all data up to the delimiter. discardBodyData(); // Read boundary - if succeeded, the stream contains an // encapsulation. return readBoundary(); } catch (MalformedStreamException e) { return false; } finally { // Restore delimiter. System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2); boundaryLength = boundary.length; boundary[0] = CR; boundary[1] = LF; } } public static boolean arrayequals(byte[] a, byte[] b, int count) { for (int i = 0; i < count; i++) { if (a[i] != b[i]) { return false; } } return true; } /** * Searches for a byte of specified value in the <code>buffer</code>, * starting at the specified <code>position</code>. * * @param value The value to find. * @param pos The starting position for searching. * @return The position of byte found, counting from beginning of the * <code>buffer</code>, or <code>-1</code> if not found. */ protected int findByte(byte value, int pos) { for (int i = pos; i < tail; i++) { if (buffer[i] == value) { return i; } } return -1; } /** * Searches for the <code>boundary</code> in the <code>buffer</code> * region delimited by <code>head</code> and <code>tail</code>. * * @return The position of the boundary found, counting from the * beginning of the <code>buffer</code>, or <code>-1</code> if * not found. */ protected int findSeparator() { int first; int match = 0; int maxpos = tail - boundaryLength; for (first = head; first <= maxpos && match != boundaryLength; first++) { first = findByte(boundary[0], first); if (first == -1 || first > maxpos) { return -1; } for (match = 1; match < boundaryLength; match++) { if (buffer[first + match] != boundary[match]) { break; } } } if (match == boundaryLength) { return first - 1; } return -1; } /** * Thrown to indicate that the input stream fails to follow the * required syntax. */ public static class MalformedStreamException extends IOException { /** * The UID to use when serializing this instance. */ private static final long serialVersionUID = 6466926458059796677L; /** * Constructs a <code>MalformedStreamException</code> with no * detail message. */ public MalformedStreamException() { super(); } /** * Constructs an <code>MalformedStreamException</code> with * the specified detail message. * * @param message The detail message. */ public MalformedStreamException(String message) { super(message); } } /** * Thrown upon attempt of setting an invalid boundary token. */ public static class IllegalBoundaryException extends IOException { /** * The UID to use when serializing this instance. */ private static final long serialVersionUID = -161533165102632918L; /** * Constructs an <code>IllegalBoundaryException</code> with no * detail message. */ public IllegalBoundaryException() { super(); } /** * Constructs an <code>IllegalBoundaryException</code> with * the specified detail message. * * @param message The detail message. */ public IllegalBoundaryException(String message) { super(message); } } /** * An {@link InputStream} for reading an items contents. */ private class ItemInputStream extends InputStream implements Closeable { /** * The number of bytes, which have been read so far. */ private long total; /** * The number of bytes, which must be hold, because * they might be a part of the boundary. */ private int pad; /** * The current offset in the buffer. */ private int pos; /** * Whether the stream is already closed. */ private boolean closed; /** * Creates a new instance. */ ItemInputStream() { findSeparator(); } /** * Called for finding the separator. */ private void findSeparator() { pos = MultipartStream.this.findSeparator(); if (pos == -1) { if (tail - head > keepRegion) { pad = keepRegion; } else { pad = tail - head; } } } /** * Returns the number of bytes, which have been read * by the stream. * * @return Number of bytes, which have been read so far. */ public long getBytesRead() { return total; } /** * Returns the number of bytes, which are currently * available, without blocking. * * @return Number of bytes in the buffer. * @throws IOException An I/O error occurs. */ @Override public int available() throws IOException { if (pos == -1) { return tail - head - pad; } return pos - head; } /** * Offset when converting negative bytes to integers. */ private static final int BYTE_POSITIVE_OFFSET = 256; /** * Returns the next byte in the stream. * * @return The next byte in the stream, as a non-negative * integer, or -1 for EOF. * @throws IOException An I/O error occurred. */ @Override public int read() throws IOException { if (closed) { //todo } if (available() == 0 && makeAvailable() == 0) { return -1; } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; } /** * Reads bytes into the given buffer. * * @param b The destination buffer, where to write to. * @param off Offset of the first byte in the buffer. * @param len Maximum number of bytes to read. * @return Number of bytes, which have been actually read, * or -1 for EOF. * @throws IOException An I/O error occurred. */ @Override public int read(byte[] b, int off, int len) throws IOException { if (closed) { //todo } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; } /** * Closes the input stream. * * @throws IOException An I/O error occurred. */ @Override public void close() throws IOException { close(false); } /** * Closes the input stream. * * @param pCloseUnderlying Whether to close the underlying stream * (hard close) * @throws IOException An I/O error occurred. */ public void close(boolean pCloseUnderlying) throws IOException { if (closed) { return; } if (pCloseUnderlying) { closed = true; input.close(); } else { for (; ; ) { int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { break; } } skip(av); } } closed = true; } /** * Skips the given number of bytes. * * @param bytes Number of bytes to skip. * @return The number of bytes, which have actually been * skipped. * @throws IOException An I/O error occurred. */ @Override public long skip(long bytes) throws IOException { int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; } /** * Attempts to read more data. * * @return Number of available bytes * @throws IOException An I/O error occurred. */ private int makeAvailable() throws IOException { if (pos != -1) { return 0; } // Move the data to the beginning of the buffer. total += tail - head - pad; System.arraycopy(buffer, tail - pad, buffer, 0, pad); // Refill buffer with new data. head = 0; tail = pad; for (; ; ) { int bytesRead = input.read(buffer, tail, bufSize - tail); if (bytesRead == -1) { // The last pad amount is left in the buffer. // Boundary can't be in there so signal an error // condition. final String msg = "Stream ended unexpectedly"; throw new MalformedStreamException(msg); } tail += bytesRead; findSeparator(); int av = available(); if (av > 0 || pos != -1) { return av; } } } public boolean isClosed() { return closed; } } }
cornelcreanga/webserver
src/main/java/com/ccreanga/webserver/ioutil/MultipartStream.java
Java
apache-2.0
22,575
package org.leguan.language.java; import org.leguan.container.Container; import java.util.List; import java.util.function.Predicate; public class JavaMethodContainer extends Container<JavaMethod> { public JavaMethodContainer (final List<JavaMethod> methods) { super (methods); } @Override public JavaMethodContainer cloneContainer(List<JavaMethod> items) { return new JavaMethodContainer(items); } public JavaMethodContainer filterContainer (final Predicate<JavaMethod> methodPredicate) { return cloneContainer(super.filteredByPredicate(methodPredicate)); } /** * selects resources with name that contains a special token * @param token token of name * @return container itself */ public JavaMethodContainer nameContains (final String token) { return filterContainer(method -> method.getName().contains(token)); } /** * select resources with name that equals the given name * @param name complete name * @return container itself */ public JavaMethodContainer nameEquals (final String name) { return filterContainer (method -> method.getName().equals(name)); } public JavaMethodContainer clone () { return cloneContainer(getAllItems()); } /** * selects static methods * @return container itself */ public JavaMethodContainer isStatic () { return filterContainer(method -> method.isStatic()); } /** * selects methods with one of the given visibilities * @param visibilities list of visibilities * @return container itself */ public JavaMethodContainer visibilities (final JavaVisibility... visibilities) { return filterContainer (new Predicate<JavaMethod>() { @Override public boolean test(JavaMethod t) { for (JavaVisibility next: visibilities) { if (t.getVisibility().equals(next)) return true; } return false; } }); } }
moley/leguan
leguan-languages/leguan-language-java/src/main/java/org/leguan/language/java/JavaMethodContainer.java
Java
apache-2.0
1,926
/** * Copyright 2014 Fernando Rincon Martin <frm.rincon@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openeos.erp.core.model; // Generated Apr 22, 2014 5:16:14 PM by Hibernate Tools 4.0.0 // Template generated from org.openeos.hibernate.hbm2java import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.hibernate.annotations.GenericGenerator; /** * Country generated by hbm2java */ @Entity @Table(name="C_COUNTRY" , uniqueConstraints = @UniqueConstraint(columnNames="COUNTRYCODE") ) public class Country implements java.io.Serializable { public static final String PROPERTY_ID = "id"; public static final String PROPERTY_NAME = "name"; public static final String PROPERTY_DESCRIPTION = "description"; public static final String PROPERTY_COUNTRYCODE = "countrycode"; public static final String PROPERTY_REGION_DEFINED = "regionDefined"; public static final String PROPERTY_REGIONNAME = "regionname"; public static final String PROPERTY_POSTAL_ADD = "postalAdd"; public static final String PROPERTY_AD_LANGUAGE = "adLanguage"; public static final String PROPERTY_REGIONS = "regions"; public static final String PROPERTY_LOCATIONS = "locations"; private String id; private String name; private String description; private String countrycode; private boolean regionDefined; private String regionname; private boolean postalAdd; private String adLanguage; private Set<Region> regions = new HashSet<Region>(0); private Set<Location> locations = new HashSet<Location>(0); public Country() { } public Country(String name, String countrycode, boolean regionDefined, boolean postalAdd) { this.name = name; this.countrycode = countrycode; this.regionDefined = regionDefined; this.postalAdd = postalAdd; } public Country(String name, String description, String countrycode, boolean regionDefined, String regionname, boolean postalAdd, String adLanguage, Set<Region> regions, Set<Location> locations) { this.name = name; this.description = description; this.countrycode = countrycode; this.regionDefined = regionDefined; this.regionname = regionname; this.postalAdd = postalAdd; this.adLanguage = adLanguage; this.regions = regions; this.locations = locations; } @GenericGenerator(name="generator", strategy="uuid")@Id @GeneratedValue(generator="generator") @Column(name="C_COUNTRY_ID", unique=true, nullable=false, length=32) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @Column(name="NAME", nullable=false, length=60) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name="DESCRIPTION") public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @Column(name="COUNTRYCODE", unique=true, nullable=false, length=2) public String getCountrycode() { return this.countrycode; } public void setCountrycode(String countrycode) { this.countrycode = countrycode; } @Column(name="HASREGION", nullable=false) public boolean isRegionDefined() { return this.regionDefined; } public void setRegionDefined(boolean regionDefined) { this.regionDefined = regionDefined; } @Column(name="REGIONNAME", length=60) public String getRegionname() { return this.regionname; } public void setRegionname(String regionname) { this.regionname = regionname; } @Column(name="HASPOSTAL_ADD", nullable=false) public boolean isPostalAdd() { return this.postalAdd; } public void setPostalAdd(boolean postalAdd) { this.postalAdd = postalAdd; } @Column(name="AD_LANGUAGE", length=6) public String getAdLanguage() { return this.adLanguage; } public void setAdLanguage(String adLanguage) { this.adLanguage = adLanguage; } @OneToMany(fetch=FetchType.LAZY, mappedBy="country") public Set<Region> getRegions() { return this.regions; } public void setRegions(Set<Region> regions) { this.regions = regions; } @OneToMany(fetch=FetchType.LAZY, mappedBy="country") public Set<Location> getLocations() { return this.locations; } public void setLocations(Set<Location> locations) { this.locations = locations; } }
frincon/openeos
modules/org.openeos.erp.core/src/main/java/org/openeos/erp/core/model/Country.java
Java
apache-2.0
5,571
/** * 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.gms; import java.io.FileOutputStream; import java.io.IOException; import java.io.IOError; import java.lang.management.ManagementFactory; import java.util.*; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.lang.StringUtils; import java.net.InetAddress; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.BoundedStatsDeque; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This FailureDetector is an implementation of the paper titled * "The Phi Accrual Failure Detector" by Hayashibara. * Check the paper and the <i>IFailureDetector</i> interface for details. */ public class FailureDetector implements IFailureDetector, FailureDetectorMBean { public static final IFailureDetector instance = new FailureDetector(); private static Logger logger_ = LoggerFactory.getLogger(FailureDetector.class); private static final int sampleSize_ = 1000; private static int phiConvictThreshold_; /* The Failure Detector has to have been up for at least 1 min. */ private static final long uptimeThreshold_ = 60000; /* The time when the module was instantiated. */ private static long creationTime_; private Map<InetAddress, ArrivalWindow> arrivalSamples_ = new Hashtable<InetAddress, ArrivalWindow>(); private List<IFailureDetectionEventListener> fdEvntListeners_ = new ArrayList<IFailureDetectionEventListener>(); public FailureDetector() { phiConvictThreshold_ = DatabaseDescriptor.getPhiConvictThreshold(); creationTime_ = System.currentTimeMillis(); // Register this instance with JMX try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); mbs.registerMBean(this, new ObjectName("org.apache.cassandra.gms:type=FailureDetector")); } catch (Exception e) { throw new RuntimeException(e); } } public String getAllEndpointStates() { StringBuilder sb = new StringBuilder(); for (Map.Entry<InetAddress, EndpointState> entry : Gossiper.instance.endpointStateMap_.entrySet()) { sb.append(entry.getKey()).append("\n"); for (Map.Entry<String, ApplicationState> state : entry.getValue().applicationState_.entrySet()) sb.append(" ").append(state.getKey()).append(":").append(state.getValue().getValue()).append("\n"); } return sb.toString(); } /** * Dump the inter arrival times for examination if necessary. */ public void dumpInterArrivalTimes() { try { FileOutputStream fos = new FileOutputStream("/var/tmp/output-" + System.currentTimeMillis() + ".dat", true); fos.write(toString().getBytes()); fos.close(); } catch (IOException e) { throw new IOError(e); } } /** * We dump the arrival window for any endpoint only if the * local Failure Detector module has been up for more than a * minute. * * @param ep for which the arrival window needs to be dumped. */ private void dumpInterArrivalTimes(InetAddress ep) { long now = System.currentTimeMillis(); if ( (now - FailureDetector.creationTime_) <= FailureDetector.uptimeThreshold_ ) return; try { FileOutputStream fos = new FileOutputStream("/var/tmp/output-" + System.currentTimeMillis() + "-" + ep + ".dat", true); ArrivalWindow hWnd = arrivalSamples_.get(ep); fos.write(hWnd.toString().getBytes()); fos.close(); } catch (IOException e) { throw new IOError(e); } } public void setPhiConvictThreshold(int phi) { phiConvictThreshold_ = phi; } public int getPhiConvictThreshold() { return phiConvictThreshold_; } public boolean isAlive(InetAddress ep) { if (ep.equals(FBUtilities.getLocalAddress())) return true; EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(ep); // we could assert not-null, but having isAlive fail screws a node over so badly that // it's worth being defensive here so minor bugs don't cause disproportionate // badness. (See CASSANDRA-1463 for an example). if (epState == null) logger_.error("unknown endpoint " + ep); return epState != null && epState.isAlive(); } public void report(InetAddress ep) { if (logger_.isTraceEnabled()) logger_.trace("reporting {}", ep); long now = System.currentTimeMillis(); ArrivalWindow heartbeatWindow = arrivalSamples_.get(ep); if ( heartbeatWindow == null ) { heartbeatWindow = new ArrivalWindow(sampleSize_); arrivalSamples_.put(ep, heartbeatWindow); } heartbeatWindow.add(now); } public void interpret(InetAddress ep) { ArrivalWindow hbWnd = arrivalSamples_.get(ep); if ( hbWnd == null ) { return; } long now = System.currentTimeMillis(); double phi = hbWnd.phi(now); if (logger_.isTraceEnabled()) logger_.trace("PHI for " + ep + " : " + phi); if ( phi > phiConvictThreshold_ ) { for ( IFailureDetectionEventListener listener : fdEvntListeners_ ) { listener.convict(ep); } } } public void remove(InetAddress ep) { arrivalSamples_.remove(ep); } public void registerFailureDetectionEventListener(IFailureDetectionEventListener listener) { fdEvntListeners_.add(listener); } public void unregisterFailureDetectionEventListener(IFailureDetectionEventListener listener) { fdEvntListeners_.remove(listener); } public String toString() { StringBuilder sb = new StringBuilder(); Set<InetAddress> eps = arrivalSamples_.keySet(); sb.append("-----------------------------------------------------------------------"); for ( InetAddress ep : eps ) { ArrivalWindow hWnd = arrivalSamples_.get(ep); sb.append(ep + " : "); sb.append(hWnd.toString()); sb.append( System.getProperty("line.separator") ); } sb.append("-----------------------------------------------------------------------"); return sb.toString(); } public static void main(String[] args) throws Throwable { } } class ArrivalWindow { private static Logger logger_ = LoggerFactory.getLogger(ArrivalWindow.class); private double tLast_ = 0L; private BoundedStatsDeque arrivalIntervals_; ArrivalWindow(int size) { arrivalIntervals_ = new BoundedStatsDeque(size); } synchronized void add(double value) { double interArrivalTime; if ( tLast_ > 0L ) { interArrivalTime = (value - tLast_); } else { interArrivalTime = Gossiper.intervalInMillis_ / 2; } tLast_ = value; arrivalIntervals_.add(interArrivalTime); } synchronized double sum() { return arrivalIntervals_.sum(); } synchronized double sumOfDeviations() { return arrivalIntervals_.sumOfDeviations(); } synchronized double mean() { return arrivalIntervals_.mean(); } synchronized double variance() { return arrivalIntervals_.variance(); } double stdev() { return arrivalIntervals_.stdev(); } void clear() { arrivalIntervals_.clear(); } double p(double t) { double mean = mean(); double exponent = (-1)*(t)/mean; return Math.pow(Math.E, exponent); } double phi(long tnow) { int size = arrivalIntervals_.size(); double log = 0d; if ( size > 0 ) { double t = tnow - tLast_; double probability = p(t); log = (-1) * Math.log10( probability ); } return log; } public String toString() { return StringUtils.join(arrivalIntervals_.iterator(), " "); } }
aguynamedben/cassandra-counters
src/java/org/apache/cassandra/gms/FailureDetector.java
Java
apache-2.0
9,534
// File generated by OpenXava: Wed Sep 11 11:56:52 CEST 2013 // Archivo generado por OpenXava: Wed Sep 11 11:56:52 CEST 2013 // WARNING: NO EDIT // OJO: NO EDITAR // Component: Customer Java interface for aggregate/Interfaz java para Agregado: DeliveryPlace package org.openxava.test.model; import java.math.*; import java.rmi.RemoteException; public interface IDeliveryPlace extends org.openxava.model.IModel { // Properties/Propiedades public static final String PROPERTY_oid = "oid"; int getOid() throws RemoteException; public static final String PROPERTY_remarks = "remarks"; String getRemarks() throws RemoteException; void setRemarks(String remarks) throws RemoteException; public static final String PROPERTY_address = "address"; String getAddress() throws RemoteException; void setAddress(String address) throws RemoteException; public static final String PROPERTY_name = "name"; String getName() throws RemoteException; void setName(String name) throws RemoteException; java.util.Collection getReceptionists() throws RemoteException; // References/Referencias // Customer : Reference/Referencia org.openxava.test.model.ICustomer getCustomer() throws RemoteException; void setCustomer(org.openxava.test.model.ICustomer newCustomer) throws RemoteException; // PreferredWarehouse : Reference/Referencia org.openxava.test.model.IWarehouse getPreferredWarehouse() throws RemoteException; void setPreferredWarehouse(org.openxava.test.model.IWarehouse newPreferredWarehouse) throws RemoteException; // Methods }
jecuendet/maven4openxava
dist/openxava/workspace/OpenXavaTest/gen-src-xava/org/openxava/test/model/IDeliveryPlace.java
Java
apache-2.0
1,576
/* SeedUrlNotFoundException * * $Id$ * * Created on Mar 9, 2005 * * Copyright (C) 2005 Mike Schwartz. * * This file is part of the Heritrix web crawler (crawler.archive.org). * * Heritrix is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * any later version. * * Heritrix is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Heritrix; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.archive.crawler.util; /** * @author Mike Schwartz, schwartz at CodeOnTheRoad dot com */ public class SeedUrlNotFoundException extends Exception { private static final long serialVersionUID = 2515927240634523493L; public SeedUrlNotFoundException(String message) { super(message); } }
searchtechnologies/heritrix-connector
engine-3.1.1/engine/src/main/java/org/archive/crawler/util/SeedUrlNotFoundException.java
Java
apache-2.0
1,170
/* * Copyright 2014-2019 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.codestar.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.codestar.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * UpdateUserProfileResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateUserProfileResultJsonUnmarshaller implements Unmarshaller<UpdateUserProfileResult, JsonUnmarshallerContext> { public UpdateUserProfileResult unmarshall(JsonUnmarshallerContext context) throws Exception { UpdateUserProfileResult updateUserProfileResult = new UpdateUserProfileResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return updateUserProfileResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("userArn", targetDepth)) { context.nextToken(); updateUserProfileResult.setUserArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("displayName", targetDepth)) { context.nextToken(); updateUserProfileResult.setDisplayName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("emailAddress", targetDepth)) { context.nextToken(); updateUserProfileResult.setEmailAddress(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("sshPublicKey", targetDepth)) { context.nextToken(); updateUserProfileResult.setSshPublicKey(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("createdTimestamp", targetDepth)) { context.nextToken(); updateUserProfileResult.setCreatedTimestamp(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("lastModifiedTimestamp", targetDepth)) { context.nextToken(); updateUserProfileResult.setLastModifiedTimestamp(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return updateUserProfileResult; } private static UpdateUserProfileResultJsonUnmarshaller instance; public static UpdateUserProfileResultJsonUnmarshaller getInstance() { if (instance == null) instance = new UpdateUserProfileResultJsonUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-codestar/src/main/java/com/amazonaws/services/codestar/model/transform/UpdateUserProfileResultJsonUnmarshaller.java
Java
apache-2.0
4,183
package com.mc.library.base; import android.support.v7.app.AppCompatActivity; import android.view.View; /** * Created by dinghui on 2016/11/4. * Activity基类 */ public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener { protected abstract void initWidget(); }
coder173025/MagicCube
library/src/main/java/com/mc/library/base/BaseActivity.java
Java
apache-2.0
307
/* * Copyright 2014 The LolDevs team (https://github.com/loldevs) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.boreeas.riotapi.com.riotgames.platform.statistics; import lombok.Data; import net.boreeas.riotapi.rtmp.serialization.Serialization; import java.util.ArrayList; import java.util.List; /** * Created on 7/19/2014. */ @Data @Serialization(name = "com.riotgames.platform.statistics.PlayerStatSummaries") public class PlayerStatSummaries { // TODO inspect private List<PlayerStatSummary> playerStatSummarySet = new ArrayList<>(); private long userId; private int season; }
loldevs/riotapi
domain/src/main/java/net/boreeas/riotapi/com/riotgames/platform/statistics/PlayerStatSummaries.java
Java
apache-2.0
1,130
/** * Support classes for DAO implementations, * providing miscellaneous utility methods. */ @NonNullApi @NonNullFields package org.springframework.dao.support; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
spring-projects/spring-framework
spring-tx/src/main/java/org/springframework/dao/support/package-info.java
Java
apache-2.0
256
package com.android.robot; import java.io.File; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.wb.swt.SWTResourceManager; import com.android.util.PropertiesUtil; public class SetApkWindow extends Dialog { protected String result; protected Shell shell; protected Display display; private Text textDir; private Text textScript; private Label lblError; private String path; /** * Create the dialog. * @param parent * @param style */ public SetApkWindow(Shell parent, int style,String path) { super(parent, style); setText("设置被测应用"); this.path = path; } /** * Open the dialog. * @return the result */ public String open() { createContents(); GridData gd_label = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_label.widthHint = 434; Composite composite2 = new Composite(shell, SWT.NONE); composite2.setLayoutData(new GridData(435, 150)); composite2.setLayout(new GridLayout(3,false)); Label lb = new Label(composite2, SWT.CENTER); lb.setText("选择应用:"); textDir = new Text(composite2, SWT.BORDER); GridData gd_textDir = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_textDir.widthHint = 270; textDir.setLayoutData(gd_textDir); textDir.setText(path); Button selectApp = new Button(composite2,SWT.CENTER); selectApp.setText("选择"); selectApp.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog (shell, SWT.MULTI | SWT.OPEN); dialog.setFilterNames (new String [] {"apk Files (*.apk)"}); dialog.setFilterExtensions (new String [] {"*.apk*"}); dialog.setFilterPath (".\\workspace"); String choice = dialog.open(); if(choice != null){ String filePath = dialog.getFilterPath(); String[] selectedFiles = dialog.getFileNames(); File apkFile = new File(filePath + "/" + selectedFiles[0]); textDir.setText(apkFile.getAbsolutePath()); } } }); Composite composite3 = new Composite(shell, SWT.NONE); GridData gd_composite3 = new GridData(435, 50); gd_composite3.verticalAlignment = SWT.FILL; composite3.setLayoutData(gd_composite3); composite3.setLayout(new GridLayout(2,false)); Button previous = new Button(composite3,SWT.NONE); GridData gd_previous = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_previous.heightHint = 25; gd_previous.widthHint = 77; previous.setLayoutData(gd_previous); previous.setText("确定"); previous.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PropertiesUtil.append("./system.properties", "aut", textDir.getText().trim(), "Aut"); result = ""; shell.close(); shell.dispose(); } }); Button cancel = new Button(composite3,SWT.NONE); GridData gd_cancel = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_cancel.heightHint = 25; gd_cancel.widthHint = 77; cancel.setLayoutData(gd_cancel); cancel.setText("取消"); cancel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { result = ""; shell.close(); shell.dispose(); } }); shell.open(); shell.layout(); while (shell!=null&&!shell.isDisposed()) { if (display!=null&&!display.readAndDispatch()) { display.sleep(); } } return result; } /** * Create contents of the dialog. */ private void createContents() { shell = new Shell(getParent(), getStyle()); shell.setSize(450, 300); shell.setText(getText()); shell.setImage(SWTResourceManager.getImage(".\\icons\\title.png")); shell.setLayout(new GridLayout(1,false)); display = getParent().getDisplay(); } }
caizhenxing/androidrobot
AndroidRobot_Spider3/src/com/android/robot/SetApkWindow.java
Java
apache-2.0
4,370